Files
Promptly/server/store.js
T

384 lines
12 KiB
JavaScript

// In-memory хранилище презентаций с нормализацией новых интерактивных слайдов
const crypto = require('crypto');
const presentations = new Map();
const uid = (prefix) => `${prefix}_${crypto.randomUUID()}`;
const num = (value, fallback) => (Number.isFinite(Number(value)) ? Number(value) : fallback);
const clamp01 = (value, fallback = 0) => Math.max(0, Math.min(1, num(value, fallback)));
const str = (value, fallback = '') => (typeof value === 'string' ? value : fallback);
const plainObject = (value) => (value && typeof value === 'object' && !Array.isArray(value) ? value : {});
const DEFAULT_GRADIENT = 'linear-gradient(135deg, #0f172a 0%, #1e1b4b 55%, #312e81 100%)';
function normalizeBackground(background) {
const bg = plainObject(background);
const type = ['color', 'gradient', 'image'].includes(bg.type)
? bg.type
: bg.image
? 'image'
: bg.gradient
? 'gradient'
: 'color';
return {
type,
color: str(bg.color, '#0f172a') || '#0f172a',
gradient: str(bg.gradient, DEFAULT_GRADIENT) || DEFAULT_GRADIENT,
image: str(bg.image, ''),
};
}
function normalizeAction(action) {
const a = plainObject(action);
const type = ['none', 'go', 'next', 'prev', 'play', 'stop', 'lua'].includes(a.type) ? a.type : 'next';
return {
type,
slideIndex: Math.max(0, Math.floor(num(a.slideIndex, 0))),
audioId: str(a.audioId, ''),
code: str(a.code, ''),
scriptNodeId: str(a.scriptNodeId, ''),
};
}
function normalizeElement(element, index) {
const el = plainObject(element);
const type = ['text', 'image', 'button', 'audio', 'video', 'window'].includes(el.type) ? el.type : 'text';
const base = {
id: str(el.id, '') || uid('el'),
type,
x: num(el.x, 10),
y: num(el.y, 10),
w: num(el.w, 40),
h: num(el.h, 15),
z: Math.floor(num(el.z, index + 1)),
};
if (type === 'text') {
return {
...base,
text: str(el.text, ''),
fontSize: num(el.fontSize, 5),
color: str(el.color, '#f8fafc'),
weight: Math.floor(num(el.weight, 700)),
align: ['left', 'center', 'right'].includes(el.align) ? el.align : 'center',
bg: str(el.bg, ''),
};
}
if (type === 'image') {
return {
...base,
src: str(el.src, ''),
fit: el.fit === 'contain' ? 'contain' : 'cover',
radius: num(el.radius, 14),
};
}
if (type === 'button') {
return {
...base,
label: str(el.label, 'Кнопка'),
bg: str(el.bg, '#6366f1'),
color: str(el.color, '#ffffff'),
fontSize: num(el.fontSize, 2.2),
radius: num(el.radius, 12),
action: normalizeAction(el.action),
};
}
if (type === 'audio') {
return {
...base,
src: str(el.src, ''),
loop: !!el.loop,
visible: el.visible !== false,
volume: clamp01(el.volume, 0.8),
label: str(el.label, 'Аудио'),
};
}
if (type === 'video') {
return {
...base,
src: str(el.src, ''),
poster: str(el.poster, ''),
fit: el.fit === 'contain' ? 'contain' : 'cover',
radius: num(el.radius, 12),
autoplay: el.autoplay !== false,
loop: !!el.loop,
muted: el.muted !== false,
controls: el.controls !== false,
label: str(el.label, 'Видео'),
};
}
if (type === 'window') {
return {
...base,
targetId: str(el.targetId, ''),
targetTitle: str(el.targetTitle, ''),
targetUrl: str(el.targetUrl, ''),
fit: el.fit === 'contain' ? 'contain' : 'contain',
radius: num(el.radius, 12),
autoStart: el.autoStart !== false,
label: str(el.label, 'Окно Chrome'),
};
}
return {
...base,
src: str(el.src, ''),
loop: !!el.loop,
visible: el.visible !== false,
volume: clamp01(el.volume, 0.8),
label: str(el.label, 'Аудио'),
};
}
function normalizeSlide(slide, index = 0) {
const s = plainObject(slide);
let elements = Array.isArray(s.elements) ? s.elements.map(normalizeElement) : [];
// Совместимость со старым форматом: text + image
if (!elements.length) {
if (str(s.text).trim()) {
elements.push(
normalizeElement(
{ type: 'text', text: s.text, x: 8, y: 34, w: 84, h: 32, fontSize: 6, align: 'center', color: '#f8fafc' },
0
)
);
}
if (str(s.image).trim()) {
elements.push(
normalizeElement({ type: 'image', src: s.image, x: 22, y: 18, w: 56, h: 48, fit: 'contain', z: 0 }, 1)
);
}
}
return {
id: str(s.id, '') || uid('slide'),
notes: str(s.notes, ''),
transition: ['none', 'fade', 'slide', 'zoom'].includes(s.transition) ? s.transition : 'fade',
background: normalizeBackground(s.background),
lua: str(s.lua, ''),
elements,
};
}
function normalizeVariables(variables) {
const result = {};
for (const [key, value] of Object.entries(plainObject(variables))) {
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
result[key] = value;
}
}
return result;
}
function defaultNodePosition(index) {
return { x: 340 + (index % 4) * 320, y: 60 + Math.floor(index / 4) * 300 };
}
function normalizeGraph(graph, slides) {
const g = plainObject(graph);
const sourcePositions = plainObject(g.positions);
const positions = {};
slides.forEach((slide, index) => {
const p = plainObject(sourcePositions[slide.id]);
const fallback = defaultNodePosition(index);
positions[slide.id] = { x: num(p.x, fallback.x), y: num(p.y, fallback.y) };
});
const scripts = (Array.isArray(g.scripts) ? g.scripts : []).map((node, index) => {
const n = plainObject(node);
return {
id: str(n.id, '') || uid('script'),
name: str(n.name, 'Скрипт') || 'Скрипт',
code: str(n.code, ''),
x: num(n.x, 60 + (index % 3) * 320),
y: num(n.y, 520 + Math.floor(index / 3) * 220),
slideId: str(n.slideId, ''),
elementId: str(n.elementId, ''),
};
});
const audios = (Array.isArray(g.audios) ? g.audios : []).map((node, index) => {
const n = plainObject(node);
return {
id: str(n.id, '') || uid('audio'),
name: str(n.name, 'Аудио') || 'Аудио',
elementId: str(n.elementId, ''),
mode: n.mode === 'stop' ? 'stop' : 'play',
x: num(n.x, 60 + (index % 3) * 320),
y: num(n.y, 840 + Math.floor(index / 3) * 110),
};
});
const variables = (Array.isArray(g.variables) ? g.variables : []).map((node, index) => {
const n = plainObject(node);
return {
id: str(n.id, '') || uid('var'),
name: str(n.name, '') || `var${index + 1}`,
x: num(n.x, 40),
y: num(n.y, 520 + index * 96),
};
});
const slideIds = new Set(slides.map((slide) => slide.id));
const idsByKind = {
slide: slideIds,
script: new Set(scripts.map((node) => node.id)),
audio: new Set(audios.map((node) => node.id)),
variable: new Set(variables.map((node) => node.id)),
};
const links = (Array.isArray(g.links) ? g.links : []).map((link) => {
const l = plainObject(link);
const from = plainObject(l.from);
const to = plainObject(l.to);
if (!from.kind || !to.kind || !Object.prototype.hasOwnProperty.call(idsByKind, from.kind) || !Object.prototype.hasOwnProperty.call(idsByKind, to.kind)) return null;
if (!idsByKind[from.kind].has(String(from.id)) || !idsByKind[to.kind].has(String(to.id))) return null;
if (!str(from.port, '') || !str(to.port, '')) return null;
return {
id: str(l.id, '') || uid('link'),
from: { kind: from.kind, id: String(from.id), port: String(from.port) },
to: { kind: to.kind, id: String(to.id), port: String(to.port) },
};
}).filter(Boolean);
// Переходы «дальше/назад» выводятся из связей — это источник истины.
const jumps = {};
links.forEach((link) => {
if (link.from.kind !== 'slide' || !['next', 'prev'].includes(link.from.port)) return;
if (link.to.kind !== 'slide' || link.to.port !== 'in') return;
jumps[link.from.id] = jumps[link.from.id] || {};
jumps[link.from.id][link.from.port] = link.to.id;
});
return { positions, scripts, audios, variables, links, jumps };
}
// Кнопки с Lua из старых версий получают отдельную ноду в графе.
function migrateLuaScripts(slides, graph) {
slides.forEach((slide) => {
(slide.elements || []).forEach((element) => {
if (element.type !== 'button' || !element.action || element.action.type !== 'lua') return;
const action = element.action;
let node = graph.scripts.find(
(item) => item.id === action.scriptNodeId || (item.elementId === element.id && item.slideId === slide.id)
);
if (!node) {
const base = graph.positions[slide.id] || { x: 60, y: 60 };
node = {
id: uid('script'),
name: `Lua · ${element.label || 'Кнопка'}`,
code: action.code || '',
x: base.x + 330,
y: base.y + 20,
slideId: slide.id,
elementId: element.id,
};
graph.scripts.push(node);
} else if (!node.code && action.code) {
node.code = action.code;
}
if (!node.elementId) {
node.elementId = element.id;
node.slideId = slide.id;
}
action.scriptNodeId = node.id;
if (node.code) action.code = node.code;
});
});
}
function normalizeCommands(commands) {
return (Array.isArray(commands) ? commands : []).map((item) => {
const command = plainObject(item);
return {
id: str(command.id, '') || uid('cmd'),
label: str(command.label, 'Команда') || 'Команда',
description: str(command.description, ''),
code: str(command.code, ''),
};
});
}
function normalizePresentation(input = {}) {
const data = plainObject(input);
const slides = Array.isArray(data.slides) ? data.slides.map(normalizeSlide) : [];
const finalSlides = slides.length ? slides : [normalizeSlide({})];
const graph = normalizeGraph(data.graph, finalSlides);
migrateLuaScripts(finalSlides, graph);
return {
title: str(data.title, '').trim() || 'Без названия',
variables: normalizeVariables(data.variables),
music: {
src: str(data.music && data.music.src, ''),
volume: clamp01(data.music && data.music.volume, 0.5),
},
lua: str(data.lua, ''),
commands: normalizeCommands(data.commands),
graph,
slides: finalSlides,
};
}
function createPresentation(input = {}) {
const id = uid('pres');
const presentation = {
id,
...normalizePresentation(input),
currentSlide: 0,
createdAt: Date.now(),
updatedAt: Date.now(),
};
presentations.set(id, presentation);
return presentation;
}
function getPresentation(id) {
return presentations.get(id);
}
function updatePresentation(id, input = {}) {
const presentation = presentations.get(id);
if (!presentation) return null;
const normalized = normalizePresentation({
title: input.title ?? presentation.title,
variables: input.variables ?? presentation.variables,
music: input.music ?? presentation.music,
lua: input.lua ?? presentation.lua,
commands: input.commands ?? presentation.commands,
graph: input.graph ?? presentation.graph,
slides: input.slides ?? presentation.slides,
});
Object.assign(presentation, normalized, { updatedAt: Date.now() });
return presentation;
}
function savePresentation(presentation) {
presentations.set(presentation.id, presentation);
return presentation;
}
function deletePresentation(id) {
return presentations.delete(id);
}
function listPresentations() {
return [...presentations.values()].map((p) => ({
id: p.id,
title: p.title,
slides: p.slides,
variables: p.variables,
music: p.music,
lua: p.lua,
commands: p.commands,
graph: p.graph,
currentSlide: p.currentSlide,
createdAt: p.createdAt,
updatedAt: p.updatedAt,
}));
}
module.exports = {
createPresentation,
getPresentation,
updatePresentation,
savePresentation,
deletePresentation,
listPresentations,
};