5631 lines
270 KiB
HTML
5631 lines
270 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="ru">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||
<title>Promptly — редактор</title>
|
||
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Ctext y='.9em' font-size='90'%3E%F0%9F%8E%A4%3C/text%3E%3C/svg%3E">
|
||
<style>
|
||
:root {
|
||
--bg: #101014;
|
||
--panel: rgba(30, 30, 30, .5);
|
||
--panel-2: rgba(30, 30, 30, .68);
|
||
--border: rgba(255, 255, 255, .08);
|
||
--accent: #4cc2ff;
|
||
--text: #e5e5e5;
|
||
--muted: #aaa;
|
||
--danger: #f87171;
|
||
}
|
||
* { box-sizing: border-box; }
|
||
html, body { height: 100%; }
|
||
body {
|
||
margin: 0; overflow: hidden; color: var(--text);
|
||
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
||
background:
|
||
radial-gradient(900px 500px at 10% -10%, rgba(99, 102, 241, .16), transparent 60%),
|
||
radial-gradient(800px 460px at 100% 0%, rgba(217, 70, 239, .1), transparent 55%),
|
||
var(--bg);
|
||
}
|
||
button { border: none; border-radius: 10px; padding: 8px 12px; font: inherit; font-size: 13px; cursor: pointer; transition: .15s; background: var(--panel-2); color: var(--text); }
|
||
button:hover:not(:disabled) { background: rgba(255, 255, 255, .13); }
|
||
button:disabled { opacity: .35; cursor: default; }
|
||
input, select, textarea { font: inherit; font-size: 13px; color: var(--text); background: rgba(255,255,255,.05); border: 1px solid var(--border); border-radius: 9px; padding: 8px 10px; width: 100%; }
|
||
input:focus, select:focus, textarea:focus { outline: 2px solid rgba(129, 140, 248, .6); border-color: transparent; }
|
||
textarea { resize: vertical; line-height: 1.45; }
|
||
select option { background: #131a2c; }
|
||
.ghost { background: rgba(255,255,255,.07); }
|
||
.primary { background: linear-gradient(90deg, #1795d8, #38bdf8); color: #fff; font-weight: 600; }
|
||
.primary:hover:not(:disabled) { filter: brightness(1.12); background: linear-gradient(90deg, #1795d8, #38bdf8); }
|
||
.danger { background: rgba(239, 68, 68, .14); color: #fca5a5; border: 1px solid rgba(239, 68, 68, .3); }
|
||
.danger:hover:not(:disabled) { background: rgba(239, 68, 68, .25); }
|
||
|
||
/* ===== Верхняя панель ===== */
|
||
.topbar {
|
||
height: 58px; display: flex; align-items: center; gap: 12px; padding: 0 16px;
|
||
background: rgba(8, 11, 22, .82); border-bottom: 1px solid var(--border);
|
||
backdrop-filter: blur(18px); position: relative; z-index: 30;
|
||
}
|
||
.back { color: var(--muted); text-decoration: none; font-size: 18px; padding: 6px 8px; border-radius: 8px; }
|
||
.back:hover { color: #fff; background: rgba(255,255,255,.07); }
|
||
.logo { font-weight: 800; font-size: 16px; letter-spacing: -.3px; white-space: nowrap; }
|
||
.logo span { background: linear-gradient(90deg, #4cc2ff, #7fd4ff); -webkit-background-clip: text; background-clip: text; color: transparent; }
|
||
.title-input { flex: 1; max-width: 420px; min-width: 120px; background: transparent; border: 1px solid transparent; font-size: 15px; font-weight: 600; padding: 8px 10px; }
|
||
.title-input:hover { border-color: var(--border); }
|
||
.title-input:focus { background: rgba(255,255,255,.05); border-color: transparent; }
|
||
.live-chip { font-size: 11.5px; color: #8fdcff; white-space: nowrap; background: rgba(217, 70, 239, .14); border: 1px solid rgba(217, 70, 239, .4); border-radius: 999px; padding: 4px 10px; }
|
||
.save-state { font-size: 12px; color: var(--muted); white-space: nowrap; margin-left: auto; }
|
||
.save-state.dirty { color: #fbbf24; }
|
||
.save-state.saving { color: var(--accent); }
|
||
.save-state.saved { color: #4ade80; }
|
||
.top-actions { display: flex; align-items: center; gap: 8px; flex-shrink: 0; }
|
||
|
||
/* ===== Каркас ===== */
|
||
.app { display: grid; grid-template-columns: 176px minmax(0, 1fr) 330px; height: calc(100vh - 58px); }
|
||
|
||
/* ===== Рейка слайдов ===== */
|
||
.rail { border-right: 1px solid var(--border); background: rgba(8, 11, 22, .5); display: flex; flex-direction: column; min-height: 0; }
|
||
.rail-head { display: flex; align-items: center; justify-content: space-between; padding: 14px 14px 8px; font-size: 11px; letter-spacing: 1px; text-transform: uppercase; color: var(--muted); font-weight: 700; }
|
||
.thumbs { flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 9px; padding: 4px 12px 12px; }
|
||
.thumb { position: relative; display: block; width: 100%; padding: 0; border: 2px solid transparent; border-radius: 10px; overflow: hidden; background: #0b1020; cursor: pointer; box-shadow: 0 2px 8px rgba(0,0,0,.25); }
|
||
.thumb:hover { border-color: rgba(129, 140, 248, .5); }
|
||
.thumb.active { border-color: #4cc2ff; box-shadow: 0 0 0 3px rgba(99, 102, 241, .2); }
|
||
.thumb .num { position: absolute; top: 5px; left: 5px; z-index: 5; font-size: 10px; font-weight: 700; background: rgba(5, 8, 18, .7); color: #e2e8f0; border-radius: 5px; padding: 1px 6px; }
|
||
.thumb-canvas { position: relative; display: block; width: 100%; aspect-ratio: 16 / 9; overflow: hidden; }
|
||
.add-slide { margin: 0 12px 14px; padding: 10px; border: 1px dashed rgba(129, 140, 248, .5); background: rgba(99,102,241,.08); color: #bfe7ff; font-weight: 600; border-radius: 10px; }
|
||
.add-slide:hover { background: rgba(99,102,241,.16); }
|
||
|
||
/* ===== Рабочая область ===== */
|
||
.workspace { display: flex; flex-direction: column; min-width: 0; min-height: 0; }
|
||
.toolbar { display: flex; align-items: center; gap: 7px; padding: 10px 14px; border-bottom: 1px solid var(--border); flex-wrap: wrap; }
|
||
.toolbar-label { font-size: 11px; text-transform: uppercase; letter-spacing: 1px; color: var(--muted); font-weight: 700; margin-right: 3px; }
|
||
.toolbar .spacer { flex: 1; }
|
||
.toolbar button { padding: 7px 11px; }
|
||
.toolbar button.danger { padding: 7px 10px; }
|
||
|
||
.stage { flex: 1; min-height: 0; display: flex; align-items: center; justify-content: center; padding: 20px; overflow: auto; }
|
||
.canvas-wrap {
|
||
position: relative; flex-shrink: 0;
|
||
width: min(100%, max(320px, calc((100vh - 235px) * 16 / 9)));
|
||
max-width: 1080px; aspect-ratio: 16 / 9;
|
||
border-radius: 14px; overflow: hidden;
|
||
box-shadow: 0 24px 70px rgba(0, 0, 0, .5), 0 0 0 1px rgba(255, 255, 255, .09);
|
||
background: #0b1020;
|
||
}
|
||
.canvas { position: absolute; inset: 0; }
|
||
.sel-box { position: absolute; z-index: 60; border: 2px solid #4cc2ff; border-radius: 3px; pointer-events: none; box-shadow: 0 0 0 1px rgba(5,8,18,.5); }
|
||
.sel-box[hidden] { display: none; }
|
||
.resize { position: absolute; width: 12px; height: 12px; background: #4cc2ff; border: 2px solid #0b1020; border-radius: 3px; pointer-events: auto; }
|
||
.resize[data-dir="nw"] { left: -7px; top: -7px; cursor: nwse-resize; }
|
||
.resize[data-dir="ne"] { right: -7px; top: -7px; cursor: nesw-resize; }
|
||
.resize[data-dir="sw"] { left: -7px; bottom: -7px; cursor: nesw-resize; }
|
||
.resize[data-dir="se"] { right: -7px; bottom: -7px; cursor: nwse-resize; }
|
||
.statusbar { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 8px 16px; border-top: 1px solid var(--border); font-size: 11.5px; color: var(--muted); }
|
||
.statusbar b { color: #bfe7ff; }
|
||
|
||
/* ===== Инспектор ===== */
|
||
.inspector { border-left: 1px solid var(--border); background: rgba(8, 11, 22, .55); overflow-y: auto; padding: 14px; display: flex; flex-direction: column; gap: 12px; }
|
||
.insp-card { background: var(--panel); border: 1px solid var(--border); border-radius: 14px; padding: 12px; display: flex; flex-direction: column; gap: 10px; }
|
||
.insp-head { display: flex; align-items: center; gap: 8px; }
|
||
.insp-title { font-size: 11px; letter-spacing: 1.1px; text-transform: uppercase; color: var(--accent); font-weight: 800; flex: 1; }
|
||
.insp-btns { display: flex; gap: 4px; }
|
||
.insp-btns button { padding: 4px 7px; font-size: 11px; border-radius: 7px; }
|
||
.fld { display: flex; flex-direction: column; gap: 5px; }
|
||
.fld > span.label, .fld > label { font-size: 10.5px; text-transform: uppercase; letter-spacing: .7px; color: var(--muted); font-weight: 700; }
|
||
.row-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
|
||
.row-4 { display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px; }
|
||
.row-4 input { padding: 7px 6px; text-align: center; }
|
||
.checkline { display: flex; align-items: center; gap: 8px; font-size: 12.5px; color: #cbd5e1; }
|
||
.checkline input { width: auto; accent-color: #4cc2ff; }
|
||
.segmented { display: flex; gap: 4px; background: rgba(255,255,255,.04); border: 1px solid var(--border); border-radius: 9px; padding: 3px; }
|
||
.segmented button { flex: 1; padding: 6px 4px; font-size: 11.5px; background: transparent; border-radius: 7px; color: var(--muted); }
|
||
.segmented button.active { background: rgba(99, 102, 241, .35); color: #fff; font-weight: 600; }
|
||
.view-toggle { flex-shrink: 0; }
|
||
.view-toggle button { padding: 6px 12px; }
|
||
a.ghost { display: inline-flex; align-items: center; gap: 5px; text-decoration: none; color: var(--text); padding: 8px 12px; border-radius: 10px; font-size: 13px; background: var(--panel-2); transition: .15s; }
|
||
a.ghost:hover { background: rgba(255,255,255,.13); }
|
||
|
||
/* ===== Граф ===== */
|
||
.stage[hidden], .graph-stage[hidden] { display: none; }
|
||
.graph-stage { flex: 1; min-height: 0; display: flex; flex-direction: column; }
|
||
.graph-toolbar { display: flex; align-items: center; gap: 7px; padding: 9px 14px; border-bottom: 1px solid var(--border); flex-wrap: wrap; }
|
||
.graph-toolbar .spacer { flex: 1; }
|
||
.graph-toolbar button { padding: 7px 11px; }
|
||
.graph-hint { font-size: 11px; color: #64748b; }
|
||
.graph-scroll {
|
||
flex: 1; min-height: 0; overflow: auto; padding: 24px;
|
||
background-image: radial-gradient(rgba(148, 163, 184, .16) 1px, transparent 1px);
|
||
background-size: 22px 22px;
|
||
}
|
||
.graph-world { position: relative; min-width: 1200px; min-height: 760px; }
|
||
.graph-svg { position: absolute; inset: 0; width: 100%; height: 100%; overflow: visible; pointer-events: none; }
|
||
.graph-nodes { position: absolute; inset: 0; }
|
||
.gnode {
|
||
position: absolute; width: 238px; border-radius: 13px; padding: 10px 0 8px;
|
||
background: linear-gradient(160deg, rgba(30, 38, 66, .96), rgba(12, 17, 33, .98));
|
||
border: 1px solid rgba(129, 140, 248, .28); cursor: grab; user-select: none;
|
||
box-shadow: 0 12px 32px rgba(0, 0, 0, .38); transition: border-color .15s, box-shadow .15s;
|
||
}
|
||
.gnode:hover { border-color: rgba(129, 140, 248, .6); }
|
||
.gnode.selected { border-color: #818cf8; box-shadow: 0 0 0 3px rgba(99, 102, 241, .24), 0 12px 32px rgba(0, 0, 0, .38); }
|
||
.gnode.script { background: linear-gradient(160deg, rgba(58, 32, 78, .96), rgba(20, 12, 33, .98)); border-color: rgba(217, 70, 239, .3); }
|
||
.gnode.script.selected { border-color: #e879f9; box-shadow: 0 0 0 3px rgba(217, 70, 239, .22), 0 12px 32px rgba(0, 0, 0, .38); }
|
||
.gnode.script .gnode-badge { color: #f0abfc; background: rgba(217, 70, 239, .18); }
|
||
.gnode.audio { background: linear-gradient(160deg, rgba(66, 43, 16, .96), rgba(26, 18, 8, .98)); border-color: rgba(251, 191, 36, .32); }
|
||
.gnode.audio.selected { border-color: #fbbf24; box-shadow: 0 0 0 3px rgba(251, 191, 36, .2), 0 12px 32px rgba(0, 0, 0, .38); }
|
||
.gnode.audio .gnode-badge { color: #fde68a; background: rgba(251, 191, 36, .16); }
|
||
.gnode.variable { background: linear-gradient(160deg, rgba(16, 55, 45, .96), rgba(7, 22, 18, .98)); border-color: rgba(52, 211, 153, .32); }
|
||
.gnode.variable.selected { border-color: #34d399; box-shadow: 0 0 0 3px rgba(52, 211, 153, .2), 0 12px 32px rgba(0, 0, 0, .38); }
|
||
.gnode.variable .gnode-badge { color: #a7f3d0; background: rgba(52, 211, 153, .16); }
|
||
.gnode.transition { background: linear-gradient(160deg, rgba(10, 48, 70, .96), rgba(4, 18, 28, .98)); border-color: rgba(76, 194, 255, .35); }
|
||
.gnode.transition.selected { border-color: #4cc2ff; box-shadow: 0 0 0 3px rgba(76, 194, 255, .22), 0 12px 32px rgba(0, 0, 0, .38); }
|
||
.gnode.transition .gnode-badge { color: #a5e3ff; background: rgba(76, 194, 255, .18); }
|
||
.gnode.anim { background: linear-gradient(160deg, rgba(66, 18, 38, .96), rgba(26, 7, 15, .98)); border-color: rgba(251, 113, 133, .35); }
|
||
.gnode.anim.selected { border-color: #fb7185; box-shadow: 0 0 0 3px rgba(251, 113, 133, .2), 0 12px 32px rgba(0, 0, 0, .38); }
|
||
.gnode.anim .gnode-badge { color: #fecdd3; background: rgba(251, 113, 133, .16); }
|
||
.gnode-body { padding: 0 12px; }
|
||
.gnode-head { display: flex; align-items: center; gap: 7px; margin-bottom: 6px; }
|
||
.gnode-badge { font-size: 9.5px; text-transform: uppercase; letter-spacing: .8px; font-weight: 800; color: #c7d2fe; background: rgba(99, 102, 241, .22); border-radius: 999px; padding: 2px 7px; }
|
||
.gnode-kind { margin-left: auto; font-size: 10px; color: #64748b; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 110px; }
|
||
.gnode-title { font-size: 13.5px; font-weight: 700; line-height: 1.3; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||
.gnode-sub { font-size: 10.5px; color: var(--muted); margin-top: 3px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||
.gnode-code { margin: 6px 0 0; font-family: ui-monospace, Consolas, monospace; font-size: 10px; line-height: 1.35; color: #a5b4fc; max-height: 32px; overflow: hidden; white-space: pre-wrap; word-break: break-word; }
|
||
.gnode-bar { height: 3px; border-radius: 999px; margin-top: 8px; background: linear-gradient(90deg, #6366f1, #a855f7); opacity: .65; }
|
||
.gnode-ports { margin-top: 8px; border-top: 1px solid rgba(255,255,255,.08); padding-top: 5px; display: flex; flex-direction: column; }
|
||
.grow { position: relative; display: flex; align-items: center; min-height: 21px; font-size: 10.5px; color: #93c5fd; }
|
||
.grow.in { padding-left: 13px; justify-content: flex-start; }
|
||
.grow.out { padding-right: 13px; justify-content: flex-end; color: #bfe7ff; }
|
||
.grow.data { color: #6ee7b7; }
|
||
.grow.audio { color: #fcd34d; }
|
||
.grow .gport-label { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 196px; }
|
||
.gport { position: absolute; top: 50%; width: 11px; height: 11px; margin-top: -5.5px; border-radius: 50%; background: #0b1020; border: 2px solid #4cc2ff; cursor: crosshair; transition: .12s; z-index: 2; }
|
||
.gport.in { left: -6px; }
|
||
.gport.out { right: -6px; }
|
||
.gport:hover { background: #4cc2ff; box-shadow: 0 0 0 4px rgba(129, 140, 248, .22); }
|
||
.gport.data { border-color: #34d399; }
|
||
.gport.data:hover { background: #34d399; box-shadow: 0 0 0 4px rgba(52, 211, 153, .2); }
|
||
.gport.audio { border-color: #fbbf24; }
|
||
.gport.audio:hover { background: #fbbf24; }
|
||
.graph-svg path.edge { pointer-events: stroke; cursor: pointer; }
|
||
.graph-svg path.edge:hover { stroke-opacity: 1; }
|
||
.graph-svg path.edge.selected { stroke-width: 3; stroke-opacity: 1; filter: drop-shadow(0 0 5px currentColor); }
|
||
.graph-world.drafting .graph-svg path { pointer-events: none !important; }
|
||
.graph-bind-list { display: flex; flex-direction: column; gap: 5px; margin: 8px 0; }
|
||
.graph-bind { display: flex; align-items: center; gap: 8px; font-size: 11.5px; color: #cbd5e1; background: rgba(255,255,255,.035); border: 1px solid var(--border); border-radius: 8px; padding: 6px 8px; }
|
||
.graph-bind .gdim { margin-left: auto; color: #64748b; font-size: 10.5px; white-space: nowrap; }
|
||
.graph-empty { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; text-align: center; color: #64748b; font-size: 13px; line-height: 1.6; padding: 40px; }
|
||
.gnode.plugin { background: linear-gradient(160deg, rgba(74, 38, 12, .96), rgba(28, 14, 6, .98)); border-color: rgba(249, 115, 22, .38); }
|
||
.gnode.plugin.selected { border-color: #f97316; box-shadow: 0 0 0 3px rgba(249, 115, 22, .22), 0 12px 32px rgba(0, 0, 0, .38); }
|
||
.gnode.plugin .gnode-badge { color: #fed7aa; background: rgba(249, 115, 22, .18); }
|
||
.gport.plugin { border-color: #f97316; }
|
||
.gport.plugin:hover { background: #f97316; box-shadow: 0 0 0 4px rgba(249, 115, 22, .22); }
|
||
.gport.anim { border-color: #fb7185; }
|
||
.gport.anim:hover { background: #fb7185; }
|
||
.gport.transition { border-color: #22d3ee; }
|
||
.gport.transition:hover { background: #22d3ee; }
|
||
.graph-body { flex: 1; min-height: 0; display: flex; }
|
||
.graph-legend { display: flex; align-items: center; gap: 9px; flex-wrap: wrap; font-size: 10.5px; color: #94a3b8; }
|
||
.graph-legend span { display: inline-flex; align-items: center; gap: 4px; white-space: nowrap; }
|
||
.graph-legend i { width: 9px; height: 9px; border-radius: 50%; display: inline-block; }
|
||
|
||
/* ===== Древо ===== */
|
||
.tree-panel {
|
||
width: 272px; flex-shrink: 0; display: flex; flex-direction: column; min-height: 0;
|
||
background: rgba(9, 13, 25, .72); border-right: 1px solid var(--border);
|
||
backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px);
|
||
}
|
||
.tree-panel[hidden] { display: none; }
|
||
.tree-panel.collapsed { width: 44px; }
|
||
.tree-panel.collapsed .tree-tabs, .tree-panel.collapsed .tree-search,
|
||
.tree-panel.collapsed .tree-scroll, .tree-panel.collapsed .tree-foot,
|
||
.tree-panel.collapsed .tree-legend { display: none; }
|
||
.tree-head { display: flex; align-items: center; gap: 6px; padding: 9px 11px; border-bottom: 1px solid var(--border); font-size: 11px; text-transform: uppercase; letter-spacing: 1px; font-weight: 800; color: #bfe7ff; }
|
||
.tree-head .tree-collapse { margin-left: auto; padding: 2px 7px; font-size: 12px; background: transparent; }
|
||
.tree-tabs { display: flex; gap: 4px; padding: 7px 9px 3px; }
|
||
.tree-tabs button { flex: 1; padding: 5px 4px; font-size: 11px; background: transparent; color: var(--muted); border-radius: 7px; }
|
||
.tree-tabs button.active { background: rgba(99, 102, 241, .3); color: #fff; }
|
||
.tree-search { margin: 6px 9px; padding: 6px 9px; font-size: 12px; }
|
||
.tree-scroll { flex: 1; overflow: auto; padding: 4px 7px 10px; }
|
||
.tree-group { margin-bottom: 5px; }
|
||
.tree-group-head {
|
||
display: flex; align-items: center; gap: 5px; width: 100%; padding: 5px 6px;
|
||
background: transparent; color: #94a3b8; font-size: 10.5px; text-transform: uppercase;
|
||
letter-spacing: .8px; font-weight: 800; text-align: left; border-radius: 7px;
|
||
}
|
||
.tree-group-head:hover { background: rgba(255, 255, 255, .05); }
|
||
.tree-group-head .caret { font-size: 9px; width: 10px; color: #64748b; }
|
||
.tree-group-head .count { margin-left: auto; color: #475569; font-weight: 600; }
|
||
.tree-items { display: flex; flex-direction: column; gap: 2px; }
|
||
.tree-item {
|
||
display: flex; align-items: center; gap: 7px; width: 100%; padding: 5px 7px;
|
||
background: transparent; border-radius: 7px; color: #dbe4f3; text-align: left;
|
||
font-size: 12px; cursor: grab; border: 1px solid transparent;
|
||
}
|
||
.tree-item:hover { background: rgba(99, 102, 241, .18); border-color: rgba(129, 140, 248, .22); }
|
||
.tree-item:active { cursor: grabbing; }
|
||
.tree-item .ti-ico { width: 15px; text-align: center; flex-shrink: 0; font-size: 12px; }
|
||
.tree-item .ti-name { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||
.tree-item .ti-meta { color: #64748b; font-size: 9.5px; flex-shrink: 0; max-width: 84px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||
.tree-item .ti-dot { width: 7px; height: 7px; border-radius: 50%; flex-shrink: 0; }
|
||
.tree-item .ti-add { padding: 0 4px; font-size: 12px; color: #64748b; background: transparent; border-radius: 5px; }
|
||
.tree-item .ti-add:hover { color: #fff; background: rgba(255, 255, 255, .12); }
|
||
.tree-plugin { border: 1px solid rgba(255, 255, 255, .05); border-radius: 9px; margin-bottom: 5px; background: rgba(255, 255, 255, .015); }
|
||
.tree-plugin-head { display: flex; align-items: center; gap: 7px; padding: 6px 8px; font-size: 12px; font-weight: 700; color: #f8fafc; }
|
||
.tree-plugin-head .ti-actions { margin-left: auto; display: flex; gap: 3px; }
|
||
.tree-plugin-head .ti-actions button { padding: 1px 5px; font-size: 10px; background: transparent; color: #94a3b8; }
|
||
.tree-plugin-head .ti-actions button:hover { color: #fff; background: rgba(255, 255, 255, .1); }
|
||
.tree-plugin-desc { padding: 0 9px 5px 28px; font-size: 10px; color: #64748b; line-height: 1.35; }
|
||
.tree-plugin .tree-items { padding: 0 5px 5px; }
|
||
.tree-empty { padding: 14px 10px; font-size: 11.5px; color: #64748b; line-height: 1.5; text-align: center; }
|
||
.tree-foot { display: flex; gap: 5px; padding: 8px; border-top: 1px solid var(--border); }
|
||
.tree-foot button { flex: 1; padding: 6px 4px; font-size: 11px; }
|
||
.tree-legend { display: flex; flex-wrap: wrap; gap: 5px 9px; padding: 7px 10px; border-top: 1px solid var(--border); font-size: 9.5px; color: #94a3b8; }
|
||
.tree-legend span { display: inline-flex; align-items: center; gap: 4px; }
|
||
.tree-legend i { width: 7px; height: 7px; border-radius: 50%; }
|
||
.tree-drop { outline: 2px dashed rgba(76, 194, 255, .7); outline-offset: -8px; }
|
||
.graph-scroll.dragover { box-shadow: inset 0 0 0 2px rgba(76, 194, 255, .35); }
|
||
|
||
/* ===== Lua-редактор ===== */
|
||
.lua-editor { position: relative; border: 1px solid var(--border); border-radius: 10px; background: #080d1a; overflow: hidden; }
|
||
.lua-editor:focus-within { border-color: rgba(76, 194, 255, .65); box-shadow: 0 0 0 2px rgba(76, 194, 255, .14); }
|
||
.lua-highlight, .lua-code {
|
||
margin: 0; font-family: ui-monospace, 'Cascadia Code', 'JetBrains Mono', Consolas, monospace;
|
||
font-size: 12px; line-height: 1.5; padding: 9px 10px; tab-size: 2; white-space: pre;
|
||
}
|
||
.lua-highlight { position: absolute; inset: 0; pointer-events: none; color: #cbd5e1; overflow: hidden; }
|
||
.lua-code {
|
||
position: relative; display: block; width: 100%; min-height: 110px; resize: vertical;
|
||
background: transparent; border: none; outline: none; color: transparent;
|
||
caret-color: #fff; -webkit-text-fill-color: transparent; overflow: auto;
|
||
}
|
||
.lua-code::selection { background: rgba(99, 102, 241, .45); }
|
||
.lua-code::placeholder { color: #475569; -webkit-text-fill-color: #475569; }
|
||
.lua-editor.compact .lua-code { min-height: 74px; }
|
||
.tok-kw { color: #c084fc; font-weight: 600; }
|
||
.tok-str { color: #86efac; }
|
||
.tok-num { color: #fbbf24; }
|
||
.tok-com { color: #64748b; font-style: italic; }
|
||
.tok-fn { color: #7dd3fc; }
|
||
.tok-api { color: #f0abfc; }
|
||
.tok-op { color: #94a3b8; }
|
||
.lua-suggest {
|
||
position: absolute; left: 8px; right: 8px; bottom: 8px; z-index: 6; max-height: 164px; overflow: auto;
|
||
background: rgba(13, 18, 34, .98); border: 1px solid rgba(129, 140, 248, .45);
|
||
border-radius: 9px; box-shadow: 0 18px 44px rgba(0, 0, 0, .55); padding: 4px;
|
||
}
|
||
.lua-suggest[hidden] { display: none; }
|
||
.lua-suggest button {
|
||
display: flex; align-items: center; gap: 7px; width: 100%; padding: 5px 8px;
|
||
background: transparent; border-radius: 6px; text-align: left; font-size: 11.5px;
|
||
font-family: ui-monospace, Consolas, monospace; color: #dbe4f3;
|
||
}
|
||
.lua-suggest button.active, .lua-suggest button:hover { background: rgba(99, 102, 241, .32); }
|
||
.lua-suggest .sg-kind { margin-left: auto; font-size: 9px; color: #64748b; font-family: inherit; }
|
||
.lua-suggest .sg-name b { color: #7dd3fc; }
|
||
|
||
/* ===== Плагины ===== */
|
||
.modal-card.wide { width: min(1120px, 100%); height: min(840px, 94vh); max-height: 94vh; }
|
||
.plugin-wrap { flex: 1; min-height: 0; display: grid; grid-template-columns: 250px minmax(0, 1fr); }
|
||
.plugin-side { border-right: 1px solid var(--border); display: flex; flex-direction: column; min-height: 0; }
|
||
.plugin-side-head { display: flex; gap: 5px; padding: 10px; border-bottom: 1px solid var(--border); }
|
||
.plugin-side-head button { flex: 1; padding: 6px 4px; font-size: 11px; }
|
||
.plugin-list { flex: 1; overflow: auto; padding: 7px; display: flex; flex-direction: column; gap: 4px; }
|
||
.plugin-list-item { display: flex; align-items: center; gap: 7px; width: 100%; padding: 8px 9px; background: transparent; border-radius: 9px; text-align: left; border: 1px solid transparent; }
|
||
.plugin-list-item:hover { background: rgba(255, 255, 255, .05); }
|
||
.plugin-list-item.active { background: rgba(99, 102, 241, .26); border-color: rgba(129, 140, 248, .45); }
|
||
.plugin-list-item .pl-dot { width: 9px; height: 9px; border-radius: 50%; flex-shrink: 0; }
|
||
.plugin-list-item .pl-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12.5px; font-weight: 600; }
|
||
.plugin-list-item .pl-count { font-size: 9.5px; color: #64748b; }
|
||
.plugin-main { display: flex; flex-direction: column; gap: 10px; padding: 14px 18px; overflow: auto; min-height: 0; }
|
||
.plugin-main .row { display: flex; gap: 8px; }
|
||
.plugin-main .row > * { flex: 1; }
|
||
.plugin-main h3 { margin: 0; font-size: 12px; text-transform: uppercase; letter-spacing: 1px; color: #bfe7ff; }
|
||
.plugin-meta { display: grid; grid-template-columns: minmax(0, 1fr) 96px; gap: 10px; }
|
||
.plugin-meta input[type="color"] { padding: 3px; height: 34px; }
|
||
.plugin-nodes { display: flex; flex-wrap: wrap; gap: 6px; }
|
||
.plugin-node-chip { display: inline-flex; align-items: center; gap: 6px; padding: 4px 8px; border-radius: 999px; background: rgba(249, 115, 22, .14); border: 1px solid rgba(249, 115, 22, .35); font-size: 11px; color: #fed7aa; }
|
||
.plugin-node-chip small { color: #94a3b8; font-size: 9.5px; }
|
||
.plugin-foot { display: flex; align-items: center; gap: 7px; margin-top: auto; padding-top: 8px; border-top: 1px solid var(--border); }
|
||
.plugin-foot .spacer { flex: 1; }
|
||
|
||
/* ===== Команды ===== */
|
||
.command-item { border: 1px solid var(--border); background: rgba(255,255,255,.03); border-radius: 12px; padding: 10px; display: flex; flex-direction: column; gap: 8px; }
|
||
.command-item + .command-item { margin-top: 8px; }
|
||
.command-item-head { display: flex; align-items: center; gap: 8px; }
|
||
.command-item-head input { flex: 1; }
|
||
.command-item-head button { padding: 5px 9px; font-size: 12px; }
|
||
.command-item textarea { font-family: ui-monospace, Consolas, monospace; font-size: 12px; }
|
||
.upload-line { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||
.upload-line .file-name { font-size: 11px; color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 160px; }
|
||
.file-progress { font-size: 11px; color: var(--accent); }
|
||
.swatches { display: flex; gap: 6px; flex-wrap: wrap; }
|
||
.swatch { width: 34px; height: 24px; border-radius: 6px; border: 1px solid rgba(255,255,255,.18); padding: 0; }
|
||
.swatch:hover { transform: translateY(-1px); }
|
||
.hint { font-size: 11px; line-height: 1.45; color: #64748b; margin: 0; }
|
||
.hint code { color: #9fd8ff; font-size: 10.5px; }
|
||
.field-actions { display: flex; gap: 6px; flex-wrap: wrap; }
|
||
.field-actions button { flex: 1; padding: 7px 8px; font-size: 12px; }
|
||
.swatch.active { border-color: #4cc2ff; box-shadow: 0 0 0 2px rgba(129, 140, 248, .35); }
|
||
|
||
/* ===== v1.2: шаблоны слайдов, выравнивание, палитры, горячие клавиши ===== */
|
||
.toolbar .sep { width: 1px; height: 22px; background: var(--border); margin: 0 5px; flex-shrink: 0; }
|
||
.rail { position: relative; }
|
||
.tpl-menu {
|
||
position: absolute; left: 12px; right: 12px; bottom: 56px; z-index: 90;
|
||
display: flex; flex-direction: column; gap: 3px; padding: 8px;
|
||
background: rgba(13, 18, 34, .97); border: 1px solid rgba(129, 140, 248, .4);
|
||
border-radius: 14px; box-shadow: 0 24px 64px rgba(0, 0, 0, .6); backdrop-filter: blur(14px);
|
||
}
|
||
.tpl-menu[hidden] { display: none; }
|
||
.tpl-menu .tpl-head { font-size: 10px; text-transform: uppercase; letter-spacing: 1px; color: var(--muted); font-weight: 800; padding: 4px 8px 6px; }
|
||
.tpl-menu button { display: flex; align-items: center; gap: 10px; text-align: left; padding: 7px 9px; border-radius: 9px; background: transparent; }
|
||
.tpl-menu button:hover { background: rgba(99, 102, 241, .22); }
|
||
.tpl-ico { font-size: 16px; width: 22px; text-align: center; flex-shrink: 0; }
|
||
.tpl-name { font-weight: 600; font-size: 12.5px; line-height: 1.2; }
|
||
.tpl-desc { display: block; font-size: 10.5px; color: var(--muted); font-weight: 400; }
|
||
.align-row { display: grid; grid-template-columns: repeat(6, 1fr); gap: 4px; }
|
||
.align-row button { padding: 6px 0; font-size: 12px; }
|
||
.palette { display: flex; flex-wrap: wrap; gap: 6px; }
|
||
.palette .p-swatch { width: 26px; height: 26px; border-radius: 8px; border: 2px solid transparent; cursor: pointer; padding: 0; box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .2); }
|
||
.palette .p-swatch:hover { transform: translateY(-1px); }
|
||
kbd {
|
||
background: rgba(255, 255, 255, .08); border: 1px solid var(--border); border-bottom-width: 2px;
|
||
border-radius: 5px; padding: 1px 5px; font-size: 10px; font-family: ui-monospace, consolas, monospace; color: #bfe7ff;
|
||
}
|
||
.statusbar .hints { display: flex; gap: 12px; flex-wrap: wrap; align-items: center; }
|
||
.statusbar .hints span { display: inline-flex; gap: 4px; align-items: center; }
|
||
.top-actions input[type="file"] { display: none; }
|
||
.inspector .muted { font-size: 11.5px; color: #64748b; }
|
||
|
||
/* ===== Модальное окно ===== */
|
||
.modal { position: fixed; inset: 0; z-index: 100; display: flex; align-items: center; justify-content: center; background: rgba(4, 6, 14, .8); backdrop-filter: blur(8px); padding: 20px; }
|
||
.modal[hidden] { display: none; }
|
||
.modal-card { width: min(640px, 100%); max-height: 90vh; display: flex; flex-direction: column; background: #101627; border: 1px solid rgba(255,255,255,.1); border-radius: 20px; box-shadow: 0 30px 90px rgba(0,0,0,.6); overflow: hidden; }
|
||
.modal-head { display: flex; align-items: center; justify-content: space-between; padding: 18px 22px; border-bottom: 1px solid var(--border); }
|
||
.modal-head h2 { margin: 0; font-size: 18px; }
|
||
.modal-head button { padding: 6px 10px; }
|
||
.modal-body { padding: 18px 22px; overflow-y: auto; display: flex; flex-direction: column; gap: 20px; }
|
||
.modal-body h3 { margin: 0 0 5px; font-size: 13px; color: #bfe7ff; }
|
||
.modal-body .section { display: flex; flex-direction: column; gap: 8px; }
|
||
.modal-body label { font-size: 11px; color: var(--muted); text-transform: uppercase; letter-spacing: .6px; font-weight: 700; display: flex; flex-direction: column; gap: 6px; }
|
||
.modal-body input[type="range"] { padding: 0; accent-color: #4cc2ff; }
|
||
.modal-foot { display: flex; justify-content: flex-end; gap: 8px; padding: 14px 22px; border-top: 1px solid var(--border); }
|
||
.vol-line { display: flex; align-items: center; gap: 10px; }
|
||
.vol-line input { flex: 1; }
|
||
.vol-line output { font-size: 12px; color: var(--muted); width: 38px; text-align: right; }
|
||
|
||
.toast { position: fixed; left: 50%; bottom: 26px; transform: translateX(-50%) translateY(10px); background: rgba(30, 41, 59, .96); border: 1px solid rgba(129, 140, 248, .45); color: #e2e8f0; padding: 10px 18px; border-radius: 11px; font-size: 12.5px; z-index: 200; opacity: 0; pointer-events: none; transition: .25s; max-width: 70vw; }
|
||
.toast.visible { opacity: 1; transform: translateX(-50%) translateY(0); }
|
||
|
||
::-webkit-scrollbar { width: 9px; height: 9px; }
|
||
::-webkit-scrollbar-thumb { background: rgba(255,255,255,.12); border-radius: 999px; }
|
||
::-webkit-scrollbar-track { background: transparent; }
|
||
|
||
@media (max-width: 1100px) {
|
||
.app { grid-template-columns: 150px minmax(0, 1fr) 290px; }
|
||
.logo span { display: none; }
|
||
}
|
||
@media (max-width: 860px) {
|
||
body { overflow: auto; }
|
||
.topbar { flex-wrap: wrap; height: auto; padding: 8px 10px; row-gap: 8px; gap: 8px; }
|
||
.topbar .back { order: 1; }
|
||
.logo { order: 2; font-size: 14px; }
|
||
.save-state { order: 3; margin-left: auto; font-size: 11.5px; }
|
||
.top-actions { order: 4; gap: 6px; }
|
||
.top-actions .lbl { display: none; }
|
||
.top-actions button { padding: 8px 10px; }
|
||
.title-input { order: 5; flex: 1 1 100%; max-width: none; background: rgba(255,255,255,.05); border-color: var(--border); }
|
||
.live-chip { order: 6; }
|
||
.app { grid-template-columns: minmax(0, 1fr); grid-template-rows: auto 1fr auto; overflow-y: auto; height: auto; min-height: calc(100vh - 108px); }
|
||
.rail { border-right: none; border-bottom: 1px solid var(--border); }
|
||
.thumbs { flex-direction: row; overflow-x: auto; }
|
||
.thumb { width: 140px; flex-shrink: 0; }
|
||
.inspector { border-left: none; border-top: 1px solid var(--border); }
|
||
.workspace { min-width: 0; }
|
||
.stage { padding: 12px; }
|
||
.canvas-wrap { width: 100%; max-width: 100%; }
|
||
.toolbar { gap: 6px; padding: 9px 12px; }
|
||
.toolbar-label { display: none; }
|
||
.toolbar .spacer { display: none; }
|
||
.toolbar button { padding: 7px 10px; font-size: 12px; }
|
||
.statusbar { font-size: 11px; padding: 8px 12px; }
|
||
}
|
||
@media (max-width: 520px) {
|
||
.toolbar button[data-act="move-up"], .toolbar button[data-act="move-down"] { display: none; }
|
||
.inspector { padding: 10px; }
|
||
.row-4 .fld input { font-size: 12px; }
|
||
}
|
||
|
||
body { background: #101014 url('/img/bipfr-bg.png') center / cover fixed no-repeat; }
|
||
.topbar { background: rgba(30, 30, 30, .62); backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px); }
|
||
.rail, .inspector { background: rgba(20, 20, 25, .55); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); }
|
||
.logo-mark { width: 12px; height: 12px; border-radius: 4px; background: #4cc2ff; box-shadow: 0 0 10px rgba(76,194,255,.7); display: inline-block; flex-shrink: 0; }
|
||
button { touch-action: manipulation; }
|
||
@media (max-width: 860px) {
|
||
body { overflow: auto; }
|
||
.toolbar button, .top-actions button { min-height: 38px; }
|
||
#tpl-menu { left: 8px; right: 8px; max-width: none; }
|
||
}
|
||
|
||
</style>
|
||
</head>
|
||
<body>
|
||
<header class="topbar">
|
||
<a class="back" href="index.html" title="На главную">←</a>
|
||
<div class="logo"><span class="logo-mark"></span>Prompt<span>ly</span></div>
|
||
<input class="title-input" id="title" placeholder="Название презентации">
|
||
<span class="live-chip" id="live-chip" hidden></span>
|
||
<span class="save-state" id="save-state">Черновик</span>
|
||
<div class="top-actions">
|
||
<a class="ghost" href="docs.html" target="_blank" rel="noopener" title="Справочник Lua"><span class="lbl">Lua</span></a>
|
||
<button class="ghost" id="commands-btn" title="Список команд докладчика">⌘ <span class="lbl">Команды</span></button>
|
||
<button class="ghost" id="settings-btn" title="Переменные, музыка и Lua"><span class="lbl">Настройки</span></button>
|
||
<button class="ghost" id="export-btn" title="Скачать презентацию файлом JSON" disabled><span class="lbl">Экспорт</span></button>
|
||
<button class="ghost" id="import-btn" title="Загрузить презентацию из JSON-файла"><span class="lbl">Импорт</span></button>
|
||
<input type="file" id="import-file" accept=".json,application/json">
|
||
<button class="ghost" id="copy-link" title="Скопировать ссылку для зрителей" disabled><span class="lbl">Зрителям</span></button>
|
||
<button class="primary" id="demo-btn">▶ Демонстрировать</button>
|
||
</div>
|
||
</header>
|
||
|
||
<div class="app">
|
||
<aside class="rail">
|
||
<div class="rail-head"><span>Слайды</span><span id="slide-count">0</span></div>
|
||
<div class="thumbs" id="thumbs"></div>
|
||
<div class="tpl-menu" id="tpl-menu" hidden>
|
||
<div class="tpl-head">Шаблон нового слайда</div>
|
||
<button data-tpl="blank"><span class="tpl-ico">▢</span><span class="tpl-name">Пустой<span class="tpl-desc">чистый холст</span></span></button>
|
||
<button data-tpl="title"><span class="tpl-ico">Т</span><span class="tpl-name">Титульный<span class="tpl-desc">крупный заголовок и подзаголовок</span></span></button>
|
||
<button data-tpl="heading"><span class="tpl-ico">З</span><span class="tpl-name">Заголовок + текст<span class="tpl-desc">классический слайд с акцентной полосой</span></span></button>
|
||
<button data-tpl="columns"><span class="tpl-ico">К</span><span class="tpl-name">Две колонки<span class="tpl-desc">сравнения, «было / стало»</span></span></button>
|
||
<button data-tpl="image"><span class="tpl-ico">И</span><span class="tpl-name">Картинка + текст<span class="tpl-desc">изображение справа, текст слева</span></span></button>
|
||
<button data-tpl="quote"><span class="tpl-ico">Ц</span><span class="tpl-name">Цитата<span class="tpl-desc">крупная цитата и автор</span></span></button>
|
||
<button data-tpl="stat"><span class="tpl-ico">П</span><span class="tpl-name">Показатели<span class="tpl-desc">три карточки с числами</span></span></button>
|
||
<button data-tpl="section"><span class="tpl-ico">Р</span><span class="tpl-name">Раздел<span class="tpl-desc">номер раздела и название</span></span></button>
|
||
</div>
|
||
<button class="add-slide" id="add-slide">+ Новый слайд</button>
|
||
</aside>
|
||
|
||
<main class="workspace">
|
||
<div class="toolbar">
|
||
<div class="segmented view-toggle">
|
||
<button data-view="canvas" class="active">Холст</button>
|
||
<button data-view="graph">Граф</button>
|
||
</div>
|
||
<button data-act="open-tree" title="Древо: элементы холста и плагины">🌳 Древо</button>
|
||
<span class="toolbar-label">Добавить</span>
|
||
<button data-add="text" title="Текст (двойной клик по элементу — нет, правьте в инспекторе)">🅣 Текст</button>
|
||
<button data-add="image">Картинка</button>
|
||
<button data-add="shape" title="Прямоугольник, эллипс, стрелка, звезда…">◆ Фигура</button>
|
||
<button data-add="button">Кнопка</button>
|
||
<button data-add="audio">Аудио</button>
|
||
<button data-add="video">Видео</button>
|
||
<button data-add="window">Окно</button>
|
||
<button data-add="lua" title="Кастомный элемент: стили и HTML через Lua">Lua</button>
|
||
<span class="sep"></span>
|
||
<button data-act="undo" title="Отменить (Ctrl+Z)">↩</button>
|
||
<button data-act="redo" title="Повторить (Ctrl+Shift+Z)">↪</button>
|
||
<span class="spacer"></span>
|
||
<button data-act="duplicate-slide" title="Дублировать слайд">⧉ Слайд</button>
|
||
<button data-act="move-up" title="Переместить слайд выше">↑</button>
|
||
<button data-act="move-down" title="Переместить слайд ниже">↓</button>
|
||
<button data-act="delete-slide" class="danger" title="Удалить слайд">Удалить</button>
|
||
</div>
|
||
|
||
<div class="stage" id="stage">
|
||
<div class="canvas-wrap" id="canvas-wrap">
|
||
<div class="canvas" id="canvas"></div>
|
||
<div class="sel-box" id="sel-box" hidden>
|
||
<span class="resize" data-dir="nw"></span>
|
||
<span class="resize" data-dir="ne"></span>
|
||
<span class="resize" data-dir="sw"></span>
|
||
<span class="resize" data-dir="se"></span>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="graph-stage" id="graph-stage" hidden>
|
||
<div class="graph-toolbar">
|
||
<span class="toolbar-label">Ноды</span>
|
||
<button data-graph-add="slide">+ Слайд</button>
|
||
<button data-graph-add="script">+ Код</button>
|
||
<button data-graph-add="audio">+ Аудио</button>
|
||
<button data-graph-add="variable">+ Переменная</button>
|
||
<button data-graph-add="transition">+ Переход</button>
|
||
<button data-graph-add="anim">+ Анимация</button>
|
||
<button data-act="tree-toggle" title="Показать/скрыть древо">🌳 Древо</button>
|
||
<button data-act="plugin-new" title="Создать Lua-плагин">+ Плагин</button>
|
||
<span class="spacer"></span>
|
||
<div class="graph-legend" id="graph-legend" title="Цвета связей">
|
||
<span><i style="background:#60a5fa"></i>навигация</span>
|
||
<span><i style="background:#f59e0b"></i>кнопка</span>
|
||
<span><i style="background:#34d399"></i>данные</span>
|
||
<span><i style="background:#fbbf24"></i>аудио</span>
|
||
<span><i style="background:#e879f9"></i>код</span>
|
||
<span><i style="background:#22d3ee"></i>переход</span>
|
||
<span><i style="background:#fb7185"></i>анимация</span>
|
||
<span><i style="background:#f97316"></i>плагин</span>
|
||
</div>
|
||
</div>
|
||
<div class="graph-body">
|
||
<aside class="tree-panel" id="tree-panel">
|
||
<div class="tree-head"><span>Древо</span><button class="tree-collapse" data-act="tree-collapse" title="Свернуть древо">‹</button></div>
|
||
<div class="tree-tabs">
|
||
<button data-tree-tab="base" class="active">База</button>
|
||
<button data-tree-tab="plugins">Плагины</button>
|
||
</div>
|
||
<input class="tree-search" id="tree-search" placeholder="Поиск по древу…" autocomplete="off">
|
||
<div class="tree-scroll" id="tree-list"></div>
|
||
<div class="tree-legend">
|
||
<span><i style="background:#60a5fa"></i>навигация</span>
|
||
<span><i style="background:#f59e0b"></i>кнопка</span>
|
||
<span><i style="background:#34d399"></i>данные</span>
|
||
<span><i style="background:#e879f9"></i>код</span>
|
||
<span><i style="background:#f97316"></i>плагин</span>
|
||
</div>
|
||
<div class="tree-foot">
|
||
<button data-act="plugin-new">+ Плагин</button>
|
||
<button data-act="plugin-edit">Редактор</button>
|
||
</div>
|
||
</aside>
|
||
<div class="graph-scroll" id="graph-scroll">
|
||
<div class="graph-world" id="graph-world">
|
||
<svg class="graph-svg" id="graph-svg"></svg>
|
||
<div class="graph-nodes" id="graph-nodes"></div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="statusbar">
|
||
<span>Слайд <b id="slide-index">1</b> из <b id="slide-total">1</b></span>
|
||
<span class="hints" id="status-hint">
|
||
<span><kbd>Ctrl+S</kbd> сохранить</span>
|
||
<span><kbd>Ctrl+Z</kbd> отменить</span>
|
||
<span><kbd>Ctrl+C/V</kbd> копировать элемент</span>
|
||
<span><kbd>↑↓←→</kbd> сдвиг элемента</span>
|
||
<span><kbd>Del</kbd> удалить</span>
|
||
</span>
|
||
</div>
|
||
</main>
|
||
|
||
<aside class="inspector" id="inspector"></aside>
|
||
</div>
|
||
|
||
<div class="modal" id="settings-modal" hidden>
|
||
<div class="modal-card">
|
||
<div class="modal-head">
|
||
<h2>Настройки презентации</h2>
|
||
<button id="close-settings" title="Закрыть">×</button>
|
||
</div>
|
||
<div class="modal-body">
|
||
<section class="section">
|
||
<h3>Глобальные переменные</h3>
|
||
<p class="hint">По одной на строку: <code>key = value</code>. Подставляются в тексты и подписи как <code>{{key}}</code>, доступны в Lua как <code>vars.key</code>. Общие для всех слайдов и зрителей.</p>
|
||
<textarea id="vars-input" rows="5" placeholder="score = 0 speaker_name = Иван"></textarea>
|
||
</section>
|
||
|
||
<section class="section">
|
||
<h3>Фоновая музыка</h3>
|
||
<label>URL аудиофайла
|
||
<input id="music-src" type="url" placeholder="https://example.com/background.mp3">
|
||
</label>
|
||
<label>Начальная громкость
|
||
<span class="vol-line">
|
||
<input id="music-volume" type="range" min="0" max="100" step="1" value="50">
|
||
<output id="music-volume-out">50%</output>
|
||
</span>
|
||
</label>
|
||
<p class="hint">Играет на всех слайдах. Во время эффектов автоматически приглушается. Докладчик меняет громкость фона и эффектов отдельно.</p>
|
||
</section>
|
||
|
||
<section class="section">
|
||
<h3>Глобальный Lua</h3>
|
||
<p class="hint">
|
||
Выполняется при старте демонстрации. API:
|
||
<code>app.go(n)</code>, <code>app.next()</code>, <code>app.prev()</code>,
|
||
<code>app.play(id)</code>, <code>app.stop(id)</code>, <code>app.music(src)</code>,
|
||
<code>app.musicPlay()</code>, <code>app.musicStop()</code>, <code>app.musicVolume(v)</code>,
|
||
<code>app.setVar(k, v)</code>, <code>app.getVar(k)</code>, <code>app.log(msg)</code>.
|
||
</p>
|
||
<textarea id="lua-input" rows="6" placeholder="vars.score = 0 app.log('Презентация готова')"></textarea>
|
||
</section>
|
||
</div>
|
||
<div class="modal-foot">
|
||
<button class="ghost" id="cancel-settings">Отмена</button>
|
||
<button class="primary" id="save-settings">Сохранить</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="modal" id="commands-modal" hidden>
|
||
<div class="modal-card">
|
||
<div class="modal-head">
|
||
<h2>Консоль команд</h2>
|
||
<button id="close-commands" title="Закрыть">×</button>
|
||
</div>
|
||
<div class="modal-body">
|
||
<p class="hint">Команды появятся у докладчика в консоли. Он выбирает нужную стрелками и запускает Enter. Каждая команда — Lua-код, который выполняется только у докладчика, а переменные синхронизируются со зрителями.</p>
|
||
<div id="commands-list"></div>
|
||
<button class="ghost" id="add-command">+ Добавить команду</button>
|
||
</div>
|
||
<div class="modal-foot">
|
||
<button class="ghost" id="cancel-commands">Отмена</button>
|
||
<button class="primary" id="save-commands">Сохранить</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="modal" id="plugin-modal" hidden>
|
||
<div class="modal-card wide">
|
||
<div class="modal-head">
|
||
<h2>Редактор плагинов</h2>
|
||
<button id="close-plugin" title="Закрыть">×</button>
|
||
</div>
|
||
<div class="plugin-wrap">
|
||
<aside class="plugin-side">
|
||
<div class="plugin-side-head">
|
||
<button class="ghost" id="plugin-new">+ Новый</button>
|
||
<button class="ghost" id="plugin-reload" title="Перечитать реестр с сервера">↻</button>
|
||
</div>
|
||
<div class="plugin-list" id="plugin-list"></div>
|
||
</aside>
|
||
<div class="plugin-main">
|
||
<div class="plugin-meta">
|
||
<label class="fld"><span class="label">Название</span><input id="plugin-name" placeholder="Например, Эффекты"></label>
|
||
<label class="fld"><span class="label">Цвет</span><input type="color" id="plugin-color" value="#f97316"></label>
|
||
</div>
|
||
<label class="fld"><span class="label">Описание</span><input id="plugin-desc" placeholder="Что делает плагин"></label>
|
||
<div class="fld">
|
||
<span class="label">Lua-модуль · каждая функция становится нодой</span>
|
||
<div id="plugin-code"></div>
|
||
</div>
|
||
<div class="muted" id="plugin-status"></div>
|
||
<div class="plugin-nodes" id="plugin-nodes"></div>
|
||
<p class="hint">Комментарий <code>-- @node Заголовок</code> перед функцией задаёт имя ноды. Плагин хранится на диске: <code>server/data/plugins/<id>.lua</code>. В ноде плагина код — снимок модуля, поэтому показ не зависит от реестра.</p>
|
||
<div class="plugin-foot">
|
||
<button class="ghost" id="plugin-delete">Удалить</button>
|
||
<span class="spacer"></span>
|
||
<button class="ghost" id="plugin-close">Закрыть</button>
|
||
<button class="primary" id="plugin-save">Сохранить</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="toast" id="toast"></div>
|
||
|
||
<script src="vendor/fengari-web.js"></script>
|
||
<script src="js/lua-bridge.js"></script>
|
||
<script src="js/slide-view.js"></script>
|
||
<script>
|
||
const DEFAULT_GRADIENT = 'linear-gradient(135deg, #0f172a 0%, #1e1b4b 55%, #312e81 100%)';
|
||
const GRADIENT_PRESETS = [
|
||
'linear-gradient(135deg, #0f172a 0%, #1e1b4b 55%, #312e81 100%)',
|
||
'linear-gradient(135deg, #111827 0%, #3b0764 55%, #831843 100%)',
|
||
'linear-gradient(135deg, #052e16 0%, #064e3b 50%, #0f766e 100%)',
|
||
'linear-gradient(135deg, #1c1917 0%, #7c2d12 55%, #b45309 100%)',
|
||
'linear-gradient(135deg, #0c0a1d 0%, #1e1b4b 45%, #0e7490 100%)',
|
||
'linear-gradient(160deg, #020617 0%, #1e293b 60%, #334155 100%)',
|
||
'linear-gradient(135deg, #450a0a 0%, #7f1d1d 55%, #b91c1c 100%)',
|
||
'linear-gradient(135deg, #172554 0%, #1d4ed8 60%, #38bdf8 100%)',
|
||
'linear-gradient(135deg, #faf5ff 0%, #e9d5ff 55%, #c4b5fd 100%)',
|
||
'linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%)',
|
||
];
|
||
const SOLID_PRESETS = [
|
||
'#0f172a', '#020617', '#1e1b4b', '#312e81', '#4c1d95', '#701a75',
|
||
'#881337', '#7f1d1d', '#7c2d12', '#713f12', '#14532d', '#064e3b',
|
||
'#0c4a6e', '#1e3a8a', '#f8fafc', '#e2e8f0',
|
||
];
|
||
const FONT_OPTIONS = [
|
||
['sans', 'Sans (системный)'],
|
||
['serif', 'Serif (Georgia)'],
|
||
['mono', 'Mono (консольный)'],
|
||
['round', 'Round (скруглённый)'],
|
||
];
|
||
const SHAPE_OPTIONS = [
|
||
['rect', 'Прямоугольник'],
|
||
['round', 'Скруглённый'],
|
||
['ellipse', 'Эллипс'],
|
||
['triangle', 'Треугольник'],
|
||
['diamond', 'Ромб'],
|
||
['hexagon', 'Шестиугольник'],
|
||
['arrow', 'Стрелка'],
|
||
['star', 'Звезда'],
|
||
['line', 'Линия'],
|
||
];
|
||
const SHAPE_FILLS = [
|
||
'#6366f1', '#8b5cf6', '#d946ef', '#ec4899', '#ef4444', '#f97316',
|
||
'#fbbf24', '#22c55e', '#14b8a6', '#0ea5e9', '#f8fafc', '#0f172a',
|
||
];
|
||
|
||
const uid = () => (crypto.randomUUID ? crypto.randomUUID() : `id_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`);
|
||
const $ = (id) => document.getElementById(id);
|
||
const esc = (value) =>
|
||
String(value ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||
const clamp = (value, min, max) => Math.max(min, Math.min(max, value));
|
||
|
||
function defaultBackground() {
|
||
return { type: 'gradient', color: '#0f172a', gradient: DEFAULT_GRADIENT, image: '' };
|
||
}
|
||
|
||
function newSlide() {
|
||
return { id: uid(), notes: '', transition: 'fade', background: defaultBackground(), lua: '', elements: [] };
|
||
}
|
||
|
||
// Шаблоны слайдов: фабрики элементов для быстрого старта.
|
||
function slideTemplates() {
|
||
const t = (over) => ({
|
||
id: uid(), type: 'text', x: 8, y: 40, w: 84, h: 20, text: 'Текст', fontSize: 5,
|
||
color: '#f8fafc', weight: 700, align: 'center', bg: '', font: 'sans',
|
||
italic: false, shadow: false, lineHeight: 1.16, opacity: 1, rotate: 0, z: 2, ...over,
|
||
});
|
||
const shape = (over) => ({
|
||
id: uid(), type: 'shape', shape: 'rect', x: 10, y: 10, w: 30, h: 8, fill: '#6366f1',
|
||
borderColor: '', borderWidth: 0, radius: 10, shadow: false, opacity: 1, rotate: 0, z: 1, ...over,
|
||
});
|
||
const img = (over) => ({
|
||
id: uid(), type: 'image', x: 55, y: 18, w: 38, h: 64, src: '', fit: 'cover',
|
||
radius: 16, shadow: true, opacity: 1, rotate: 0, z: 2, ...over,
|
||
});
|
||
return {
|
||
blank: () => [],
|
||
title: () => [
|
||
shape({ shape: 'rect', x: 42, y: 63, w: 16, h: 1.2, fill: '#a855f7', radius: 99 }),
|
||
t({ y: 30, h: 22, fontSize: 9, weight: 800, text: 'Заголовок презентации' }),
|
||
t({ y: 55, h: 12, fontSize: 3.4, weight: 400, color: '#c7d2fe', text: 'подзаголовок · автор · дата' }),
|
||
],
|
||
heading: () => [
|
||
shape({ shape: 'rect', x: 8, y: 12, w: 1.4, h: 12, fill: '#818cf8', radius: 99 }),
|
||
t({ x: 11, y: 11, w: 80, h: 14, fontSize: 6, weight: 800, align: 'left', text: 'Заголовок слайда' }),
|
||
t({ x: 11, y: 30, w: 78, h: 55, fontSize: 3, weight: 400, align: 'left', color: '#e2e8f0', lineHeight: 1.5, text: 'Основной текст слайда.\nВторой абзац — здесь важна структура и воздух между блоками.' }),
|
||
],
|
||
columns: () => [
|
||
t({ y: 8, h: 12, fontSize: 5.4, weight: 800, text: 'Сравнение' }),
|
||
shape({ shape: 'round', x: 7, y: 26, w: 41, h: 62, fill: 'rgba(99,102,241,.16)', borderColor: 'rgba(129,140,248,.5)', borderWidth: 2, radius: 16 }),
|
||
shape({ shape: 'round', x: 52, y: 26, w: 41, h: 62, fill: 'rgba(217,70,239,.12)', borderColor: 'rgba(232,121,249,.45)', borderWidth: 2, radius: 16 }),
|
||
t({ x: 9, y: 30, w: 37, h: 10, fontSize: 3.4, weight: 700, color: '#a5b4fc', text: 'Было' }),
|
||
t({ x: 9, y: 42, w: 37, h: 42, fontSize: 2.4, weight: 400, align: 'left', color: '#cbd5e1', lineHeight: 1.5, text: '• пункт один\n• пункт два\n• пункт три' }),
|
||
t({ x: 54, y: 30, w: 37, h: 10, fontSize: 3.4, weight: 700, color: '#f0abfc', text: 'Стало' }),
|
||
t({ x: 54, y: 42, w: 37, h: 42, fontSize: 2.4, weight: 400, align: 'left', color: '#cbd5e1', lineHeight: 1.5, text: '• пункт один\n• пункт два\n• пункт три' }),
|
||
],
|
||
image: () => [
|
||
t({ x: 7, y: 20, w: 44, h: 14, fontSize: 5.2, weight: 800, align: 'left', text: 'Картинка и мысль' }),
|
||
t({ x: 7, y: 38, w: 44, h: 40, fontSize: 2.6, weight: 400, align: 'left', color: '#cbd5e1', lineHeight: 1.5, text: 'Описание того, что видно на изображении справа. Загрузите файл в инспекторе.' }),
|
||
img({}),
|
||
],
|
||
quote: () => [
|
||
t({ y: 12, h: 18, fontSize: 12, weight: 800, color: '#a855f7', text: '«' }),
|
||
t({ x: 14, y: 28, w: 72, h: 32, fontSize: 4.6, weight: 600, italic: true, align: 'center', lineHeight: 1.4, text: 'Простота — высшая форма сложности.' }),
|
||
t({ x: 14, y: 66, w: 72, h: 10, fontSize: 2.6, weight: 400, color: '#94a3b8', text: '— Леонардо да Винчи' }),
|
||
],
|
||
stat: () => {
|
||
const cards = [];
|
||
const data = [['87%', 'рост конверсии'], ['2.4×', 'ускорение'], ['15 мин', 'экономия в день']];
|
||
data.forEach((item, i) => {
|
||
const x = 7 + i * 30;
|
||
cards.push(shape({ shape: 'round', x, y: 26, w: 26, h: 48, fill: 'rgba(255,255,255,.05)', borderColor: 'rgba(129,140,248,.35)', borderWidth: 2, radius: 16 }));
|
||
cards.push(t({ x, y: 34, w: 26, h: 16, fontSize: 6.4, weight: 800, color: '#a5b4fc', text: item[0] }));
|
||
cards.push(t({ x, y: 54, w: 26, h: 12, fontSize: 2.2, weight: 400, color: '#94a3b8', text: item[1] }));
|
||
});
|
||
return [t({ y: 8, h: 14, fontSize: 5.4, weight: 800, text: 'Ключевые показатели' }), ...cards];
|
||
},
|
||
section: () => [
|
||
shape({ shape: 'ellipse', x: 43, y: 14, w: 14, h: 25, fill: 'rgba(168,85,247,.25)', borderColor: '#a855f7', borderWidth: 3 }),
|
||
t({ y: 18, h: 16, fontSize: 8, weight: 800, color: '#e9d5ff', text: '02' }),
|
||
t({ y: 44, h: 16, fontSize: 6.4, weight: 800, text: 'Название раздела' }),
|
||
t({ y: 64, h: 10, fontSize: 2.6, weight: 400, color: '#94a3b8', text: 'короткое описание раздела' }),
|
||
],
|
||
};
|
||
}
|
||
|
||
function hydrateSlide(slide) {
|
||
const source = slide || {};
|
||
return {
|
||
id: source.id || uid(),
|
||
notes: source.notes || '',
|
||
transition: source.transition || 'fade',
|
||
background: { ...defaultBackground(), ...(source.background || {}) },
|
||
lua: source.lua || '',
|
||
elements: (source.elements || []).map((element) => ({
|
||
...element,
|
||
id: element.id || uid(),
|
||
action: element.type === 'button'
|
||
? { type: 'next', slideIndex: 0, audioId: '', code: '', scriptNodeId: '', ...(element.action || {}) }
|
||
: element.action,
|
||
...(element.type === 'lua' ? {
|
||
code: element.code || '',
|
||
label: element.label || 'Lua-элемент',
|
||
computed: {
|
||
style: (element.computed && element.computed.style) || {},
|
||
css: (element.computed && element.computed.css) || '',
|
||
html: (element.computed && element.computed.html) || '',
|
||
text: (element.computed && element.computed.text) || '',
|
||
at: (element.computed && element.computed.at) || 0,
|
||
},
|
||
} : {}),
|
||
})),
|
||
};
|
||
}
|
||
|
||
const state = {
|
||
id: null,
|
||
title: '',
|
||
slides: [newSlide()],
|
||
variables: {},
|
||
music: { src: '', volume: 0.5 },
|
||
lua: '',
|
||
commands: [],
|
||
graph: { positions: {}, scripts: [], audios: [], variables: [], transitions: [], anims: [], plugins: [], links: [], jumps: {} },
|
||
view: 'canvas',
|
||
selectedNode: null,
|
||
selectedLink: null,
|
||
commandDraft: [],
|
||
windowTargets: [],
|
||
windowEndpoint: '',
|
||
selected: 0,
|
||
selectedEl: null,
|
||
saving: false,
|
||
pending: false,
|
||
dirty: false,
|
||
updatedAt: 0,
|
||
clipboard: null,
|
||
tree: { tab: 'base', query: '', collapsed: {}, plugins: {}, open: true },
|
||
pluginRegistry: [],
|
||
pluginDraft: null,
|
||
};
|
||
|
||
// История для Ctrl+Z / Ctrl+Shift+Z: снимки всего документа.
|
||
const undoHistory = { stack: [], index: -1, limit: 60, lastPush: 0 };
|
||
let restoringHistory = false;
|
||
|
||
const titleInput = $('title');
|
||
const thumbsEl = $('thumbs');
|
||
const canvasWrap = $('canvas-wrap');
|
||
const canvasEl = $('canvas');
|
||
const selBox = $('sel-box');
|
||
const inspectorEl = $('inspector');
|
||
const saveStateEl = $('save-state');
|
||
const liveChip = $('live-chip');
|
||
const copyLinkBtn = $('copy-link');
|
||
const settingsModal = $('settings-modal');
|
||
const commandsModal = $('commands-modal');
|
||
const stageEl = $('stage');
|
||
const graphStage = $('graph-stage');
|
||
const graphWorld = $('graph-world');
|
||
const graphSvg = $('graph-svg');
|
||
const graphNodesEl = $('graph-nodes');
|
||
const graphScroll = $('graph-scroll');
|
||
const treePanel = $('tree-panel');
|
||
const treeListEl = $('tree-list');
|
||
const treeSearchEl = $('tree-search');
|
||
const pluginModal = $('plugin-modal');
|
||
const pluginListEl = $('plugin-list');
|
||
const pluginCodeEl = $('plugin-code');
|
||
const commandsListEl = $('commands-list');
|
||
|
||
const LINK_COLORS = {
|
||
nav: '#60a5fa',
|
||
button: '#f59e0b',
|
||
data: '#34d399',
|
||
audio: '#fbbf24',
|
||
logic: '#e879f9',
|
||
transition: '#22d3ee',
|
||
anim: '#fb7185',
|
||
plugin: '#f97316',
|
||
};
|
||
|
||
const PASS_THROUGH_KINDS = new Set(['transition', 'anim', 'plugin']);
|
||
|
||
function linkKind(link) {
|
||
const from = link.from || {};
|
||
const to = link.to || {};
|
||
if (from.kind === 'variable' || to.kind === 'variable') return 'data';
|
||
if (from.kind === 'slide' && String(from.port || '').startsWith('btn:')) return 'button';
|
||
if (from.kind === 'audio' || to.kind === 'audio') return 'audio';
|
||
if (from.kind === 'script' || to.kind === 'script') return 'logic';
|
||
if (from.kind === 'plugin' || to.kind === 'plugin') return 'plugin';
|
||
if (from.kind === 'transition' || to.kind === 'transition') return 'transition';
|
||
if (from.kind === 'anim' || to.kind === 'anim') return 'anim';
|
||
return 'nav';
|
||
}
|
||
|
||
const currentSlide = () => state.slides[state.selected];
|
||
|
||
function selectedElement() {
|
||
if (!state.selectedEl) return null;
|
||
return (currentSlide().elements || []).find((element) => element.id === state.selectedEl) || null;
|
||
}
|
||
|
||
// ==================== Граф ====================
|
||
function graphDefaultPosition(index) {
|
||
return { x: 340 + (index % 4) * 320, y: 60 + Math.floor(index / 4) * 300 };
|
||
}
|
||
|
||
// Оценка габаритов нод для поиска свободного места без наложений.
|
||
function graphNodeBoxes(ignoreKind, ignoreId) {
|
||
const boxes = [];
|
||
state.slides.forEach((slide, index) => {
|
||
const p = state.graph.positions[slide.id] || graphDefaultPosition(index);
|
||
const ports = 3 + slideButtonPorts(slide).length + slideVarPorts(slide).length;
|
||
boxes.push({ kind: 'slide', id: slide.id, x: p.x, y: p.y, w: 250, h: 118 + ports * 21 });
|
||
});
|
||
state.graph.scripts.forEach((node) => boxes.push({ kind: 'script', id: node.id, x: node.x, y: node.y, w: 250, h: 150 }));
|
||
(state.graph.audios || []).forEach((node) => boxes.push({ kind: 'audio', id: node.id, x: node.x, y: node.y, w: 250, h: 130 }));
|
||
(state.graph.variables || []).forEach((node) => boxes.push({ kind: 'variable', id: node.id, x: node.x, y: node.y, w: 250, h: 130 }));
|
||
(state.graph.transitions || []).forEach((node) => boxes.push({ kind: 'transition', id: node.id, x: node.x, y: node.y, w: 250, h: 150 }));
|
||
(state.graph.anims || []).forEach((node) => boxes.push({ kind: 'anim', id: node.id, x: node.x, y: node.y, w: 250, h: 150 }));
|
||
(state.graph.plugins || []).forEach((node) => boxes.push({ kind: 'plugin', id: node.id, x: node.x, y: node.y, w: 250, h: 150 }));
|
||
return boxes.filter((box) => box.kind !== ignoreKind || box.id !== ignoreId);
|
||
}
|
||
|
||
function findFreeNodeSpot(x, y, ignoreKind, ignoreId, size) {
|
||
const boxes = graphNodeBoxes(ignoreKind, ignoreId);
|
||
const w = (size && size.w) || 250;
|
||
const h = (size && size.h) || 150;
|
||
const overlaps = (box) => boxes.some((other) =>
|
||
box.x < other.x + other.w + 18
|
||
&& box.x + box.w + 18 > other.x
|
||
&& box.y < other.y + other.h + 18
|
||
&& box.y + box.h + 18 > other.y
|
||
);
|
||
const fits = (cx, cy) => {
|
||
const candidate = { x: Math.max(20, cx), y: Math.max(20, cy), w, h };
|
||
return overlaps(candidate) ? null : { x: candidate.x, y: candidate.y };
|
||
};
|
||
const exact = fits(x, y);
|
||
if (exact) return exact;
|
||
// Расходящаяся сетка: сначала ближние позиции, затем всё дальше.
|
||
const stepX = 320;
|
||
const stepY = 300;
|
||
const baseX = Math.round(x / stepX) * stepX;
|
||
const baseY = Math.round(y / stepY) * stepY;
|
||
for (let radius = 1; radius <= 12; radius += 1) {
|
||
for (let dx = -radius; dx <= radius; dx += 1) {
|
||
for (let dy = -radius; dy <= radius; dy += 1) {
|
||
if (Math.max(Math.abs(dx), Math.abs(dy)) !== radius) continue;
|
||
const spot = fits(baseX + dx * stepX, baseY + dy * stepY);
|
||
if (spot) return spot;
|
||
}
|
||
}
|
||
}
|
||
return { x: Math.max(20, x), y: Math.max(20, y) };
|
||
}
|
||
|
||
function findScriptNode(id) {
|
||
return state.graph.scripts.find((node) => node.id === id) || null;
|
||
}
|
||
|
||
function findTransitionNode(id) {
|
||
return (state.graph.transitions || []).find((node) => node.id === id) || null;
|
||
}
|
||
|
||
function findAnimNode(id) {
|
||
return (state.graph.anims || []).find((node) => node.id === id) || null;
|
||
}
|
||
|
||
function findAudioNode(id) {
|
||
return (state.graph.audios || []).find((node) => node.id === id) || null;
|
||
}
|
||
|
||
function findVariableNode(id) {
|
||
return (state.graph.variables || []).find((node) => node.id === id) || null;
|
||
}
|
||
|
||
function findPluginNode(id) {
|
||
return (state.graph.plugins || []).find((node) => node.id === id) || null;
|
||
}
|
||
|
||
function findNodeByKind(kind, id) {
|
||
if (kind === 'slide') return state.slides.find((slide) => slide.id === id) || null;
|
||
if (kind === 'script') return findScriptNode(id);
|
||
if (kind === 'audio') return findAudioNode(id);
|
||
if (kind === 'variable') return findVariableNode(id);
|
||
if (kind === 'transition') return findTransitionNode(id);
|
||
if (kind === 'anim') return findAnimNode(id);
|
||
if (kind === 'plugin') return findPluginNode(id);
|
||
return null;
|
||
}
|
||
|
||
function findVariableByName(name) {
|
||
return (state.graph.variables || []).find((node) => node.name === name) || null;
|
||
}
|
||
|
||
function scriptNodeForElement(elementId) {
|
||
return state.graph.scripts.find((node) => node.elementId === elementId) || null;
|
||
}
|
||
|
||
function findLinkedElement(node) {
|
||
if (!node || !node.elementId) return null;
|
||
for (const slide of state.slides) {
|
||
const element = (slide.elements || []).find((item) => item.id === node.elementId);
|
||
if (element) return { slide, element };
|
||
}
|
||
return null;
|
||
}
|
||
|
||
function findAudioElement(id) {
|
||
if (!id) return null;
|
||
for (const slide of state.slides) {
|
||
const element = (slide.elements || []).find((item) => item.type === 'audio' && item.id === id);
|
||
if (element) return { slide, element };
|
||
}
|
||
return null;
|
||
}
|
||
|
||
function nodeRef(kind, id) {
|
||
if (kind === 'slide') {
|
||
if (!state.graph.positions[id]) state.graph.positions[id] = { x: 0, y: 0 };
|
||
return state.graph.positions[id];
|
||
}
|
||
if (kind === 'script') return findScriptNode(id);
|
||
if (kind === 'audio') return findAudioNode(id);
|
||
if (kind === 'variable') return findVariableNode(id);
|
||
if (kind === 'transition') return findTransitionNode(id);
|
||
if (kind === 'anim') return findAnimNode(id);
|
||
if (kind === 'plugin') return findPluginNode(id);
|
||
return null;
|
||
}
|
||
|
||
function slideVarPorts(slide) {
|
||
const ports = [];
|
||
const seen = new Set();
|
||
(slide.elements || []).forEach((element) => {
|
||
if (element.type !== 'text') return;
|
||
const matches = String(element.text || '').match(/\{\{\s*[\w.-]+\s*\}\}/g) || [];
|
||
matches.forEach((raw) => {
|
||
const name = raw.replace(/[{}]/g, '').trim();
|
||
if (!name) return;
|
||
const key = `var:${element.id}:${name}`;
|
||
if (seen.has(key)) return;
|
||
seen.add(key);
|
||
ports.push({ key, name, elementId: element.id });
|
||
});
|
||
});
|
||
return ports;
|
||
}
|
||
|
||
function slideButtonPorts(slide) {
|
||
return (slide.elements || [])
|
||
.filter((element) => element.type === 'button')
|
||
.map((element) => ({ key: `btn:${element.id}`, label: element.label || 'Кнопка', elementId: element.id }));
|
||
}
|
||
|
||
const escapeRx = (value) => String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||
|
||
function removeVarPlaceholder(elementId, name) {
|
||
for (const slide of state.slides) {
|
||
const element = (slide.elements || []).find((item) => item.id === elementId);
|
||
if (!element || typeof element.text !== 'string') continue;
|
||
element.text = element.text
|
||
.replace(new RegExp(`\\{\\{\\s*${escapeRx(name)}\\s*\\}\\}`, 'g'), '')
|
||
.trim();
|
||
return;
|
||
}
|
||
}
|
||
|
||
function hasLink(from, to) {
|
||
return state.graph.links.some((link) =>
|
||
link.from.kind === from.kind && link.from.id === from.id && link.from.port === from.port
|
||
&& link.to.kind === to.kind && link.to.id === to.id && link.to.port === to.port
|
||
);
|
||
}
|
||
|
||
function pushLink(from, to) {
|
||
if (hasLink(from, to)) return null;
|
||
const link = {
|
||
id: uid(),
|
||
from: { kind: from.kind, id: from.id, port: from.port },
|
||
to: { kind: to.kind, id: to.id, port: to.port },
|
||
};
|
||
state.graph.links.push(link);
|
||
return link;
|
||
}
|
||
|
||
function ensureAudioNode(elementId, mode) {
|
||
let node = state.graph.audios.find((item) => item.elementId === elementId);
|
||
if (!node) {
|
||
const found = findAudioElement(elementId);
|
||
const slide = found ? found.slide : currentSlide();
|
||
const base = slide && state.graph.positions[slide.id] ? state.graph.positions[slide.id] : { x: 340, y: 60 };
|
||
const index = state.graph.audios.length;
|
||
const spot = findFreeNodeSpot(base.x + 330, base.y + 200 + (index % 3) * 96, 'audio', '');
|
||
node = {
|
||
id: uid(),
|
||
name: found && found.element.label ? found.element.label : 'Аудио',
|
||
elementId,
|
||
mode: mode || 'play',
|
||
x: spot.x,
|
||
y: spot.y,
|
||
};
|
||
state.graph.audios.push(node);
|
||
}
|
||
if (mode) node.mode = mode;
|
||
return node;
|
||
}
|
||
|
||
function ensureVariableNode(name) {
|
||
let node = findVariableByName(name);
|
||
if (!node) {
|
||
const anchor = state.slides[0] ? state.graph.positions[state.slides[0].id] : { x: 340, y: 60 };
|
||
const index = state.graph.variables.length;
|
||
const spot = findFreeNodeSpot(
|
||
Math.max(20, (anchor ? anchor.x : 340) - 300),
|
||
(anchor ? anchor.y : 60) + 20 + (index % 6) * 120,
|
||
'variable',
|
||
''
|
||
);
|
||
node = {
|
||
id: uid(),
|
||
name: name || `var${index + 1}`,
|
||
x: spot.x,
|
||
y: spot.y,
|
||
};
|
||
state.graph.variables.push(node);
|
||
}
|
||
return node;
|
||
}
|
||
|
||
// Достраивает связи по действиям кнопок и вставкам {{переменная}}.
|
||
function graphPortExists(kind, id, port) {
|
||
if (kind === 'slide') {
|
||
const slide = state.slides.find((item) => item.id === id);
|
||
if (!slide) return false;
|
||
if (port === 'in' || port === 'next' || port === 'prev') return true;
|
||
if (port.startsWith('btn:')) {
|
||
const elementId = port.slice(4);
|
||
return (slide.elements || []).some((el) => el.type === 'button' && el.id === elementId);
|
||
}
|
||
if (port.startsWith('var:')) return slideVarPorts(slide).some((item) => item.key === port);
|
||
return false;
|
||
}
|
||
if (kind === 'script') return !!findScriptNode(id) && port === 'in';
|
||
if (kind === 'audio') return !!findAudioNode(id) && port === 'in';
|
||
if (kind === 'variable') return !!findVariableNode(id) && port === 'value';
|
||
if (kind === 'transition') return !!findTransitionNode(id) && (port === 'in' || port === 'out');
|
||
if (kind === 'anim') return !!findAnimNode(id) && (port === 'in' || port === 'out');
|
||
if (kind === 'plugin') return !!findPluginNode(id) && (port === 'in' || port === 'out');
|
||
return false;
|
||
}
|
||
|
||
function pruneGraphLinks() {
|
||
state.graph.links = state.graph.links.filter((link) =>
|
||
graphPortExists(link.from.kind, link.from.id, link.from.port)
|
||
&& graphPortExists(link.to.kind, link.to.id, link.to.port)
|
||
);
|
||
}
|
||
|
||
function ensureLinksFromModel() {
|
||
pruneGraphLinks();
|
||
state.slides.forEach((slide) => {
|
||
(slide.elements || []).forEach((element) => {
|
||
if (element.type !== 'button' || !element.action) return;
|
||
const action = element.action;
|
||
const from = { kind: 'slide', id: slide.id, port: `btn:${element.id}` };
|
||
const exists = state.graph.links.some((link) =>
|
||
link.from.kind === from.kind && link.from.id === from.id && link.from.port === from.port
|
||
);
|
||
if (exists) return;
|
||
if (action.type === 'go') {
|
||
const target = state.slides[Number(action.slideIndex) || 0];
|
||
if (target) pushLink(from, { kind: 'slide', id: target.id, port: 'in' });
|
||
} else if (action.type === 'lua') {
|
||
const node = action.scriptNodeId ? findScriptNode(action.scriptNodeId) : scriptNodeForElement(element.id);
|
||
if (node) pushLink(from, { kind: 'script', id: node.id, port: 'in' });
|
||
} else if ((action.type === 'play' || action.type === 'stop') && action.audioId) {
|
||
const node = ensureAudioNode(action.audioId, action.type);
|
||
pushLink(from, { kind: 'audio', id: node.id, port: 'in' });
|
||
}
|
||
});
|
||
|
||
slideVarPorts(slide).forEach((port) => {
|
||
const connected = state.graph.links.some((link) =>
|
||
link.to.kind === 'slide' && link.to.id === slide.id && link.to.port === port.key
|
||
);
|
||
if (connected) return;
|
||
const variable = ensureVariableNode(port.name);
|
||
pushLink(
|
||
{ kind: 'variable', id: variable.id, port: 'value' },
|
||
{ kind: 'slide', id: slide.id, port: port.key }
|
||
);
|
||
});
|
||
});
|
||
}
|
||
|
||
// Переходы «дальше/назад» выводятся из цепочки связей.
|
||
// Цепь может проходить через переходы, анимации и ноды плагинов (порты in/out).
|
||
function rebuildJumps() {
|
||
const outgoing = new Map();
|
||
state.graph.links.forEach((link) => {
|
||
const key = `${link.from.kind}|${link.from.id}`;
|
||
if (!outgoing.has(key)) outgoing.set(key, []);
|
||
outgoing.get(key).push(link);
|
||
});
|
||
const jumps = {};
|
||
state.graph.links.forEach((link) => {
|
||
if (link.from.kind !== 'slide' || (link.from.port !== 'next' && link.from.port !== 'prev')) return;
|
||
const port = link.from.port;
|
||
let current = link;
|
||
const visited = new Set();
|
||
for (let step = 0; current && step < 32; step += 1) {
|
||
const key = `${current.to.kind}|${current.to.id}`;
|
||
if (visited.has(key)) break;
|
||
visited.add(key);
|
||
if (current.to.kind === 'slide' && current.to.port === 'in') {
|
||
jumps[link.from.id] = jumps[link.from.id] || {};
|
||
if (!jumps[link.from.id][port]) jumps[link.from.id][port] = current.to.id;
|
||
break;
|
||
}
|
||
if (PASS_THROUGH_KINDS.has(current.to.kind) && current.to.port === 'in') {
|
||
current = (outgoing.get(key) || []).find((item) => item.from.port === 'out');
|
||
continue;
|
||
}
|
||
break;
|
||
}
|
||
});
|
||
state.graph.jumps = jumps;
|
||
}
|
||
|
||
function isNavLink(link) {
|
||
return link.from.kind === 'slide'
|
||
&& (link.from.port === 'next' || link.from.port === 'prev')
|
||
&& (link.to.kind === 'slide' || PASS_THROUGH_KINDS.has(link.to.kind));
|
||
}
|
||
|
||
function transitionForSlide(slideId) {
|
||
return (state.graph.transitions || []).find((node) => node.slideId === slideId) || null;
|
||
}
|
||
|
||
// Нода перехода, через которую входят на слайд. Создаётся по требованию.
|
||
function ensureTransitionNodeForSlide(slide) {
|
||
if (!slide) return null;
|
||
let node = transitionForSlide(slide.id);
|
||
if (!node) {
|
||
const index = state.slides.indexOf(slide);
|
||
const base = state.graph.positions[slide.id] || graphDefaultPosition(Math.max(0, index));
|
||
const spot = findFreeNodeSpot(Math.max(20, base.x - 330), base.y + 40, 'transition', '');
|
||
node = {
|
||
id: uid(),
|
||
name: `Переход · слайд ${index + 1}`,
|
||
code: DEFAULT_TRANSITION_LUA,
|
||
slideId: slide.id,
|
||
x: spot.x,
|
||
y: spot.y,
|
||
};
|
||
state.graph.transitions = state.graph.transitions || [];
|
||
state.graph.transitions.push(node);
|
||
}
|
||
return node;
|
||
}
|
||
|
||
// Автоцепь: prev.next → transition.in, transition.out → next.in.
|
||
// Ручную связь «Дальше» не перезаписываем.
|
||
function chainSlides(fromSlide, toSlide) {
|
||
if (!fromSlide || !toSlide || fromSlide.id === toSlide.id) return false;
|
||
const hasNext = state.graph.links.some((link) =>
|
||
link.from.kind === 'slide' && link.from.id === fromSlide.id && link.from.port === 'next'
|
||
);
|
||
if (hasNext) return false;
|
||
const transition = ensureTransitionNodeForSlide(toSlide);
|
||
if (!transition) return false;
|
||
pushLink(
|
||
{ kind: 'slide', id: fromSlide.id, port: 'next' },
|
||
{ kind: 'transition', id: transition.id, port: 'in' }
|
||
);
|
||
pushLink(
|
||
{ kind: 'transition', id: transition.id, port: 'out' },
|
||
{ kind: 'slide', id: toSlide.id, port: 'in' }
|
||
);
|
||
return true;
|
||
}
|
||
|
||
function ensureSlideChain(force = false) {
|
||
if (state.slides.length < 2) return;
|
||
if (!force && state.graph.links.some(isNavLink)) return;
|
||
for (let i = 0; i < state.slides.length - 1; i += 1) {
|
||
chainSlides(state.slides[i], state.slides[i + 1]);
|
||
}
|
||
rebuildJumps();
|
||
}
|
||
|
||
function findElementSlide(elementId) {
|
||
for (const slide of state.slides) {
|
||
if ((slide.elements || []).some((element) => element.id === elementId)) return slide;
|
||
}
|
||
return null;
|
||
}
|
||
|
||
// Действие кнопки из инспектора переносим в её выход в графе.
|
||
function syncButtonLink(element) {
|
||
if (!element || element.type !== 'button') return;
|
||
const slide = findElementSlide(element.id);
|
||
if (!slide) return;
|
||
const port = `btn:${element.id}`;
|
||
state.graph.links = state.graph.links.filter((link) =>
|
||
!(link.from.kind === 'slide' && link.from.id === slide.id && link.from.port === port)
|
||
);
|
||
const action = element.action;
|
||
const from = { kind: 'slide', id: slide.id, port };
|
||
if (action && action.type === 'go') {
|
||
const target = state.slides[Number(action.slideIndex) || 0];
|
||
if (target) pushLink(from, { kind: 'slide', id: target.id, port: 'in' });
|
||
} else if (action && action.type === 'lua') {
|
||
const node = action.scriptNodeId ? findScriptNode(action.scriptNodeId) : scriptNodeForElement(element.id);
|
||
if (node) pushLink(from, { kind: 'script', id: node.id, port: 'in' });
|
||
} else if (action && (action.type === 'play' || action.type === 'stop') && action.audioId) {
|
||
const node = ensureAudioNode(action.audioId, action.type);
|
||
pushLink(from, { kind: 'audio', id: node.id, port: 'in' });
|
||
}
|
||
rebuildJumps();
|
||
}
|
||
|
||
// Переносит связи графа в модель: действия кнопок, переходы next/prev и переменные.
|
||
function applyGraphLinks() {
|
||
const byKey = new Map();
|
||
state.graph.links.forEach((link) => {
|
||
byKey.set(`${link.from.kind}|${link.from.id}|${link.from.port}`, link);
|
||
});
|
||
|
||
state.slides.forEach((slide) => {
|
||
(slide.elements || []).forEach((element) => {
|
||
if (element.type !== 'button') return;
|
||
const link = byKey.get(`slide|${slide.id}|btn:${element.id}`);
|
||
if (!link) return;
|
||
if (link.to.kind === 'slide') {
|
||
const index = state.slides.findIndex((item) => item.id === link.to.id);
|
||
if (index >= 0) {
|
||
element.action = {
|
||
...(element.action || {}),
|
||
type: 'go', slideIndex: index, audioId: '', code: '', scriptNodeId: '',
|
||
};
|
||
}
|
||
} else if (link.to.kind === 'script') {
|
||
const node = findScriptNode(link.to.id);
|
||
if (node) {
|
||
node.slideId = slide.id;
|
||
node.elementId = element.id;
|
||
element.action = {
|
||
...(element.action || {}),
|
||
type: 'lua', slideIndex: 0, audioId: '', code: node.code, scriptNodeId: node.id,
|
||
};
|
||
}
|
||
} else if (link.to.kind === 'audio') {
|
||
const node = findAudioNode(link.to.id);
|
||
if (node && node.elementId) {
|
||
element.action = {
|
||
...(element.action || {}),
|
||
type: node.mode === 'stop' ? 'stop' : 'play',
|
||
slideIndex: 0, audioId: node.elementId, code: '', scriptNodeId: '',
|
||
};
|
||
}
|
||
}
|
||
});
|
||
});
|
||
|
||
// Переменная → порт текста: меняем имя в {{...}}, порт переименовываем.
|
||
state.graph.links.forEach((link) => {
|
||
if (link.from.kind !== 'variable' || link.to.kind !== 'slide') return;
|
||
if (!link.to.port.startsWith('var:')) return;
|
||
const parts = link.to.port.split(':');
|
||
if (parts.length < 3) return;
|
||
const elementId = parts[1];
|
||
const oldName = parts.slice(2).join(':');
|
||
const variable = findVariableNode(link.from.id);
|
||
const slide = state.slides.find((item) => item.id === link.to.id);
|
||
const element = slide && (slide.elements || []).find((item) => item.id === elementId);
|
||
if (!variable || !element || typeof element.text !== 'string' || variable.name === oldName) return;
|
||
element.text = element.text.replace(
|
||
new RegExp(`\\{\\{\\s*${escapeRx(oldName)}\\s*\\}\\}`, 'g'),
|
||
`{{${variable.name}}}`
|
||
);
|
||
link.to.port = `var:${elementId}:${variable.name}`;
|
||
});
|
||
|
||
rebuildJumps();
|
||
}
|
||
|
||
function renameVariableNode(node, name) {
|
||
const oldName = node.name;
|
||
const nextName = String(name || '').trim();
|
||
if (!nextName || nextName === oldName) return;
|
||
node.name = nextName;
|
||
state.graph.links.forEach((link) => {
|
||
if (link.from.kind !== 'variable' || link.from.id !== node.id || link.to.kind !== 'slide') return;
|
||
if (!link.to.port.startsWith('var:')) return;
|
||
const parts = link.to.port.split(':');
|
||
if (parts.length < 3) return;
|
||
const elementId = parts[1];
|
||
const oldInPort = parts.slice(2).join(':');
|
||
const slide = state.slides.find((item) => item.id === link.to.id);
|
||
const element = slide && (slide.elements || []).find((item) => item.id === elementId);
|
||
if (!element || typeof element.text !== 'string') return;
|
||
if (oldInPort === oldName) {
|
||
element.text = element.text.replace(
|
||
new RegExp(`\\{\\{\\s*${escapeRx(oldName)}\\s*\\}\\}`, 'g'),
|
||
`{{${nextName}}}`
|
||
);
|
||
}
|
||
link.to.port = `var:${elementId}:${nextName}`;
|
||
});
|
||
}
|
||
|
||
|
||
function ensureGraphPositions() {
|
||
state.slides.forEach((slide, index) => {
|
||
if (!state.graph.positions[slide.id]) state.graph.positions[slide.id] = graphDefaultPosition(index);
|
||
});
|
||
}
|
||
|
||
function ensureScriptNode(element, slide) {
|
||
if (!element || element.type !== 'button') return null;
|
||
if (!element.action) element.action = { type: 'lua', slideIndex: 0, audioId: '', code: '', scriptNodeId: '' };
|
||
const action = element.action;
|
||
let node = action.scriptNodeId ? findScriptNode(action.scriptNodeId) : null;
|
||
if (!node) node = scriptNodeForElement(element.id);
|
||
if (!node) {
|
||
const base = state.graph.positions[slide.id] || graphDefaultPosition(state.slides.indexOf(slide));
|
||
node = {
|
||
id: uid(),
|
||
name: `Lua · ${element.label || 'Кнопка'}`,
|
||
code: action.code || '',
|
||
x: base.x + 330,
|
||
y: base.y + 20,
|
||
slideId: slide.id,
|
||
elementId: element.id,
|
||
};
|
||
state.graph.scripts.push(node);
|
||
}
|
||
action.scriptNodeId = node.id;
|
||
node.slideId = slide.id;
|
||
node.elementId = element.id;
|
||
if (node.code && node.code !== action.code) action.code = node.code;
|
||
else if (!node.code && action.code) node.code = action.code;
|
||
return node;
|
||
}
|
||
|
||
function hydrateGraph(graph) {
|
||
const source = graph && typeof graph === 'object' ? graph : {};
|
||
const positions = {};
|
||
state.slides.forEach((slide, index) => {
|
||
const p = (source.positions && source.positions[slide.id]) || {};
|
||
const fallback = graphDefaultPosition(index);
|
||
positions[slide.id] = {
|
||
x: Number.isFinite(Number(p.x)) ? Number(p.x) : fallback.x,
|
||
y: Number.isFinite(Number(p.y)) ? Number(p.y) : fallback.y,
|
||
};
|
||
});
|
||
const scripts = (Array.isArray(source.scripts) ? source.scripts : []).map((node, index) => ({
|
||
id: node.id || uid(),
|
||
name: node.name || 'Lua-скрипт',
|
||
code: node.code || '',
|
||
x: Number.isFinite(Number(node.x)) ? Number(node.x) : 60 + (index % 3) * 320,
|
||
y: Number.isFinite(Number(node.y)) ? Number(node.y) : 520 + Math.floor(index / 3) * 220,
|
||
slideId: node.slideId || '',
|
||
elementId: node.elementId || '',
|
||
}));
|
||
const audios = (Array.isArray(source.audios) ? source.audios : []).map((node, index) => ({
|
||
id: node.id || uid(),
|
||
name: node.name || 'Аудио',
|
||
elementId: node.elementId || '',
|
||
mode: node.mode === 'stop' ? 'stop' : 'play',
|
||
x: Number.isFinite(Number(node.x)) ? Number(node.x) : 60 + (index % 3) * 320,
|
||
y: Number.isFinite(Number(node.y)) ? Number(node.y) : 840 + Math.floor(index / 3) * 110,
|
||
}));
|
||
const variables = (Array.isArray(source.variables) ? source.variables : []).map((node, index) => ({
|
||
id: node.id || uid(),
|
||
name: String(node.name || `var${index + 1}`),
|
||
x: Number.isFinite(Number(node.x)) ? Number(node.x) : 40,
|
||
y: Number.isFinite(Number(node.y)) ? Number(node.y) : 520 + index * 96,
|
||
}));
|
||
const transitions = (Array.isArray(source.transitions) ? source.transitions : []).map((node, index) => ({
|
||
id: node.id || uid(),
|
||
name: node.name || 'Переход',
|
||
code: node.code || '',
|
||
slideId: node.slideId || '',
|
||
x: Number.isFinite(Number(node.x)) ? Number(node.x) : 60 + (index % 3) * 320,
|
||
y: Number.isFinite(Number(node.y)) ? Number(node.y) : 1120 + Math.floor(index / 3) * 200,
|
||
}));
|
||
const anims = (Array.isArray(source.anims) ? source.anims : []).map((node, index) => ({
|
||
id: node.id || uid(),
|
||
name: node.name || 'Анимация',
|
||
code: node.code || '',
|
||
slideId: node.slideId || '',
|
||
elementId: node.elementId || '',
|
||
x: Number.isFinite(Number(node.x)) ? Number(node.x) : 140 + (index % 3) * 320,
|
||
y: Number.isFinite(Number(node.y)) ? Number(node.y) : 1320 + Math.floor(index / 3) * 200,
|
||
}));
|
||
const pluginNodes = (Array.isArray(source.plugins) ? source.plugins : []).map((node, index) => ({
|
||
id: node.id || uid(),
|
||
pluginId: node.pluginId || '',
|
||
fn: node.fn || '',
|
||
name: node.name || 'Плагин',
|
||
description: node.description || '',
|
||
color: node.color || '#f97316',
|
||
code: node.code || '',
|
||
args: node.args || '',
|
||
x: Number.isFinite(Number(node.x)) ? Number(node.x) : 60 + (index % 3) * 320,
|
||
y: Number.isFinite(Number(node.y)) ? Number(node.y) : 1440 + Math.floor(index / 3) * 200,
|
||
}));
|
||
const links = (Array.isArray(source.links) ? source.links : []).map((link) => {
|
||
const from = link && link.from ? link.from : {};
|
||
const to = link && link.to ? link.to : {};
|
||
const kinds = ['slide', 'script', 'audio', 'variable', 'transition', 'anim', 'plugin'];
|
||
if (!kinds.includes(from.kind) || !kinds.includes(to.kind)) return null;
|
||
if (!from.id || !to.id || !from.port || !to.port) return null;
|
||
return {
|
||
id: link.id || uid(),
|
||
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);
|
||
state.graph = { positions, scripts, audios, variables, transitions, anims, plugins: pluginNodes, links, jumps: {} };
|
||
state.slides.forEach((slide) => {
|
||
(slide.elements || []).forEach((element) => {
|
||
if (element.type === 'button' && element.action && element.action.type === 'lua') ensureScriptNode(element, slide);
|
||
});
|
||
});
|
||
ensureLinksFromModel();
|
||
ensureSlideChain();
|
||
rebuildJumps();
|
||
}
|
||
|
||
function applyScriptNodeToElement(node) {
|
||
const linked = findLinkedElement(node);
|
||
if (!linked) return;
|
||
linked.element.action = {
|
||
...(linked.element.action || {}),
|
||
type: 'lua',
|
||
scriptNodeId: node.id,
|
||
code: node.code,
|
||
};
|
||
}
|
||
|
||
function setStatus(cls, text) {
|
||
saveStateEl.className = `save-state ${cls}`;
|
||
saveStateEl.textContent = text;
|
||
}
|
||
|
||
let toastTimer = null;
|
||
function toast(message) {
|
||
const el = $('toast');
|
||
el.textContent = message;
|
||
el.classList.add('visible');
|
||
clearTimeout(toastTimer);
|
||
toastTimer = setTimeout(() => el.classList.remove('visible'), 2600);
|
||
}
|
||
|
||
// ==================== Lua-редактор: подсветка и автодополнение ====================
|
||
const LUA_KEYWORDS = new Set([
|
||
'and', 'break', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if',
|
||
'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while',
|
||
]);
|
||
const LUA_BUILTINS = new Set([
|
||
'vars', 'app', 'anim', 'string', 'math', 'table', 'os', 'io', 'tostring', 'tonumber',
|
||
'ipairs', 'pairs', 'print', 'type', 'next', 'select', 'error', 'pcall', 'xpcall', 'require',
|
||
'setmetatable', 'getmetatable', 'rawget', 'rawset', 'unpack', 'assert', 'coroutine',
|
||
]);
|
||
const LUA_COMPLETIONS = [
|
||
{ insert: 'app.go(1)', label: 'app.go(index)', kind: 'навигация' },
|
||
{ insert: 'app.next()', label: 'app.next()', kind: 'навигация' },
|
||
{ insert: 'app.prev()', label: 'app.prev()', kind: 'навигация' },
|
||
{ insert: 'app.play(id)', label: 'app.play(id)', kind: 'аудио' },
|
||
{ insert: 'app.stop(id)', label: 'app.stop(id)', kind: 'аудио' },
|
||
{ insert: 'app.music(src)', label: 'app.music(src)', kind: 'аудио' },
|
||
{ insert: 'app.musicPlay()', label: 'app.musicPlay()', kind: 'аудио' },
|
||
{ insert: 'app.musicStop()', label: 'app.musicStop()', kind: 'аудио' },
|
||
{ insert: 'app.musicVolume(v)', label: 'app.musicVolume(v)', kind: 'аудио' },
|
||
{ insert: 'app.setVar(k, v)', label: 'app.setVar(k, v)', kind: 'переменные' },
|
||
{ insert: 'app.getVar(k)', label: 'app.getVar(k)', kind: 'переменные' },
|
||
{ insert: 'app.log(msg)', label: 'app.log(msg)', kind: 'лог' },
|
||
{ insert: 'anim.play(target, frames, opts)', label: 'anim.play(target, frames, opts)', kind: 'анимация' },
|
||
{ insert: 'anim.fadeIn(target, duration, delay)', label: 'anim.fadeIn(target, duration, delay)', kind: 'анимация' },
|
||
{ insert: 'anim.fadeOut(target, duration, delay)', label: 'anim.fadeOut(target, duration, delay)', kind: 'анимация' },
|
||
{ insert: 'anim.clear(target)', label: 'anim.clear(target)', kind: 'анимация' },
|
||
{ insert: 'sleep(ms)', label: 'sleep(ms)', kind: 'пауза' },
|
||
{ insert: 'vars.', label: 'vars.<key>', kind: 'переменные' },
|
||
{ insert: 'string.format(', label: 'string.format(fmt, …)', kind: 'string' },
|
||
{ insert: 'string.gmatch(', label: 'string.gmatch(s, pattern)', kind: 'string' },
|
||
{ insert: 'math.floor(', label: 'math.floor(x)', kind: 'math' },
|
||
{ insert: 'table.insert(', label: 'table.insert(t, value)', kind: 'table' },
|
||
{ insert: 'function ', label: 'function name(args) … end', kind: 'функция' },
|
||
{ insert: 'for i = 1, n do\n \nend', label: 'for i = 1, n do … end', kind: 'цикл' },
|
||
{ insert: 'if then\n \nend', label: 'if … then … end', kind: 'условие' },
|
||
{ insert: '-- @node ', label: '-- @node Заголовок', kind: 'плагин' },
|
||
];
|
||
|
||
function highlightLua(code) {
|
||
const src = String(code || '');
|
||
let out = '';
|
||
let i = 0;
|
||
const isWord = (ch) => /[A-Za-z0-9_]/.test(ch || '');
|
||
while (i < src.length) {
|
||
const ch = src[i];
|
||
const rest = src.slice(i);
|
||
if (rest.startsWith('--')) {
|
||
let end;
|
||
if (rest.startsWith('--[[')) {
|
||
const close = src.indexOf(']]', i + 4);
|
||
end = close < 0 ? src.length : close + 2;
|
||
} else {
|
||
const close = src.indexOf('\n', i);
|
||
end = close < 0 ? src.length : close;
|
||
}
|
||
out += `<span class="tok-com">${esc(src.slice(i, end))}</span>`;
|
||
i = end;
|
||
continue;
|
||
}
|
||
if (rest.startsWith('[[')) {
|
||
const close = src.indexOf(']]', i + 2);
|
||
const end = close < 0 ? src.length : close + 2;
|
||
out += `<span class="tok-str">${esc(src.slice(i, end))}</span>`;
|
||
i = end;
|
||
continue;
|
||
}
|
||
if (ch === '"' || ch === "'") {
|
||
let j = i + 1;
|
||
while (j < src.length) {
|
||
if (src[j] === '\\') { j += 2; continue; }
|
||
if (src[j] === ch) { j += 1; break; }
|
||
j += 1;
|
||
}
|
||
out += `<span class="tok-str">${esc(src.slice(i, j))}</span>`;
|
||
i = j;
|
||
continue;
|
||
}
|
||
if (/[0-9]/.test(ch) && !isWord(src[i - 1])) {
|
||
let j = i + 1;
|
||
while (/[0-9a-fA-FxX._]/.test(src[j] || '')) j += 1;
|
||
out += `<span class="tok-num">${esc(src.slice(i, j))}</span>`;
|
||
i = j;
|
||
continue;
|
||
}
|
||
if (/[A-Za-z_]/.test(ch)) {
|
||
let j = i + 1;
|
||
while (isWord(src[j])) j += 1;
|
||
const word = src.slice(i, j);
|
||
const after = src.slice(j).match(/^\s*\(/);
|
||
let cls = '';
|
||
if (LUA_KEYWORDS.has(word)) cls = 'tok-kw';
|
||
else if (after) cls = 'tok-fn';
|
||
else if (LUA_BUILTINS.has(word)) cls = 'tok-api';
|
||
out += cls ? `<span class="${cls}">${esc(word)}</span>` : esc(word);
|
||
i = j;
|
||
continue;
|
||
}
|
||
if ('+-*/%=<>~#^&|'.includes(ch)) {
|
||
out += `<span class="tok-op">${esc(ch)}</span>`;
|
||
i += 1;
|
||
continue;
|
||
}
|
||
out += esc(ch);
|
||
i += 1;
|
||
}
|
||
return out + '\n';
|
||
}
|
||
|
||
function luaEditorMarkup(options = {}) {
|
||
const attrs = options.nodeProp
|
||
? ` data-node-prop="${esc(options.nodeProp)}"`
|
||
: options.prop ? ` data-prop="${esc(options.prop)}"` : '';
|
||
return `<div class="lua-editor${options.compact ? ' compact' : ''}" data-lua-editor>
|
||
<pre class="lua-highlight" aria-hidden="true"></pre>
|
||
<textarea class="lua-code" rows="${Number(options.rows) || 8}" spellcheck="false"${attrs} placeholder="${esc(options.placeholder || '')}">${esc(options.value || '')}</textarea>
|
||
<div class="lua-suggest" hidden></div>
|
||
</div>`;
|
||
}
|
||
|
||
function createLuaEditor(wrapper, options = {}) {
|
||
if (!wrapper) return null;
|
||
const textarea = wrapper.querySelector('.lua-code');
|
||
const highlight = wrapper.querySelector('.lua-highlight');
|
||
const suggest = wrapper.querySelector('.lua-suggest');
|
||
if (!textarea || !highlight) return null;
|
||
let suggestIndex = 0;
|
||
let suggestItems = [];
|
||
|
||
const sync = () => {
|
||
highlight.innerHTML = highlightLua(textarea.value);
|
||
highlight.scrollTop = textarea.scrollTop;
|
||
highlight.scrollLeft = textarea.scrollLeft;
|
||
};
|
||
const hideSuggest = () => {
|
||
suggest.hidden = true;
|
||
suggest.innerHTML = '';
|
||
suggestItems = [];
|
||
};
|
||
const currentWord = () => {
|
||
const pos = textarea.selectionStart;
|
||
const before = textarea.value.slice(0, pos);
|
||
const match = before.match(/[A-Za-z_][\w.]*$/);
|
||
return match ? { word: match[0], start: pos - match[0].length } : null;
|
||
};
|
||
const applyItem = (item) => {
|
||
const token = currentWord();
|
||
const start = token ? token.start : textarea.selectionStart;
|
||
const end = textarea.selectionStart;
|
||
textarea.value = `${textarea.value.slice(0, start)}${item.insert}${textarea.value.slice(end)}`;
|
||
const caret = start + item.insert.length;
|
||
textarea.selectionStart = caret;
|
||
textarea.selectionEnd = caret;
|
||
hideSuggest();
|
||
sync();
|
||
textarea.dispatchEvent(new Event('input', { bubbles: true }));
|
||
textarea.focus();
|
||
};
|
||
const paintSuggest = () => {
|
||
suggest.innerHTML = suggestItems.map((item, index) =>
|
||
`<button type="button" data-sg-index="${index}" class="${index === suggestIndex ? 'active' : ''}"><span class="sg-name">${highlightLua(item.label || item.insert).replace(/^\s+|\n$/g, '')}</span><span class="sg-kind">${esc(item.kind || '')}</span></button>`
|
||
).join('');
|
||
suggest.hidden = !suggestItems.length;
|
||
suggest.querySelectorAll('button').forEach((button) => {
|
||
button.addEventListener('mousedown', (event) => event.preventDefault());
|
||
button.addEventListener('click', () => applyItem(suggestItems[Number(button.dataset.sgIndex)]));
|
||
});
|
||
};
|
||
const showSuggest = (force = false) => {
|
||
const token = currentWord();
|
||
const query = (token ? token.word : '').toLowerCase();
|
||
if (!force && (!query || query.length < 1)) { hideSuggest(); return; }
|
||
suggestItems = LUA_COMPLETIONS
|
||
.filter((item) => !query || item.insert.toLowerCase().startsWith(query) || item.label.toLowerCase().includes(query))
|
||
.slice(0, 12);
|
||
suggestIndex = 0;
|
||
paintSuggest();
|
||
};
|
||
|
||
textarea.addEventListener('input', () => {
|
||
sync();
|
||
if (typeof options.onInput === 'function') options.onInput(textarea.value);
|
||
showSuggest();
|
||
});
|
||
textarea.addEventListener('scroll', () => {
|
||
highlight.scrollTop = textarea.scrollTop;
|
||
highlight.scrollLeft = textarea.scrollLeft;
|
||
});
|
||
textarea.addEventListener('keydown', (event) => {
|
||
if (!suggest.hidden && suggestItems.length) {
|
||
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
|
||
event.preventDefault();
|
||
suggestIndex = (suggestIndex + (event.key === 'ArrowDown' ? 1 : -1) + suggestItems.length) % suggestItems.length;
|
||
paintSuggest();
|
||
return;
|
||
}
|
||
if (event.key === 'Enter' || event.key === 'Tab') {
|
||
event.preventDefault();
|
||
applyItem(suggestItems[suggestIndex]);
|
||
return;
|
||
}
|
||
if (event.key === 'Escape') {
|
||
event.preventDefault();
|
||
hideSuggest();
|
||
return;
|
||
}
|
||
}
|
||
if (event.key === 'Tab') {
|
||
event.preventDefault();
|
||
const start = textarea.selectionStart;
|
||
textarea.value = `${textarea.value.slice(0, start)} ${textarea.value.slice(textarea.selectionEnd)}`;
|
||
textarea.selectionStart = textarea.selectionEnd = start + 2;
|
||
sync();
|
||
} else if (event.key === ' ' && event.ctrlKey) {
|
||
event.preventDefault();
|
||
showSuggest(true);
|
||
}
|
||
});
|
||
textarea.addEventListener('blur', () => {
|
||
setTimeout(() => { if (document.activeElement !== textarea) hideSuggest(); }, 140);
|
||
});
|
||
sync();
|
||
wrapper.dataset.luaReady = '1';
|
||
return { textarea, sync, showSuggest };
|
||
}
|
||
|
||
function mountLuaEditor(host, options = {}) {
|
||
if (!host) return null;
|
||
host.innerHTML = luaEditorMarkup(options);
|
||
return createLuaEditor(host.firstElementChild, options);
|
||
}
|
||
|
||
function enhanceLuaEditors(root) {
|
||
if (!root) return;
|
||
root.querySelectorAll('[data-lua-editor]').forEach((wrapper) => {
|
||
if (wrapper.dataset.luaReady) return;
|
||
createLuaEditor(wrapper, {});
|
||
});
|
||
}
|
||
|
||
// ==================== Кастомный Lua-элемент ====================
|
||
const DEFAULT_LUA_ELEMENT = [
|
||
'-- Верните таблицу: style / css / html / text.',
|
||
'-- Ключи style пишутся как в JS: backgroundColor, borderRadius, fontSize.',
|
||
'return {',
|
||
" style = {",
|
||
" background = 'rgba(15, 23, 42, .78)',",
|
||
" border = '1px solid rgba(129, 140, 248, .5)',",
|
||
" borderRadius = '20px',",
|
||
" boxShadow = '0 24px 60px rgba(0, 0, 0, .4)',",
|
||
" color = '#e2e8f0',",
|
||
" padding = '22px',",
|
||
" fontSize = '1.8cqw'",
|
||
' },',
|
||
" html = '<b>Lua-элемент</b><br><span style=\"opacity:.7\">стили и HTML вычислены в Lua</span>'",
|
||
'}',
|
||
].join('\n');
|
||
|
||
function computeLuaElement(element) {
|
||
if (!element || element.type !== 'lua') return;
|
||
if (!window.createLuaRuntime) {
|
||
toast('Lua-рантайм не загружен');
|
||
return;
|
||
}
|
||
if (!String(element.code || '').trim()) {
|
||
toast('Добавьте Lua-код, возвращающий таблицу стилей');
|
||
return;
|
||
}
|
||
let runtime;
|
||
try {
|
||
runtime = window.createLuaRuntime({
|
||
vars: { ...(state.variables || {}) },
|
||
log: (message) => console.log('[lua:element]', message),
|
||
error: (message) => toast(String(message)),
|
||
});
|
||
} catch (error) {
|
||
toast('Не удалось запустить Lua');
|
||
return;
|
||
}
|
||
const result = runtime.eval(element.code, `Lua-элемент «${element.label || 'без названия'}»`);
|
||
if (result === null || result === undefined) {
|
||
toast('Lua вернул пустое значение');
|
||
return;
|
||
}
|
||
const style = {};
|
||
const pushStyle = (value) => {
|
||
Object.entries(value && typeof value === 'object' ? value : {}).forEach(([key, item]) => {
|
||
if (item === null || item === undefined || typeof item === 'object') return;
|
||
style[key] = String(item);
|
||
});
|
||
};
|
||
let html = '';
|
||
let text = '';
|
||
let css = '';
|
||
if (typeof result === 'string' || typeof result === 'number') {
|
||
text = String(result);
|
||
} else if (typeof result === 'object') {
|
||
pushStyle(result.style);
|
||
Object.entries(result).forEach(([key, value]) => {
|
||
if (['style', 'css', 'html', 'text'].includes(key)) return;
|
||
if (value !== null && value !== undefined && typeof value !== 'object') style[key] = String(value);
|
||
});
|
||
html = typeof result.html === 'string' ? result.html : '';
|
||
text = typeof result.text === 'string' || typeof result.text === 'number' ? String(result.text) : '';
|
||
css = typeof result.css === 'string' ? result.css : '';
|
||
}
|
||
element.computed = { style, css, html, text, at: Date.now() };
|
||
renderCanvas();
|
||
renderInspector();
|
||
scheduleThumbs();
|
||
scheduleSave(true);
|
||
toast('Lua-элемент вычислен');
|
||
}
|
||
|
||
// ==================== Древо ====================
|
||
const TREE_BASE_ELEMENTS = [
|
||
{ kind: 'text', icon: 'Т', label: 'Текст' },
|
||
{ kind: 'image', icon: '▧', label: 'Картинка' },
|
||
{ kind: 'shape', icon: '◆', label: 'Фигура' },
|
||
{ kind: 'button', icon: '▶', label: 'Кнопка' },
|
||
{ kind: 'audio', icon: '♪', label: 'Аудио' },
|
||
{ kind: 'video', icon: '▤', label: 'Видео' },
|
||
{ kind: 'window', icon: '⧉', label: 'Окно Chrome' },
|
||
{ kind: 'lua', icon: 'λ', label: 'Lua-элемент' },
|
||
];
|
||
const TREE_BASE_NODES = [
|
||
{ kind: 'slide', icon: '▭', label: 'Слайд' },
|
||
{ kind: 'script', icon: 'λ', label: 'Код' },
|
||
{ kind: 'transition', icon: '⇥', label: 'Переход' },
|
||
{ kind: 'anim', icon: '✦', label: 'Анимация' },
|
||
{ kind: 'variable', icon: '⌘', label: 'Переменная' },
|
||
{ kind: 'audio', icon: '♪', label: 'Аудио-нода' },
|
||
];
|
||
|
||
function treeGroup(id, label, itemsHtml, count) {
|
||
const collapsed = !!state.tree.collapsed[id];
|
||
return `<div class="tree-group">
|
||
<button class="tree-group-head" data-tree-group="${esc(id)}"><span class="caret">${collapsed ? '▸' : '▾'}</span>${esc(label)}<span class="count">${count}</span></button>
|
||
${collapsed ? '' : `<div class="tree-items">${itemsHtml}</div>`}
|
||
</div>`;
|
||
}
|
||
|
||
function treeItem(attrs, icon, name, meta, extra = '') {
|
||
return `<div class="tree-item" draggable="true" ${attrs}>
|
||
<span class="ti-ico">${icon}</span>
|
||
<span class="ti-name">${esc(name)}</span>
|
||
${meta ? `<span class="ti-meta">${esc(meta)}</span>` : ''}
|
||
${extra}
|
||
</div>`;
|
||
}
|
||
|
||
function renderTree() {
|
||
if (!treeListEl) return;
|
||
const query = String(state.tree.query || '').trim().toLowerCase();
|
||
const match = (text) => !query || String(text || '').toLowerCase().includes(query);
|
||
const tabs = treePanel.querySelectorAll('[data-tree-tab]');
|
||
tabs.forEach((button) => button.classList.toggle('active', button.dataset.treeTab === state.tree.tab));
|
||
let html = '';
|
||
|
||
if (state.tree.tab === 'plugins') {
|
||
const plugins = (state.pluginRegistry || []).filter((plugin) => {
|
||
if (!query) return true;
|
||
if (match(plugin.name) || match(plugin.description)) return true;
|
||
return (plugin.nodes || []).some((node) => match(node.name) || match(node.fn) || match(node.description));
|
||
});
|
||
if (!plugins.length) {
|
||
html = `<div class="tree-empty">${query ? 'Плагины не найдены.' : 'Реестр пуст. Создайте плагин — его функции появятся здесь как ноды.'}<br><br><button class="primary" data-act="plugin-new">+ Новый плагин</button></div>`;
|
||
} else {
|
||
html = plugins.map((plugin) => {
|
||
const closed = !!state.tree.plugins[plugin.id];
|
||
const nodes = (plugin.nodes || []).filter((node) => !query || match(node.name) || match(node.fn) || match(node.description) || match(plugin.name));
|
||
const items = nodes.map((node) => treeItem(
|
||
`data-tree-action="add-plugin" data-drag-kind="plugin" data-plugin-id="${esc(plugin.id)}" data-fn="${esc(node.fn)}"`,
|
||
'ƒ',
|
||
node.name || node.fn,
|
||
node.args ? `(${node.args})` : '',
|
||
`<button class="ti-add" data-tree-action="add-plugin" data-plugin-id="${esc(plugin.id)}" data-fn="${esc(node.fn)}" title="Добавить ноду в граф">+</button>`
|
||
)).join('');
|
||
return `<div class="tree-plugin">
|
||
<div class="tree-plugin-head">
|
||
<span class="ti-dot" style="background:${esc(plugin.color || '#f97316')}"></span>
|
||
<span>${esc(plugin.name)}</span>
|
||
<span class="ti-actions">
|
||
<button data-tree-action="toggle-plugin" data-plugin-id="${esc(plugin.id)}" title="Свернуть">${closed ? '▸' : '▾'}</button>
|
||
<button data-tree-action="edit-plugin" data-plugin-id="${esc(plugin.id)}" title="Редактировать плагин">✎</button>
|
||
</span>
|
||
</div>
|
||
<div class="tree-plugin-desc">${esc(plugin.description || 'Без описания')}</div>
|
||
${closed ? '' : `<div class="tree-items">${items || '<div class="tree-empty">В плагине нет функций.</div>'}</div>`}
|
||
</div>`;
|
||
}).join('');
|
||
}
|
||
} else {
|
||
// База: элементы холста, ноды графа, содержимое текущего слайда.
|
||
const elementItems = TREE_BASE_ELEMENTS.filter((item) => match(item.label) || match(item.kind)).map((item) =>
|
||
treeItem(`data-tree-action="add-element" data-drag-kind="element" data-kind="${item.kind}"`,
|
||
item.icon, item.label, 'на холст',
|
||
`<button class="ti-add" data-tree-action="add-element" data-kind="${item.kind}" title="Добавить на слайд">+</button>`)
|
||
).join('');
|
||
if (elementItems) html += treeGroup('elements', 'Элементы холста', elementItems, TREE_BASE_ELEMENTS.length);
|
||
|
||
const nodeItems = TREE_BASE_NODES.filter((item) => match(item.label) || match(item.kind)).map((item) =>
|
||
treeItem(`data-tree-action="add-node" data-drag-kind="node" data-node-kind="${item.kind}"`,
|
||
item.icon, item.label, 'в граф',
|
||
`<button class="ti-add" data-tree-action="add-node" data-node-kind="${item.kind}" title="Добавить ноду">+</button>`)
|
||
).join('');
|
||
if (nodeItems) html += treeGroup('nodes', 'Базовые ноды', nodeItems, TREE_BASE_NODES.length);
|
||
|
||
const slide = currentSlide();
|
||
const elementNodes = (slide && slide.elements || []).filter((element) => match(element.label || element.text || element.type)).map((element) => {
|
||
const label = element.label || (element.type === 'text' ? String(element.text || '').slice(0, 40) : element.type);
|
||
return treeItem(
|
||
`data-tree-action="select-element" data-slide-index="${state.selected}" data-element-id="${esc(element.id)}"`,
|
||
element.type === 'lua' ? 'λ' : element.type === 'button' ? '▶' : element.type === 'text' ? 'Т' : '◆',
|
||
label || element.type,
|
||
element.type
|
||
);
|
||
}).join('');
|
||
if (elementNodes) html += treeGroup('slide-elements', `Элементы слайда ${state.selected + 1}`, elementNodes, (slide && slide.elements || []).length);
|
||
|
||
const slideItems = state.slides.filter((item, index) => match(`слайд ${index + 1}`)).map((item, index) =>
|
||
treeItem(`data-tree-action="select-slide" data-slide-id="${esc(item.id)}"`, '▭',
|
||
`Слайд ${index + 1}`,
|
||
item === currentSlide() ? 'текущий' : '',
|
||
`<button class="ti-add" data-tree-action="select-slide" data-slide-id="${esc(item.id)}" title="Открыть слайд">→</button>`)
|
||
).join('');
|
||
if (slideItems) html += treeGroup('slides', 'Слайды', slideItems, state.slides.length);
|
||
|
||
const activeNodes = [];
|
||
(state.graph.scripts || []).forEach((node) => activeNodes.push({ type: 'script', id: node.id, icon: 'λ', name: node.name || 'Lua-скрипт', meta: 'код' }));
|
||
(state.graph.transitions || []).forEach((node) => activeNodes.push({ type: 'transition', id: node.id, icon: '⇥', name: node.name || 'Переход', meta: 'переход' }));
|
||
(state.graph.anims || []).forEach((node) => activeNodes.push({ type: 'anim', id: node.id, icon: '✦', name: node.name || 'Анимация', meta: 'анимация' }));
|
||
(state.graph.plugins || []).forEach((node) => activeNodes.push({ type: 'plugin', id: node.id, icon: 'ƒ', name: node.name || 'Плагин', meta: node.fn || 'плагин' }));
|
||
(state.graph.variables || []).forEach((node) => activeNodes.push({ type: 'variable', id: node.id, icon: '⌘', name: node.name || 'Переменная', meta: 'данные' }));
|
||
const activeHtml = activeNodes.filter((node) => match(node.name) || match(node.meta)).map((node) =>
|
||
treeItem(`data-tree-action="select-node" data-node-type="${node.type}" data-node-id="${esc(node.id || '')}"`, node.icon, node.name, node.meta)
|
||
).join('');
|
||
if (activeHtml) html += treeGroup('active-nodes', 'Ноды графа', activeHtml, activeNodes.length);
|
||
}
|
||
if (!html) html = '<div class="tree-empty">Ничего не найдено.</div>';
|
||
treeListEl.innerHTML = html;
|
||
}
|
||
|
||
function setTreeOpen(open) {
|
||
state.tree.open = !!open;
|
||
if (treePanel) treePanel.classList.toggle('collapsed', !open);
|
||
const button = treePanel && treePanel.querySelector('.tree-collapse');
|
||
if (button) button.textContent = open ? '‹' : '›';
|
||
}
|
||
|
||
function applyTreeDrag(payload, point) {
|
||
if (!payload) return;
|
||
if (payload.kind === 'element') {
|
||
addElement(payload.element, point);
|
||
} else if (payload.kind === 'node') {
|
||
const kind = payload.nodeKind;
|
||
if (kind === 'slide') addSlide();
|
||
else if (kind === 'script') addScriptNode();
|
||
else if (kind === 'transition') addTransitionNode();
|
||
else if (kind === 'anim') addAnimNode();
|
||
else if (kind === 'variable') addVariableNode();
|
||
else if (kind === 'audio') addAudioNode();
|
||
if (point && state.selectedNode) {
|
||
if (state.selectedNode.type === 'slide') {
|
||
state.graph.positions[state.selectedNode.id] = {
|
||
x: Math.max(20, point.x),
|
||
y: Math.max(20, point.y),
|
||
};
|
||
} else {
|
||
const node = findNodeByKind(state.selectedNode.type, state.selectedNode.id);
|
||
if (node) {
|
||
node.x = Math.max(20, point.x);
|
||
node.y = Math.max(20, point.y);
|
||
}
|
||
}
|
||
renderAll();
|
||
scheduleSave();
|
||
}
|
||
} else if (payload.kind === 'plugin') {
|
||
addPluginNode(payload.pluginId, payload.fn, point);
|
||
}
|
||
}
|
||
|
||
// ==================== Редактор плагинов ====================
|
||
const PLUGIN_TEMPLATE = [
|
||
'-- Promptly plugin: новый модуль',
|
||
'-- Комментарий "-- @node Заголовок" задаёт имя ноды.',
|
||
'',
|
||
'-- @node Приветствие',
|
||
'function hello(target)',
|
||
" target = target or 'slide'",
|
||
" anim.fadeIn(target, 420)",
|
||
" app.log('hello')",
|
||
'end',
|
||
'',
|
||
'-- @node Счётчик',
|
||
'function bump(key, amount)',
|
||
" key = tostring(key or 'count')",
|
||
' amount = tonumber(amount) or 1',
|
||
' vars[key] = (tonumber(vars[key]) or 0) + amount',
|
||
' return { [key] = vars[key] }',
|
||
'end',
|
||
].join('\n');
|
||
|
||
function derivePluginNodesClient(code) {
|
||
const source = String(code || '');
|
||
const nodes = [];
|
||
const seen = new Set();
|
||
const re = /(?:^|\n)[ \t]*(?:local[ \t]+)?function[ \t]+([A-Za-z_][A-Za-z0-9_]*)[ \t]*\(([^)]*)\)/g;
|
||
let match;
|
||
while ((match = re.exec(source))) {
|
||
const fn = match[1];
|
||
if (seen.has(fn)) continue;
|
||
seen.add(fn);
|
||
const before = source.slice(0, match.index).split('\n').slice(-6);
|
||
const comments = [];
|
||
for (let i = before.length - 1; i >= 0; i -= 1) {
|
||
const line = before[i].trim();
|
||
if (!line.startsWith('--')) break;
|
||
comments.unshift(line.replace(/^--\s?/, '').trim());
|
||
}
|
||
let title = '';
|
||
const description = [];
|
||
comments.forEach((line) => {
|
||
if (/^@node\s+/i.test(line)) title = line.replace(/^@node\s+/i, '').trim();
|
||
else if (line) description.push(line);
|
||
});
|
||
nodes.push({
|
||
fn,
|
||
name: title || fn.replace(/_/g, ' '),
|
||
description: description.join(' · '),
|
||
args: match[2].trim(),
|
||
});
|
||
}
|
||
return nodes;
|
||
}
|
||
|
||
function newPluginDraft() {
|
||
return {
|
||
id: '',
|
||
name: 'Новый плагин',
|
||
description: '',
|
||
color: '#f97316',
|
||
code: PLUGIN_TEMPLATE,
|
||
};
|
||
}
|
||
|
||
async function loadPlugins() {
|
||
try {
|
||
const response = await fetch('/api/plugins');
|
||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||
const data = await response.json();
|
||
state.pluginRegistry = Array.isArray(data.plugins) ? data.plugins : [];
|
||
} catch (error) {
|
||
state.pluginRegistry = state.pluginRegistry || [];
|
||
toast('Не удалось загрузить реестр плагинов');
|
||
}
|
||
renderTree();
|
||
if (!pluginModal.hidden && state.pluginDraft) renderPluginEditor();
|
||
return state.pluginRegistry;
|
||
}
|
||
|
||
function pluginDraftFrom(plugin) {
|
||
if (!plugin) return newPluginDraft();
|
||
return {
|
||
id: plugin.id,
|
||
name: plugin.name || '',
|
||
description: plugin.description || '',
|
||
color: plugin.color || '#f97316',
|
||
code: plugin.code || '',
|
||
};
|
||
}
|
||
|
||
function renderPluginEditor() {
|
||
const draft = state.pluginDraft || newPluginDraft();
|
||
state.pluginDraft = draft;
|
||
pluginListEl.innerHTML = (state.pluginRegistry || []).map((plugin) => `
|
||
<button class="plugin-list-item${plugin.id === draft.id ? ' active' : ''}" data-plugin-pick="${esc(plugin.id)}">
|
||
<span class="pl-dot" style="background:${esc(plugin.color || '#f97316')}"></span>
|
||
<span class="pl-name">${esc(plugin.name)}</span>
|
||
<span class="pl-count">${(plugin.nodes || []).length}</span>
|
||
</button>`).join('') || '<div class="tree-empty">Плагинов пока нет.</div>';
|
||
$('plugin-name').value = draft.name || '';
|
||
$('plugin-desc').value = draft.description || '';
|
||
$('plugin-color').value = /^#[0-9a-f]{6}$/i.test(draft.color || '') ? draft.color : '#f97316';
|
||
$('plugin-delete').disabled = !draft.id;
|
||
mountLuaEditor(pluginCodeEl, {
|
||
value: draft.code,
|
||
rows: 18,
|
||
placeholder: PLUGIN_TEMPLATE,
|
||
onInput: (value) => {
|
||
draft.code = value;
|
||
state.pluginDirty = true;
|
||
renderPluginNodesPreview();
|
||
},
|
||
});
|
||
renderPluginNodesPreview();
|
||
}
|
||
|
||
function renderPluginNodesPreview() {
|
||
const draft = state.pluginDraft || newPluginDraft();
|
||
const nodes = draft.id
|
||
? ((state.pluginRegistry.find((plugin) => plugin.id === draft.id) || {}).nodes || derivePluginNodesClient(draft.code))
|
||
: derivePluginNodesClient(draft.code);
|
||
const parsed = derivePluginNodesClient(draft.code);
|
||
const list = parsed.length ? parsed : nodes;
|
||
$('plugin-nodes').innerHTML = list.length
|
||
? list.map((node) => `<span class="plugin-node-chip">ƒ ${esc(node.name || node.fn)} <small>${esc(node.args || '')}</small></span>`).join('')
|
||
: '<span class="muted">Функции не найдены — ноды не появятся.</span>';
|
||
$('plugin-status').innerHTML = `${draft.id ? `id: <code>${esc(draft.id)}</code>` : 'Новый плагин'} · функций-нод: <b>${list.length}</b>${state.pluginDirty ? ' · есть несохранённые правки' : ''}`;
|
||
}
|
||
|
||
async function openPluginEditor(id = null) {
|
||
if (!(state.pluginRegistry || []).length) await loadPlugins();
|
||
let plugin = id ? (state.pluginRegistry || []).find((item) => item.id === id) : null;
|
||
if (id && !plugin) {
|
||
try {
|
||
const response = await fetch(`/api/plugins/${encodeURIComponent(id)}`);
|
||
if (response.ok) plugin = await response.json();
|
||
} catch (error) {
|
||
/* плагин мог быть удалён */
|
||
}
|
||
}
|
||
state.pluginDraft = pluginDraftFrom(plugin);
|
||
state.pluginDirty = false;
|
||
pluginModal.hidden = false;
|
||
renderPluginEditor();
|
||
}
|
||
|
||
function closePluginEditor() {
|
||
pluginModal.hidden = true;
|
||
state.pluginDraft = null;
|
||
state.pluginDirty = false;
|
||
}
|
||
|
||
function syncPluginNodes(plugin) {
|
||
(state.graph.plugins || []).forEach((node) => {
|
||
if (node.pluginId !== plugin.id) return;
|
||
const fn = pluginFunction(plugin, node.fn);
|
||
node.code = plugin.code || node.code;
|
||
node.color = plugin.color || node.color;
|
||
if (fn) {
|
||
node.name = `${plugin.name} · ${fn.name || fn.fn}`;
|
||
node.description = fn.description || plugin.description || '';
|
||
}
|
||
});
|
||
}
|
||
|
||
async function savePluginDraft() {
|
||
const draft = state.pluginDraft;
|
||
if (!draft) return;
|
||
draft.name = $('plugin-name').value.trim() || 'Без названия';
|
||
draft.description = $('plugin-desc').value;
|
||
draft.color = $('plugin-color').value;
|
||
try {
|
||
const response = await fetch(draft.id ? `/api/plugins/${encodeURIComponent(draft.id)}` : '/api/plugins', {
|
||
method: draft.id ? 'PUT' : 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify(draft),
|
||
});
|
||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||
const saved = await response.json();
|
||
state.pluginRegistry = (state.pluginRegistry || []).filter((plugin) => plugin.id !== saved.id);
|
||
state.pluginRegistry.push(saved);
|
||
state.pluginRegistry.sort((a, b) => String(a.name).localeCompare(String(b.name), 'ru'));
|
||
state.pluginDraft = pluginDraftFrom(saved);
|
||
state.pluginDirty = false;
|
||
syncPluginNodes(saved);
|
||
renderPluginEditor();
|
||
renderTree();
|
||
renderAll();
|
||
scheduleSave(true);
|
||
toast(`Плагин «${saved.name}» сохранён на диск`);
|
||
} catch (error) {
|
||
toast('Не удалось сохранить плагин');
|
||
}
|
||
}
|
||
|
||
async function deletePluginDraft() {
|
||
const draft = state.pluginDraft;
|
||
if (!draft || !draft.id) return;
|
||
const confirmed = typeof confirm === 'function' ? confirm(`Удалить плагин «${draft.name}»? Ноды в презентации сохранят снимок кода.`) : true;
|
||
if (!confirmed) return;
|
||
try {
|
||
const response = await fetch(`/api/plugins/${encodeURIComponent(draft.id)}`, { method: 'DELETE' });
|
||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||
state.pluginRegistry = (state.pluginRegistry || []).filter((plugin) => plugin.id !== draft.id);
|
||
state.pluginDraft = newPluginDraft();
|
||
state.pluginDirty = false;
|
||
renderPluginEditor();
|
||
renderTree();
|
||
toast('Плагин удалён с диска');
|
||
} catch (error) {
|
||
toast('Не удалось удалить плагин');
|
||
}
|
||
}
|
||
|
||
// ==================== Рендер ====================
|
||
function renderCanvas() {
|
||
SlideView.render(canvasEl, currentSlide(), {
|
||
variables: state.variables,
|
||
editable: true,
|
||
selectedId: state.selectedEl,
|
||
placeholder: 'Пустой слайд — добавьте элементы на панели сверху',
|
||
});
|
||
renderSelection();
|
||
}
|
||
|
||
function renderSelection() {
|
||
const element = selectedElement();
|
||
if (!element) {
|
||
selBox.hidden = true;
|
||
return;
|
||
}
|
||
selBox.hidden = false;
|
||
selBox.style.left = `${element.x}%`;
|
||
selBox.style.top = `${element.y}%`;
|
||
selBox.style.width = `${element.w}%`;
|
||
selBox.style.height = `${element.h}%`;
|
||
}
|
||
|
||
let thumbsTimer = null;
|
||
function scheduleThumbs() {
|
||
clearTimeout(thumbsTimer);
|
||
thumbsTimer = setTimeout(renderThumbs, 140);
|
||
}
|
||
|
||
function renderThumbs() {
|
||
thumbsEl.innerHTML = '';
|
||
state.slides.forEach((slide, index) => {
|
||
const button = document.createElement('button');
|
||
button.className = 'thumb' + (index === state.selected ? ' active' : '');
|
||
button.innerHTML = `<span class="num">${index + 1}</span><span class="thumb-canvas"></span>`;
|
||
SlideView.render(button.querySelector('.thumb-canvas'), slide, { variables: state.variables, staticPreview: true });
|
||
button.addEventListener('click', () => selectSlide(index));
|
||
thumbsEl.appendChild(button);
|
||
});
|
||
$('slide-count').textContent = String(state.slides.length);
|
||
$('slide-total').textContent = String(state.slides.length);
|
||
}
|
||
|
||
function selectSlide(index) {
|
||
state.selected = clamp(index, 0, state.slides.length - 1);
|
||
state.selectedEl = null;
|
||
const slide = currentSlide();
|
||
if (slide) state.selectedNode = { type: 'slide', id: slide.id };
|
||
renderAll();
|
||
}
|
||
|
||
function renderAll() {
|
||
ensureGraphPositions();
|
||
$('slide-index').textContent = String(state.selected + 1);
|
||
$('slide-total').textContent = String(state.slides.length);
|
||
renderThumbs();
|
||
renderCanvas();
|
||
renderInspector();
|
||
renderTree();
|
||
if (state.view === 'graph') renderGraph();
|
||
}
|
||
|
||
function setView(view) {
|
||
state.view = view === 'graph' ? 'graph' : 'canvas';
|
||
stageEl.hidden = state.view !== 'canvas';
|
||
graphStage.hidden = state.view !== 'graph';
|
||
document.querySelectorAll('[data-view]').forEach((button) => {
|
||
button.classList.toggle('active', button.dataset.view === state.view);
|
||
});
|
||
if (state.view === 'graph') {
|
||
if (!state.selectedNode) {
|
||
const slide = currentSlide();
|
||
if (slide) state.selectedNode = { type: 'slide', id: slide.id };
|
||
}
|
||
ensureLinksFromModel();
|
||
rebuildJumps();
|
||
renderGraph();
|
||
}
|
||
renderInspector();
|
||
renderTree();
|
||
}
|
||
|
||
function renderGraph() {
|
||
if (!graphNodesEl || state.view !== 'graph') return;
|
||
ensureGraphPositions();
|
||
graphNodesEl.innerHTML = '';
|
||
|
||
let maxX = 1200;
|
||
let maxY = 760;
|
||
const track = (x, y, extraX, extraY) => {
|
||
maxX = Math.max(maxX, Number(x) + (extraX || 300));
|
||
maxY = Math.max(maxY, Number(y) + (extraY || 280));
|
||
};
|
||
|
||
const selectedNode = state.selectedNode;
|
||
const portHtml = (nodeKind, nodeId, portKey, dir, label, variant) => `
|
||
<div class="grow ${dir === 'out' ? 'out' : 'in'}${variant ? ` ${variant}` : ''}">
|
||
<span class="gport-label">${esc(label)}</span>
|
||
<span class="gport ${dir}${variant ? ` ${variant}` : ''}"
|
||
data-port-kind="${dir}"
|
||
data-link-node-kind="${nodeKind}"
|
||
data-link-node-id="${esc(nodeId)}"
|
||
data-port-key="${esc(portKey)}"></span>
|
||
</div>`;
|
||
|
||
state.slides.forEach((slide, index) => {
|
||
const p = state.graph.positions[slide.id] || graphDefaultPosition(index);
|
||
track(p.x, p.y, 250, 320);
|
||
const node = document.createElement('div');
|
||
const isSelected = selectedNode && selectedNode.type === 'slide' && selectedNode.id === slide.id;
|
||
node.className = 'gnode slide' + (isSelected ? ' selected' : '');
|
||
node.dataset.nodeKind = 'slide';
|
||
node.dataset.nodeId = slide.id;
|
||
node.style.left = `${p.x}px`;
|
||
node.style.top = `${p.y}px`;
|
||
|
||
const elements = slide.elements || [];
|
||
const firstText = elements.find((el) => el.type === 'text' && String(el.text || '').trim());
|
||
const title = firstText ? String(firstText.text).trim().slice(0, 48) : `Слайд ${index + 1}`;
|
||
const media = elements.filter((el) => el.type === 'video' || el.type === 'window').length;
|
||
const meta = [`${elements.length} эл.`, media ? `${media} медиа` : ''].filter(Boolean).join(' · ');
|
||
|
||
node.innerHTML = `
|
||
<div class="gnode-body">
|
||
<div class="gnode-head">
|
||
<span class="gnode-badge">Слайд ${index + 1}</span>
|
||
<span class="gnode-kind"></span>
|
||
</div>
|
||
<div class="gnode-title"></div>
|
||
<div class="gnode-sub"></div>
|
||
<div class="gnode-bar"></div>
|
||
</div>
|
||
<div class="gnode-ports">
|
||
${portHtml('slide', slide.id, 'in', 'in', 'вход')}
|
||
${slideVarPorts(slide).map((port) => portHtml('slide', slide.id, port.key, 'in', `⌘ ${port.name}`, 'data')).join('')}
|
||
${portHtml('slide', slide.id, 'next', 'out', 'Дальше')}
|
||
${portHtml('slide', slide.id, 'prev', 'out', 'Назад')}
|
||
${slideButtonPorts(slide).map((port) => portHtml('slide', slide.id, port.key, 'out', port.label)).join('')}
|
||
</div>`;
|
||
node.querySelector('.gnode-kind').textContent = meta;
|
||
node.querySelector('.gnode-title').textContent = title;
|
||
node.querySelector('.gnode-sub').textContent = slide.notes ? String(slide.notes).split('\n')[0].slice(0, 52) : 'без пометок';
|
||
const bg = slide.background || {};
|
||
node.querySelector('.gnode-bar').style.background =
|
||
bg.type === 'gradient' && bg.gradient ? bg.gradient : bg.type === 'image' && bg.image ? `url("${bg.image}") center/cover` : (bg.color || '#6366f1');
|
||
bindGraphNode(node, 'slide', slide.id);
|
||
node.addEventListener('dblclick', () => {
|
||
state.selected = index;
|
||
state.selectedEl = null;
|
||
setView('canvas');
|
||
});
|
||
graphNodesEl.appendChild(node);
|
||
bindPortEvents(node, 'slide', slide.id);
|
||
});
|
||
|
||
state.graph.scripts.forEach((script) => {
|
||
track(script.x, script.y, 250, 240);
|
||
const node = document.createElement('div');
|
||
const isSelected = selectedNode && selectedNode.type === 'script' && selectedNode.id === script.id;
|
||
node.className = 'gnode script' + (isSelected ? ' selected' : '');
|
||
node.dataset.nodeKind = 'script';
|
||
node.dataset.nodeId = script.id;
|
||
node.style.left = `${script.x}px`;
|
||
node.style.top = `${script.y}px`;
|
||
const linked = findLinkedElement(script);
|
||
node.innerHTML = `
|
||
<div class="gnode-body">
|
||
<div class="gnode-head">
|
||
<span class="gnode-badge">Lua</span>
|
||
<span class="gnode-kind"></span>
|
||
</div>
|
||
<div class="gnode-title"></div>
|
||
<pre class="gnode-code"></pre>
|
||
</div>
|
||
<div class="gnode-ports">
|
||
${portHtml('script', script.id, 'in', 'in', 'запуск')}
|
||
</div>`;
|
||
node.querySelector('.gnode-kind').textContent = linked ? (linked.element.label || 'кнопка') : 'свободный код';
|
||
node.querySelector('.gnode-title').textContent = script.name || 'Lua-скрипт';
|
||
node.querySelector('.gnode-code').textContent = String(script.code || '').split('\n').slice(0, 2).join('\n') || '— пустой скрипт —';
|
||
bindGraphNode(node, 'script', script.id);
|
||
graphNodesEl.appendChild(node);
|
||
bindPortEvents(node, 'script', script.id);
|
||
});
|
||
|
||
state.graph.audios.forEach((audioNode) => {
|
||
track(audioNode.x, audioNode.y, 250, 220);
|
||
const node = document.createElement('div');
|
||
const isSelected = selectedNode && selectedNode.type === 'audio' && selectedNode.id === audioNode.id;
|
||
node.className = 'gnode audio' + (isSelected ? ' selected' : '');
|
||
node.dataset.nodeKind = 'audio';
|
||
node.dataset.nodeId = audioNode.id;
|
||
node.style.left = `${audioNode.x}px`;
|
||
node.style.top = `${audioNode.y}px`;
|
||
const found = findAudioElement(audioNode.elementId);
|
||
const fileName = found && found.element.src ? String(found.element.src).split('/').pop().slice(0, 34) : 'файл не выбран';
|
||
node.innerHTML = `
|
||
<div class="gnode-body">
|
||
<div class="gnode-head">
|
||
<span class="gnode-badge">Аудио</span>
|
||
<span class="gnode-kind">${audioNode.mode === 'stop' ? 'STOP' : 'PLAY'}</span>
|
||
</div>
|
||
<div class="gnode-title"></div>
|
||
<div class="gnode-sub"></div>
|
||
</div>
|
||
<div class="gnode-ports">
|
||
${portHtml('audio', audioNode.id, 'in', 'in', 'запуск', 'audio')}
|
||
</div>`;
|
||
node.querySelector('.gnode-title').textContent = audioNode.name || 'Аудио';
|
||
node.querySelector('.gnode-sub').textContent = fileName;
|
||
bindGraphNode(node, 'audio', audioNode.id);
|
||
graphNodesEl.appendChild(node);
|
||
bindPortEvents(node, 'audio', audioNode.id);
|
||
});
|
||
|
||
state.graph.variables.forEach((variable) => {
|
||
track(variable.x, variable.y, 220, 200);
|
||
const node = document.createElement('div');
|
||
const isSelected = selectedNode && selectedNode.type === 'variable' && selectedNode.id === variable.id;
|
||
node.className = 'gnode variable' + (isSelected ? ' selected' : '');
|
||
node.dataset.nodeKind = 'variable';
|
||
node.dataset.nodeId = variable.id;
|
||
node.style.left = `${variable.x}px`;
|
||
node.style.top = `${variable.y}px`;
|
||
const value = Object.prototype.hasOwnProperty.call(state.variables, variable.name)
|
||
? state.variables[variable.name]
|
||
: '—';
|
||
node.innerHTML = `
|
||
<div class="gnode-body">
|
||
<div class="gnode-head">
|
||
<span class="gnode-badge">Переменная</span>
|
||
<span class="gnode-kind">${esc(String(value)).slice(0, 22)}</span>
|
||
</div>
|
||
<div class="gnode-title"></div>
|
||
<div class="gnode-sub">соедините с ⌘-портом слайда</div>
|
||
</div>
|
||
<div class="gnode-ports">
|
||
${portHtml('variable', variable.id, 'value', 'out', `{{${variable.name}}}`, 'data')}
|
||
</div>`;
|
||
node.querySelector('.gnode-title').textContent = variable.name;
|
||
bindGraphNode(node, 'variable', variable.id);
|
||
graphNodesEl.appendChild(node);
|
||
bindPortEvents(node, 'variable', variable.id);
|
||
});
|
||
|
||
(state.graph.transitions || []).forEach((transNode) => {
|
||
track(transNode.x, transNode.y, 250, 240);
|
||
const node = document.createElement('div');
|
||
const isSelected = selectedNode && selectedNode.type === 'transition' && selectedNode.id === transNode.id;
|
||
node.className = 'gnode transition' + (isSelected ? ' selected' : '');
|
||
node.dataset.nodeKind = 'transition';
|
||
node.dataset.nodeId = transNode.id;
|
||
node.style.left = `${transNode.x}px`;
|
||
node.style.top = `${transNode.y}px`;
|
||
const slideIndex = state.slides.findIndex((item) => item.id === transNode.slideId);
|
||
node.innerHTML = `
|
||
<div class="gnode-body">
|
||
<div class="gnode-head">
|
||
<span class="gnode-badge">Переход</span>
|
||
<span class="gnode-kind"></span>
|
||
</div>
|
||
<div class="gnode-title"></div>
|
||
<pre class="gnode-code"></pre>
|
||
</div>
|
||
<div class="gnode-ports">
|
||
${portHtml('transition', transNode.id, 'in', 'in', 'вход', 'transition')}
|
||
${portHtml('transition', transNode.id, 'out', 'out', 'выход', 'transition')}
|
||
</div>`;
|
||
node.querySelector('.gnode-kind').textContent = slideIndex >= 0 ? `слайд ${slideIndex + 1}` : 'не привязан';
|
||
node.querySelector('.gnode-title').textContent = transNode.name || 'Переход';
|
||
node.querySelector('.gnode-code').textContent = String(transNode.code || '').split('\n').slice(0, 2).join('\n') || '— пустой код —';
|
||
bindGraphNode(node, 'transition', transNode.id);
|
||
graphNodesEl.appendChild(node);
|
||
bindPortEvents(node, 'transition', transNode.id);
|
||
});
|
||
|
||
(state.graph.anims || []).forEach((animNode) => {
|
||
track(animNode.x, animNode.y, 250, 240);
|
||
const node = document.createElement('div');
|
||
const isSelected = selectedNode && selectedNode.type === 'anim' && selectedNode.id === animNode.id;
|
||
node.className = 'gnode anim' + (isSelected ? ' selected' : '');
|
||
node.dataset.nodeKind = 'anim';
|
||
node.dataset.nodeId = animNode.id;
|
||
node.style.left = `${animNode.x}px`;
|
||
node.style.top = `${animNode.y}px`;
|
||
const slideIndex = state.slides.findIndex((item) => item.id === animNode.slideId);
|
||
const linkedEl = slideIndex >= 0
|
||
? (state.slides[slideIndex].elements || []).find((item) => item.id === animNode.elementId)
|
||
: null;
|
||
node.innerHTML = `
|
||
<div class="gnode-body">
|
||
<div class="gnode-head">
|
||
<span class="gnode-badge">Анимация</span>
|
||
<span class="gnode-kind"></span>
|
||
</div>
|
||
<div class="gnode-title"></div>
|
||
<pre class="gnode-code"></pre>
|
||
</div>
|
||
<div class="gnode-ports">
|
||
${portHtml('anim', animNode.id, 'in', 'in', 'вход', 'anim')}
|
||
${portHtml('anim', animNode.id, 'out', 'out', 'выход', 'anim')}
|
||
</div>`;
|
||
node.querySelector('.gnode-kind').textContent = linkedEl
|
||
? `эл.: ${linkedEl.type}`
|
||
: slideIndex >= 0 ? `слайд ${slideIndex + 1}` : 'не привязан';
|
||
node.querySelector('.gnode-title').textContent = animNode.name || 'Анимация';
|
||
node.querySelector('.gnode-code').textContent = String(animNode.code || '').split('\n').slice(0, 2).join('\n') || '— пустой код —';
|
||
bindGraphNode(node, 'anim', animNode.id);
|
||
graphNodesEl.appendChild(node);
|
||
bindPortEvents(node, 'anim', animNode.id);
|
||
});
|
||
|
||
(state.graph.plugins || []).forEach((pluginNode) => {
|
||
track(pluginNode.x, pluginNode.y, 250, 240);
|
||
const node = document.createElement('div');
|
||
const isSelected = selectedNode && selectedNode.type === 'plugin' && selectedNode.id === pluginNode.id;
|
||
node.className = 'gnode plugin' + (isSelected ? ' selected' : '');
|
||
node.dataset.nodeKind = 'plugin';
|
||
node.dataset.nodeId = pluginNode.id;
|
||
node.style.left = `${pluginNode.x}px`;
|
||
node.style.top = `${pluginNode.y}px`;
|
||
const fn = pluginNode.fn || 'function';
|
||
node.innerHTML = `
|
||
<div class="gnode-body">
|
||
<div class="gnode-head">
|
||
<span class="gnode-badge">Плагин</span>
|
||
<span class="gnode-kind"></span>
|
||
</div>
|
||
<div class="gnode-title"></div>
|
||
<div class="gnode-sub"></div>
|
||
<pre class="gnode-code"></pre>
|
||
</div>
|
||
<div class="gnode-ports">
|
||
${portHtml('plugin', pluginNode.id, 'in', 'in', 'вход', 'plugin')}
|
||
${portHtml('plugin', pluginNode.id, 'out', 'out', 'выход', 'plugin')}
|
||
</div>`;
|
||
node.querySelector('.gnode-kind').textContent = pluginNode.pluginId ? 'Lua-модуль' : 'без плагина';
|
||
node.querySelector('.gnode-title').textContent = pluginNode.name || fn;
|
||
node.querySelector('.gnode-sub').textContent = pluginNode.description || `${fn}() · ${pluginNode.args ? `аргументы: ${pluginNode.args}` : 'без аргументов'}`;
|
||
node.querySelector('.gnode-code').textContent = `function ${fn}(…)`;
|
||
bindGraphNode(node, 'plugin', pluginNode.id);
|
||
graphNodesEl.appendChild(node);
|
||
bindPortEvents(node, 'plugin', pluginNode.id);
|
||
});
|
||
|
||
graphWorld.style.width = `${maxX}px`;
|
||
graphWorld.style.height = `${maxY}px`;
|
||
if (!state.slides.length) {
|
||
const empty = document.createElement('div');
|
||
empty.className = 'graph-empty';
|
||
empty.textContent = 'Добавьте слайд, чтобы построить граф.';
|
||
graphNodesEl.appendChild(empty);
|
||
}
|
||
drawGraphEdges();
|
||
}
|
||
|
||
function edgeGeometry(from, to) {
|
||
const bend = Math.max(44, Math.abs(to.x - from.x) * 0.42);
|
||
return `M ${from.x} ${from.y} C ${from.x + bend} ${from.y}, ${to.x - bend} ${to.y}, ${to.x} ${to.y}`;
|
||
}
|
||
|
||
function drawGraphEdges() {
|
||
if (!graphSvg) return;
|
||
const portMap = new Map();
|
||
graphNodesEl.querySelectorAll('.gport').forEach((el) => {
|
||
portMap.set(`${el.dataset.linkNodeKind}|${el.dataset.linkNodeId}|${el.dataset.portKey}`, el);
|
||
});
|
||
const worldRect = graphWorld.getBoundingClientRect();
|
||
const pointOf = (ref) => {
|
||
const el = portMap.get(`${ref.kind}|${ref.id}|${ref.port}`);
|
||
if (!el) return null;
|
||
const rect = el.getBoundingClientRect();
|
||
return {
|
||
x: rect.left - worldRect.left + rect.width / 2,
|
||
y: rect.top - worldRect.top + rect.height / 2,
|
||
};
|
||
};
|
||
|
||
const colors = LINK_COLORS;
|
||
const defs = `<defs>${Object.entries(colors).map(([kind, color]) => `
|
||
<marker id="graph-arrow-${kind}" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto">
|
||
<path d="M0,0 L10,5 L0,10 z" fill="${color}"></path>
|
||
</marker>`).join('')}</defs>`;
|
||
|
||
const paths = [];
|
||
state.graph.links.forEach((link) => {
|
||
const from = pointOf(link.from);
|
||
const to = pointOf(link.to);
|
||
if (!from || !to) return;
|
||
const kind = linkKind(link);
|
||
const color = colors[kind] || colors.nav;
|
||
const selected = state.selectedLink === link.id;
|
||
paths.push(`<path class="edge${selected ? ' selected' : ''}" data-link-id="${link.id}" d="${edgeGeometry(from, to)}" fill="none" stroke="${color}" stroke-width="${selected ? 2.8 : 1.7}" stroke-opacity="${selected ? 1 : 0.78}" marker-end="url(#graph-arrow-${kind})"></path>`);
|
||
});
|
||
|
||
if (state.linkDraft) {
|
||
const draft = state.linkDraft;
|
||
const anchor = pointOf(draft.from);
|
||
if (anchor) {
|
||
const from = draft.from.dir === 'out' ? anchor : { x: draft.x, y: draft.y };
|
||
const to = draft.from.dir === 'out' ? { x: draft.x, y: draft.y } : anchor;
|
||
const kind = draft.from.kind === 'variable' ? 'data' : 'nav';
|
||
paths.push(`<path d="${edgeGeometry(from, to)}" fill="none" stroke="${colors[kind]}" stroke-width="2" stroke-dasharray="6 5" opacity="0.85" marker-end="url(#graph-arrow-${kind})"></path>`);
|
||
}
|
||
}
|
||
|
||
graphSvg.innerHTML = defs + paths.join('');
|
||
}
|
||
|
||
let graphDrag = null;
|
||
|
||
function bindGraphNode(nodeEl, kind, id) {
|
||
nodeEl.addEventListener('pointerdown', (event) => {
|
||
if (event.button !== 0) return;
|
||
if (event.target.closest && event.target.closest('.gport')) return;
|
||
event.preventDefault();
|
||
event.stopPropagation();
|
||
const point = nodeRef(kind, id);
|
||
if (!point) return;
|
||
graphDrag = {
|
||
kind,
|
||
id,
|
||
point,
|
||
startX: event.clientX,
|
||
startY: event.clientY,
|
||
originX: point.x,
|
||
originY: point.y,
|
||
moved: false,
|
||
};
|
||
window.addEventListener('pointermove', onGraphPointerMove);
|
||
window.addEventListener('pointerup', onGraphPointerUp);
|
||
document.body.style.cursor = 'grabbing';
|
||
});
|
||
}
|
||
|
||
function bindPortEvents(nodeEl, kind, id) {
|
||
nodeEl.querySelectorAll('.gport').forEach((portEl) => {
|
||
portEl.addEventListener('pointerdown', (event) => {
|
||
if (event.button !== 0) return;
|
||
event.preventDefault();
|
||
event.stopPropagation();
|
||
startLinkDrag({
|
||
kind,
|
||
id,
|
||
port: portEl.dataset.portKey,
|
||
dir: portEl.dataset.portKind,
|
||
}, event);
|
||
});
|
||
portEl.addEventListener('click', (event) => event.stopPropagation());
|
||
});
|
||
}
|
||
|
||
function startLinkDrag(from, event) {
|
||
const rect = graphWorld.getBoundingClientRect();
|
||
state.linkDraft = { from, x: event.clientX - rect.left, y: event.clientY - rect.top };
|
||
graphWorld.classList.add('drafting');
|
||
document.body.style.cursor = 'crosshair';
|
||
drawGraphEdges();
|
||
window.addEventListener('pointermove', onLinkMove);
|
||
window.addEventListener('pointerup', onLinkUp);
|
||
}
|
||
|
||
function onLinkMove(event) {
|
||
if (!state.linkDraft) return;
|
||
const rect = graphWorld.getBoundingClientRect();
|
||
state.linkDraft.x = event.clientX - rect.left;
|
||
state.linkDraft.y = event.clientY - rect.top;
|
||
drawGraphEdges();
|
||
}
|
||
|
||
function canLink(out, inp) {
|
||
if (out.dir !== 'out' || inp.dir !== 'in') return false;
|
||
if (out.kind === 'variable') {
|
||
return out.port === 'value' && inp.kind === 'slide' && String(inp.port).startsWith('var:');
|
||
}
|
||
if (inp.kind === 'slide' && String(inp.port).startsWith('var:')) return false;
|
||
if (out.kind === 'slide' && (out.port === 'next' || out.port === 'prev')) {
|
||
return inp.port === 'in' && (inp.kind === 'slide' || PASS_THROUGH_KINDS.has(inp.kind));
|
||
}
|
||
if (inp.kind === 'slide') return inp.port === 'in';
|
||
if (inp.kind === 'script' || inp.kind === 'audio') return inp.port === 'in';
|
||
if (PASS_THROUGH_KINDS.has(inp.kind)) return inp.port === 'in';
|
||
return false;
|
||
}
|
||
|
||
function onLinkUp(event) {
|
||
window.removeEventListener('pointermove', onLinkMove);
|
||
window.removeEventListener('pointerup', onLinkUp);
|
||
graphWorld.classList.remove('drafting');
|
||
document.body.style.cursor = '';
|
||
const draft = state.linkDraft;
|
||
state.linkDraft = null;
|
||
if (!draft) return;
|
||
const hit = document.elementFromPoint(event.clientX, event.clientY);
|
||
const portEl = hit && hit.closest ? hit.closest('.gport') : null;
|
||
if (!portEl) { drawGraphEdges(); return; }
|
||
const target = {
|
||
kind: portEl.dataset.linkNodeKind,
|
||
id: portEl.dataset.linkNodeId,
|
||
port: portEl.dataset.portKey,
|
||
dir: portEl.dataset.portKind,
|
||
};
|
||
if (target.kind === draft.from.kind && target.id === draft.from.id && target.port === draft.from.port) {
|
||
drawGraphEdges();
|
||
return;
|
||
}
|
||
const out = draft.from.dir === 'out' ? draft.from : target;
|
||
const inp = draft.from.dir === 'out' ? target : draft.from;
|
||
if (!canLink(out, inp)) {
|
||
toast('Соединяйте выход со входом: слайд, переход, анимация, плагин, код или аудио');
|
||
drawGraphEdges();
|
||
return;
|
||
}
|
||
addGraphLink(out, inp);
|
||
}
|
||
|
||
function addGraphLink(out, inp) {
|
||
if (inp.kind === 'slide' && inp.port.startsWith('var:')) {
|
||
state.graph.links = state.graph.links.filter((link) =>
|
||
!(link.to.kind === 'slide' && link.to.id === inp.id && link.to.port === inp.port)
|
||
);
|
||
}
|
||
// У навигационных и pass-through выходов может быть только одна ветка.
|
||
const singleOut = (out.kind === 'slide' && (out.port === 'next' || out.port === 'prev'))
|
||
|| (PASS_THROUGH_KINDS.has(out.kind) && out.port === 'out');
|
||
if (singleOut) {
|
||
state.graph.links = state.graph.links.filter((link) =>
|
||
!(link.from.kind === out.kind && link.from.id === out.id && link.from.port === out.port)
|
||
);
|
||
}
|
||
state.graph.links = state.graph.links.filter((link) =>
|
||
!(link.from.kind === out.kind && link.from.id === out.id && link.from.port === out.port
|
||
&& link.to.kind === inp.kind && link.to.id === inp.id && link.to.port === inp.port)
|
||
);
|
||
state.graph.links.push({
|
||
id: uid(),
|
||
from: { kind: out.kind, id: out.id, port: out.port },
|
||
to: { kind: inp.kind, id: inp.id, port: inp.port },
|
||
});
|
||
applyGraphLinks();
|
||
state.selectedLink = null;
|
||
renderAll();
|
||
scheduleSave();
|
||
toast('Связь добавлена');
|
||
}
|
||
|
||
function removeGraphLink(linkId) {
|
||
const link = state.graph.links.find((item) => item.id === linkId);
|
||
if (!link) return;
|
||
if (link.from.kind === 'variable' && link.to.kind === 'slide' && link.to.port.startsWith('var:')) {
|
||
const parts = link.to.port.split(':');
|
||
if (parts.length >= 3) removeVarPlaceholder(parts[1], parts.slice(2).join(':'));
|
||
}
|
||
state.graph.links = state.graph.links.filter((item) => item.id !== linkId);
|
||
if (link.from.kind === 'slide' && link.from.port.startsWith('btn:')) {
|
||
const elementId = link.from.port.slice(4);
|
||
const slide = state.slides.find((item) => item.id === link.from.id);
|
||
const button = slide && (slide.elements || []).find((item) => item.id === elementId);
|
||
if (button) button.action = { type: 'none', slideIndex: 0, audioId: '', code: '', scriptNodeId: '' };
|
||
}
|
||
applyGraphLinks();
|
||
state.selectedLink = null;
|
||
renderAll();
|
||
scheduleSave();
|
||
toast('Связь удалена');
|
||
}
|
||
|
||
function onGraphPointerMove(event) {
|
||
if (!graphDrag) return;
|
||
const dx = event.clientX - graphDrag.startX;
|
||
const dy = event.clientY - graphDrag.startY;
|
||
if (Math.abs(dx) > 3 || Math.abs(dy) > 3) graphDrag.moved = true;
|
||
graphDrag.point.x = Math.max(0, graphDrag.originX + dx);
|
||
graphDrag.point.y = Math.max(0, graphDrag.originY + dy);
|
||
const node = graphNodesEl.querySelector(
|
||
`[data-node-kind="${graphDrag.kind}"][data-node-id="${graphDrag.id}"]`
|
||
);
|
||
if (node) {
|
||
node.style.left = `${graphDrag.point.x}px`;
|
||
node.style.top = `${graphDrag.point.y}px`;
|
||
}
|
||
drawGraphEdges();
|
||
}
|
||
|
||
function onGraphPointerUp() {
|
||
window.removeEventListener('pointermove', onGraphPointerMove);
|
||
window.removeEventListener('pointerup', onGraphPointerUp);
|
||
document.body.style.cursor = '';
|
||
if (!graphDrag) return;
|
||
const dragState = graphDrag;
|
||
graphDrag = null;
|
||
if (dragState.moved) {
|
||
scheduleSave();
|
||
renderGraph();
|
||
} else {
|
||
selectGraphNode(dragState.kind, dragState.id);
|
||
}
|
||
}
|
||
|
||
function selectGraphNode(kind, id) {
|
||
if (kind === 'slide') {
|
||
const index = state.slides.findIndex((slide) => slide.id === id);
|
||
if (index < 0) return;
|
||
state.selected = index;
|
||
state.selectedEl = null;
|
||
state.selectedNode = { type: 'slide', id };
|
||
} else if (kind === 'script') {
|
||
const script = findScriptNode(id);
|
||
if (!script) return;
|
||
state.selectedNode = { type: 'script', id };
|
||
const linked = findLinkedElement(script);
|
||
if (linked) {
|
||
const index = state.slides.indexOf(linked.slide);
|
||
if (index >= 0) {
|
||
state.selected = index;
|
||
state.selectedEl = linked.element.id;
|
||
}
|
||
}
|
||
} else if (kind === 'audio') {
|
||
if (!findAudioNode(id)) return;
|
||
state.selectedNode = { type: 'audio', id };
|
||
} else if (kind === 'variable') {
|
||
if (!findVariableNode(id)) return;
|
||
state.selectedNode = { type: 'variable', id };
|
||
} else if (kind === 'transition') {
|
||
if (!findTransitionNode(id)) return;
|
||
state.selectedNode = { type: 'transition', id };
|
||
} else if (kind === 'anim') {
|
||
if (!findAnimNode(id)) return;
|
||
state.selectedNode = { type: 'anim', id };
|
||
} else if (kind === 'plugin') {
|
||
if (!findPluginNode(id)) return;
|
||
state.selectedNode = { type: 'plugin', id };
|
||
}
|
||
state.selectedLink = null;
|
||
renderAll();
|
||
}
|
||
|
||
|
||
// ==================== Инспектор ====================
|
||
function option(value, label, current) {
|
||
return `<option value="${esc(value)}"${value === current ? ' selected' : ''}>${esc(label)}</option>`;
|
||
}
|
||
|
||
function audioOptions(current) {
|
||
const options = [];
|
||
state.slides.forEach((slide, index) => {
|
||
(slide.elements || []).forEach((element) => {
|
||
if (element.type !== 'audio') return;
|
||
const label = `${element.label || element.src || 'Аудио'} · слайд ${index + 1}`;
|
||
options.push(option(element.id, label, current));
|
||
});
|
||
});
|
||
if (!options.length) return '<option value="">— нет аудио на слайдах —</option>';
|
||
return options.join('');
|
||
}
|
||
|
||
function slideOptions(current) {
|
||
return state.slides.map((_, index) => option(String(index), `Слайд ${index + 1}`, String(current))).join('');
|
||
}
|
||
|
||
function geometryFields(element) {
|
||
return `
|
||
<div class="row-4">
|
||
<label class="fld"><span class="label">X %</span><input type="number" data-prop="x" step="1" value="${Number(element.x) || 0}"></label>
|
||
<label class="fld"><span class="label">Y %</span><input type="number" data-prop="y" step="1" value="${Number(element.y) || 0}"></label>
|
||
<label class="fld"><span class="label">Ш %</span><input type="number" data-prop="w" step="1" min="2" value="${Number(element.w) || 10}"></label>
|
||
<label class="fld"><span class="label">В %</span><input type="number" data-prop="h" step="1" min="2" value="${Number(element.h) || 10}"></label>
|
||
</div>`;
|
||
}
|
||
|
||
function elementInspector(element) {
|
||
const typeNames = { text: 'Текст', image: 'Картинка', shape: 'Фигура', button: 'Кнопка', audio: 'Аудио', video: 'Видео', window: 'Окно Chrome', lua: 'Lua-элемент' };
|
||
let fields = '';
|
||
|
||
if (element.type === 'text') {
|
||
const textVars = [...String(element.text || '').matchAll(/\{\{\s*([\w.-]+)\s*\}\}/g)].map((match) => match[1]);
|
||
const currentVar = textVars[0] || '';
|
||
const varNames = [...new Set([
|
||
...(state.graph.variables || []).map((node) => node.name),
|
||
...Object.keys(state.variables || {}),
|
||
])].filter(Boolean);
|
||
if (currentVar && !varNames.includes(currentVar)) varNames.unshift(currentVar);
|
||
fields = `
|
||
<label class="fld"><span class="label">Текст</span>
|
||
<textarea data-prop="text" rows="3" placeholder="Текст слайда">${esc(element.text || '')}</textarea>
|
||
</label>
|
||
<label class="fld"><span class="label">Переменная</span>
|
||
<select data-var-bind="${esc(element.id)}">
|
||
<option value="">— без переменной —</option>
|
||
${varNames.map((name) => option(name, `{{${name}}} · ${state.variables[name] ?? '—'}`, currentVar)).join('')}
|
||
</select>
|
||
</label>
|
||
<div class="row-2">
|
||
<label class="fld"><span class="label">Размер (cwq)</span><input type="number" data-prop="fontSize" step="0.1" min="0.6" value="${Number(element.fontSize) || 5}"></label>
|
||
<label class="fld"><span class="label">Цвет</span><input type="color" data-prop="color" value="${esc(element.color || '#f8fafc')}"></label>
|
||
</div>
|
||
<div class="row-2">
|
||
<label class="fld"><span class="label">Насыщенность</span>
|
||
<select data-prop="weight">
|
||
${option('300', 'Light', String(element.weight))}
|
||
${option('400', 'Regular', String(element.weight))}
|
||
${option('600', 'Semibold', String(element.weight))}
|
||
${option('700', 'Bold', String(element.weight))}
|
||
${option('800', 'Extra bold', String(element.weight))}
|
||
</select>
|
||
</label>
|
||
<label class="fld"><span class="label">Выравнивание</span>
|
||
<select data-prop="align">
|
||
${option('left', 'Слева', element.align)}
|
||
${option('center', 'По центру', element.align)}
|
||
${option('right', 'Справа', element.align)}
|
||
</select>
|
||
</label>
|
||
</div>
|
||
<div class="row-2">
|
||
<label class="fld"><span class="label">Шрифт</span>
|
||
<select data-prop="font">
|
||
${FONT_OPTIONS.map(([value, label]) => option(value, label, element.font || 'sans')).join('')}
|
||
</select>
|
||
</label>
|
||
<label class="fld"><span class="label">Межстрочный</span>
|
||
<input type="number" data-prop="lineHeight" step="0.05" min="0.8" max="3" value="${Number(element.lineHeight) || 1.16}">
|
||
</label>
|
||
</div>
|
||
<div class="row-2">
|
||
<div class="fld">
|
||
<label class="checkline"><input type="checkbox" data-prop="italic" ${element.italic ? 'checked' : ''}> Курсив</label>
|
||
<label class="checkline"><input type="checkbox" data-prop="shadow" ${element.shadow ? 'checked' : ''}> Тень текста</label>
|
||
</div>
|
||
<label class="fld"><span class="label">Подложка (CSS)</span>
|
||
<input data-prop="bg" value="${esc(element.bg || '')}" placeholder="rgba(15, 23, 42, .6)">
|
||
</label>
|
||
</div>
|
||
<p class="hint">Переменные подставляются как <code>{{name}}</code>.</p>`;
|
||
} else if (element.type === 'image') {
|
||
fields = `
|
||
<label class="fld"><span class="label">URL изображения</span>
|
||
<input type="url" data-prop="src" value="${esc(element.src || '')}" placeholder="https://images.unsplash.com/...">
|
||
</label>
|
||
<div class="upload-line">
|
||
<button class="ghost" data-act="image-upload">Загрузить файл</button>
|
||
<span class="file-name">${element.src ? esc(String(element.src).split('/').pop().slice(0, 30)) : 'файл не выбран'}</span>
|
||
<input type="file" data-upload="image" accept="image/*" hidden>
|
||
</div>
|
||
<div class="row-2">
|
||
<label class="fld"><span class="label">Вписывание</span>
|
||
<select data-prop="fit">
|
||
${option('cover', 'Заполнить', element.fit)}
|
||
${option('contain', 'Вписать', element.fit)}
|
||
</select>
|
||
</label>
|
||
<label class="fld"><span class="label">Скругление</span><input type="number" data-prop="radius" min="0" step="1" value="${Number(element.radius) || 0}"></label>
|
||
</div>
|
||
<label class="checkline"><input type="checkbox" data-prop="shadow" ${element.shadow ? 'checked' : ''}> Тень</label>`;
|
||
} else if (element.type === 'shape') {
|
||
fields = `
|
||
<label class="fld"><span class="label">Фигура</span>
|
||
<select data-prop="shape">
|
||
${SHAPE_OPTIONS.map(([value, label]) => option(value, label, element.shape)).join('')}
|
||
</select>
|
||
</label>
|
||
<label class="fld"><span class="label">Заливка (цвет или rgba)</span>
|
||
<div class="palette">
|
||
${SHAPE_FILLS.map((color) => `<button class="p-swatch${element.fill === color ? ' active' : ''}" data-fill="${color}" style="background:${color}" title="${color}"></button>`).join('')}
|
||
</div>
|
||
<input data-prop="fill" value="${esc(element.fill || '#6366f1')}" placeholder="#6366f1 или rgba(99,102,241,.2)">
|
||
</label>
|
||
<div class="row-2">
|
||
<label class="fld"><span class="label">Обводка (цвет/rgba)</span><input data-prop="borderColor" value="${esc(element.borderColor || '')}" placeholder="без обводки"></label>
|
||
<label class="fld"><span class="label">Толщина обводки</span><input type="number" data-prop="borderWidth" min="0" max="20" step="0.5" value="${Number(element.borderWidth) || 0}"></label>
|
||
</div>
|
||
<div class="row-2">
|
||
<label class="fld"><span class="label">Скругление углов</span><input type="number" data-prop="radius" min="0" max="45" step="1" value="${Number(element.radius) || 0}"></label>
|
||
<div class="fld">
|
||
<label class="checkline"><input type="checkbox" data-prop="shadow" ${element.shadow ? 'checked' : ''}> Тень</label>
|
||
</div>
|
||
</div>
|
||
<p class="hint">Фигуры — быстрый способ строить схемы, плашки и акценты. В заливку и обводку можно писать <code>rgba(99,102,241,.2)</code> для полупрозрачности.</p>`;
|
||
} else if (element.type === 'button') {
|
||
const action = element.action || { type: 'next' };
|
||
let actionFields = '';
|
||
if (action.type === 'go') {
|
||
actionFields = `<label class="fld"><span class="label">Целевой слайд</span><select data-prop="action.slideIndex">${slideOptions(Number(action.slideIndex) || 0)}</select></label>`;
|
||
} else if (action.type === 'play' || action.type === 'stop') {
|
||
actionFields = `
|
||
<label class="fld"><span class="label">Аудиоэлемент</span>
|
||
<select data-prop="action.audioId">
|
||
${action.type === 'stop' ? '<option value="">— остановить всё —</option>' : ''}
|
||
${audioOptions(action.audioId)}
|
||
</select>
|
||
</label>`;
|
||
} else if (action.type === 'lua') {
|
||
actionFields = `
|
||
<label class="fld"><span class="label">Lua-код</span>
|
||
<textarea data-prop="action.code" rows="4" placeholder="vars.score = vars.score + 1 app.log(vars.score)">${esc(action.code || '')}</textarea>
|
||
</label>`;
|
||
}
|
||
|
||
fields = `
|
||
<label class="fld"><span class="label">Подпись</span><input data-prop="label" value="${esc(element.label || '')}"></label>
|
||
<div class="row-2">
|
||
<label class="fld"><span class="label">Фон</span><input type="color" data-prop="bg" value="${esc(element.bg || '#6366f1')}"></label>
|
||
<label class="fld"><span class="label">Текст</span><input type="color" data-prop="color" value="${esc(element.color || '#ffffff')}"></label>
|
||
</div>
|
||
<div class="row-2">
|
||
<label class="fld"><span class="label">Размер</span><input type="number" data-prop="fontSize" step="0.1" min="0.6" value="${Number(element.fontSize) || 2.2}"></label>
|
||
<label class="fld"><span class="label">Скругление</span><input type="number" data-prop="radius" min="0" step="1" value="${Number(element.radius) || 12}"></label>
|
||
</div>
|
||
<label class="fld"><span class="label">Действие кнопки</span>
|
||
<select data-prop="action.type">
|
||
${option('none', 'Без действия', action.type)}
|
||
${option('go', 'Перейти на слайд', action.type)}
|
||
${option('next', 'Следующий слайд', action.type)}
|
||
${option('prev', 'Предыдущий слайд', action.type)}
|
||
${option('play', 'Запустить аудио', action.type)}
|
||
${option('stop', 'Остановить аудио', action.type)}
|
||
${option('lua', 'Выполнить Lua', action.type)}
|
||
</select>
|
||
</label>
|
||
${actionFields}
|
||
<p class="hint">Кнопки и аудио управляются докладчиком в режиме показа.</p>`;
|
||
} else if (element.type === 'audio') {
|
||
fields = `
|
||
<label class="fld"><span class="label">URL аудио</span>
|
||
<input type="url" data-prop="src" value="${esc(element.src || '')}" placeholder="https://example.com/sound.mp3">
|
||
</label>
|
||
<label class="fld"><span class="label">Подпись</span><input data-prop="label" value="${esc(element.label || '')}"></label>
|
||
<div class="row-2">
|
||
<label class="fld"><span class="label">Громкость</span><input type="range" data-prop="volume" min="0" max="100" step="1" value="${Math.round(clamp01v(element.volume, 0.8) * 100)}"></label>
|
||
<div class="fld">
|
||
<label class="checkline"><input type="checkbox" data-prop="loop" ${element.loop ? 'checked' : ''}> Повтор</label>
|
||
<label class="checkline"><input type="checkbox" data-prop="visible" ${element.visible !== false ? 'checked' : ''}> Видно на слайде</label>
|
||
</div>
|
||
</div>
|
||
<div class="field-actions">
|
||
<button data-act="audio-preview">▶ Прослушать</button>
|
||
<button data-act="audio-to-music">Сделать фоновой</button>
|
||
</div>
|
||
<p class="hint">Скрытое аудио (без галочки «Видно») запускается только докладчиком с панели интерактива.</p>`;
|
||
} else if (element.type === 'video') {
|
||
fields = `
|
||
<label class="fld"><span class="label">Ссылка на видео</span>
|
||
<input type="url" data-prop="src" value="${esc(element.src || '')}" placeholder="https://example.com/video.mp4">
|
||
</label>
|
||
<div class="upload-line">
|
||
<button class="ghost" data-act="video-upload">Загрузить файл</button>
|
||
<span class="file-name">${element.src ? esc(String(element.src).split('/').pop()) : 'файл не выбран'}</span>
|
||
<input type="file" data-upload="video" accept="video/*" hidden>
|
||
</div>
|
||
<label class="fld"><span class="label">Постер (URL)</span>
|
||
<input type="url" data-prop="poster" value="${esc(element.poster || '')}" placeholder="Необязательно">
|
||
</label>
|
||
<label class="fld"><span class="label">Подпись</span><input data-prop="label" value="${esc(element.label || '')}"></label>
|
||
<div class="row-2">
|
||
<label class="fld"><span class="label">Вписывание</span>
|
||
<select data-prop="fit">
|
||
${option('cover', 'Заполнить', element.fit)}
|
||
${option('contain', 'Вписать', element.fit)}
|
||
</select>
|
||
</label>
|
||
<label class="fld"><span class="label">Скругление</span><input type="number" data-prop="radius" min="0" step="1" value="${Number(element.radius) || 0}"></label>
|
||
</div>
|
||
<div class="row-2">
|
||
<div class="fld">
|
||
<label class="checkline"><input type="checkbox" data-prop="autoplay" ${element.autoplay !== false ? 'checked' : ''}> Автозапуск</label>
|
||
<label class="checkline"><input type="checkbox" data-prop="loop" ${element.loop ? 'checked' : ''}> Повтор</label>
|
||
</div>
|
||
<div class="fld">
|
||
<label class="checkline"><input type="checkbox" data-prop="muted" ${element.muted !== false ? 'checked' : ''}> Без звука</label>
|
||
<label class="checkline"><input type="checkbox" data-prop="controls" ${element.controls !== false ? 'checked' : ''}> Управление</label>
|
||
</div>
|
||
</div>
|
||
<p class="hint">Файл сохраняется на сервере в <code>public/uploads</code>. Докладчик управляет видео, зрители получают те же команды.</p>`;
|
||
} else if (element.type === 'window') {
|
||
const current = String(element.targetId || '');
|
||
const known = state.windowTargets.some((target) => target.id === current);
|
||
const targetOptions = state.windowTargets.map((target) =>
|
||
option(target.id, `${target.title || 'Без названия'} — ${target.url || ''}`.slice(0, 90), current)
|
||
);
|
||
if (current && !known) targetOptions.unshift(option(current, `Сохранённая цель · ${current.slice(0, 12)}`, current));
|
||
if (!targetOptions.length) targetOptions.push('<option value="">— окна Chrome не найдены —</option>');
|
||
fields = `
|
||
<label class="fld"><span class="label">Окно Chrome</span>
|
||
<select data-prop="targetId" id="window-target-select">${targetOptions.join('')}</select>
|
||
</label>
|
||
<div class="field-actions">
|
||
<button data-act="window-refresh">↻ Обновить список окон</button>
|
||
</div>
|
||
<label class="fld"><span class="label">Подпись</span><input data-prop="label" value="${esc(element.label || '')}"></label>
|
||
<div class="row-2">
|
||
<label class="fld"><span class="label">Скругление</span><input type="number" data-prop="radius" min="0" step="1" value="${Number(element.radius) || 0}"></label>
|
||
<div class="fld">
|
||
<label class="checkline"><input type="checkbox" data-prop="autoStart" ${element.autoStart !== false ? 'checked' : ''}> Запускать сразу</label>
|
||
</div>
|
||
</div>
|
||
<p class="hint">Запустите отдельный Chrome с <code>--remote-debugging-port=9222</code> и отдельным <code>--user-data-dir</code>. Клики по трансляции и пульт докладчика управляют этим окном. Произвольные нативные приложения браузер перехватывать не может.</p>`;
|
||
} else if (element.type === 'lua') {
|
||
const computed = element.computed || {};
|
||
const styleKeys = Object.keys(computed.style || {});
|
||
fields = `
|
||
<label class="fld"><span class="label">Подпись</span><input data-prop="label" value="${esc(element.label || '')}"></label>
|
||
<div class="fld">
|
||
<span class="label">Lua-код · верните таблицу</span>
|
||
${luaEditorMarkup({ prop: 'code', value: element.code || DEFAULT_LUA_ELEMENT, rows: 12 })}
|
||
</div>
|
||
<p class="hint">Верните таблицу с полями <code>style</code>, <code>css</code>, <code>html</code>, <code>text</code>. Ключи стиля — как в JS: <code>backgroundColor</code>, <code>borderRadius</code>, <code>fontSize: '1.8cqw'</code>. Можно вернуть просто строку — она станет текстом.</p>
|
||
<div class="field-actions">
|
||
<button class="primary" data-act="lua-compute">▶ Вычислить</button>
|
||
<button data-act="lua-reset">Сбросить стили</button>
|
||
</div>
|
||
<div class="muted">Вычислено: ${computed.at ? new Date(computed.at).toLocaleString('ru-RU') : 'ещё нет'} · стилей: ${styleKeys.length}${computed.html ? ' · есть HTML' : ''}${computed.css ? ' · есть CSS' : ''}</div>`;
|
||
}
|
||
|
||
return `
|
||
<div class="insp-card">
|
||
<div class="insp-head">
|
||
<span class="insp-title">${typeNames[element.type] || 'Элемент'}</span>
|
||
<div class="insp-btns">
|
||
<button data-act="el-front" title="На передний план">↑</button>
|
||
<button data-act="el-back" title="На задний план">↓</button>
|
||
<button data-act="el-duplicate" title="Дублировать (Ctrl+D)">⧉</button>
|
||
<button data-act="el-delete" class="danger" title="Удалить (Del)">Удалить</button>
|
||
</div>
|
||
</div>
|
||
${geometryFields(element)}
|
||
<div class="fld">
|
||
<span class="label">Выравнивание на слайде</span>
|
||
<div class="align-row">
|
||
<button data-act="align-left" title="К левому краю">⫷</button>
|
||
<button data-act="align-hcenter" title="По центру горизонтально">⇔</button>
|
||
<button data-act="align-right" title="К правому краю">⫸</button>
|
||
<button data-act="align-top" title="К верхнему краю">⤒</button>
|
||
<button data-act="align-vcenter" title="По центру вертикально">⇕</button>
|
||
<button data-act="align-bottom" title="К нижнему краю">⤓</button>
|
||
</div>
|
||
</div>
|
||
<div class="row-2">
|
||
<label class="fld"><span class="label">Прозрачность</span>
|
||
<input type="range" data-prop="opacity" min="0" max="100" step="1" value="${Math.round(clamp01v(element.opacity, 1) * 100)}">
|
||
</label>
|
||
<label class="fld"><span class="label">Поворот, °</span>
|
||
<input type="number" data-prop="rotate" step="1" min="-180" max="180" value="${Number(element.rotate) || 0}">
|
||
</label>
|
||
</div>
|
||
${fields}
|
||
</div>`;
|
||
}
|
||
|
||
const clamp01v = (value, fallback) => {
|
||
const n = Number(value);
|
||
return Number.isFinite(n) ? Math.max(0, Math.min(1, n)) : fallback;
|
||
};
|
||
|
||
function backgroundInspector(slide) {
|
||
const bg = slide.background || defaultBackground();
|
||
const type = bg.type || 'gradient';
|
||
let fields = '';
|
||
if (type === 'color') {
|
||
fields = `
|
||
<label class="fld"><span class="label">Цвет фона</span><input type="color" data-prop="background.color" value="${esc(bg.color || '#0f172a')}"></label>
|
||
<div class="palette">
|
||
${SOLID_PRESETS.map((color) => `<button class="p-swatch${bg.color === color ? ' active' : ''}" data-bgcolor="${color}" style="background:${color}" title="${color}"></button>`).join('')}
|
||
</div>`;
|
||
} else if (type === 'gradient') {
|
||
fields = `
|
||
<label class="fld"><span class="label">CSS-градиент</span>
|
||
<input data-prop="background.gradient" value="${esc(bg.gradient || DEFAULT_GRADIENT)}">
|
||
</label>
|
||
<div class="swatches">
|
||
${GRADIENT_PRESETS.map((preset) => `<button class="swatch" data-bgpreset="${esc(preset)}" style="background:${esc(preset)}" title="Применить градиент"></button>`).join('')}
|
||
</div>`;
|
||
} else {
|
||
fields = `
|
||
<label class="fld"><span class="label">URL фонового изображения</span>
|
||
<input type="url" data-prop="background.image" value="${esc(bg.image || '')}" placeholder="https://images.unsplash.com/...">
|
||
</label>
|
||
<div class="upload-line">
|
||
<button class="ghost" data-act="bg-upload">Загрузить файл</button>
|
||
<span class="file-name">${bg.image ? esc(String(bg.image).split('/').pop().slice(0, 30)) : 'файл не выбран'}</span>
|
||
<input type="file" data-upload="background" accept="image/*" hidden>
|
||
</div>`;
|
||
}
|
||
|
||
return `
|
||
<div class="insp-card">
|
||
<div class="insp-head">
|
||
<span class="insp-title">Слайд ${state.selected + 1}</span>
|
||
<span class="muted">${currentSlide().elements.length} эл.</span>
|
||
</div>
|
||
<div class="fld">
|
||
<span class="label">Фон</span>
|
||
<div class="segmented">
|
||
<button data-bgtype="color" class="${type === 'color' ? 'active' : ''}">Цвет</button>
|
||
<button data-bgtype="gradient" class="${type === 'gradient' ? 'active' : ''}">Градиент</button>
|
||
<button data-bgtype="image" class="${type === 'image' ? 'active' : ''}">Картинка</button>
|
||
</div>
|
||
</div>
|
||
${fields}
|
||
<label class="fld"><span class="label">Переход</span>
|
||
<select data-prop="transition">
|
||
${option('none', 'Без анимации', slide.transition)}
|
||
${option('fade', 'Плавное появление', slide.transition)}
|
||
${option('slide', 'Сдвиг', slide.transition)}
|
||
${option('zoom', 'Приближение', slide.transition)}
|
||
${option('flip', 'Переворот 3D', slide.transition)}
|
||
${option('rise', 'Всплытие', slide.transition)}
|
||
</select>
|
||
</label>
|
||
<label class="fld"><span class="label">Пометки докладчика</span>
|
||
<textarea data-prop="notes" rows="4" placeholder="Что сказать на этом слайде...">${esc(slide.notes || '')}</textarea>
|
||
</label>
|
||
<label class="fld"><span class="label">Lua этого слайда</span>
|
||
<textarea data-prop="lua" rows="4" placeholder="Запускается при входе на слайд vars.count = (vars.count or 0) + 1">${esc(slide.lua || '')}</textarea>
|
||
</label>
|
||
<p class="hint">Lua выполняется у докладчика. Переменные синхронизируются со зрителями.</p>
|
||
</div>`;
|
||
}
|
||
|
||
function buttonLinkOptions(node) {
|
||
const current = node.slideId && node.elementId ? `${node.slideId}|${node.elementId}` : '';
|
||
let html = '<option value="">— не привязана —</option>';
|
||
state.slides.forEach((slide, index) => {
|
||
(slide.elements || []).forEach((element) => {
|
||
if (element.type !== 'button') return;
|
||
const value = `${slide.id}|${element.id}`;
|
||
html += option(value, `Кнопка «${element.label || 'без подписи'}» · слайд ${index + 1}`, current);
|
||
});
|
||
});
|
||
return html;
|
||
}
|
||
|
||
function scriptNodeInspector(node) {
|
||
const linked = findLinkedElement(node);
|
||
return `
|
||
<div class="insp-card">
|
||
<div class="insp-head">
|
||
<span class="insp-title">Lua-нода</span>
|
||
<div class="insp-btns">
|
||
<button data-act="node-delete" class="danger" title="Удалить ноду">Удалить</button>
|
||
</div>
|
||
</div>
|
||
<label class="fld"><span class="label">Название</span>
|
||
<input data-node-prop="name" value="${esc(node.name || '')}">
|
||
</label>
|
||
<label class="fld"><span class="label">Lua-код</span>
|
||
<textarea data-node-prop="code" rows="10" spellcheck="false" placeholder="vars.score = (vars.score or 0) + 1 app.log('score')">${esc(node.code || '')}</textarea>
|
||
</label>
|
||
<label class="fld"><span class="label">Привязать к кнопке</span>
|
||
<select data-node-link>${buttonLinkOptions(node)}</select>
|
||
</label>
|
||
<div class="field-actions">
|
||
<button data-act="node-open-slide" ${linked ? '' : 'disabled'}>Открыть слайд</button>
|
||
<button data-act="node-new-script">+ Ещё нода</button>
|
||
</div>
|
||
<p class="hint">Этот код синхронизирован с Lua-кнопкой: правки здесь сразу меняют кнопку и наоборот. Свободную ноду можно привязать к любой кнопке.</p>
|
||
</div>`;
|
||
}
|
||
|
||
function graphSlideOptions(currentId) {
|
||
return state.slides.map((slide, index) => {
|
||
const firstText = (slide.elements || []).find((el) => el.type === 'text' && String(el.text || '').trim());
|
||
const label = firstText ? String(firstText.text).trim().slice(0, 26) : `Слайд ${index + 1}`;
|
||
return `<option value="${esc(slide.id)}"${slide.id === currentId ? ' selected' : ''}>${index + 1}. ${esc(label)}</option>`;
|
||
}).join('');
|
||
}
|
||
|
||
function transitionNodeInspector(node) {
|
||
return `
|
||
<div class="insp-card">
|
||
<div class="insp-head">
|
||
<span class="insp-title">Переход · Lua</span>
|
||
<div class="insp-btns">
|
||
<button data-act="node-delete" class="danger" title="Удалить ноду">Удалить</button>
|
||
</div>
|
||
</div>
|
||
<label class="fld"><span class="label">Название</span>
|
||
<input data-node-prop="name" value="${esc(node.name || '')}">
|
||
</label>
|
||
<label class="fld"><span class="label">Слайд</span>
|
||
<select data-node-prop="slideId">${graphSlideOptions(node.slideId)}</select>
|
||
</label>
|
||
<label class="fld"><span class="label">Lua-код перехода</span>
|
||
<textarea data-node-prop="code" rows="10" spellcheck="false" placeholder="anim.play('in', { opacity = {0, 1} }, { duration = 400 })">${esc(node.code || '')}</textarea>
|
||
</label>
|
||
<p class="hint">Выполняется вместо встроенного перехода при входе на слайд. Цели: <code>in</code> — новый слайд, <code>out</code> — старый, id элемента, <code>slide</code>. API: <code>anim.play / fadeIn / fadeOut / clear</code>, <code>sleep(мс)</code>, свойства: opacity, x, y, w, h, scale, rotate.</p>
|
||
</div>`;
|
||
}
|
||
|
||
function animNodeInspector(node) {
|
||
const slide = state.slides.find((item) => item.id === node.slideId);
|
||
const elementOptions = (slide ? slide.elements || [] : []).map((el) => {
|
||
const label = el.label || el.text ? String(el.label || el.text).trim().slice(0, 24) : el.type;
|
||
return `<option value="${esc(el.id)}"${el.id === node.elementId ? ' selected' : ''}>${esc(label)}</option>`;
|
||
}).join('');
|
||
return `
|
||
<div class="insp-card">
|
||
<div class="insp-head">
|
||
<span class="insp-title">Анимация · Lua</span>
|
||
<div class="insp-btns">
|
||
<button data-act="node-delete" class="danger" title="Удалить ноду">Удалить</button>
|
||
</div>
|
||
</div>
|
||
<label class="fld"><span class="label">Название</span>
|
||
<input data-node-prop="name" value="${esc(node.name || '')}">
|
||
</label>
|
||
<label class="fld"><span class="label">Слайд</span>
|
||
<select data-node-prop="slideId">${graphSlideOptions(node.slideId)}</select>
|
||
</label>
|
||
<label class="fld"><span class="label">Элемент (подсказка)</span>
|
||
<select data-node-prop="elementId"><option value="">— весь слайд —</option>${elementOptions}</select>
|
||
</label>
|
||
<label class="fld"><span class="label">Lua-код анимации</span>
|
||
<textarea data-node-prop="code" rows="10" spellcheck="false" placeholder="anim.play('slide', { opacity = {0, 1} }, { duration = 400 })">${esc(node.code || '')}</textarea>
|
||
</label>
|
||
<p class="hint">Выполняется при входе на слайд после перехода. Внутри можно анимировать любые элементы по id: <code>anim.play(id, { y = {6, 0} }, { duration = 400, delay = 200 })</code>. Паузы — <code>sleep(мс)</code>.</p>
|
||
</div>`;
|
||
}
|
||
|
||
function pluginNodeInspector(node) {
|
||
const plugin = pluginById(node.pluginId);
|
||
const functions = (plugin && plugin.nodes) || [];
|
||
const pluginOptions = (state.pluginRegistry || []).map((item) =>
|
||
option(item.id, `${item.name} · ${(item.nodes || []).length} нод`, node.pluginId)
|
||
).join('');
|
||
const fnOptions = functions.map((item) =>
|
||
option(item.fn, `${item.name || item.fn}(${item.args || ''})`, node.fn)
|
||
).join('');
|
||
return `
|
||
<div class="insp-card">
|
||
<div class="insp-head">
|
||
<span class="insp-title">Плагин · нода</span>
|
||
<div class="insp-btns">
|
||
<button data-act="plugin-edit" title="Открыть редактор плагинов">✎</button>
|
||
<button data-act="node-delete" class="danger" title="Удалить ноду">Удалить</button>
|
||
</div>
|
||
</div>
|
||
<label class="fld"><span class="label">Плагин</span>
|
||
<select data-node-prop="pluginId">
|
||
<option value="">— не выбран —</option>
|
||
${pluginOptions}
|
||
</select>
|
||
</label>
|
||
<label class="fld"><span class="label">Функция-нода</span>
|
||
<select data-node-prop="fn">
|
||
<option value="">— выберите функцию —</option>
|
||
${fnOptions}
|
||
</select>
|
||
</label>
|
||
<label class="fld"><span class="label">Название</span>
|
||
<input data-node-prop="name" value="${esc(node.name || '')}">
|
||
</label>
|
||
<label class="fld"><span class="label">Аргументы вызова (Lua)</span>
|
||
<input data-node-prop="args" value="${esc(node.args || '')}" placeholder="'slide', 1.1">
|
||
</label>
|
||
<div class="muted">${esc(node.description || 'Без описания')}</div>
|
||
${plugin ? '' : '<p class="hint">Плагин отсутствует в реестре: нода продолжит работать по снимку кода.</p>'}
|
||
<div class="field-actions">
|
||
<button data-act="node-open-plugin">Открыть плагин</button>
|
||
<button data-act="node-new-plugin">+ Ещё нода</button>
|
||
</div>
|
||
<p class="hint">Нода выполняется при проходе по цепи: вход → плагин → выход. Код модуля сохранён снимком, поэтому показ не зависит от загрузки реестра.</p>
|
||
</div>`;
|
||
}
|
||
|
||
function graphHomeInspector() {
|
||
return `
|
||
<div class="insp-card">
|
||
<div class="insp-head"><span class="insp-title">Граф</span></div>
|
||
<p class="hint">Каждый слайд — нода с входом и выходами. Тяните от выхода «Дальше», «Назад» или кнопки к входу другого слайда, кода или аудио. Переменные — отдельные ноды: соедините выход с портом <code>⌘ имя</code>, и текст с <code>{{имя}}</code> обновится.</p>
|
||
<div class="muted">Слайды: ${state.slides.length} · код: ${state.graph.scripts.length} · аудио: ${state.graph.audios.length} · переменные: ${state.graph.variables.length} · переходы: ${(state.graph.transitions || []).length} · анимации: ${(state.graph.anims || []).length} · плагины: ${(state.graph.plugins || []).length} · связи: ${state.graph.links.length}</div>
|
||
<div class="field-actions">
|
||
<button data-act="graph-to-canvas">Открыть холст</button>
|
||
<button data-act="graph-add-script">+ Код</button>
|
||
<button data-act="graph-add-variable">+ Переменная</button>
|
||
<button data-act="graph-add-transition">+ Переход</button>
|
||
<button data-act="graph-add-anim">+ Анимация</button>
|
||
<button data-act="plugin-edit">Плагины…</button>
|
||
</div>
|
||
</div>`;
|
||
}
|
||
|
||
function actionLabel(action) {
|
||
if (!action) return 'нет действия';
|
||
if (action.type === 'go') return `→ слайд ${(Number(action.slideIndex) || 0) + 1}`;
|
||
if (action.type === 'next') return '→ дальше';
|
||
if (action.type === 'prev') return '← назад';
|
||
if (action.type === 'play') return '▶ аудио';
|
||
if (action.type === 'stop') return '■ аудио';
|
||
if (action.type === 'lua') return 'Lua-код';
|
||
return 'без действия';
|
||
}
|
||
|
||
function variableNodeInspector(node) {
|
||
const bound = state.graph.links.filter((link) => link.from.kind === 'variable' && link.from.id === node.id).length;
|
||
const value = state.variables[node.name];
|
||
return `
|
||
<div class="insp-card">
|
||
<div class="insp-head">
|
||
<span class="insp-title">Переменная</span>
|
||
<div class="insp-btns"><button data-act="node-delete" class="danger" title="Удалить ноду">Удалить</button></div>
|
||
</div>
|
||
<label class="fld"><span class="label">Имя</span>
|
||
<input data-node-prop="name" value="${esc(node.name || '')}" placeholder="score">
|
||
</label>
|
||
<div class="muted">Текущее значение: <b>${esc(value === undefined ? '—' : String(value))}</b> · связей: ${bound}</div>
|
||
<p class="hint">Выход соединяется с портом <code>⌘ имя</code> на ноде слайда. Вставка <code>{{${esc(node.name)}}}</code> в тексте обновится автоматически.</p>
|
||
<div class="field-actions">
|
||
<button data-act="node-new-variable">+ Ещё переменная</button>
|
||
</div>
|
||
</div>`;
|
||
}
|
||
|
||
function audioNodeInspector(node) {
|
||
const audios = [];
|
||
state.slides.forEach((slide, index) => {
|
||
(slide.elements || []).forEach((element) => {
|
||
if (element.type === 'audio') audios.push({ element, index });
|
||
});
|
||
});
|
||
const current = node.elementId || '';
|
||
if (current && !audios.some((item) => item.element.id === current)) {
|
||
audios.unshift({ element: { id: current, label: 'Сохранённый элемент' }, index: -1 });
|
||
}
|
||
const options = audios.map((item) =>
|
||
option(item.element.id, `${item.element.label || 'Аудио'} · слайд ${item.index + 1}`, current)
|
||
).join('');
|
||
return `
|
||
<div class="insp-card">
|
||
<div class="insp-head">
|
||
<span class="insp-title">Аудио-нода</span>
|
||
<div class="insp-btns"><button data-act="node-delete" class="danger" title="Удалить ноду">Удалить</button></div>
|
||
</div>
|
||
<label class="fld"><span class="label">Название</span>
|
||
<input data-node-prop="name" value="${esc(node.name || '')}">
|
||
</label>
|
||
<label class="fld"><span class="label">Аудиоэлемент</span>
|
||
<select data-node-prop="elementId">
|
||
<option value="">— не выбран —</option>
|
||
${options}
|
||
</select>
|
||
</label>
|
||
<label class="fld"><span class="label">Команда</span>
|
||
<select data-node-prop="mode">
|
||
${option('play', '▶ Запустить', node.mode === 'stop' ? 'stop' : 'play')}
|
||
${option('stop', '■ Остановить', node.mode === 'stop' ? 'stop' : 'play')}
|
||
</select>
|
||
</label>
|
||
<p class="hint">Вход аудио-ноды соединяется с выходом кнопки. Кнопка получит действие «Запустить аудио».</p>
|
||
<div class="field-actions">
|
||
<button data-act="node-new-audio">+ Ещё аудио</button>
|
||
</div>
|
||
</div>`;
|
||
}
|
||
|
||
function slideGraphInspector(slide) {
|
||
const index = state.slides.indexOf(slide);
|
||
const buttons = (slide.elements || []).filter((element) => element.type === 'button');
|
||
const vars = slideVarPorts(slide);
|
||
const jumps = state.graph.jumps[slide.id] || {};
|
||
const targetTitle = (id) => {
|
||
const at = state.slides.findIndex((item) => item.id === id);
|
||
return at >= 0 ? `слайд ${at + 1}` : '—';
|
||
};
|
||
return `
|
||
<div class="insp-card">
|
||
<div class="insp-head">
|
||
<span class="insp-title">Слайд ${index + 1} · граф</span>
|
||
<div class="insp-btns"><button data-act="node-open-canvas">Открыть холст</button></div>
|
||
</div>
|
||
<div class="muted">Дальше: ${jumps.next ? targetTitle(jumps.next) : 'по порядку'} · Назад: ${jumps.prev ? targetTitle(jumps.prev) : 'по порядку'}</div>
|
||
${buttons.length ? `<div class="graph-bind-list">${buttons.map((button) => `
|
||
<div class="graph-bind"><span>▸ ${esc(button.label || 'Кнопка')}</span><span class="gdim">${esc(actionLabel(button.action))}</span></div>`).join('')}</div>` : '<p class="hint">На слайде нет кнопок. Выходы «Дальше» и «Назад» работают с клавиатуры.</p>'}
|
||
${vars.length ? `<div class="muted">Переменные: ${vars.map((port) => `{{${esc(port.name)}}}`).join(', ')}</div>` : ''}
|
||
<p class="hint">Тяните от порта «Дальше», «Назад» или кнопки к входу другого слайда. Клик по связи и Delete удаляют её.</p>
|
||
</div>`;
|
||
}
|
||
|
||
function renderInspector() {
|
||
if (state.view === 'graph') {
|
||
const selected = state.selectedNode;
|
||
if (selected && selected.type === 'script') {
|
||
const node = findScriptNode(selected.id);
|
||
inspectorEl.innerHTML = node ? scriptNodeInspector(node) : graphHomeInspector();
|
||
} else if (selected && selected.type === 'transition') {
|
||
const node = findTransitionNode(selected.id);
|
||
inspectorEl.innerHTML = node ? transitionNodeInspector(node) : graphHomeInspector();
|
||
} else if (selected && selected.type === 'anim') {
|
||
const node = findAnimNode(selected.id);
|
||
inspectorEl.innerHTML = node ? animNodeInspector(node) : graphHomeInspector();
|
||
} else if (selected && selected.type === 'variable') {
|
||
const node = findVariableNode(selected.id);
|
||
inspectorEl.innerHTML = node ? variableNodeInspector(node) : graphHomeInspector();
|
||
} else if (selected && selected.type === 'audio') {
|
||
const node = findAudioNode(selected.id);
|
||
inspectorEl.innerHTML = node ? audioNodeInspector(node) : graphHomeInspector();
|
||
} else if (selected && selected.type === 'plugin') {
|
||
const node = findPluginNode(selected.id);
|
||
inspectorEl.innerHTML = node ? pluginNodeInspector(node) : graphHomeInspector();
|
||
} else if (selected && selected.type === 'slide') {
|
||
const slide = state.slides.find((item) => item.id === selected.id) || currentSlide();
|
||
inspectorEl.innerHTML = slideGraphInspector(slide) + backgroundInspector(slide);
|
||
} else {
|
||
inspectorEl.innerHTML = graphHomeInspector() + backgroundInspector(currentSlide());
|
||
}
|
||
return;
|
||
}
|
||
const element = selectedElement();
|
||
inspectorEl.innerHTML = (element ? elementInspector(element) : '') + backgroundInspector(currentSlide());
|
||
enhanceLuaEditors(inspectorEl);
|
||
if (element && element.type === 'window') loadWindowTargets(false);
|
||
}
|
||
|
||
let lastTargetsFetch = 0;
|
||
async function loadWindowTargets(notify) {
|
||
// Не дёргаем CDP чаще раза в 4 секунды, если не просят принудительно.
|
||
if (!notify && Date.now() - lastTargetsFetch < 4000 && state.windowTargets.length) return;
|
||
lastTargetsFetch = Date.now();
|
||
try {
|
||
const response = await fetch('/api/windows');
|
||
const data = await response.json();
|
||
state.windowTargets = Array.isArray(data.targets) ? data.targets : [];
|
||
state.windowEndpoint = data.endpoint || '';
|
||
const select = inspectorEl.querySelector('#window-target-select');
|
||
const element = selectedElement();
|
||
if (select && element && element.type === 'window') {
|
||
const current = String(element.targetId || '');
|
||
const items = state.windowTargets.map((target) =>
|
||
option(target.id, `${target.title || 'Без названия'} — ${target.url || ''}`.slice(0, 90), current)
|
||
);
|
||
if (current && !state.windowTargets.some((target) => target.id === current)) {
|
||
items.unshift(option(current, `Сохранённая цель · ${current.slice(0, 12)}`, current));
|
||
}
|
||
if (!items.length) items.push('<option value="">— окна Chrome не найдены —</option>');
|
||
select.innerHTML = items.join('');
|
||
}
|
||
if (notify) {
|
||
toast(state.windowTargets.length
|
||
? `Найдено окон: ${state.windowTargets.length}`
|
||
: `Chrome не найден на ${state.windowEndpoint || '127.0.0.1:9222'}`);
|
||
}
|
||
} catch (error) {
|
||
if (notify) toast('Не удалось получить список окон');
|
||
}
|
||
}
|
||
|
||
// ==================== Элементы ====================
|
||
function defaultElement(type) {
|
||
const base = {
|
||
id: uid(), type, opacity: 1, rotate: 0,
|
||
z: Math.max(0, ...(currentSlide().elements || []).map((el) => Number(el.z) || 0)) + 1,
|
||
};
|
||
if (type === 'text') {
|
||
return { ...base, x: 10, y: 38, w: 80, h: 24, text: 'Новый текст', fontSize: 6, color: '#f8fafc', weight: 700, align: 'center', bg: '', font: 'sans', italic: false, shadow: false, lineHeight: 1.16 };
|
||
}
|
||
if (type === 'image') {
|
||
return { ...base, x: 30, y: 18, w: 40, h: 50, src: '', fit: 'cover', radius: 14, shadow: false };
|
||
}
|
||
if (type === 'shape') {
|
||
return { ...base, x: 32, y: 30, w: 36, h: 40, shape: 'rect', fill: '#6366f1', borderColor: '', borderWidth: 0, radius: 12, shadow: false };
|
||
}
|
||
if (type === 'button') {
|
||
return { ...base, x: 35, y: 62, w: 30, h: 11, label: 'Кнопка', bg: '#6366f1', color: '#ffffff', fontSize: 2.4, radius: 12, shadow: true, action: { type: 'next', slideIndex: 0, audioId: '', code: '', scriptNodeId: '' } };
|
||
}
|
||
if (type === 'video') {
|
||
return { ...base, x: 20, y: 16, w: 60, h: 56, src: '', poster: '', fit: 'cover', radius: 12, autoplay: true, loop: false, muted: true, controls: true, label: 'Видео' };
|
||
}
|
||
if (type === 'window') {
|
||
return { ...base, x: 12, y: 14, w: 62, h: 58, targetId: '', targetTitle: '', radius: 12, autoStart: true, label: 'Окно Chrome' };
|
||
}
|
||
if (type === 'lua') {
|
||
return {
|
||
...base, x: 26, y: 24, w: 48, h: 36,
|
||
label: 'Lua-элемент',
|
||
code: typeof DEFAULT_LUA_ELEMENT === 'string' ? DEFAULT_LUA_ELEMENT : '',
|
||
computed: { style: {}, css: '', html: '', text: '', at: 0 },
|
||
};
|
||
}
|
||
return { ...base, x: 30, y: 82, w: 40, h: 8, src: '', loop: false, visible: true, volume: 0.8, label: 'Аудио' };
|
||
}
|
||
|
||
function addElement(type, point) {
|
||
pushHistory(true);
|
||
const element = defaultElement(type);
|
||
if (point) {
|
||
element.x = clamp(Number(point.x) || 0, 0, 100 - (Number(element.w) || 10));
|
||
element.y = clamp(Number(point.y) || 0, 0, 100 - (Number(element.h) || 10));
|
||
}
|
||
currentSlide().elements.push(element);
|
||
state.selectedEl = element.id;
|
||
renderCanvas();
|
||
renderInspector();
|
||
scheduleThumbs();
|
||
scheduleSave(true);
|
||
}
|
||
|
||
function selectElement(id) {
|
||
if (state.selectedEl === id) return;
|
||
state.selectedEl = id;
|
||
renderCanvas();
|
||
renderInspector();
|
||
}
|
||
|
||
function addSlide(template = 'blank') {
|
||
pushHistory(true);
|
||
const slide = newSlide();
|
||
const factory = slideTemplates()[template] || slideTemplates().blank;
|
||
slide.elements = factory();
|
||
const previous = currentSlide();
|
||
state.slides.push(slide);
|
||
state.graph.positions[slide.id] = graphDefaultPosition(state.slides.length - 1);
|
||
chainSlides(previous, slide);
|
||
rebuildJumps();
|
||
state.selected = state.slides.length - 1;
|
||
state.selectedEl = null;
|
||
state.selectedNode = { type: 'slide', id: slide.id };
|
||
renderAll();
|
||
scheduleSave(true);
|
||
}
|
||
|
||
function duplicateSelectedElement() {
|
||
const element = selectedElement();
|
||
if (!element) return;
|
||
pushHistory(true);
|
||
const copy = { ...element, id: uid(), x: clamp(element.x + 3, 0, 100 - element.w), y: clamp(element.y + 3, 0, 100 - element.h) };
|
||
if (element.action) copy.action = { ...element.action };
|
||
if (element.type === 'button' && element.action && element.action.type === 'lua') {
|
||
const original = element.action.scriptNodeId
|
||
? findScriptNode(element.action.scriptNodeId)
|
||
: scriptNodeForElement(element.id);
|
||
if (original) {
|
||
const spot = findFreeNodeSpot(original.x + 320, original.y + 40, 'script', '');
|
||
const node = {
|
||
...original,
|
||
id: uid(),
|
||
x: spot.x,
|
||
y: spot.y,
|
||
slideId: currentSlide().id,
|
||
elementId: copy.id,
|
||
};
|
||
state.graph.scripts.push(node);
|
||
copy.action.scriptNodeId = node.id;
|
||
copy.action.code = node.code;
|
||
}
|
||
}
|
||
currentSlide().elements.push(copy);
|
||
ensureLinksFromModel();
|
||
rebuildJumps();
|
||
state.selectedEl = copy.id;
|
||
renderCanvas();
|
||
renderInspector();
|
||
scheduleThumbs();
|
||
scheduleSave(true);
|
||
}
|
||
|
||
function pasteElement() {
|
||
if (!state.clipboard) { toast('Буфер обмена пуст'); return; }
|
||
pushHistory(true);
|
||
const copy = JSON.parse(JSON.stringify(state.clipboard));
|
||
copy.id = uid();
|
||
copy.x = clamp((Number(copy.x) || 0) + 3, 0, 96);
|
||
copy.y = clamp((Number(copy.y) || 0) + 3, 0, 96);
|
||
copy.z = Math.max(0, ...(currentSlide().elements || []).map((el) => Number(el.z) || 0)) + 1;
|
||
if (copy.type === 'button' && copy.action && copy.action.type === 'lua' && copy.action.scriptNodeId) {
|
||
const original = findScriptNode(copy.action.scriptNodeId);
|
||
if (original) {
|
||
const spot = findFreeNodeSpot((Number(original.x) || 60) + 320, (Number(original.y) || 60) + 40, 'script', '');
|
||
const node = { ...original, id: uid(), x: spot.x, y: spot.y, slideId: currentSlide().id, elementId: copy.id };
|
||
state.graph.scripts.push(node);
|
||
copy.action.scriptNodeId = node.id;
|
||
copy.action.code = node.code;
|
||
}
|
||
}
|
||
currentSlide().elements.push(copy);
|
||
ensureLinksFromModel();
|
||
rebuildJumps();
|
||
state.selectedEl = copy.id;
|
||
renderCanvas();
|
||
renderInspector();
|
||
scheduleThumbs();
|
||
scheduleSave(true);
|
||
toast('Элемент вставлен');
|
||
}
|
||
|
||
function nudgeSelected(dx, dy) {
|
||
const element = selectedElement();
|
||
if (!element) return;
|
||
element.x = clamp((Number(element.x) || 0) + dx, -40, 130);
|
||
element.y = clamp((Number(element.y) || 0) + dy, -40, 130);
|
||
applyElementStyles(element);
|
||
scheduleThumbs();
|
||
scheduleSave();
|
||
}
|
||
|
||
function duplicateSlide() {
|
||
pushHistory(true);
|
||
const source = currentSlide();
|
||
const copyId = uid();
|
||
const copy = {
|
||
...source,
|
||
id: copyId,
|
||
background: { ...(source.background || {}) },
|
||
elements: (source.elements || []).map((element) => {
|
||
const nextElement = { ...element, id: uid() };
|
||
if (element.action) nextElement.action = { ...element.action };
|
||
if (element.type === 'button' && element.action && element.action.type === 'lua') {
|
||
const original = element.action.scriptNodeId
|
||
? findScriptNode(element.action.scriptNodeId)
|
||
: scriptNodeForElement(element.id);
|
||
if (original) {
|
||
const spot = findFreeNodeSpot(original.x + 320, original.y + 40, 'script', '');
|
||
const node = {
|
||
...original,
|
||
id: uid(),
|
||
x: spot.x,
|
||
y: spot.y,
|
||
slideId: copyId,
|
||
elementId: nextElement.id,
|
||
};
|
||
state.graph.scripts.push(node);
|
||
nextElement.action.scriptNodeId = node.id;
|
||
nextElement.action.code = node.code;
|
||
}
|
||
}
|
||
return nextElement;
|
||
}),
|
||
};
|
||
const sourcePos = state.graph.positions[source.id] || graphDefaultPosition(state.selected);
|
||
const copyPos = findFreeNodeSpot(sourcePos.x, sourcePos.y + 300, 'slide', copyId, { w: 250, h: 300 });
|
||
state.graph.positions[copy.id] = copyPos;
|
||
state.slides.splice(state.selected + 1, 0, copy);
|
||
ensureLinksFromModel();
|
||
rebuildJumps();
|
||
state.selected += 1;
|
||
state.selectedEl = null;
|
||
state.selectedNode = { type: 'slide', id: copy.id };
|
||
renderAll();
|
||
scheduleSave(true);
|
||
}
|
||
|
||
function deleteSlide() {
|
||
if (state.slides.length <= 1) {
|
||
toast('Нельзя удалить единственный слайд');
|
||
return;
|
||
}
|
||
pushHistory(true);
|
||
const removed = currentSlide();
|
||
state.graph.scripts.forEach((node) => {
|
||
if (node.slideId === removed.id) {
|
||
node.slideId = '';
|
||
node.elementId = '';
|
||
}
|
||
});
|
||
cleanupSlideLinks(removed);
|
||
state.slides.splice(state.selected, 1);
|
||
state.selected = Math.min(state.selected, state.slides.length - 1);
|
||
state.selectedEl = null;
|
||
const slide = currentSlide();
|
||
state.selectedNode = { type: 'slide', id: slide.id };
|
||
renderAll();
|
||
scheduleSave(true);
|
||
}
|
||
|
||
function moveSlide(delta) {
|
||
const target = state.selected + delta;
|
||
if (target < 0 || target >= state.slides.length) return;
|
||
pushHistory(true);
|
||
const [slide] = state.slides.splice(state.selected, 1);
|
||
state.slides.splice(target, 0, slide);
|
||
state.selected = target;
|
||
state.selectedEl = null;
|
||
renderAll();
|
||
scheduleSave(true);
|
||
}
|
||
|
||
// ==================== Перетаскивание ====================
|
||
let drag = null;
|
||
|
||
function elementNode(id) {
|
||
return canvasEl.querySelector(`[data-el="${id}"]`);
|
||
}
|
||
|
||
function applyElementStyles(element) {
|
||
const node = elementNode(element.id);
|
||
if (node) {
|
||
node.style.left = `${element.x}%`;
|
||
node.style.top = `${element.y}%`;
|
||
node.style.width = `${element.w}%`;
|
||
node.style.height = `${element.h}%`;
|
||
}
|
||
renderSelection();
|
||
}
|
||
|
||
canvasWrap.addEventListener('pointerdown', (event) => {
|
||
if (event.button !== 0) return;
|
||
const handle = event.target.closest('.resize');
|
||
const node = event.target.closest('.sv-el');
|
||
|
||
if (handle) {
|
||
const element = selectedElement();
|
||
if (!element) return;
|
||
event.preventDefault();
|
||
drag = {
|
||
mode: 'resize',
|
||
dir: handle.dataset.dir,
|
||
element,
|
||
startX: event.clientX,
|
||
startY: event.clientY,
|
||
rect: canvasEl.getBoundingClientRect(),
|
||
original: { x: element.x, y: element.y, w: element.w, h: element.h },
|
||
};
|
||
startDragListeners();
|
||
return;
|
||
}
|
||
|
||
if (!node) {
|
||
selectElement(null);
|
||
return;
|
||
}
|
||
|
||
event.preventDefault();
|
||
selectElement(node.dataset.el);
|
||
const element = selectedElement();
|
||
if (!element) return;
|
||
drag = {
|
||
mode: 'move',
|
||
element,
|
||
startX: event.clientX,
|
||
startY: event.clientY,
|
||
rect: canvasEl.getBoundingClientRect(),
|
||
original: { x: element.x, y: element.y, w: element.w, h: element.h },
|
||
};
|
||
startDragListeners();
|
||
});
|
||
|
||
function startDragListeners() {
|
||
window.addEventListener('pointermove', onDragMove);
|
||
window.addEventListener('pointerup', onDragEnd);
|
||
document.body.style.cursor = drag.mode === 'move' ? 'grabbing' : 'nwse-resize';
|
||
}
|
||
|
||
function onDragMove(event) {
|
||
if (!drag) return;
|
||
const rect = drag.rect;
|
||
const dx = ((event.clientX - drag.startX) / rect.width) * 100;
|
||
const dy = ((event.clientY - drag.startY) / rect.height) * 100;
|
||
const original = drag.original;
|
||
const element = drag.element;
|
||
|
||
if (drag.mode === 'move') {
|
||
element.x = clamp(original.x + dx, 0, 100 - element.w);
|
||
element.y = clamp(original.y + dy, 0, 100 - element.h);
|
||
} else {
|
||
let x = original.x;
|
||
let y = original.y;
|
||
let w = original.w;
|
||
let h = original.h;
|
||
if (drag.dir.includes('e')) w = original.w + dx;
|
||
if (drag.dir.includes('s')) h = original.h + dy;
|
||
if (drag.dir.includes('w')) {
|
||
w = original.w - dx;
|
||
x = original.x + dx;
|
||
}
|
||
if (drag.dir.includes('n')) {
|
||
h = original.h - dy;
|
||
y = original.y + dy;
|
||
}
|
||
w = clamp(w, 2, 100); h = clamp(h, 2, 100);
|
||
x = clamp(x, 0, 100 - w); y = clamp(y, 0, 100 - h);
|
||
if (drag.dir.includes('w') && x + w > 100) w = 100 - x;
|
||
if (drag.dir.includes('n') && y + h > 100) h = 100 - y;
|
||
element.x = x; element.y = y; element.w = w; element.h = h;
|
||
}
|
||
applyElementStyles(element);
|
||
}
|
||
|
||
function onDragEnd() {
|
||
window.removeEventListener('pointermove', onDragMove);
|
||
window.removeEventListener('pointerup', onDragEnd);
|
||
document.body.style.cursor = '';
|
||
if (!drag) return;
|
||
drag = null;
|
||
renderSelection();
|
||
renderInspector();
|
||
scheduleThumbs();
|
||
scheduleSave();
|
||
}
|
||
|
||
// ==================== Инспектор: ввод ====================
|
||
function setPath(target, path, value) {
|
||
const parts = path.split('.');
|
||
let cursor = target;
|
||
for (let i = 0; i < parts.length - 1; i += 1) {
|
||
if (!cursor[parts[i]] || typeof cursor[parts[i]] !== 'object') cursor[parts[i]] = {};
|
||
cursor = cursor[parts[i]];
|
||
}
|
||
cursor[parts[parts.length - 1]] = value;
|
||
}
|
||
|
||
function handleInspectorInput(input, commit) {
|
||
const prop = input.dataset.prop;
|
||
if (!prop) return;
|
||
const slide = currentSlide();
|
||
const target = prop.startsWith('background.') || ['notes', 'lua', 'transition'].includes(prop)
|
||
? slide
|
||
: selectedElement();
|
||
if (!target) return;
|
||
|
||
let value;
|
||
if (input.type === 'checkbox') value = input.checked;
|
||
else if (input.type === 'number' || input.type === 'range') {
|
||
if (input.value === '') return;
|
||
value = Number(input.value);
|
||
} else value = input.value;
|
||
|
||
if (prop === 'volume') value = clamp(Number(value) / 100, 0, 1);
|
||
if (prop === 'opacity') value = clamp(Number(value) / 100, 0, 1);
|
||
if (prop === 'action.slideIndex') value = Number(value) || 0;
|
||
|
||
setPath(target, prop, value);
|
||
if (prop === 'action.type') {
|
||
if (value === 'lua') ensureScriptNode(target, currentSlide());
|
||
if (target && target.type === 'button' && target.action) {
|
||
if (value === 'go') {
|
||
target.action.audioId = '';
|
||
target.action.code = '';
|
||
target.action.scriptNodeId = '';
|
||
} else if (value === 'play' || value === 'stop') {
|
||
target.action.code = '';
|
||
target.action.scriptNodeId = '';
|
||
} else if (value === 'lua') {
|
||
target.action.audioId = '';
|
||
} else {
|
||
target.action.audioId = '';
|
||
target.action.code = '';
|
||
target.action.scriptNodeId = '';
|
||
}
|
||
}
|
||
}
|
||
if (target && target.type === 'button' && ['action.type', 'action.slideIndex', 'action.audioId'].includes(prop)) {
|
||
syncButtonLink(target);
|
||
}
|
||
if (prop === 'action.code' && target && target.type === 'button') {
|
||
const node = target.action && target.action.scriptNodeId
|
||
? findScriptNode(target.action.scriptNodeId)
|
||
: scriptNodeForElement(target.id);
|
||
if (node) node.code = value;
|
||
}
|
||
if (prop === 'targetId') {
|
||
const found = state.windowTargets.find((item) => item.id === value);
|
||
target.targetTitle = found ? found.title : '';
|
||
}
|
||
if (prop === 'label' && target && target.type === 'button' && target.action && target.action.scriptNodeId) {
|
||
const node = findScriptNode(target.action.scriptNodeId);
|
||
if (node && /^Lua · /.test(node.name || '')) node.name = `Lua · ${value || 'Кнопка'}`;
|
||
}
|
||
renderCanvas();
|
||
scheduleThumbs();
|
||
scheduleSave();
|
||
if (commit) {
|
||
if (prop === 'action.type' || prop === 'background.type' || prop === 'text') renderInspector();
|
||
}
|
||
}
|
||
|
||
function handleNodeInput(input, commit) {
|
||
const selected = state.selectedNode;
|
||
if (!selected) return;
|
||
const prop = input.dataset.nodeProp;
|
||
|
||
if (selected.type === 'script') {
|
||
const node = findScriptNode(selected.id);
|
||
if (!node) return;
|
||
if (prop === 'name') node.name = input.value;
|
||
if (prop === 'code') {
|
||
node.code = input.value;
|
||
applyScriptNodeToElement(node);
|
||
renderCanvas();
|
||
scheduleThumbs();
|
||
}
|
||
if (commit) renderGraph();
|
||
} else if (selected.type === 'variable') {
|
||
const node = findVariableNode(selected.id);
|
||
if (!node) return;
|
||
if (prop === 'name') {
|
||
renameVariableNode(node, input.value);
|
||
applyGraphLinks();
|
||
renderCanvas();
|
||
scheduleThumbs();
|
||
}
|
||
if (commit) renderAll();
|
||
} else if (selected.type === 'transition') {
|
||
const node = findTransitionNode(selected.id);
|
||
if (!node) return;
|
||
if (prop === 'name') node.name = input.value;
|
||
if (prop === 'code') node.code = input.value;
|
||
if (prop === 'slideId') node.slideId = input.value;
|
||
if (commit) renderGraph();
|
||
} else if (selected.type === 'anim') {
|
||
const node = findAnimNode(selected.id);
|
||
if (!node) return;
|
||
if (prop === 'name') node.name = input.value;
|
||
if (prop === 'code') node.code = input.value;
|
||
if (prop === 'slideId') node.slideId = input.value;
|
||
if (prop === 'elementId') node.elementId = input.value;
|
||
if (commit) renderGraph();
|
||
} else if (selected.type === 'audio') {
|
||
const node = findAudioNode(selected.id);
|
||
if (!node) return;
|
||
if (prop === 'name') node.name = input.value;
|
||
if (prop === 'elementId') {
|
||
node.elementId = input.value;
|
||
const found = findAudioElement(input.value);
|
||
if (found) node.name = found.element.label || node.name;
|
||
}
|
||
if (prop === 'mode') node.mode = input.value === 'stop' ? 'stop' : 'play';
|
||
applyGraphLinks();
|
||
if (commit) renderAll();
|
||
} else if (selected.type === 'plugin') {
|
||
const node = findPluginNode(selected.id);
|
||
if (!node) return;
|
||
if (prop === 'name') node.name = input.value;
|
||
if (prop === 'args') node.args = input.value;
|
||
if (prop === 'pluginId') {
|
||
const plugin = pluginById(input.value);
|
||
node.pluginId = input.value;
|
||
if (plugin) {
|
||
const fn = pluginFunction(plugin, node.fn) || (plugin.nodes || [])[0];
|
||
node.fn = fn ? fn.fn : '';
|
||
node.name = fn ? `${plugin.name} · ${fn.name || fn.fn}` : plugin.name;
|
||
node.description = (fn && fn.description) || plugin.description || '';
|
||
node.color = plugin.color || node.color;
|
||
node.code = plugin.code || '';
|
||
}
|
||
}
|
||
if (prop === 'fn') {
|
||
const plugin = pluginById(node.pluginId);
|
||
const fn = pluginFunction(plugin, input.value);
|
||
node.fn = input.value;
|
||
if (fn) {
|
||
node.name = `${plugin.name} · ${fn.name || fn.fn}`;
|
||
node.description = fn.description || plugin.description || '';
|
||
}
|
||
}
|
||
if (commit) renderAll();
|
||
}
|
||
scheduleSave();
|
||
}
|
||
|
||
function attachScriptToButton(node, value) {
|
||
const previous = findLinkedElement(node);
|
||
if (previous) {
|
||
previous.element.action = { ...(previous.element.action || {}), scriptNodeId: '' };
|
||
}
|
||
if (!value) {
|
||
node.slideId = '';
|
||
node.elementId = '';
|
||
renderAll();
|
||
scheduleSave();
|
||
return;
|
||
}
|
||
const [slideId, elementId] = value.split('|');
|
||
const slide = state.slides.find((item) => item.id === slideId);
|
||
const element = slide && (slide.elements || []).find((item) => item.id === elementId);
|
||
if (!element) return;
|
||
const otherId = element.action && element.action.scriptNodeId;
|
||
if (otherId && otherId !== node.id) {
|
||
const other = findScriptNode(otherId);
|
||
if (other) {
|
||
other.slideId = '';
|
||
other.elementId = '';
|
||
}
|
||
}
|
||
if (!String(node.code || '').trim() && element.action && element.action.code) {
|
||
node.code = element.action.code;
|
||
}
|
||
node.slideId = slide.id;
|
||
node.elementId = element.id;
|
||
element.action = {
|
||
...(element.action || {}),
|
||
type: 'lua',
|
||
scriptNodeId: node.id,
|
||
code: node.code,
|
||
};
|
||
syncButtonLink(element);
|
||
renderAll();
|
||
scheduleSave();
|
||
}
|
||
|
||
function cleanupElementLinks(elementId) {
|
||
state.graph.links = state.graph.links.filter((link) => {
|
||
if (link.from.kind === 'slide' && link.from.port === `btn:${elementId}`) return false;
|
||
if (link.to.kind === 'slide' && link.to.port.startsWith(`var:${elementId}:`)) return false;
|
||
return true;
|
||
});
|
||
const audioNodes = state.graph.audios.filter((node) => node.elementId === elementId);
|
||
audioNodes.forEach((node) => {
|
||
state.graph.links = state.graph.links.filter((link) =>
|
||
!(link.from.kind === 'audio' && link.from.id === node.id)
|
||
&& !(link.to.kind === 'audio' && link.to.id === node.id)
|
||
);
|
||
});
|
||
state.graph.audios = state.graph.audios.filter((node) => node.elementId !== elementId);
|
||
rebuildJumps();
|
||
}
|
||
|
||
function cleanupSlideLinks(slide) {
|
||
if (!slide) return;
|
||
(slide.elements || []).forEach((element) => cleanupElementLinks(element.id));
|
||
state.graph.links = state.graph.links.filter((link) =>
|
||
!(link.from.kind === 'slide' && link.from.id === slide.id)
|
||
&& !(link.to.kind === 'slide' && link.to.id === slide.id)
|
||
);
|
||
delete state.graph.positions[slide.id];
|
||
rebuildJumps();
|
||
}
|
||
|
||
function deleteTransitionNode(node) {
|
||
state.graph.links = state.graph.links.filter((link) =>
|
||
!(link.from.kind === 'transition' && link.from.id === node.id)
|
||
&& !(link.to.kind === 'transition' && link.to.id === node.id)
|
||
);
|
||
state.graph.transitions = (state.graph.transitions || []).filter((item) => item.id !== node.id);
|
||
const slide = currentSlide();
|
||
state.selectedNode = slide ? { type: 'slide', id: slide.id } : null;
|
||
rebuildJumps();
|
||
renderAll();
|
||
scheduleSave(true);
|
||
toast('Нода перехода удалена');
|
||
}
|
||
|
||
function deleteAnimNode(node) {
|
||
state.graph.links = state.graph.links.filter((link) =>
|
||
!(link.from.kind === 'anim' && link.from.id === node.id)
|
||
&& !(link.to.kind === 'anim' && link.to.id === node.id)
|
||
);
|
||
state.graph.anims = (state.graph.anims || []).filter((item) => item.id !== node.id);
|
||
const slide = currentSlide();
|
||
state.selectedNode = slide ? { type: 'slide', id: slide.id } : null;
|
||
rebuildJumps();
|
||
renderAll();
|
||
scheduleSave(true);
|
||
toast('Нода анимации удалена');
|
||
}
|
||
|
||
function deleteScriptNode(node) {
|
||
const linked = findLinkedElement(node);
|
||
if (linked) {
|
||
linked.element.action = { ...(linked.element.action || {}), type: 'none', scriptNodeId: '', code: '' };
|
||
}
|
||
state.graph.links = state.graph.links.filter((link) =>
|
||
!(link.to.kind === 'script' && link.to.id === node.id)
|
||
&& !(linked && link.from.kind === 'slide' && link.from.port === `btn:${linked.element.id}`)
|
||
);
|
||
state.graph.scripts = state.graph.scripts.filter((item) => item.id !== node.id);
|
||
const slide = currentSlide();
|
||
state.selectedNode = slide ? { type: 'slide', id: slide.id } : null;
|
||
renderAll();
|
||
scheduleSave();
|
||
toast('Нода удалена');
|
||
}
|
||
|
||
function addScriptNode() {
|
||
const base = state.graph.positions[currentSlide().id] || graphDefaultPosition(state.selected);
|
||
const spot = findFreeNodeSpot(base.x + 320, base.y + 140, 'script', '');
|
||
const node = {
|
||
id: uid(),
|
||
name: 'Lua-скрипт',
|
||
code: '',
|
||
x: spot.x,
|
||
y: spot.y,
|
||
slideId: '',
|
||
elementId: '',
|
||
};
|
||
state.graph.scripts.push(node);
|
||
state.selectedNode = { type: 'script', id: node.id };
|
||
if (state.view !== 'graph') setView('graph');
|
||
else renderAll();
|
||
scheduleSave();
|
||
toast('Добавлена нода кода');
|
||
}
|
||
|
||
const DEFAULT_TRANSITION_LUA = [
|
||
'-- Кастомный переход: in — новый слайд, out — старый',
|
||
"anim.play('out', { opacity = {1, 0}, scale = {1, 1.05} }, { duration = 320 })",
|
||
"anim.play('in', { opacity = {0, 1}, y = {5, 0} }, { duration = 520, delay = 100 })",
|
||
].join('\n');
|
||
const DEFAULT_ANIM_LUA = [
|
||
'-- Анимация при входе на слайд. Цели: id элемента, slide, in, out',
|
||
"anim.play('slide', { opacity = {0, 1}, scale = {0.97, 1} }, { duration = 450 })",
|
||
'-- sleep(200) — пауза между шагами',
|
||
].join('\n');
|
||
|
||
function addTransitionNode() {
|
||
const slide = currentSlide();
|
||
const base = (slide && state.graph.positions[slide.id]) || graphDefaultPosition(state.selected);
|
||
const spot = findFreeNodeSpot(base.x + 320, base.y + 330, 'transition', '');
|
||
const node = {
|
||
id: uid(),
|
||
name: 'Переход',
|
||
code: DEFAULT_TRANSITION_LUA,
|
||
slideId: slide ? slide.id : '',
|
||
x: spot.x,
|
||
y: spot.y,
|
||
};
|
||
state.graph.transitions.push(node);
|
||
state.selectedNode = { type: 'transition', id: node.id };
|
||
if (state.view !== 'graph') setView('graph');
|
||
else renderAll();
|
||
scheduleSave(true);
|
||
toast('Добавлена нода перехода');
|
||
}
|
||
|
||
function addAnimNode() {
|
||
const slide = currentSlide();
|
||
const base = (slide && state.graph.positions[slide.id]) || graphDefaultPosition(state.selected);
|
||
const spot = findFreeNodeSpot(base.x + 320, base.y + 500, 'anim', '');
|
||
const node = {
|
||
id: uid(),
|
||
name: 'Анимация',
|
||
code: DEFAULT_ANIM_LUA,
|
||
slideId: slide ? slide.id : '',
|
||
elementId: state.selectedEl || '',
|
||
x: spot.x,
|
||
y: spot.y,
|
||
};
|
||
state.graph.anims.push(node);
|
||
state.selectedNode = { type: 'anim', id: node.id };
|
||
if (state.view !== 'graph') setView('graph');
|
||
else renderAll();
|
||
scheduleSave(true);
|
||
toast('Добавлена нода анимации');
|
||
}
|
||
|
||
function pluginById(id) {
|
||
return (state.pluginRegistry || []).find((plugin) => plugin.id === id) || null;
|
||
}
|
||
|
||
function pluginFunction(plugin, fn) {
|
||
return ((plugin && plugin.nodes) || []).find((node) => node.fn === fn) || null;
|
||
}
|
||
|
||
// Создаёт экземпляр ноды плагина. В ноду кладём снимок кода модуля.
|
||
function addPluginNode(pluginId, fn, position) {
|
||
const plugin = pluginById(pluginId);
|
||
if (!plugin) {
|
||
toast('Плагин не найден в реестре');
|
||
return null;
|
||
}
|
||
const functions = plugin.nodes || [];
|
||
const selected = pluginFunction(plugin, fn) || functions[0];
|
||
if (!selected) {
|
||
toast('В плагине нет функций-нод');
|
||
return null;
|
||
}
|
||
const base = (currentSlide() && state.graph.positions[currentSlide().id]) || graphDefaultPosition(state.selected);
|
||
const x = position ? position.x : base.x + 360;
|
||
const y = position ? position.y : base.y + 180 + state.graph.plugins.length * 20;
|
||
const spot = findFreeNodeSpot(x, y, 'plugin', '');
|
||
const node = {
|
||
id: uid(),
|
||
pluginId: plugin.id,
|
||
fn: selected.fn,
|
||
name: `${plugin.name} · ${selected.name || selected.fn}`,
|
||
description: selected.description || plugin.description || '',
|
||
color: plugin.color || '#f97316',
|
||
code: plugin.code || '',
|
||
args: '',
|
||
x: spot.x,
|
||
y: spot.y,
|
||
};
|
||
state.graph.plugins = state.graph.plugins || [];
|
||
state.graph.plugins.push(node);
|
||
state.selectedNode = { type: 'plugin', id: node.id };
|
||
if (state.view !== 'graph') setView('graph');
|
||
else renderAll();
|
||
scheduleSave(true);
|
||
toast(`Нода плагина «${selected.name || selected.fn}» добавлена`);
|
||
return node;
|
||
}
|
||
|
||
function deletePluginNode(node) {
|
||
state.graph.links = state.graph.links.filter((link) =>
|
||
!(link.from.kind === 'plugin' && link.from.id === node.id)
|
||
&& !(link.to.kind === 'plugin' && link.to.id === node.id)
|
||
);
|
||
state.graph.plugins = (state.graph.plugins || []).filter((item) => item.id !== node.id);
|
||
const slide = currentSlide();
|
||
state.selectedNode = slide ? { type: 'slide', id: slide.id } : null;
|
||
rebuildJumps();
|
||
renderAll();
|
||
scheduleSave();
|
||
toast('Нода плагина удалена');
|
||
}
|
||
|
||
function addVariableNode() {
|
||
const base = currentSlide() ? state.graph.positions[currentSlide().id] : { x: 340, y: 60 };
|
||
let index = state.graph.variables.length + 1;
|
||
let name = `var${index}`;
|
||
while (findVariableByName(name)) {
|
||
index += 1;
|
||
name = `var${index}`;
|
||
}
|
||
const spot = findFreeNodeSpot(
|
||
Math.max(20, (base ? base.x : 340) - 300),
|
||
(base ? base.y : 60) + 20 + state.graph.variables.length * 120,
|
||
'variable',
|
||
''
|
||
);
|
||
const node = {
|
||
id: uid(),
|
||
name,
|
||
x: spot.x,
|
||
y: spot.y,
|
||
};
|
||
state.graph.variables.push(node);
|
||
const element = selectedElement();
|
||
if (element && element.type === 'text') {
|
||
bindElementVariable(element.id, name);
|
||
} else if (state.view !== 'graph') {
|
||
setView('graph');
|
||
} else {
|
||
renderAll();
|
||
}
|
||
state.selectedNode = { type: 'variable', id: node.id };
|
||
renderAll();
|
||
scheduleSave();
|
||
toast('Добавлена нода переменной');
|
||
}
|
||
|
||
function addAudioNode() {
|
||
const found = [];
|
||
state.slides.forEach((slide) => (slide.elements || []).forEach((element) => {
|
||
if (element.type === 'audio') found.push(element);
|
||
}));
|
||
if (!found.length) {
|
||
toast('Сначала добавьте аудио-элемент на слайд');
|
||
return;
|
||
}
|
||
const node = ensureAudioNode(found[0].id, 'play');
|
||
const base = state.graph.positions[currentSlide().id] || { x: 340, y: 60 };
|
||
const spot = findFreeNodeSpot(base.x + 330, base.y + 200 + (state.graph.audios.length % 3) * 96, 'audio', node.id);
|
||
node.x = spot.x;
|
||
node.y = spot.y;
|
||
state.selectedNode = { type: 'audio', id: node.id };
|
||
if (state.view !== 'graph') setView('graph');
|
||
else renderAll();
|
||
scheduleSave();
|
||
toast('Добавлена аудио-нода');
|
||
}
|
||
|
||
function bindElementVariable(elementId, name) {
|
||
const slide = currentSlide();
|
||
const element = slide && (slide.elements || []).find((item) => item.id === elementId);
|
||
if (!element) return;
|
||
const varName = String(name || '').trim();
|
||
state.graph.links = state.graph.links.filter((link) =>
|
||
!(link.to.kind === 'slide' && link.to.id === slide.id && link.to.port.startsWith(`var:${elementId}:`))
|
||
);
|
||
if (!varName) {
|
||
element.text = String(element.text || '').replace(/\{\{\s*[\w.-]+\s*\}\}/g, '').trim();
|
||
renderAll();
|
||
scheduleThumbs();
|
||
scheduleSave();
|
||
return;
|
||
}
|
||
const text = String(element.text || '');
|
||
if (/\{\{\s*[\w.-]+\s*\}\}/.test(text)) {
|
||
element.text = text.replace(/\{\{\s*[\w.-]+\s*\}\}/g, `{{${varName}}}`);
|
||
} else {
|
||
element.text = `${text}${text ? ' ' : ''}{{${varName}}}`;
|
||
}
|
||
const variable = ensureVariableNode(varName);
|
||
pushLink(
|
||
{ kind: 'variable', id: variable.id, port: 'value' },
|
||
{ kind: 'slide', id: slide.id, port: `var:${elementId}:${varName}` }
|
||
);
|
||
renderAll();
|
||
scheduleThumbs();
|
||
scheduleSave();
|
||
toast(`Текст привязан к {{${varName}}}`);
|
||
}
|
||
|
||
function deleteAudioNode(node) {
|
||
state.graph.links = state.graph.links.filter((link) =>
|
||
!(link.from.kind === 'audio' && link.from.id === node.id) && !(link.to.kind === 'audio' && link.to.id === node.id)
|
||
);
|
||
state.graph.audios = state.graph.audios.filter((item) => item.id !== node.id);
|
||
if (node.elementId) {
|
||
state.slides.forEach((slide) => {
|
||
(slide.elements || []).forEach((element) => {
|
||
if (element.type !== 'button' || !element.action) return;
|
||
if ((element.action.type === 'play' || element.action.type === 'stop') && element.action.audioId === node.elementId) {
|
||
element.action = { ...element.action, type: 'none', audioId: '', scriptNodeId: '' };
|
||
}
|
||
});
|
||
});
|
||
}
|
||
const slide = currentSlide();
|
||
state.selectedNode = slide ? { type: 'slide', id: slide.id } : null;
|
||
renderAll();
|
||
scheduleSave();
|
||
toast('Аудио-нода удалена');
|
||
}
|
||
|
||
function deleteVariableNode(node) {
|
||
state.graph.links
|
||
.filter((link) => link.from.kind === 'variable' && link.from.id === node.id)
|
||
.forEach((link) => {
|
||
if (link.to.kind !== 'slide' || !link.to.port.startsWith('var:')) return;
|
||
const parts = link.to.port.split(':');
|
||
if (parts.length >= 3) removeVarPlaceholder(parts[1], parts.slice(2).join(':'));
|
||
});
|
||
state.graph.links = state.graph.links.filter((link) =>
|
||
!(link.from.kind === 'variable' && link.from.id === node.id) && !(link.to.kind === 'variable' && link.to.id === node.id)
|
||
);
|
||
state.graph.variables = state.graph.variables.filter((item) => item.id !== node.id);
|
||
const slide = currentSlide();
|
||
state.selectedNode = slide ? { type: 'slide', id: slide.id } : null;
|
||
renderAll();
|
||
scheduleThumbs();
|
||
scheduleSave();
|
||
toast('Нода переменной удалена');
|
||
}
|
||
|
||
inspectorEl.addEventListener('input', (event) => {
|
||
const input = event.target;
|
||
if (input.dataset && input.dataset.nodeProp) handleNodeInput(input);
|
||
else if (input.dataset && input.dataset.prop) handleInspectorInput(input, false);
|
||
});
|
||
|
||
inspectorEl.addEventListener('change', (event) => {
|
||
const input = event.target;
|
||
if (input.dataset && input.dataset.nodeProp) {
|
||
handleNodeInput(input, true);
|
||
return;
|
||
}
|
||
if (input.dataset && input.dataset.varBind) {
|
||
bindElementVariable(input.dataset.varBind, input.value);
|
||
return;
|
||
}
|
||
if (input.matches('[data-upload="video"]')) {
|
||
const file = input.files && input.files[0];
|
||
if (file) uploadVideo(file);
|
||
return;
|
||
}
|
||
if (input.matches('[data-upload="image"]')) {
|
||
const file = input.files && input.files[0];
|
||
if (file) uploadImage(file);
|
||
return;
|
||
}
|
||
if (input.matches('[data-upload="background"]')) {
|
||
const file = input.files && input.files[0];
|
||
if (file) uploadBackground(file);
|
||
return;
|
||
}
|
||
if (input.matches('[data-node-link]')) {
|
||
const node = state.selectedNode && state.selectedNode.type === 'script'
|
||
? findScriptNode(state.selectedNode.id)
|
||
: null;
|
||
if (node) attachScriptToButton(node, input.value);
|
||
return;
|
||
}
|
||
if (input.dataset && input.dataset.prop) handleInspectorInput(input, true);
|
||
});
|
||
|
||
async function uploadFile(file) {
|
||
const response = await fetch(`/api/uploads?name=${encodeURIComponent(file.name)}`, {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': file.type || 'application/octet-stream' },
|
||
body: file,
|
||
});
|
||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||
return response.json();
|
||
}
|
||
|
||
async function uploadVideo(file) {
|
||
const element = selectedElement();
|
||
if (!element || element.type !== 'video') return;
|
||
toast(`Загрузка «${file.name}»…`);
|
||
try {
|
||
const data = await uploadFile(file);
|
||
element.src = data.url;
|
||
renderCanvas();
|
||
renderInspector();
|
||
scheduleThumbs();
|
||
scheduleSave();
|
||
const mb = Math.round(((data.size || 0) / 1024 / 1024) * 10) / 10;
|
||
toast(`Видео загружено · ${mb} МБ`);
|
||
} catch (error) {
|
||
toast('Не удалось загрузить видео');
|
||
}
|
||
}
|
||
|
||
async function uploadImage(file) {
|
||
const element = selectedElement();
|
||
if (!element || element.type !== 'image') return;
|
||
toast(`Загрузка «${file.name}»…`);
|
||
try {
|
||
const data = await uploadFile(file);
|
||
element.src = data.url;
|
||
renderCanvas();
|
||
renderInspector();
|
||
scheduleThumbs();
|
||
scheduleSave();
|
||
toast('Изображение загружено');
|
||
} catch (error) {
|
||
toast('Не удалось загрузить изображение');
|
||
}
|
||
}
|
||
|
||
async function uploadBackground(file) {
|
||
const slide = currentSlide();
|
||
toast(`Загрузка «${file.name}»…`);
|
||
try {
|
||
const data = await uploadFile(file);
|
||
slide.background = slide.background || defaultBackground();
|
||
slide.background.type = 'image';
|
||
slide.background.image = data.url;
|
||
renderCanvas();
|
||
renderInspector();
|
||
scheduleThumbs();
|
||
scheduleSave();
|
||
toast('Фон загружен');
|
||
} catch (error) {
|
||
toast('Не удалось загрузить фон');
|
||
}
|
||
}
|
||
|
||
inspectorEl.addEventListener('click', (event) => {
|
||
const bgType = event.target.closest('[data-bgtype]');
|
||
if (bgType) {
|
||
const slide = currentSlide();
|
||
slide.background = slide.background || defaultBackground();
|
||
slide.background.type = bgType.dataset.bgtype;
|
||
if (slide.background.type === 'gradient' && !slide.background.gradient) slide.background.gradient = DEFAULT_GRADIENT;
|
||
renderCanvas();
|
||
renderInspector();
|
||
scheduleThumbs();
|
||
scheduleSave();
|
||
return;
|
||
}
|
||
|
||
const preset = event.target.closest('[data-bgpreset]');
|
||
if (preset) {
|
||
const slide = currentSlide();
|
||
slide.background = slide.background || defaultBackground();
|
||
slide.background.type = 'gradient';
|
||
slide.background.gradient = preset.dataset.bgpreset;
|
||
renderCanvas();
|
||
renderInspector();
|
||
scheduleThumbs();
|
||
scheduleSave();
|
||
return;
|
||
}
|
||
|
||
const fillSwatch = event.target.closest('[data-fill]');
|
||
if (fillSwatch) {
|
||
const element = selectedElement();
|
||
if (element && element.type === 'shape') {
|
||
element.fill = fillSwatch.dataset.fill;
|
||
renderCanvas();
|
||
renderInspector();
|
||
scheduleThumbs();
|
||
scheduleSave();
|
||
}
|
||
return;
|
||
}
|
||
|
||
const bgColor = event.target.closest('[data-bgcolor]');
|
||
if (bgColor) {
|
||
const slide = currentSlide();
|
||
slide.background = slide.background || defaultBackground();
|
||
slide.background.type = 'color';
|
||
slide.background.color = bgColor.dataset.bgcolor;
|
||
renderCanvas();
|
||
renderInspector();
|
||
scheduleThumbs();
|
||
scheduleSave();
|
||
return;
|
||
}
|
||
|
||
const actionBtn = event.target.closest('[data-act]');
|
||
if (!actionBtn) return;
|
||
const act = actionBtn.dataset.act;
|
||
const element = selectedElement();
|
||
const selected = state.selectedNode;
|
||
const scriptNode = selected && selected.type === 'script' ? findScriptNode(selected.id) : null;
|
||
const variableNode = selected && selected.type === 'variable' ? findVariableNode(selected.id) : null;
|
||
const audioNode = selected && selected.type === 'audio' ? findAudioNode(selected.id) : null;
|
||
const transitionNode = selected && selected.type === 'transition' ? findTransitionNode(selected.id) : null;
|
||
const animNode = selected && selected.type === 'anim' ? findAnimNode(selected.id) : null;
|
||
const pluginNode = selected && selected.type === 'plugin' ? findPluginNode(selected.id) : null;
|
||
|
||
// Выравнивание выбранного элемента по слайду
|
||
if (act.startsWith('align-') && element) {
|
||
pushHistory(true);
|
||
if (act === 'align-left') element.x = 4;
|
||
if (act === 'align-right') element.x = 96 - element.w;
|
||
if (act === 'align-hcenter') element.x = (100 - element.w) / 2;
|
||
if (act === 'align-top') element.y = 4;
|
||
if (act === 'align-bottom') element.y = 96 - element.h;
|
||
if (act === 'align-vcenter') element.y = (100 - element.h) / 2;
|
||
renderCanvas();
|
||
renderInspector();
|
||
scheduleThumbs();
|
||
scheduleSave(true);
|
||
return;
|
||
}
|
||
|
||
if (act === 'video-upload') {
|
||
const input = inspectorEl.querySelector('[data-upload="video"]');
|
||
if (input) input.click();
|
||
} else if (act === 'image-upload') {
|
||
const input = inspectorEl.querySelector('[data-upload="image"]');
|
||
if (input) input.click();
|
||
} else if (act === 'bg-upload') {
|
||
const input = inspectorEl.querySelector('[data-upload="background"]');
|
||
if (input) input.click();
|
||
} else if (act === 'window-refresh') {
|
||
loadWindowTargets(true);
|
||
} else if (act === 'graph-to-canvas' || act === 'node-open-canvas') {
|
||
setView('canvas');
|
||
} else if (act === 'graph-add-script' || act === 'node-new-script') {
|
||
addScriptNode();
|
||
} else if (act === 'graph-add-variable' || act === 'node-new-variable') {
|
||
addVariableNode();
|
||
} else if (act === 'node-new-audio') {
|
||
addAudioNode();
|
||
} else if (act === 'node-delete') {
|
||
if (scriptNode) deleteScriptNode(scriptNode);
|
||
else if (variableNode) deleteVariableNode(variableNode);
|
||
else if (audioNode) deleteAudioNode(audioNode);
|
||
else if (transitionNode) deleteTransitionNode(transitionNode);
|
||
else if (animNode) deleteAnimNode(animNode);
|
||
else if (pluginNode) deletePluginNode(pluginNode);
|
||
} else if (act === 'plugin-new') {
|
||
openPluginEditor(null);
|
||
} else if (act === 'plugin-edit' || act === 'node-open-plugin') {
|
||
openPluginEditor(pluginNode ? pluginNode.pluginId : null);
|
||
} else if (act === 'node-new-plugin') {
|
||
if (pluginNode) addPluginNode(pluginNode.pluginId, pluginNode.fn);
|
||
else openPluginEditor(null);
|
||
} else if (act === 'tree-toggle') {
|
||
setTreeOpen(!state.tree.open || treePanel.classList.contains('collapsed'));
|
||
} else if (act === 'tree-collapse') {
|
||
setTreeOpen(false);
|
||
} else if (act === 'open-tree') {
|
||
setView('graph');
|
||
setTreeOpen(true);
|
||
} else if (act === 'lua-compute' && element && element.type === 'lua') {
|
||
computeLuaElement(element);
|
||
} else if (act === 'lua-reset' && element && element.type === 'lua') {
|
||
element.computed = { style: {}, css: '', html: '', text: '', at: 0 };
|
||
renderCanvas();
|
||
renderInspector();
|
||
scheduleThumbs();
|
||
scheduleSave(true);
|
||
} else if (act === 'graph-add-transition') {
|
||
addTransitionNode();
|
||
} else if (act === 'graph-add-anim') {
|
||
addAnimNode();
|
||
} else if (act === 'node-open-slide' && scriptNode) {
|
||
const linked = findLinkedElement(scriptNode);
|
||
if (linked) {
|
||
state.selected = state.slides.indexOf(linked.slide);
|
||
state.selectedEl = linked.element.id;
|
||
}
|
||
setView('canvas');
|
||
renderAll();
|
||
} else if (act === 'el-delete' && element) {
|
||
const node = element.action && element.action.scriptNodeId
|
||
? findScriptNode(element.action.scriptNodeId)
|
||
: scriptNodeForElement(element.id);
|
||
if (node) {
|
||
node.slideId = '';
|
||
node.elementId = '';
|
||
}
|
||
cleanupElementLinks(element.id);
|
||
pushHistory(true);
|
||
currentSlide().elements = currentSlide().elements.filter((item) => item.id !== element.id);
|
||
state.selectedEl = null;
|
||
renderCanvas();
|
||
renderInspector();
|
||
scheduleThumbs();
|
||
scheduleSave(true);
|
||
} else if (act === 'el-duplicate' && element) {
|
||
duplicateSelectedElement();
|
||
} else if (act === 'el-front' && element) {
|
||
element.z = Math.max(0, ...currentSlide().elements.map((item) => Number(item.z) || 0)) + 1;
|
||
renderCanvas();
|
||
scheduleThumbs();
|
||
scheduleSave();
|
||
} else if (act === 'el-back' && element) {
|
||
element.z = Math.min(0, ...currentSlide().elements.map((item) => Number(item.z) || 0)) - 1;
|
||
renderCanvas();
|
||
scheduleThumbs();
|
||
scheduleSave();
|
||
} else if (act === 'audio-preview' && element) {
|
||
if (!element.src) { toast('Укажите URL аудио'); return; }
|
||
if (window._previewAudio) { window._previewAudio.pause(); window._previewAudio = null; }
|
||
const preview = new Audio(element.src);
|
||
preview.volume = clamp(Number(element.volume) || 0.8, 0, 1);
|
||
window._previewAudio = preview;
|
||
preview.play().catch(() => toast('Не удалось воспроизвести аудио'));
|
||
} else if (act === 'audio-to-music' && element) {
|
||
if (!element.src) { toast('Укажите URL аудио'); return; }
|
||
state.music.src = element.src;
|
||
toast('Аудио назначено фоновой музыкой');
|
||
scheduleSave();
|
||
}
|
||
});
|
||
|
||
// ==================== Верхняя панель / слайды ====================
|
||
document.querySelector('.toolbar').addEventListener('click', (event) => {
|
||
const view = event.target.closest('[data-view]');
|
||
if (view) { setView(view.dataset.view); return; }
|
||
const add = event.target.closest('[data-add]');
|
||
if (add) { addElement(add.dataset.add); return; }
|
||
const action = event.target.closest('[data-act]');
|
||
if (!action) return;
|
||
if (action.dataset.act === 'duplicate-slide') duplicateSlide();
|
||
if (action.dataset.act === 'move-up') moveSlide(-1);
|
||
if (action.dataset.act === 'move-down') moveSlide(1);
|
||
if (action.dataset.act === 'delete-slide') deleteSlide();
|
||
if (action.dataset.act === 'undo') undo();
|
||
if (action.dataset.act === 'redo') redo();
|
||
if (action.dataset.act === 'open-tree') {
|
||
setView('graph');
|
||
setTreeOpen(true);
|
||
}
|
||
});
|
||
|
||
document.querySelector('.graph-toolbar').addEventListener('click', (event) => {
|
||
const add = event.target.closest('[data-graph-add]');
|
||
if (add) {
|
||
if (add.dataset.graphAdd === 'slide') addSlide();
|
||
if (add.dataset.graphAdd === 'script') addScriptNode();
|
||
if (add.dataset.graphAdd === 'audio') addAudioNode();
|
||
if (add.dataset.graphAdd === 'variable') addVariableNode();
|
||
if (add.dataset.graphAdd === 'transition') addTransitionNode();
|
||
if (add.dataset.graphAdd === 'anim') addAnimNode();
|
||
return;
|
||
}
|
||
const action = event.target.closest('[data-act]');
|
||
if (!action) return;
|
||
if (action.dataset.act === 'plugin-new') openPluginEditor(null);
|
||
if (action.dataset.act === 'plugin-edit') openPluginEditor(null);
|
||
if (action.dataset.act === 'tree-toggle') setTreeOpen(!state.tree.open || treePanel.classList.contains('collapsed'));
|
||
});
|
||
|
||
if (treePanel) {
|
||
treePanel.addEventListener('click', (event) => {
|
||
const tab = event.target.closest('[data-tree-tab]');
|
||
if (tab) {
|
||
state.tree.tab = tab.dataset.treeTab === 'plugins' ? 'plugins' : 'base';
|
||
renderTree();
|
||
return;
|
||
}
|
||
const group = event.target.closest('[data-tree-group]');
|
||
if (group) {
|
||
const id = group.dataset.treeGroup;
|
||
state.tree.collapsed[id] = !state.tree.collapsed[id];
|
||
renderTree();
|
||
return;
|
||
}
|
||
const action = event.target.closest('[data-tree-action]');
|
||
if (!action) {
|
||
const panelAction = event.target.closest('[data-act]');
|
||
if (panelAction) {
|
||
if (panelAction.dataset.act === 'plugin-new') openPluginEditor(null);
|
||
if (panelAction.dataset.act === 'plugin-edit') openPluginEditor(null);
|
||
if (panelAction.dataset.act === 'tree-collapse') setTreeOpen(false);
|
||
}
|
||
return;
|
||
}
|
||
const act = action.dataset.treeAction;
|
||
if (act === 'add-element') {
|
||
addElement(action.dataset.kind);
|
||
} else if (act === 'add-node') {
|
||
applyTreeDrag({ kind: 'node', nodeKind: action.dataset.nodeKind });
|
||
} else if (act === 'add-plugin') {
|
||
addPluginNode(action.dataset.pluginId, action.dataset.fn);
|
||
} else if (act === 'toggle-plugin') {
|
||
const id = action.dataset.pluginId;
|
||
state.tree.plugins[id] = !state.tree.plugins[id];
|
||
renderTree();
|
||
} else if (act === 'edit-plugin') {
|
||
openPluginEditor(action.dataset.pluginId);
|
||
} else if (act === 'select-slide') {
|
||
const index = state.slides.findIndex((slide) => slide.id === action.dataset.slideId);
|
||
if (index >= 0) {
|
||
state.selected = index;
|
||
state.selectedEl = null;
|
||
const slide = currentSlide();
|
||
state.selectedNode = slide ? { type: 'slide', id: slide.id } : null;
|
||
renderAll();
|
||
}
|
||
} else if (act === 'select-element') {
|
||
const index = Number(action.dataset.slideIndex) || 0;
|
||
state.selected = clamp(index, 0, state.slides.length - 1);
|
||
state.selectedEl = action.dataset.elementId;
|
||
setView('canvas');
|
||
renderAll();
|
||
} else if (act === 'select-node') {
|
||
state.selectedNode = { type: action.dataset.nodeType, id: action.dataset.nodeId };
|
||
state.selectedLink = null;
|
||
if (state.view !== 'graph') setView('graph');
|
||
else renderAll();
|
||
}
|
||
});
|
||
}
|
||
|
||
if (treeSearchEl) {
|
||
treeSearchEl.addEventListener('input', () => {
|
||
state.tree.query = treeSearchEl.value;
|
||
renderTree();
|
||
});
|
||
}
|
||
|
||
// Drag-and-drop из древа на холст и в граф.
|
||
function treeDragPayload(event) {
|
||
const item = event.target.closest('[data-drag-kind]');
|
||
if (!item) return null;
|
||
const kind = item.dataset.dragKind;
|
||
if (kind === 'element') return { kind, element: item.dataset.kind };
|
||
if (kind === 'node') return { kind, nodeKind: item.dataset.nodeKind };
|
||
if (kind === 'plugin') return { kind, pluginId: item.dataset.pluginId, fn: item.dataset.fn };
|
||
return null;
|
||
}
|
||
|
||
document.addEventListener('dragstart', (event) => {
|
||
const payload = treeDragPayload(event);
|
||
if (!payload) return;
|
||
event.dataTransfer.effectAllowed = 'copy';
|
||
event.dataTransfer.setData('application/x-promptly', JSON.stringify(payload));
|
||
event.dataTransfer.setData('text/plain', JSON.stringify(payload));
|
||
});
|
||
|
||
function readDragPayload(event) {
|
||
try {
|
||
const raw = event.dataTransfer.getData('application/x-promptly') || event.dataTransfer.getData('text/plain');
|
||
if (raw) return JSON.parse(raw);
|
||
} catch (error) { /* не наш drag */ }
|
||
return null;
|
||
}
|
||
|
||
if (canvasWrap) {
|
||
canvasWrap.addEventListener('dragover', (event) => {
|
||
if (!readDragPayload(event) && !(event.dataTransfer && event.dataTransfer.types.includes('application/x-promptly'))) return;
|
||
event.preventDefault();
|
||
event.dataTransfer.dropEffect = 'copy';
|
||
canvasWrap.classList.add('tree-drop');
|
||
});
|
||
canvasWrap.addEventListener('dragleave', () => canvasWrap.classList.remove('tree-drop'));
|
||
canvasWrap.addEventListener('drop', (event) => {
|
||
const payload = readDragPayload(event);
|
||
canvasWrap.classList.remove('tree-drop');
|
||
if (!payload) return;
|
||
event.preventDefault();
|
||
let point = null;
|
||
if (payload.kind === 'element') {
|
||
const rect = canvasEl.getBoundingClientRect();
|
||
point = {
|
||
x: clamp(((event.clientX - rect.left) / rect.width) * 100, 0, 92),
|
||
y: clamp(((event.clientY - rect.top) / rect.height) * 100, 0, 92),
|
||
};
|
||
}
|
||
if (state.view !== 'canvas') setView('canvas');
|
||
applyTreeDrag(payload, point);
|
||
});
|
||
}
|
||
|
||
if (graphScroll) {
|
||
graphScroll.addEventListener('dragover', (event) => {
|
||
event.preventDefault();
|
||
event.dataTransfer.dropEffect = 'copy';
|
||
graphScroll.classList.add('dragover');
|
||
});
|
||
graphScroll.addEventListener('dragleave', (event) => {
|
||
if (event.target === graphScroll || !graphScroll.contains(event.relatedTarget)) graphScroll.classList.remove('dragover');
|
||
});
|
||
graphScroll.addEventListener('drop', (event) => {
|
||
const payload = readDragPayload(event);
|
||
graphScroll.classList.remove('dragover');
|
||
if (!payload) return;
|
||
event.preventDefault();
|
||
const rect = graphWorld.getBoundingClientRect();
|
||
const point = {
|
||
x: Math.max(20, event.clientX - rect.left - 60),
|
||
y: Math.max(20, event.clientY - rect.top - 20),
|
||
};
|
||
if (payload.kind === 'element') {
|
||
// Элемент из древа на граф: добавляем на текущий слайд, без координат графа.
|
||
applyTreeDrag(payload, null);
|
||
} else {
|
||
applyTreeDrag(payload, point);
|
||
}
|
||
});
|
||
}
|
||
|
||
// ==================== Редактор плагинов: события ====================
|
||
if (pluginModal) {
|
||
$('close-plugin').addEventListener('click', closePluginEditor);
|
||
$('plugin-close').addEventListener('click', closePluginEditor);
|
||
pluginModal.addEventListener('click', (event) => {
|
||
if (event.target === pluginModal) closePluginEditor();
|
||
});
|
||
$('plugin-new').addEventListener('click', () => {
|
||
state.pluginDraft = newPluginDraft();
|
||
state.pluginDirty = false;
|
||
renderPluginEditor();
|
||
const input = $('plugin-name');
|
||
if (input) input.focus();
|
||
});
|
||
$('plugin-reload').addEventListener('click', async () => {
|
||
await loadPlugins();
|
||
toast('Реестр плагинов перечитан');
|
||
});
|
||
$('plugin-save').addEventListener('click', savePluginDraft);
|
||
$('plugin-delete').addEventListener('click', deletePluginDraft);
|
||
pluginListEl.addEventListener('click', (event) => {
|
||
const pick = event.target.closest('[data-plugin-pick]');
|
||
if (!pick) return;
|
||
const plugin = (state.pluginRegistry || []).find((item) => item.id === pick.dataset.pluginPick);
|
||
if (!plugin) return;
|
||
state.pluginDraft = pluginDraftFrom(plugin);
|
||
state.pluginDirty = false;
|
||
renderPluginEditor();
|
||
});
|
||
['plugin-name', 'plugin-desc'].forEach((id) => {
|
||
const input = $(id);
|
||
if (input) input.addEventListener('input', () => { state.pluginDirty = true; });
|
||
});
|
||
const colorInput = $('plugin-color');
|
||
if (colorInput) colorInput.addEventListener('input', () => { state.pluginDirty = true; });
|
||
}
|
||
|
||
if (graphSvg) {
|
||
graphSvg.addEventListener('click', (event) => {
|
||
const edge = event.target.closest('path.edge');
|
||
if (!edge) return;
|
||
state.selectedLink = edge.dataset.linkId;
|
||
drawGraphEdges();
|
||
});
|
||
}
|
||
|
||
const tplMenu = $('tpl-menu');
|
||
$('add-slide').addEventListener('click', (event) => {
|
||
event.stopPropagation();
|
||
tplMenu.hidden = !tplMenu.hidden;
|
||
});
|
||
tplMenu.addEventListener('click', (event) => {
|
||
const button = event.target.closest('[data-tpl]');
|
||
if (!button) return;
|
||
tplMenu.hidden = true;
|
||
addSlide(button.dataset.tpl);
|
||
toast('Слайд добавлен из шаблона');
|
||
});
|
||
document.addEventListener('click', (event) => {
|
||
if (!tplMenu.hidden && !event.target.closest('#tpl-menu') && !event.target.closest('#add-slide')) {
|
||
tplMenu.hidden = true;
|
||
}
|
||
});
|
||
|
||
titleInput.addEventListener('input', () => {
|
||
state.title = titleInput.value;
|
||
scheduleSave();
|
||
});
|
||
|
||
// ==================== Сохранение ====================
|
||
let saveTimer = null;
|
||
function scheduleSave(discrete = false) {
|
||
if (!restoringHistory) pushHistory(discrete);
|
||
state.dirty = true;
|
||
setStatus('dirty', 'Изменения не сохранены');
|
||
clearTimeout(saveTimer);
|
||
saveTimer = setTimeout(save, 700);
|
||
}
|
||
|
||
// ------- История (undo/redo) -------
|
||
function docSnapshot() {
|
||
return JSON.stringify({
|
||
title: state.title,
|
||
slides: state.slides,
|
||
variables: state.variables,
|
||
music: state.music,
|
||
lua: state.lua,
|
||
commands: state.commands,
|
||
graph: state.graph,
|
||
});
|
||
}
|
||
|
||
function pushHistory(force = false) {
|
||
const snap = docSnapshot();
|
||
if (undoHistory.index >= 0 && undoHistory.stack[undoHistory.index] === snap) return;
|
||
const now = Date.now();
|
||
// Непрерывный ввод (печать, ползунки) склеиваем в один шаг за 450 мс.
|
||
if (!force && undoHistory.index >= 0 && now - undoHistory.lastPush < 450) return;
|
||
undoHistory.lastPush = now;
|
||
undoHistory.stack = undoHistory.stack.slice(0, undoHistory.index + 1);
|
||
undoHistory.stack.push(snap);
|
||
if (undoHistory.stack.length > undoHistory.limit) undoHistory.stack.shift();
|
||
undoHistory.index = undoHistory.stack.length - 1;
|
||
}
|
||
|
||
function restoreSnapshot(snap) {
|
||
const data = JSON.parse(snap);
|
||
restoringHistory = true;
|
||
try {
|
||
state.title = data.title || '';
|
||
titleInput.value = state.title;
|
||
state.slides = (data.slides || []).map(hydrateSlide);
|
||
if (!state.slides.length) state.slides = [newSlide()];
|
||
state.variables = data.variables || {};
|
||
state.music = data.music || { src: '', volume: 0.5 };
|
||
state.lua = data.lua || '';
|
||
state.commands = Array.isArray(data.commands) ? data.commands : [];
|
||
hydrateGraph(data.graph);
|
||
state.selected = clamp(state.selected, 0, state.slides.length - 1);
|
||
state.selectedEl = null;
|
||
state.selectedNode = { type: 'slide', id: state.slides[state.selected].id };
|
||
renderAll();
|
||
scheduleSave();
|
||
} finally {
|
||
restoringHistory = false;
|
||
}
|
||
}
|
||
|
||
function undo() {
|
||
if (undoHistory.index <= 0) { toast('Нечего отменять'); return; }
|
||
undoHistory.index -= 1;
|
||
restoreSnapshot(undoHistory.stack[undoHistory.index]);
|
||
toast('Шаг отменён');
|
||
}
|
||
|
||
function redo() {
|
||
if (undoHistory.index >= undoHistory.stack.length - 1) { toast('Нечего повторять'); return; }
|
||
undoHistory.index += 1;
|
||
restoreSnapshot(undoHistory.stack[undoHistory.index]);
|
||
toast('Шаг повторён');
|
||
}
|
||
|
||
async function save() {
|
||
if (state.saving) { state.pending = true; return; }
|
||
state.saving = true;
|
||
setStatus('saving', 'Сохранение…');
|
||
const payload = {
|
||
title: state.title.trim() || 'Без названия',
|
||
slides: state.slides,
|
||
variables: state.variables,
|
||
music: state.music,
|
||
lua: state.lua,
|
||
commands: state.commands,
|
||
graph: state.graph,
|
||
};
|
||
const url = state.id ? `/api/presentations/${state.id}` : '/api/presentations';
|
||
const method = state.id ? 'PUT' : 'POST';
|
||
try {
|
||
const response = await fetch(url, {
|
||
method,
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify(payload),
|
||
});
|
||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||
const presentation = await response.json();
|
||
if (!state.id) {
|
||
state.id = presentation.id;
|
||
undoHistory.stack = [];
|
||
undoHistory.index = -1;
|
||
pushHistory(true);
|
||
history.replaceState(null, '', `editor.html?id=${presentation.id}`);
|
||
}
|
||
state.updatedAt = presentation.updatedAt || Date.now();
|
||
state.dirty = false;
|
||
copyLinkBtn.disabled = false;
|
||
$('export-btn').disabled = false;
|
||
state.saving = false;
|
||
setStatus('saved', 'Сохранено');
|
||
if (state.pending) {
|
||
state.pending = false;
|
||
save();
|
||
}
|
||
} catch (error) {
|
||
state.saving = false;
|
||
setStatus('dirty', 'Ошибка сохранения');
|
||
}
|
||
}
|
||
|
||
// Дожимаем несохранённые правки при закрытии вкладки.
|
||
window.addEventListener('pagehide', () => {
|
||
if (!state.dirty || !saveTimer) return;
|
||
clearTimeout(saveTimer);
|
||
saveTimer = null;
|
||
const payload = JSON.stringify({
|
||
title: state.title.trim() || 'Без названия',
|
||
slides: state.slides,
|
||
variables: state.variables,
|
||
music: state.music,
|
||
lua: state.lua,
|
||
commands: state.commands,
|
||
graph: state.graph,
|
||
});
|
||
if (state.id && navigator.sendBeacon) {
|
||
navigator.sendBeacon(
|
||
`/api/presentations/${state.id}`,
|
||
new Blob([payload], { type: 'application/json' })
|
||
);
|
||
}
|
||
});
|
||
|
||
function audienceUrl() {
|
||
const url = new URL('viewer.html', location.href);
|
||
url.searchParams.set('id', state.id);
|
||
url.searchParams.set('mode', 'audience');
|
||
return url.toString();
|
||
}
|
||
|
||
copyLinkBtn.addEventListener('click', async () => {
|
||
if (!state.id) return;
|
||
const original = copyLinkBtn.innerHTML;
|
||
try {
|
||
await navigator.clipboard.writeText(audienceUrl());
|
||
copyLinkBtn.textContent = 'Скопировано';
|
||
} catch (error) {
|
||
window.prompt('Ссылка для зрителей:', audienceUrl());
|
||
}
|
||
setTimeout(() => (copyLinkBtn.innerHTML = original), 1600);
|
||
});
|
||
|
||
$('demo-btn').addEventListener('click', async () => {
|
||
clearTimeout(saveTimer);
|
||
await save();
|
||
if (state.id) window.open(`viewer.html?id=${state.id}&mode=speaker`, '_blank');
|
||
});
|
||
|
||
document.addEventListener('keydown', (event) => {
|
||
const target = event.target;
|
||
const isField = !!(target && target.matches && target.matches('input, textarea, select'))
|
||
|| !!(target && target.isContentEditable);
|
||
const mod = event.ctrlKey || event.metaKey;
|
||
if (mod && event.key.toLowerCase() === 's') {
|
||
event.preventDefault();
|
||
clearTimeout(saveTimer);
|
||
save();
|
||
}
|
||
if (mod && event.key.toLowerCase() === 'z') {
|
||
event.preventDefault();
|
||
if (event.shiftKey) redo(); else undo();
|
||
return;
|
||
}
|
||
if (mod && event.key.toLowerCase() === 'y') {
|
||
event.preventDefault();
|
||
redo();
|
||
return;
|
||
}
|
||
if (mod && event.key.toLowerCase() === 'c' && !isField && state.view === 'canvas' && state.selectedEl) {
|
||
const el = selectedElement();
|
||
if (el) {
|
||
state.clipboard = JSON.parse(JSON.stringify(el));
|
||
toast('Элемент скопирован · Ctrl+V — вставить');
|
||
}
|
||
return;
|
||
}
|
||
if (mod && event.key.toLowerCase() === 'v' && !isField && state.view === 'canvas' && state.clipboard) {
|
||
event.preventDefault();
|
||
pasteElement();
|
||
return;
|
||
}
|
||
if (mod && event.key.toLowerCase() === 'd' && !isField && state.view === 'canvas' && state.selectedEl) {
|
||
event.preventDefault();
|
||
duplicateSelectedElement();
|
||
return;
|
||
}
|
||
// Тонкая подводка выбранного элемента стрелками (Shift — шаг крупнее)
|
||
if (!isField && !mod && state.view === 'canvas' && state.selectedEl && event.key.startsWith('Arrow')) {
|
||
const step = event.shiftKey ? 2.5 : 0.5;
|
||
if (event.key === 'ArrowLeft') { event.preventDefault(); nudgeSelected(-step, 0); return; }
|
||
if (event.key === 'ArrowRight') { event.preventDefault(); nudgeSelected(step, 0); return; }
|
||
if (event.key === 'ArrowUp') { event.preventDefault(); nudgeSelected(0, -step); return; }
|
||
if (event.key === 'ArrowDown') { event.preventDefault(); nudgeSelected(0, step); return; }
|
||
}
|
||
if (event.key === 'Delete' && state.view === 'graph' && !isField) {
|
||
if (state.selectedLink) {
|
||
removeGraphLink(state.selectedLink);
|
||
return;
|
||
}
|
||
const selected = state.selectedNode;
|
||
if (selected && selected.type === 'variable') {
|
||
const node = findVariableNode(selected.id);
|
||
if (node) deleteVariableNode(node);
|
||
return;
|
||
}
|
||
if (selected && selected.type === 'audio') {
|
||
const node = findAudioNode(selected.id);
|
||
if (node) deleteAudioNode(node);
|
||
return;
|
||
}
|
||
if (selected && selected.type === 'script') {
|
||
const node = findScriptNode(selected.id);
|
||
if (node) deleteScriptNode(node);
|
||
return;
|
||
}
|
||
if (selected && selected.type === 'transition') {
|
||
const node = findTransitionNode(selected.id);
|
||
if (node) deleteTransitionNode(node);
|
||
return;
|
||
}
|
||
if (selected && selected.type === 'anim') {
|
||
const node = findAnimNode(selected.id);
|
||
if (node) deleteAnimNode(node);
|
||
return;
|
||
}
|
||
if (selected && selected.type === 'plugin') {
|
||
const node = findPluginNode(selected.id);
|
||
if (node) deletePluginNode(node);
|
||
return;
|
||
}
|
||
}
|
||
if (event.key === 'Delete' && state.view === 'canvas' && state.selectedEl && !isField) {
|
||
const element = selectedElement();
|
||
if (!element) return;
|
||
const node = element.action && element.action.scriptNodeId
|
||
? findScriptNode(element.action.scriptNodeId)
|
||
: scriptNodeForElement(element.id);
|
||
if (node) {
|
||
node.slideId = '';
|
||
node.elementId = '';
|
||
}
|
||
cleanupElementLinks(element.id);
|
||
pushHistory(true);
|
||
currentSlide().elements = currentSlide().elements.filter((item) => item.id !== element.id);
|
||
state.selectedEl = null;
|
||
renderCanvas();
|
||
renderInspector();
|
||
scheduleThumbs();
|
||
scheduleSave(true);
|
||
}
|
||
if (event.key === 'Escape') {
|
||
selectElement(null);
|
||
state.selectedLink = null;
|
||
settingsModal.hidden = true;
|
||
commandsModal.hidden = true;
|
||
if (tplMenu) tplMenu.hidden = true;
|
||
}
|
||
});
|
||
|
||
// ==================== Настройки презентации ====================
|
||
function varsToText(variables) {
|
||
return Object.entries(variables || {})
|
||
.map(([key, value]) => `${key} = ${value}`)
|
||
.join('\n');
|
||
}
|
||
|
||
function parseVars(text) {
|
||
const result = {};
|
||
String(text || '').split('\n').forEach((line) => {
|
||
const trimmed = line.trim();
|
||
if (!trimmed || trimmed.startsWith('#')) return;
|
||
const index = trimmed.indexOf('=');
|
||
if (index <= 0) return;
|
||
const key = trimmed.slice(0, index).trim();
|
||
let value = trimmed.slice(index + 1).trim();
|
||
if (!key) return;
|
||
if (value === 'true') value = true;
|
||
else if (value === 'false') value = false;
|
||
else if (/^-?\d+(\.\d+)?$/.test(value)) value = Number(value);
|
||
else if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
|
||
value = value.slice(1, -1);
|
||
}
|
||
result[key] = value;
|
||
});
|
||
return result;
|
||
}
|
||
|
||
function openSettings() {
|
||
$('vars-input').value = varsToText(state.variables);
|
||
$('music-src').value = state.music.src || '';
|
||
$('music-volume').value = String(Math.round((state.music.volume ?? 0.5) * 100));
|
||
$('music-volume-out').textContent = `${Math.round((state.music.volume ?? 0.5) * 100)}%`;
|
||
$('lua-input').value = state.lua || '';
|
||
settingsModal.hidden = false;
|
||
}
|
||
|
||
$('settings-btn').addEventListener('click', openSettings);
|
||
$('close-settings').addEventListener('click', () => (settingsModal.hidden = true));
|
||
$('cancel-settings').addEventListener('click', () => (settingsModal.hidden = true));
|
||
settingsModal.addEventListener('click', (event) => {
|
||
if (event.target === settingsModal) settingsModal.hidden = true;
|
||
});
|
||
|
||
$('music-volume').addEventListener('input', () => {
|
||
$('music-volume-out').textContent = `${$('music-volume').value}%`;
|
||
});
|
||
|
||
$('save-settings').addEventListener('click', () => {
|
||
state.variables = parseVars($('vars-input').value);
|
||
state.music = {
|
||
src: $('music-src').value.trim(),
|
||
volume: clamp(Number($('music-volume').value) / 100, 0, 1),
|
||
};
|
||
state.lua = $('lua-input').value;
|
||
settingsModal.hidden = true;
|
||
renderCanvas();
|
||
renderThumbs();
|
||
scheduleSave();
|
||
toast('Настройки сохранены');
|
||
});
|
||
|
||
// ==================== Команды ====================
|
||
function renderCommandsEditor() {
|
||
commandsListEl.innerHTML = '';
|
||
if (!state.commandDraft.length) {
|
||
commandsListEl.innerHTML = '<p class="hint">Пока нет команд. Добавьте первую — например, «Следующий раздел» с вызовом <code>app.next()</code>.</p>';
|
||
return;
|
||
}
|
||
state.commandDraft.forEach((command, index) => {
|
||
const item = document.createElement('div');
|
||
item.className = 'command-item';
|
||
item.innerHTML = `
|
||
<div class="command-item-head">
|
||
<input data-command="label" placeholder="Название команды">
|
||
<button class="danger" data-command-delete="${index}" title="Удалить">Удалить</button>
|
||
</div>
|
||
<input data-command="description" placeholder="Короткое описание для докладчика">
|
||
<textarea data-command="code" rows="4" spellcheck="false" placeholder="vars.step = (vars.step or 0) + 1 app.log(vars.step)"></textarea>`;
|
||
item.querySelector('[data-command="label"]').value = command.label || '';
|
||
item.querySelector('[data-command="description"]').value = command.description || '';
|
||
item.querySelector('[data-command="code"]').value = command.code || '';
|
||
commandsListEl.appendChild(item);
|
||
});
|
||
}
|
||
|
||
commandsListEl.addEventListener('input', (event) => {
|
||
const field = event.target.dataset.command;
|
||
if (!field) return;
|
||
const item = event.target.closest('.command-item');
|
||
const index = [...commandsListEl.querySelectorAll('.command-item')].indexOf(item);
|
||
if (index < 0 || !state.commandDraft[index]) return;
|
||
state.commandDraft[index][field] = event.target.value;
|
||
});
|
||
|
||
commandsListEl.addEventListener('click', (event) => {
|
||
const remove = event.target.closest('[data-command-delete]');
|
||
if (!remove) return;
|
||
state.commandDraft.splice(Number(remove.dataset.commandDelete), 1);
|
||
renderCommandsEditor();
|
||
});
|
||
|
||
$('add-command').addEventListener('click', () => {
|
||
state.commandDraft.push({
|
||
id: uid(),
|
||
label: `Команда ${state.commandDraft.length + 1}`,
|
||
description: '',
|
||
code: '',
|
||
});
|
||
renderCommandsEditor();
|
||
const fields = commandsListEl.querySelectorAll('[data-command="label"]');
|
||
if (fields.length) fields[fields.length - 1].focus();
|
||
});
|
||
|
||
function openCommands() {
|
||
state.commandDraft = state.commands.map((command) => ({ ...command }));
|
||
renderCommandsEditor();
|
||
commandsModal.hidden = false;
|
||
}
|
||
|
||
$('commands-btn').addEventListener('click', openCommands);
|
||
$('close-commands').addEventListener('click', () => (commandsModal.hidden = true));
|
||
$('cancel-commands').addEventListener('click', () => (commandsModal.hidden = true));
|
||
commandsModal.addEventListener('click', (event) => {
|
||
if (event.target === commandsModal) commandsModal.hidden = true;
|
||
});
|
||
$('save-commands').addEventListener('click', () => {
|
||
state.commands = state.commandDraft
|
||
.map((command) => ({
|
||
id: command.id || uid(),
|
||
label: String(command.label || '').trim() || 'Команда',
|
||
description: String(command.description || '').trim(),
|
||
code: command.code || '',
|
||
}))
|
||
.filter((command) => String(command.code).trim() || command.label !== 'Команда');
|
||
commandsModal.hidden = true;
|
||
scheduleSave();
|
||
toast(`Команд в консоли: ${state.commands.length}`);
|
||
});
|
||
|
||
// ==================== Живой статус и синхронизация между окнами ====================
|
||
function applyRemote(presentation) {
|
||
state.updatedAt = Number(presentation.updatedAt) || state.updatedAt;
|
||
state.title = presentation.title || '';
|
||
titleInput.value = state.title;
|
||
state.slides = (presentation.slides || []).map(hydrateSlide);
|
||
if (!state.slides.length) state.slides = [newSlide()];
|
||
state.variables = presentation.variables || {};
|
||
state.music = presentation.music || { src: '', volume: 0.5 };
|
||
state.lua = presentation.lua || '';
|
||
state.commands = Array.isArray(presentation.commands) ? presentation.commands : [];
|
||
hydrateGraph(presentation.graph);
|
||
state.selected = clamp(state.selected, 0, state.slides.length - 1);
|
||
state.selectedEl = null;
|
||
renderAll();
|
||
undoHistory.stack = [];
|
||
undoHistory.index = -1;
|
||
pushHistory(true);
|
||
toast('Презентация обновлена из другого окна');
|
||
}
|
||
|
||
function connectLiveStatus() {
|
||
let ws;
|
||
const wsProto = () => (location.protocol === 'https:' ? 'wss' : 'ws');
|
||
const connect = () => {
|
||
ws = new WebSocket(`${wsProto()}://${location.host}/`);
|
||
ws.onmessage = (event) => {
|
||
let message;
|
||
try { message = JSON.parse(event.data); } catch (error) { return; }
|
||
if (message.type === 'sessions' && state.id) {
|
||
const session = message.sessions.find((item) => item.presentationId === state.id);
|
||
if (session) {
|
||
liveChip.hidden = false;
|
||
liveChip.textContent = `● Демонстрация · ${session.viewers} зр.`;
|
||
} else {
|
||
liveChip.hidden = true;
|
||
}
|
||
}
|
||
// Совместное редактирование: если документ изменился в другом окне
|
||
// и у нас нет несохранённых правок — подтягиваем свежую версию.
|
||
if (message.type === 'presentations' && state.id && !state.dirty) {
|
||
const fresh = (message.presentations || []).find((item) => item.id === state.id);
|
||
if (fresh && Number(fresh.updatedAt) > Number(state.updatedAt)) applyRemote(fresh);
|
||
}
|
||
if (message.type === 'plugins' && Array.isArray(message.plugins)) {
|
||
state.pluginRegistry = message.plugins;
|
||
renderTree();
|
||
if (!pluginModal.hidden && state.pluginDraft && !state.pluginDirty) {
|
||
const fresh = message.plugins.find((plugin) => plugin.id === state.pluginDraft.id);
|
||
if (fresh) {
|
||
state.pluginDraft = pluginDraftFrom(fresh);
|
||
renderPluginEditor();
|
||
}
|
||
}
|
||
}
|
||
};
|
||
ws.onclose = () => setTimeout(connect, 2000);
|
||
ws.onerror = () => ws.close();
|
||
};
|
||
connect();
|
||
}
|
||
|
||
// ==================== Загрузка ====================
|
||
async function init() {
|
||
const id = new URLSearchParams(location.search).get('id');
|
||
if (id) {
|
||
try {
|
||
const response = await fetch(`/api/presentations/${encodeURIComponent(id)}`);
|
||
if (response.ok) {
|
||
const presentation = await response.json();
|
||
state.id = presentation.id;
|
||
state.title = presentation.title || '';
|
||
state.variables = presentation.variables || {};
|
||
state.music = presentation.music || { src: '', volume: 0.5 };
|
||
state.lua = presentation.lua || '';
|
||
state.commands = Array.isArray(presentation.commands) ? presentation.commands : [];
|
||
state.slides = (presentation.slides || []).map(hydrateSlide);
|
||
if (!state.slides.length) state.slides = [newSlide()];
|
||
hydrateGraph(presentation.graph);
|
||
titleInput.value = state.title;
|
||
state.updatedAt = Number(presentation.updatedAt) || Date.now();
|
||
copyLinkBtn.disabled = false;
|
||
$('export-btn').disabled = false;
|
||
setStatus('saved', 'Загружено');
|
||
} else {
|
||
history.replaceState(null, '', 'editor.html');
|
||
setStatus('dirty', 'Презентация не найдена — создаётся новая');
|
||
}
|
||
} catch (error) {
|
||
setStatus('dirty', 'Ошибка загрузки');
|
||
}
|
||
}
|
||
await loadPlugins();
|
||
renderAll();
|
||
pushHistory(true); // базовый снимок для Ctrl+Z
|
||
connectLiveStatus();
|
||
}
|
||
|
||
// ==================== Экспорт / импорт ====================
|
||
$('export-btn').addEventListener('click', async () => {
|
||
clearTimeout(saveTimer);
|
||
await save();
|
||
const payload = {
|
||
app: 'promptly',
|
||
version: 2,
|
||
exportedAt: new Date().toISOString(),
|
||
title: state.title,
|
||
slides: state.slides,
|
||
variables: state.variables,
|
||
music: state.music,
|
||
lua: state.lua,
|
||
commands: state.commands,
|
||
graph: state.graph,
|
||
};
|
||
const blob = new Blob([JSON.stringify(payload, null, 2)], { type: 'application/json' });
|
||
const link = document.createElement('a');
|
||
const safeTitle = String(state.title || 'presentation').replace(/[^\wа-яёА-ЯЁ -]+/gi, '').trim().slice(0, 48) || 'presentation';
|
||
link.href = URL.createObjectURL(blob);
|
||
link.download = `${safeTitle}.promptly.json`;
|
||
link.click();
|
||
setTimeout(() => URL.revokeObjectURL(link.href), 4000);
|
||
toast('JSON-файл презентации скачан');
|
||
});
|
||
|
||
$('import-btn').addEventListener('click', () => $('import-file').click());
|
||
$('import-file').addEventListener('change', async (event) => {
|
||
const file = event.target.files && event.target.files[0];
|
||
event.target.value = '';
|
||
if (!file) return;
|
||
try {
|
||
const data = JSON.parse(await file.text());
|
||
if (!data || !Array.isArray(data.slides)) throw new Error('bad format');
|
||
const response = await fetch('/api/presentations', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify(data),
|
||
});
|
||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||
const created = await response.json();
|
||
toast('Презентация импортирована');
|
||
location.href = `editor.html?id=${encodeURIComponent(created.id)}`;
|
||
} catch (error) {
|
||
toast('Не удалось импортировать: проверьте JSON-файл');
|
||
}
|
||
});
|
||
|
||
init();
|
||
</script>
|
||
</body>
|
||
</html>
|