3172 lines
146 KiB
HTML
3172 lines
146 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: #080b16;
|
||
--panel: rgba(255, 255, 255, .04);
|
||
--panel-2: rgba(255, 255, 255, .065);
|
||
--border: rgba(255, 255, 255, .09);
|
||
--accent: #818cf8;
|
||
--text: #e8ecf6;
|
||
--muted: #94a3b8;
|
||
--danger: #f87171;
|
||
}
|
||
* { box-sizing: border-box; }
|
||
html, body { height: 100%; }
|
||
body {
|
||
margin: 0; overflow: hidden; color: var(--text);
|
||
font-family: system-ui, -apple-system, 'Segoe UI', 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, #6366f1, #a855f7); color: #fff; font-weight: 600; }
|
||
.primary:hover:not(:disabled) { filter: brightness(1.12); background: linear-gradient(90deg, #6366f1, #a855f7); }
|
||
.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, #818cf8, #e879f9); -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: #f0abfc; 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: #818cf8; 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: #c7d2fe; 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 #818cf8; 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: #818cf8; 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: #c7d2fe; }
|
||
|
||
/* ===== Инспектор ===== */
|
||
.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: #818cf8; }
|
||
.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-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: #c7d2fe; }
|
||
.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 #818cf8; cursor: crosshair; transition: .12s; z-index: 2; }
|
||
.gport.in { left: -6px; }
|
||
.gport.out { right: -6px; }
|
||
.gport:hover { background: #818cf8; 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; }
|
||
|
||
/* ===== Команды ===== */
|
||
.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: #a5b4fc; font-size: 10.5px; }
|
||
.field-actions { display: flex; gap: 6px; flex-wrap: wrap; }
|
||
.field-actions button { flex: 1; padding: 7px 8px; font-size: 12px; }
|
||
.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: #c7d2fe; }
|
||
.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: #818cf8; }
|
||
.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; }
|
||
}
|
||
</style>
|
||
</head>
|
||
<body>
|
||
<header class="topbar">
|
||
<a class="back" href="index.html" title="На главную">←</a>
|
||
<div class="logo">🎤 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="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>
|
||
<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>
|
||
<span class="toolbar-label">Добавить</span>
|
||
<button data-add="text">Текст</button>
|
||
<button data-add="image">Картинка</button>
|
||
<button data-add="button">Кнопка</button>
|
||
<button data-add="audio">Аудио</button>
|
||
<button data-add="video">Видео</button>
|
||
<button data-add="window">Окно</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>
|
||
<span class="spacer"></span>
|
||
<span class="graph-hint">Тяните от выхода <span style="color:#fbbf24">◯</span> ко входу · клик по линии — выбор · Delete — удалить · двойной клик по слайду — холст</span>
|
||
</div>
|
||
<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 class="statusbar">
|
||
<span>Слайд <b id="slide-index">1</b> из <b id="slide-total">1</b></span>
|
||
<span id="status-hint">Перетаскивайте элементы · Ctrl+S — сохранить</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="toast" id="toast"></div>
|
||
|
||
<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(135deg, #f8fafc 0%, #e2e8f0 100%)',
|
||
];
|
||
|
||
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 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,
|
||
})),
|
||
};
|
||
}
|
||
|
||
const state = {
|
||
id: null,
|
||
title: '',
|
||
slides: [newSlide()],
|
||
variables: {},
|
||
music: { src: '', volume: 0.5 },
|
||
lua: '',
|
||
commands: [],
|
||
graph: { positions: {}, scripts: [], audios: [], variables: [], links: [], jumps: {} },
|
||
view: 'canvas',
|
||
selectedNode: null,
|
||
commandDraft: [],
|
||
windowTargets: [],
|
||
windowEndpoint: '',
|
||
selected: 0,
|
||
selectedEl: null,
|
||
saving: false,
|
||
pending: 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 commandsListEl = $('commands-list');
|
||
|
||
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 }));
|
||
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 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 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);
|
||
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';
|
||
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 }
|
||
);
|
||
});
|
||
});
|
||
}
|
||
|
||
function rebuildJumps() {
|
||
const jumps = {};
|
||
state.graph.links.forEach((link) => {
|
||
if (link.from.kind !== 'slide' || (link.from.port !== 'next' && link.from.port !== 'prev')) return;
|
||
if (link.to.kind !== 'slide' || link.to.port !== 'in') return;
|
||
jumps[link.from.id] = jumps[link.from.id] || {};
|
||
jumps[link.from.id][link.from.port] = link.to.id;
|
||
});
|
||
state.graph.jumps = jumps;
|
||
}
|
||
|
||
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 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'];
|
||
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, links, jumps: {} };
|
||
state.slides.forEach((slide) => {
|
||
(slide.elements || []).forEach((element) => {
|
||
if (element.type === 'button' && element.action && element.action.type === 'lua') ensureScriptNode(element, slide);
|
||
});
|
||
});
|
||
ensureLinksFromModel();
|
||
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);
|
||
}
|
||
|
||
// ==================== Рендер ====================
|
||
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();
|
||
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();
|
||
}
|
||
|
||
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 === 'data' ? ' data' : variant === 'audio' ? ' audio' : ''}"
|
||
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);
|
||
});
|
||
|
||
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 = { slide: '#818cf8', script: '#e879f9', audio: '#fbbf24', data: '#34d399' };
|
||
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 = link.from.kind === 'variable'
|
||
? 'data'
|
||
: link.to.kind === 'audio' ? 'audio' : link.to.kind === 'script' ? 'script' : 'slide';
|
||
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="${colors[kind]}" 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' : 'slide';
|
||
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' && inp.port.startsWith('var:');
|
||
}
|
||
if (out.kind === 'slide' && (out.port === 'next' || out.port === 'prev')) {
|
||
return inp.kind === 'slide' && inp.port === 'in';
|
||
}
|
||
if (inp.kind === 'slide') return inp.port === 'in';
|
||
if (inp.kind === 'script' || inp.kind === 'audio') return true;
|
||
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)
|
||
);
|
||
}
|
||
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 };
|
||
}
|
||
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: 'Картинка', button: 'Кнопка', audio: 'Аудио', video: 'Видео', window: 'Окно Chrome' };
|
||
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>
|
||
<label class="fld"><span class="label">Подложка (CSS)</span>
|
||
<input data-prop="bg" value="${esc(element.bg || '')}" placeholder="rgba(15, 23, 42, .6)">
|
||
</label>
|
||
<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="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>`;
|
||
} 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((Number(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>`;
|
||
}
|
||
|
||
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="Дублировать">⧉</button>
|
||
<button data-act="el-delete" class="danger" title="Удалить">🗑</button>
|
||
</div>
|
||
</div>
|
||
${geometryFields(element)}
|
||
${fields}
|
||
</div>`;
|
||
}
|
||
|
||
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>`;
|
||
} 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>`;
|
||
}
|
||
|
||
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)}
|
||
</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 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.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>
|
||
</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 === '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 === '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());
|
||
if (element && element.type === 'window') loadWindowTargets(false);
|
||
}
|
||
|
||
async function loadWindowTargets(notify) {
|
||
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, 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: '' };
|
||
}
|
||
if (type === 'image') {
|
||
return { ...base, x: 30, y: 18, w: 40, h: 50, src: '', fit: 'cover', radius: 14 };
|
||
}
|
||
if (type === 'button') {
|
||
return { ...base, x: 35, y: 62, w: 30, h: 11, label: 'Кнопка', bg: '#6366f1', color: '#ffffff', fontSize: 2.4, radius: 12, 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' };
|
||
}
|
||
return { ...base, x: 30, y: 82, w: 40, h: 8, src: '', loop: false, visible: true, volume: 0.8, label: 'Аудио' };
|
||
}
|
||
|
||
function addElement(type) {
|
||
const element = defaultElement(type);
|
||
currentSlide().elements.push(element);
|
||
state.selectedEl = element.id;
|
||
renderCanvas();
|
||
renderInspector();
|
||
scheduleThumbs();
|
||
scheduleSave();
|
||
}
|
||
|
||
function selectElement(id) {
|
||
if (state.selectedEl === id) return;
|
||
state.selectedEl = id;
|
||
renderCanvas();
|
||
renderInspector();
|
||
}
|
||
|
||
function addSlide() {
|
||
const slide = newSlide();
|
||
state.slides.push(slide);
|
||
state.graph.positions[slide.id] = graphDefaultPosition(state.slides.length - 1);
|
||
state.selected = state.slides.length - 1;
|
||
state.selectedEl = null;
|
||
state.selectedNode = { type: 'slide', id: slide.id };
|
||
renderAll();
|
||
scheduleSave();
|
||
}
|
||
|
||
function duplicateSlide() {
|
||
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();
|
||
}
|
||
|
||
function deleteSlide() {
|
||
if (state.slides.length <= 1) {
|
||
toast('Нельзя удалить единственный слайд');
|
||
return;
|
||
}
|
||
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();
|
||
}
|
||
|
||
function moveSlide(delta) {
|
||
const target = state.selected + delta;
|
||
if (target < 0 || target >= state.slides.length) return;
|
||
const [slide] = state.slides.splice(state.selected, 1);
|
||
state.slides.splice(target, 0, slide);
|
||
state.selected = target;
|
||
state.selectedEl = null;
|
||
renderAll();
|
||
scheduleSave();
|
||
}
|
||
|
||
// ==================== Перетаскивание ====================
|
||
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 === '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 === '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();
|
||
}
|
||
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 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('Добавлена нода кода');
|
||
}
|
||
|
||
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-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 uploadVideo(file) {
|
||
const element = selectedElement();
|
||
if (!element || element.type !== 'video') return;
|
||
toast(`Загрузка «${file.name}»…`);
|
||
try {
|
||
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}`);
|
||
const data = await response.json();
|
||
element.src = data.url;
|
||
renderCanvas();
|
||
renderInspector();
|
||
scheduleThumbs();
|
||
scheduleSave();
|
||
const mb = Math.round(((data.size || 0) / 1024 / 1024) * 10) / 10;
|
||
toast(`Видео загружено · ${mb} МБ`);
|
||
} 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 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;
|
||
|
||
if (act === 'video-upload') {
|
||
const input = inspectorEl.querySelector('[data-upload="video"]');
|
||
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 (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);
|
||
currentSlide().elements = currentSlide().elements.filter((item) => item.id !== element.id);
|
||
state.selectedEl = null;
|
||
renderCanvas();
|
||
renderInspector();
|
||
scheduleThumbs();
|
||
scheduleSave();
|
||
} else if (act === 'el-duplicate' && element) {
|
||
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();
|
||
} 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();
|
||
});
|
||
|
||
document.querySelector('.graph-toolbar').addEventListener('click', (event) => {
|
||
const add = event.target.closest('[data-graph-add]');
|
||
if (!add) return;
|
||
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 (graphSvg) {
|
||
graphSvg.addEventListener('click', (event) => {
|
||
const edge = event.target.closest('path.edge');
|
||
if (!edge) return;
|
||
state.selectedLink = edge.dataset.linkId;
|
||
drawGraphEdges();
|
||
});
|
||
}
|
||
|
||
$('add-slide').addEventListener('click', addSlide);
|
||
|
||
titleInput.addEventListener('input', () => {
|
||
state.title = titleInput.value;
|
||
scheduleSave();
|
||
});
|
||
|
||
// ==================== Сохранение ====================
|
||
let saveTimer = null;
|
||
function scheduleSave() {
|
||
setStatus('dirty', 'Изменения не сохранены');
|
||
clearTimeout(saveTimer);
|
||
saveTimer = setTimeout(save, 700);
|
||
}
|
||
|
||
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;
|
||
history.replaceState(null, '', `editor.html?id=${presentation.id}`);
|
||
}
|
||
copyLinkBtn.disabled = false;
|
||
state.saving = false;
|
||
setStatus('saved', 'Сохранено');
|
||
if (state.pending) {
|
||
state.pending = false;
|
||
save();
|
||
}
|
||
} catch (error) {
|
||
state.saving = false;
|
||
setStatus('dirty', 'Ошибка сохранения');
|
||
}
|
||
}
|
||
|
||
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'));
|
||
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 's') {
|
||
event.preventDefault();
|
||
clearTimeout(saveTimer);
|
||
save();
|
||
}
|
||
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 (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);
|
||
currentSlide().elements = currentSlide().elements.filter((item) => item.id !== element.id);
|
||
state.selectedEl = null;
|
||
renderCanvas();
|
||
renderInspector();
|
||
scheduleThumbs();
|
||
scheduleSave();
|
||
}
|
||
if (event.key === 'Escape') {
|
||
selectElement(null);
|
||
state.selectedLink = null;
|
||
settingsModal.hidden = true;
|
||
commandsModal.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 connectLiveStatus() {
|
||
let ws;
|
||
const connect = () => {
|
||
ws = new WebSocket(`ws://${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;
|
||
}
|
||
}
|
||
};
|
||
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;
|
||
copyLinkBtn.disabled = false;
|
||
setStatus('saved', 'Загружено');
|
||
} else {
|
||
history.replaceState(null, '', 'editor.html');
|
||
setStatus('dirty', 'Презентация не найдена — создаётся новая');
|
||
}
|
||
} catch (error) {
|
||
setStatus('dirty', 'Ошибка загрузки');
|
||
}
|
||
}
|
||
renderAll();
|
||
connectLiveStatus();
|
||
}
|
||
|
||
init();
|
||
</script>
|
||
</body>
|
||
</html>
|