Репозитории /
Promptly /
public/editor.html
editor.html
| 1 | <!DOCTYPE html> |
| 2 | <html lang="ru"> |
| 3 | <head> |
| 4 | <meta charset="UTF-8"> |
| 5 | <meta name="viewport" content="width=device-width, initial-scale=1.0"> |
| 6 | <title>Promptly — редактор</title> |
| 7 | <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"> |
| 8 | <style> |
| 9 | :root { |
| 10 | --bg: #101014; |
| 11 | --panel: rgba(30, 30, 30, .5); |
| 12 | --panel-2: rgba(30, 30, 30, .68); |
| 13 | --border: rgba(255, 255, 255, .08); |
| 14 | --accent: #4cc2ff; |
| 15 | --text: #e5e5e5; |
| 16 | --muted: #aaa; |
| 17 | --danger: #f87171; |
| 18 | } |
| 19 | * { box-sizing: border-box; } |
| 20 | html, body { height: 100%; } |
| 21 | body { |
| 22 | margin: 0; overflow: hidden; color: var(--text); |
| 23 | font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; |
| 24 | background: |
| 25 | radial-gradient(900px 500px at 10% -10%, rgba(99, 102, 241, .16), transparent 60%), |
| 26 | radial-gradient(800px 460px at 100% 0%, rgba(217, 70, 239, .1), transparent 55%), |
| 27 | var(--bg); |
| 28 | } |
| 29 | 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); } |
| 30 | button:hover:not(:disabled) { background: rgba(255, 255, 255, .13); } |
| 31 | button:disabled { opacity: .35; cursor: default; } |
| 32 | 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%; } |
| 33 | input:focus, select:focus, textarea:focus { outline: 2px solid rgba(129, 140, 248, .6); border-color: transparent; } |
| 34 | textarea { resize: vertical; line-height: 1.45; } |
| 35 | select option { background: #131a2c; } |
| 36 | .ghost { background: rgba(255,255,255,.07); } |
| 37 | .primary { background: linear-gradient(90deg, #1795d8, #38bdf8); color: #fff; font-weight: 600; } |
| 38 | .primary:hover:not(:disabled) { filter: brightness(1.12); background: linear-gradient(90deg, #1795d8, #38bdf8); } |
| 39 | .danger { background: rgba(239, 68, 68, .14); color: #fca5a5; border: 1px solid rgba(239, 68, 68, .3); } |
| 40 | .danger:hover:not(:disabled) { background: rgba(239, 68, 68, .25); } |
| 41 | |
| 42 | /* ===== Верхняя панель ===== */ |
| 43 | .topbar { |
| 44 | height: 58px; display: flex; align-items: center; gap: 12px; padding: 0 16px; |
| 45 | background: rgba(8, 11, 22, .82); border-bottom: 1px solid var(--border); |
| 46 | backdrop-filter: blur(18px); position: relative; z-index: 30; |
| 47 | } |
| 48 | .back { color: var(--muted); text-decoration: none; font-size: 18px; padding: 6px 8px; border-radius: 8px; } |
| 49 | .back:hover { color: #fff; background: rgba(255,255,255,.07); } |
| 50 | .logo { font-weight: 800; font-size: 16px; letter-spacing: -.3px; white-space: nowrap; } |
| 51 | .logo span { background: linear-gradient(90deg, #4cc2ff, #7fd4ff); -webkit-background-clip: text; background-clip: text; color: transparent; } |
| 52 | .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; } |
| 53 | .title-input:hover { border-color: var(--border); } |
| 54 | .title-input:focus { background: rgba(255,255,255,.05); border-color: transparent; } |
| 55 | .live-chip { font-size: 11.5px; color: #8fdcff; white-space: nowrap; background: rgba(217, 70, 239, .14); border: 1px solid rgba(217, 70, 239, .4); border-radius: 999px; padding: 4px 10px; } |
| 56 | .save-state { font-size: 12px; color: var(--muted); white-space: nowrap; margin-left: auto; } |
| 57 | .save-state.dirty { color: #fbbf24; } |
| 58 | .save-state.saving { color: var(--accent); } |
| 59 | .save-state.saved { color: #4ade80; } |
| 60 | .top-actions { display: flex; align-items: center; gap: 8px; flex-shrink: 0; } |
| 61 | |
| 62 | /* ===== Каркас ===== */ |
| 63 | .app { display: grid; grid-template-columns: 176px minmax(0, 1fr) 330px; height: calc(100vh - 58px); } |
| 64 | |
| 65 | /* ===== Рейка слайдов ===== */ |
| 66 | .rail { border-right: 1px solid var(--border); background: rgba(8, 11, 22, .5); display: flex; flex-direction: column; min-height: 0; } |
| 67 | .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; } |
| 68 | .thumbs { flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 9px; padding: 4px 12px 12px; } |
| 69 | .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); } |
| 70 | .thumb:hover { border-color: rgba(129, 140, 248, .5); } |
| 71 | .thumb.active { border-color: #4cc2ff; box-shadow: 0 0 0 3px rgba(99, 102, 241, .2); } |
| 72 | .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; } |
| 73 | .thumb-canvas { position: relative; display: block; width: 100%; aspect-ratio: 16 / 9; overflow: hidden; } |
| 74 | .add-slide { margin: 0 12px 14px; padding: 10px; border: 1px dashed rgba(129, 140, 248, .5); background: rgba(99,102,241,.08); color: #bfe7ff; font-weight: 600; border-radius: 10px; } |
| 75 | .add-slide:hover { background: rgba(99,102,241,.16); } |
| 76 | |
| 77 | /* ===== Рабочая область ===== */ |
| 78 | .workspace { display: flex; flex-direction: column; min-width: 0; min-height: 0; } |
| 79 | .toolbar { display: flex; align-items: center; gap: 7px; padding: 10px 14px; border-bottom: 1px solid var(--border); flex-wrap: wrap; } |
| 80 | .toolbar-label { font-size: 11px; text-transform: uppercase; letter-spacing: 1px; color: var(--muted); font-weight: 700; margin-right: 3px; } |
| 81 | .toolbar .spacer { flex: 1; } |
| 82 | .toolbar button { padding: 7px 11px; } |
| 83 | .toolbar button.danger { padding: 7px 10px; } |
| 84 | |
| 85 | .stage { flex: 1; min-height: 0; display: flex; align-items: center; justify-content: center; padding: 20px; overflow: auto; } |
| 86 | .canvas-wrap { |
| 87 | position: relative; flex-shrink: 0; |
| 88 | width: min(100%, max(320px, calc((100vh - 235px) * 16 / 9))); |
| 89 | max-width: 1080px; aspect-ratio: 16 / 9; |
| 90 | border-radius: 14px; overflow: hidden; |
| 91 | box-shadow: 0 24px 70px rgba(0, 0, 0, .5), 0 0 0 1px rgba(255, 255, 255, .09); |
| 92 | background: #0b1020; |
| 93 | } |
| 94 | .canvas { position: absolute; inset: 0; } |
| 95 | .sel-box { position: absolute; z-index: 60; border: 2px solid #4cc2ff; border-radius: 3px; pointer-events: none; box-shadow: 0 0 0 1px rgba(5,8,18,.5); } |
| 96 | .sel-box[hidden] { display: none; } |
| 97 | .resize { position: absolute; width: 12px; height: 12px; background: #4cc2ff; border: 2px solid #0b1020; border-radius: 3px; pointer-events: auto; } |
| 98 | .resize[data-dir="nw"] { left: -7px; top: -7px; cursor: nwse-resize; } |
| 99 | .resize[data-dir="ne"] { right: -7px; top: -7px; cursor: nesw-resize; } |
| 100 | .resize[data-dir="sw"] { left: -7px; bottom: -7px; cursor: nesw-resize; } |
| 101 | .resize[data-dir="se"] { right: -7px; bottom: -7px; cursor: nwse-resize; } |
| 102 | .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); } |
| 103 | .statusbar b { color: #bfe7ff; } |
| 104 | |
| 105 | /* ===== Инспектор ===== */ |
| 106 | .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; } |
| 107 | .insp-card { background: var(--panel); border: 1px solid var(--border); border-radius: 14px; padding: 12px; display: flex; flex-direction: column; gap: 10px; } |
| 108 | .insp-head { display: flex; align-items: center; gap: 8px; } |
| 109 | .insp-title { font-size: 11px; letter-spacing: 1.1px; text-transform: uppercase; color: var(--accent); font-weight: 800; flex: 1; } |
| 110 | .insp-btns { display: flex; gap: 4px; } |
| 111 | .insp-btns button { padding: 4px 7px; font-size: 11px; border-radius: 7px; } |
| 112 | .fld { display: flex; flex-direction: column; gap: 5px; } |
| 113 | .fld > span.label, .fld > label { font-size: 10.5px; text-transform: uppercase; letter-spacing: .7px; color: var(--muted); font-weight: 700; } |
| 114 | .row-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; } |
| 115 | .row-4 { display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px; } |
| 116 | .row-4 input { padding: 7px 6px; text-align: center; } |
| 117 | .checkline { display: flex; align-items: center; gap: 8px; font-size: 12.5px; color: #cbd5e1; } |
| 118 | .checkline input { width: auto; accent-color: #4cc2ff; } |
| 119 | .segmented { display: flex; gap: 4px; background: rgba(255,255,255,.04); border: 1px solid var(--border); border-radius: 9px; padding: 3px; } |
| 120 | .segmented button { flex: 1; padding: 6px 4px; font-size: 11.5px; background: transparent; border-radius: 7px; color: var(--muted); } |
| 121 | .segmented button.active { background: rgba(99, 102, 241, .35); color: #fff; font-weight: 600; } |
| 122 | .view-toggle { flex-shrink: 0; } |
| 123 | .view-toggle button { padding: 6px 12px; } |
| 124 | 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; } |
| 125 | a.ghost:hover { background: rgba(255,255,255,.13); } |
| 126 | |
| 127 | /* ===== Граф ===== */ |
| 128 | .stage[hidden], .graph-stage[hidden] { display: none; } |
| 129 | .graph-stage { flex: 1; min-height: 0; display: flex; flex-direction: column; } |
| 130 | .graph-toolbar { display: flex; align-items: center; gap: 7px; padding: 9px 14px; border-bottom: 1px solid var(--border); flex-wrap: wrap; } |
| 131 | .graph-toolbar .spacer { flex: 1; } |
| 132 | .graph-toolbar button { padding: 7px 11px; } |
| 133 | .graph-hint { font-size: 11px; color: #64748b; } |
| 134 | .graph-scroll { |
| 135 | flex: 1; min-height: 0; overflow: auto; padding: 24px; |
| 136 | background-image: radial-gradient(rgba(148, 163, 184, .16) 1px, transparent 1px); |
| 137 | background-size: 22px 22px; |
| 138 | } |
| 139 | .graph-world { position: relative; min-width: 1200px; min-height: 760px; } |
| 140 | .graph-svg { position: absolute; inset: 0; width: 100%; height: 100%; overflow: visible; pointer-events: none; } |
| 141 | .graph-nodes { position: absolute; inset: 0; } |
| 142 | .gnode { |
| 143 | position: absolute; width: 238px; border-radius: 13px; padding: 10px 0 8px; |
| 144 | background: linear-gradient(160deg, rgba(30, 38, 66, .96), rgba(12, 17, 33, .98)); |
| 145 | border: 1px solid rgba(129, 140, 248, .28); cursor: grab; user-select: none; |
| 146 | box-shadow: 0 12px 32px rgba(0, 0, 0, .38); transition: border-color .15s, box-shadow .15s; |
| 147 | } |
| 148 | .gnode:hover { border-color: rgba(129, 140, 248, .6); } |
| 149 | .gnode.selected { border-color: #818cf8; box-shadow: 0 0 0 3px rgba(99, 102, 241, .24), 0 12px 32px rgba(0, 0, 0, .38); } |
| 150 | .gnode.script { background: linear-gradient(160deg, rgba(58, 32, 78, .96), rgba(20, 12, 33, .98)); border-color: rgba(217, 70, 239, .3); } |
| 151 | .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); } |
| 152 | .gnode.script .gnode-badge { color: #f0abfc; background: rgba(217, 70, 239, .18); } |
| 153 | .gnode.audio { background: linear-gradient(160deg, rgba(66, 43, 16, .96), rgba(26, 18, 8, .98)); border-color: rgba(251, 191, 36, .32); } |
| 154 | .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); } |
| 155 | .gnode.audio .gnode-badge { color: #fde68a; background: rgba(251, 191, 36, .16); } |
| 156 | .gnode.variable { background: linear-gradient(160deg, rgba(16, 55, 45, .96), rgba(7, 22, 18, .98)); border-color: rgba(52, 211, 153, .32); } |
| 157 | .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); } |
| 158 | .gnode.variable .gnode-badge { color: #a7f3d0; background: rgba(52, 211, 153, .16); } |
| 159 | .gnode.transition { background: linear-gradient(160deg, rgba(10, 48, 70, .96), rgba(4, 18, 28, .98)); border-color: rgba(76, 194, 255, .35); } |
| 160 | .gnode.transition.selected { border-color: #4cc2ff; box-shadow: 0 0 0 3px rgba(76, 194, 255, .22), 0 12px 32px rgba(0, 0, 0, .38); } |
| 161 | .gnode.transition .gnode-badge { color: #a5e3ff; background: rgba(76, 194, 255, .18); } |
| 162 | .gnode.anim { background: linear-gradient(160deg, rgba(66, 18, 38, .96), rgba(26, 7, 15, .98)); border-color: rgba(251, 113, 133, .35); } |
| 163 | .gnode.anim.selected { border-color: #fb7185; box-shadow: 0 0 0 3px rgba(251, 113, 133, .2), 0 12px 32px rgba(0, 0, 0, .38); } |
| 164 | .gnode.anim .gnode-badge { color: #fecdd3; background: rgba(251, 113, 133, .16); } |
| 165 | .gnode-body { padding: 0 12px; } |
| 166 | .gnode-head { display: flex; align-items: center; gap: 7px; margin-bottom: 6px; } |
| 167 | .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; } |
| 168 | .gnode-kind { margin-left: auto; font-size: 10px; color: #64748b; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 110px; } |
| 169 | .gnode-title { font-size: 13.5px; font-weight: 700; line-height: 1.3; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } |
| 170 | .gnode-sub { font-size: 10.5px; color: var(--muted); margin-top: 3px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } |
| 171 | .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; } |
| 172 | .gnode-bar { height: 3px; border-radius: 999px; margin-top: 8px; background: linear-gradient(90deg, #6366f1, #a855f7); opacity: .65; } |
| 173 | .gnode-ports { margin-top: 8px; border-top: 1px solid rgba(255,255,255,.08); padding-top: 5px; display: flex; flex-direction: column; } |
| 174 | .grow { position: relative; display: flex; align-items: center; min-height: 21px; font-size: 10.5px; color: #93c5fd; } |
| 175 | .grow.in { padding-left: 13px; justify-content: flex-start; } |
| 176 | .grow.out { padding-right: 13px; justify-content: flex-end; color: #bfe7ff; } |
| 177 | .grow.data { color: #6ee7b7; } |
| 178 | .grow.audio { color: #fcd34d; } |
| 179 | .grow .gport-label { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 196px; } |
| 180 | .gport { position: absolute; top: 50%; width: 11px; height: 11px; margin-top: -5.5px; border-radius: 50%; background: #0b1020; border: 2px solid #4cc2ff; cursor: crosshair; transition: .12s; z-index: 2; } |
| 181 | .gport.in { left: -6px; } |
| 182 | .gport.out { right: -6px; } |
| 183 | .gport:hover { background: #4cc2ff; box-shadow: 0 0 0 4px rgba(129, 140, 248, .22); } |
| 184 | .gport.data { border-color: #34d399; } |
| 185 | .gport.data:hover { background: #34d399; box-shadow: 0 0 0 4px rgba(52, 211, 153, .2); } |
| 186 | .gport.audio { border-color: #fbbf24; } |
| 187 | .gport.audio:hover { background: #fbbf24; } |
| 188 | .graph-svg path.edge { pointer-events: stroke; cursor: pointer; } |
| 189 | .graph-svg path.edge:hover { stroke-opacity: 1; } |
| 190 | .graph-svg path.edge.selected { stroke-width: 3; stroke-opacity: 1; filter: drop-shadow(0 0 5px currentColor); } |
| 191 | .graph-world.drafting .graph-svg path { pointer-events: none !important; } |
| 192 | .graph-bind-list { display: flex; flex-direction: column; gap: 5px; margin: 8px 0; } |
| 193 | .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; } |
| 194 | .graph-bind .gdim { margin-left: auto; color: #64748b; font-size: 10.5px; white-space: nowrap; } |
| 195 | .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; } |
| 196 | .gnode.plugin { background: linear-gradient(160deg, rgba(74, 38, 12, .96), rgba(28, 14, 6, .98)); border-color: rgba(249, 115, 22, .38); } |
| 197 | .gnode.plugin.selected { border-color: #f97316; box-shadow: 0 0 0 3px rgba(249, 115, 22, .22), 0 12px 32px rgba(0, 0, 0, .38); } |
| 198 | .gnode.plugin .gnode-badge { color: #fed7aa; background: rgba(249, 115, 22, .18); } |
| 199 | .gport.plugin { border-color: #f97316; } |
| 200 | .gport.plugin:hover { background: #f97316; box-shadow: 0 0 0 4px rgba(249, 115, 22, .22); } |
| 201 | .gport.anim { border-color: #fb7185; } |
| 202 | .gport.anim:hover { background: #fb7185; } |
| 203 | .gport.transition { border-color: #22d3ee; } |
| 204 | .gport.transition:hover { background: #22d3ee; } |
| 205 | .graph-body { flex: 1; min-height: 0; display: flex; } |
| 206 | .graph-legend { display: flex; align-items: center; gap: 9px; flex-wrap: wrap; font-size: 10.5px; color: #94a3b8; } |
| 207 | .graph-legend span { display: inline-flex; align-items: center; gap: 4px; white-space: nowrap; } |
| 208 | .graph-legend i { width: 9px; height: 9px; border-radius: 50%; display: inline-block; } |
| 209 | |
| 210 | /* ===== Древо ===== */ |
| 211 | .tree-panel { |
| 212 | width: 272px; flex-shrink: 0; display: flex; flex-direction: column; min-height: 0; |
| 213 | background: rgba(9, 13, 25, .72); border-right: 1px solid var(--border); |
| 214 | backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); |
| 215 | } |
| 216 | .tree-panel[hidden] { display: none; } |
| 217 | .tree-panel.collapsed { width: 44px; } |
| 218 | .tree-panel.collapsed .tree-tabs, .tree-panel.collapsed .tree-search, |
| 219 | .tree-panel.collapsed .tree-scroll, .tree-panel.collapsed .tree-foot, |
| 220 | .tree-panel.collapsed .tree-legend { display: none; } |
| 221 | .tree-head { display: flex; align-items: center; gap: 6px; padding: 9px 11px; border-bottom: 1px solid var(--border); font-size: 11px; text-transform: uppercase; letter-spacing: 1px; font-weight: 800; color: #bfe7ff; } |
| 222 | .tree-head .tree-collapse { margin-left: auto; padding: 2px 7px; font-size: 12px; background: transparent; } |
| 223 | .tree-tabs { display: flex; gap: 4px; padding: 7px 9px 3px; } |
| 224 | .tree-tabs button { flex: 1; padding: 5px 4px; font-size: 11px; background: transparent; color: var(--muted); border-radius: 7px; } |
| 225 | .tree-tabs button.active { background: rgba(99, 102, 241, .3); color: #fff; } |
| 226 | .tree-search { margin: 6px 9px; padding: 6px 9px; font-size: 12px; } |
| 227 | .tree-scroll { flex: 1; overflow: auto; padding: 4px 7px 10px; } |
| 228 | .tree-group { margin-bottom: 5px; } |
| 229 | .tree-group-head { |
| 230 | display: flex; align-items: center; gap: 5px; width: 100%; padding: 5px 6px; |
| 231 | background: transparent; color: #94a3b8; font-size: 10.5px; text-transform: uppercase; |
| 232 | letter-spacing: .8px; font-weight: 800; text-align: left; border-radius: 7px; |
| 233 | } |
| 234 | .tree-group-head:hover { background: rgba(255, 255, 255, .05); } |
| 235 | .tree-group-head .caret { font-size: 9px; width: 10px; color: #64748b; } |
| 236 | .tree-group-head .count { margin-left: auto; color: #475569; font-weight: 600; } |
| 237 | .tree-items { display: flex; flex-direction: column; gap: 2px; } |
| 238 | .tree-item { |
| 239 | display: flex; align-items: center; gap: 7px; width: 100%; padding: 5px 7px; |
| 240 | background: transparent; border-radius: 7px; color: #dbe4f3; text-align: left; |
| 241 | font-size: 12px; cursor: grab; border: 1px solid transparent; |
| 242 | } |
| 243 | .tree-item:hover { background: rgba(99, 102, 241, .18); border-color: rgba(129, 140, 248, .22); } |
| 244 | .tree-item:active { cursor: grabbing; } |
| 245 | .tree-item .ti-ico { width: 15px; text-align: center; flex-shrink: 0; font-size: 12px; } |
| 246 | .tree-item .ti-name { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } |
| 247 | .tree-item .ti-meta { color: #64748b; font-size: 9.5px; flex-shrink: 0; max-width: 84px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } |
| 248 | .tree-item .ti-dot { width: 7px; height: 7px; border-radius: 50%; flex-shrink: 0; } |
| 249 | .tree-item .ti-add { padding: 0 4px; font-size: 12px; color: #64748b; background: transparent; border-radius: 5px; } |
| 250 | .tree-item .ti-add:hover { color: #fff; background: rgba(255, 255, 255, .12); } |
| 251 | .tree-plugin { border: 1px solid rgba(255, 255, 255, .05); border-radius: 9px; margin-bottom: 5px; background: rgba(255, 255, 255, .015); } |
| 252 | .tree-plugin-head { display: flex; align-items: center; gap: 7px; padding: 6px 8px; font-size: 12px; font-weight: 700; color: #f8fafc; } |
| 253 | .tree-plugin-head .ti-actions { margin-left: auto; display: flex; gap: 3px; } |
| 254 | .tree-plugin-head .ti-actions button { padding: 1px 5px; font-size: 10px; background: transparent; color: #94a3b8; } |
| 255 | .tree-plugin-head .ti-actions button:hover { color: #fff; background: rgba(255, 255, 255, .1); } |
| 256 | .tree-plugin-desc { padding: 0 9px 5px 28px; font-size: 10px; color: #64748b; line-height: 1.35; } |
| 257 | .tree-plugin .tree-items { padding: 0 5px 5px; } |
| 258 | .tree-empty { padding: 14px 10px; font-size: 11.5px; color: #64748b; line-height: 1.5; text-align: center; } |
| 259 | .tree-foot { display: flex; gap: 5px; padding: 8px; border-top: 1px solid var(--border); } |
| 260 | .tree-foot button { flex: 1; padding: 6px 4px; font-size: 11px; } |
| 261 | .tree-legend { display: flex; flex-wrap: wrap; gap: 5px 9px; padding: 7px 10px; border-top: 1px solid var(--border); font-size: 9.5px; color: #94a3b8; } |
| 262 | .tree-legend span { display: inline-flex; align-items: center; gap: 4px; } |
| 263 | .tree-legend i { width: 7px; height: 7px; border-radius: 50%; } |
| 264 | .tree-drop { outline: 2px dashed rgba(76, 194, 255, .7); outline-offset: -8px; } |
| 265 | .graph-scroll.dragover { box-shadow: inset 0 0 0 2px rgba(76, 194, 255, .35); } |
| 266 | |
| 267 | /* ===== Lua-редактор ===== */ |
| 268 | .lua-editor { position: relative; border: 1px solid var(--border); border-radius: 10px; background: #080d1a; overflow: hidden; } |
| 269 | .lua-editor:focus-within { border-color: rgba(76, 194, 255, .65); box-shadow: 0 0 0 2px rgba(76, 194, 255, .14); } |
| 270 | .lua-highlight, .lua-code { |
| 271 | margin: 0; font-family: ui-monospace, 'Cascadia Code', 'JetBrains Mono', Consolas, monospace; |
| 272 | font-size: 12px; line-height: 1.5; padding: 9px 10px; tab-size: 2; white-space: pre; |
| 273 | } |
| 274 | .lua-highlight { position: absolute; inset: 0; pointer-events: none; color: #cbd5e1; overflow: hidden; } |
| 275 | .lua-code { |
| 276 | position: relative; display: block; width: 100%; min-height: 110px; resize: vertical; |
| 277 | background: transparent; border: none; outline: none; color: transparent; |
| 278 | caret-color: #fff; -webkit-text-fill-color: transparent; overflow: auto; |
| 279 | } |
| 280 | .lua-code::selection { background: rgba(99, 102, 241, .45); } |
| 281 | .lua-code::placeholder { color: #475569; -webkit-text-fill-color: #475569; } |
| 282 | .lua-editor.compact .lua-code { min-height: 74px; } |
| 283 | .tok-kw { color: #c084fc; font-weight: 600; } |
| 284 | .tok-str { color: #86efac; } |
| 285 | .tok-num { color: #fbbf24; } |
| 286 | .tok-com { color: #64748b; font-style: italic; } |
| 287 | .tok-fn { color: #7dd3fc; } |
| 288 | .tok-api { color: #f0abfc; } |
| 289 | .tok-op { color: #94a3b8; } |
| 290 | .lua-suggest { |
| 291 | position: absolute; left: 8px; right: 8px; bottom: 8px; z-index: 6; max-height: 164px; overflow: auto; |
| 292 | background: rgba(13, 18, 34, .98); border: 1px solid rgba(129, 140, 248, .45); |
| 293 | border-radius: 9px; box-shadow: 0 18px 44px rgba(0, 0, 0, .55); padding: 4px; |
| 294 | } |
| 295 | .lua-suggest[hidden] { display: none; } |
| 296 | .lua-suggest button { |
| 297 | display: flex; align-items: center; gap: 7px; width: 100%; padding: 5px 8px; |
| 298 | background: transparent; border-radius: 6px; text-align: left; font-size: 11.5px; |
| 299 | font-family: ui-monospace, Consolas, monospace; color: #dbe4f3; |
| 300 | } |
| 301 | .lua-suggest button.active, .lua-suggest button:hover { background: rgba(99, 102, 241, .32); } |
| 302 | .lua-suggest .sg-kind { margin-left: auto; font-size: 9px; color: #64748b; font-family: inherit; } |
| 303 | .lua-suggest .sg-name b { color: #7dd3fc; } |
| 304 | |
| 305 | /* ===== Плагины ===== */ |
| 306 | .modal-card.wide { width: min(1120px, 100%); height: min(840px, 94vh); max-height: 94vh; } |
| 307 | .plugin-wrap { flex: 1; min-height: 0; display: grid; grid-template-columns: 250px minmax(0, 1fr); } |
| 308 | .plugin-side { border-right: 1px solid var(--border); display: flex; flex-direction: column; min-height: 0; } |
| 309 | .plugin-side-head { display: flex; gap: 5px; padding: 10px; border-bottom: 1px solid var(--border); } |
| 310 | .plugin-side-head button { flex: 1; padding: 6px 4px; font-size: 11px; } |
| 311 | .plugin-list { flex: 1; overflow: auto; padding: 7px; display: flex; flex-direction: column; gap: 4px; } |
| 312 | .plugin-list-item { display: flex; align-items: center; gap: 7px; width: 100%; padding: 8px 9px; background: transparent; border-radius: 9px; text-align: left; border: 1px solid transparent; } |
| 313 | .plugin-list-item:hover { background: rgba(255, 255, 255, .05); } |
| 314 | .plugin-list-item.active { background: rgba(99, 102, 241, .26); border-color: rgba(129, 140, 248, .45); } |
| 315 | .plugin-list-item .pl-dot { width: 9px; height: 9px; border-radius: 50%; flex-shrink: 0; } |
| 316 | .plugin-list-item .pl-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12.5px; font-weight: 600; } |
| 317 | .plugin-list-item .pl-count { font-size: 9.5px; color: #64748b; } |
| 318 | .plugin-main { display: flex; flex-direction: column; gap: 10px; padding: 14px 18px; overflow: auto; min-height: 0; } |
| 319 | .plugin-main .row { display: flex; gap: 8px; } |
| 320 | .plugin-main .row > * { flex: 1; } |
| 321 | .plugin-main h3 { margin: 0; font-size: 12px; text-transform: uppercase; letter-spacing: 1px; color: #bfe7ff; } |
| 322 | .plugin-meta { display: grid; grid-template-columns: minmax(0, 1fr) 96px; gap: 10px; } |
| 323 | .plugin-meta input[type="color"] { padding: 3px; height: 34px; } |
| 324 | .plugin-nodes { display: flex; flex-wrap: wrap; gap: 6px; } |
| 325 | .plugin-node-chip { display: inline-flex; align-items: center; gap: 6px; padding: 4px 8px; border-radius: 999px; background: rgba(249, 115, 22, .14); border: 1px solid rgba(249, 115, 22, .35); font-size: 11px; color: #fed7aa; } |
| 326 | .plugin-node-chip small { color: #94a3b8; font-size: 9.5px; } |
| 327 | .plugin-foot { display: flex; align-items: center; gap: 7px; margin-top: auto; padding-top: 8px; border-top: 1px solid var(--border); } |
| 328 | .plugin-foot .spacer { flex: 1; } |
| 329 | |
| 330 | /* ===== Команды ===== */ |
| 331 | .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; } |
| 332 | .command-item + .command-item { margin-top: 8px; } |
| 333 | .command-item-head { display: flex; align-items: center; gap: 8px; } |
| 334 | .command-item-head input { flex: 1; } |
| 335 | .command-item-head button { padding: 5px 9px; font-size: 12px; } |
| 336 | .command-item textarea { font-family: ui-monospace, Consolas, monospace; font-size: 12px; } |
| 337 | .upload-line { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; } |
| 338 | .upload-line .file-name { font-size: 11px; color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 160px; } |
| 339 | .file-progress { font-size: 11px; color: var(--accent); } |
| 340 | .swatches { display: flex; gap: 6px; flex-wrap: wrap; } |
| 341 | .swatch { width: 34px; height: 24px; border-radius: 6px; border: 1px solid rgba(255,255,255,.18); padding: 0; } |
| 342 | .swatch:hover { transform: translateY(-1px); } |
| 343 | .hint { font-size: 11px; line-height: 1.45; color: #64748b; margin: 0; } |
| 344 | .hint code { color: #9fd8ff; font-size: 10.5px; } |
| 345 | .field-actions { display: flex; gap: 6px; flex-wrap: wrap; } |
| 346 | .field-actions button { flex: 1; padding: 7px 8px; font-size: 12px; } |
| 347 | .swatch.active { border-color: #4cc2ff; box-shadow: 0 0 0 2px rgba(129, 140, 248, .35); } |
| 348 | |
| 349 | /* ===== v1.2: шаблоны слайдов, выравнивание, палитры, горячие клавиши ===== */ |
| 350 | .toolbar .sep { width: 1px; height: 22px; background: var(--border); margin: 0 5px; flex-shrink: 0; } |
| 351 | .rail { position: relative; } |
| 352 | .tpl-menu { |
| 353 | position: absolute; left: 12px; right: 12px; bottom: 56px; z-index: 90; |
| 354 | display: flex; flex-direction: column; gap: 3px; padding: 8px; |
| 355 | background: rgba(13, 18, 34, .97); border: 1px solid rgba(129, 140, 248, .4); |
| 356 | border-radius: 14px; box-shadow: 0 24px 64px rgba(0, 0, 0, .6); backdrop-filter: blur(14px); |
| 357 | } |
| 358 | .tpl-menu[hidden] { display: none; } |
| 359 | .tpl-menu .tpl-head { font-size: 10px; text-transform: uppercase; letter-spacing: 1px; color: var(--muted); font-weight: 800; padding: 4px 8px 6px; } |
| 360 | .tpl-menu button { display: flex; align-items: center; gap: 10px; text-align: left; padding: 7px 9px; border-radius: 9px; background: transparent; } |
| 361 | .tpl-menu button:hover { background: rgba(99, 102, 241, .22); } |
| 362 | .tpl-ico { font-size: 16px; width: 22px; text-align: center; flex-shrink: 0; } |
| 363 | .tpl-name { font-weight: 600; font-size: 12.5px; line-height: 1.2; } |
| 364 | .tpl-desc { display: block; font-size: 10.5px; color: var(--muted); font-weight: 400; } |
| 365 | .align-row { display: grid; grid-template-columns: repeat(6, 1fr); gap: 4px; } |
| 366 | .align-row button { padding: 6px 0; font-size: 12px; } |
| 367 | .palette { display: flex; flex-wrap: wrap; gap: 6px; } |
| 368 | .palette .p-swatch { width: 26px; height: 26px; border-radius: 8px; border: 2px solid transparent; cursor: pointer; padding: 0; box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .2); } |
| 369 | .palette .p-swatch:hover { transform: translateY(-1px); } |
| 370 | kbd { |
| 371 | background: rgba(255, 255, 255, .08); border: 1px solid var(--border); border-bottom-width: 2px; |
| 372 | border-radius: 5px; padding: 1px 5px; font-size: 10px; font-family: ui-monospace, consolas, monospace; color: #bfe7ff; |
| 373 | } |
| 374 | .statusbar .hints { display: flex; gap: 12px; flex-wrap: wrap; align-items: center; } |
| 375 | .statusbar .hints span { display: inline-flex; gap: 4px; align-items: center; } |
| 376 | .top-actions input[type="file"] { display: none; } |
| 377 | .inspector .muted { font-size: 11.5px; color: #64748b; } |
| 378 | |
| 379 | /* ===== Модальное окно ===== */ |
| 380 | .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; } |
| 381 | .modal[hidden] { display: none; } |
| 382 | .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; } |
| 383 | .modal-head { display: flex; align-items: center; justify-content: space-between; padding: 18px 22px; border-bottom: 1px solid var(--border); } |
| 384 | .modal-head h2 { margin: 0; font-size: 18px; } |
| 385 | .modal-head button { padding: 6px 10px; } |
| 386 | .modal-body { padding: 18px 22px; overflow-y: auto; display: flex; flex-direction: column; gap: 20px; } |
| 387 | .modal-body h3 { margin: 0 0 5px; font-size: 13px; color: #bfe7ff; } |
| 388 | .modal-body .section { display: flex; flex-direction: column; gap: 8px; } |
| 389 | .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; } |
| 390 | .modal-body input[type="range"] { padding: 0; accent-color: #4cc2ff; } |
| 391 | .modal-foot { display: flex; justify-content: flex-end; gap: 8px; padding: 14px 22px; border-top: 1px solid var(--border); } |
| 392 | .vol-line { display: flex; align-items: center; gap: 10px; } |
| 393 | .vol-line input { flex: 1; } |
| 394 | .vol-line output { font-size: 12px; color: var(--muted); width: 38px; text-align: right; } |
| 395 | |
| 396 | .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; } |
| 397 | .toast.visible { opacity: 1; transform: translateX(-50%) translateY(0); } |
| 398 | |
| 399 | ::-webkit-scrollbar { width: 9px; height: 9px; } |
| 400 | ::-webkit-scrollbar-thumb { background: rgba(255,255,255,.12); border-radius: 999px; } |
| 401 | ::-webkit-scrollbar-track { background: transparent; } |
| 402 | |
| 403 | @media (max-width: 1100px) { |
| 404 | .app { grid-template-columns: 150px minmax(0, 1fr) 290px; } |
| 405 | .logo span { display: none; } |
| 406 | } |
| 407 | @media (max-width: 860px) { |
| 408 | body { overflow: auto; } |
| 409 | .topbar { flex-wrap: wrap; height: auto; padding: 8px 10px; row-gap: 8px; gap: 8px; } |
| 410 | .topbar .back { order: 1; } |
| 411 | .logo { order: 2; font-size: 14px; } |
| 412 | .save-state { order: 3; margin-left: auto; font-size: 11.5px; } |
| 413 | .top-actions { order: 4; gap: 6px; } |
| 414 | .top-actions .lbl { display: none; } |
| 415 | .top-actions button { padding: 8px 10px; } |
| 416 | .title-input { order: 5; flex: 1 1 100%; max-width: none; background: rgba(255,255,255,.05); border-color: var(--border); } |
| 417 | .live-chip { order: 6; } |
| 418 | .app { grid-template-columns: minmax(0, 1fr); grid-template-rows: auto 1fr auto; overflow-y: auto; height: auto; min-height: calc(100vh - 108px); } |
| 419 | .rail { border-right: none; border-bottom: 1px solid var(--border); } |
| 420 | .thumbs { flex-direction: row; overflow-x: auto; } |
| 421 | .thumb { width: 140px; flex-shrink: 0; } |
| 422 | .inspector { border-left: none; border-top: 1px solid var(--border); } |
| 423 | .workspace { min-width: 0; } |
| 424 | .stage { padding: 12px; } |
| 425 | .canvas-wrap { width: 100%; max-width: 100%; } |
| 426 | .toolbar { gap: 6px; padding: 9px 12px; } |
| 427 | .toolbar-label { display: none; } |
| 428 | .toolbar .spacer { display: none; } |
| 429 | .toolbar button { padding: 7px 10px; font-size: 12px; } |
| 430 | .statusbar { font-size: 11px; padding: 8px 12px; } |
| 431 | } |
| 432 | @media (max-width: 520px) { |
| 433 | .toolbar button[data-act="move-up"], .toolbar button[data-act="move-down"] { display: none; } |
| 434 | .inspector { padding: 10px; } |
| 435 | .row-4 .fld input { font-size: 12px; } |
| 436 | } |
| 437 | |
| 438 | body { background: #101014 url('/img/bipfr-bg.png') center / cover fixed no-repeat; } |
| 439 | .topbar { background: rgba(30, 30, 30, .62); backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px); } |
| 440 | .rail, .inspector { background: rgba(20, 20, 25, .55); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); } |
| 441 | .logo-mark { width: 12px; height: 12px; border-radius: 4px; background: #4cc2ff; box-shadow: 0 0 10px rgba(76,194,255,.7); display: inline-block; flex-shrink: 0; } |
| 442 | button { touch-action: manipulation; } |
| 443 | @media (max-width: 860px) { |
| 444 | body { overflow: auto; } |
| 445 | .toolbar button, .top-actions button { min-height: 38px; } |
| 446 | #tpl-menu { left: 8px; right: 8px; max-width: none; } |
| 447 | } |
| 448 | |
| 449 | </style> |
| 450 | </head> |
| 451 | <body> |
| 452 | <header class="topbar"> |
| 453 | <a class="back" href="index.html" title="На главную">←</a> |
| 454 | <div class="logo"><span class="logo-mark"></span>Prompt<span>ly</span></div> |
| 455 | <input class="title-input" id="title" placeholder="Название презентации"> |
| 456 | <span class="live-chip" id="live-chip" hidden></span> |
| 457 | <span class="save-state" id="save-state">Черновик</span> |
| 458 | <div class="top-actions"> |
| 459 | <a class="ghost" href="docs.html" target="_blank" rel="noopener" title="Справочник Lua"><span class="lbl">Lua</span></a> |
| 460 | <button class="ghost" id="commands-btn" title="Список команд докладчика">⌘ <span class="lbl">Команды</span></button> |
| 461 | <button class="ghost" id="settings-btn" title="Переменные, музыка и Lua"><span class="lbl">Настройки</span></button> |
| 462 | <button class="ghost" id="export-btn" title="Скачать презентацию файлом JSON" disabled><span class="lbl">Экспорт</span></button> |
| 463 | <button class="ghost" id="import-btn" title="Загрузить презентацию из JSON-файла"><span class="lbl">Импорт</span></button> |
| 464 | <input type="file" id="import-file" accept=".json,application/json"> |
| 465 | <button class="ghost" id="copy-link" title="Скопировать ссылку для зрителей" disabled><span class="lbl">Зрителям</span></button> |
| 466 | <button class="primary" id="demo-btn">▶ Демонстрировать</button> |
| 467 | </div> |
| 468 | </header> |
| 469 | |
| 470 | <div class="app"> |
| 471 | <aside class="rail"> |
| 472 | <div class="rail-head"><span>Слайды</span><span id="slide-count">0</span></div> |
| 473 | <div class="thumbs" id="thumbs"></div> |
| 474 | <div class="tpl-menu" id="tpl-menu" hidden> |
| 475 | <div class="tpl-head">Шаблон нового слайда</div> |
| 476 | <button data-tpl="blank"><span class="tpl-ico">▢</span><span class="tpl-name">Пустой<span class="tpl-desc">чистый холст</span></span></button> |
| 477 | <button data-tpl="title"><span class="tpl-ico">Т</span><span class="tpl-name">Титульный<span class="tpl-desc">крупный заголовок и подзаголовок</span></span></button> |
| 478 | <button data-tpl="heading"><span class="tpl-ico">З</span><span class="tpl-name">Заголовок + текст<span class="tpl-desc">классический слайд с акцентной полосой</span></span></button> |
| 479 | <button data-tpl="columns"><span class="tpl-ico">К</span><span class="tpl-name">Две колонки<span class="tpl-desc">сравнения, «было / стало»</span></span></button> |
| 480 | <button data-tpl="image"><span class="tpl-ico">И</span><span class="tpl-name">Картинка + текст<span class="tpl-desc">изображение справа, текст слева</span></span></button> |
| 481 | <button data-tpl="quote"><span class="tpl-ico">Ц</span><span class="tpl-name">Цитата<span class="tpl-desc">крупная цитата и автор</span></span></button> |
| 482 | <button data-tpl="stat"><span class="tpl-ico">П</span><span class="tpl-name">Показатели<span class="tpl-desc">три карточки с числами</span></span></button> |
| 483 | <button data-tpl="section"><span class="tpl-ico">Р</span><span class="tpl-name">Раздел<span class="tpl-desc">номер раздела и название</span></span></button> |
| 484 | </div> |
| 485 | <button class="add-slide" id="add-slide">+ Новый слайд</button> |
| 486 | </aside> |
| 487 | |
| 488 | <main class="workspace"> |
| 489 | <div class="toolbar"> |
| 490 | <div class="segmented view-toggle"> |
| 491 | <button data-view="canvas" class="active">Холст</button> |
| 492 | <button data-view="graph">Граф</button> |
| 493 | </div> |
| 494 | <button data-act="open-tree" title="Древо: элементы холста и плагины">🌳 Древо</button> |
| 495 | <span class="toolbar-label">Добавить</span> |
| 496 | <button data-add="text" title="Текст (двойной клик по элементу — нет, правьте в инспекторе)">🅣 Текст</button> |
| 497 | <button data-add="image">Картинка</button> |
| 498 | <button data-add="shape" title="Прямоугольник, эллипс, стрелка, звезда…">◆ Фигура</button> |
| 499 | <button data-add="button">Кнопка</button> |
| 500 | <button data-add="audio">Аудио</button> |
| 501 | <button data-add="video">Видео</button> |
| 502 | <button data-add="window">Окно</button> |
| 503 | <button data-add="lua" title="Кастомный элемент: стили и HTML через Lua">Lua</button> |
| 504 | <span class="sep"></span> |
| 505 | <button data-act="undo" title="Отменить (Ctrl+Z)">↩</button> |
| 506 | <button data-act="redo" title="Повторить (Ctrl+Shift+Z)">↪</button> |
| 507 | <span class="spacer"></span> |
| 508 | <button data-act="duplicate-slide" title="Дублировать слайд">⧉ Слайд</button> |
| 509 | <button data-act="move-up" title="Переместить слайд выше">↑</button> |
| 510 | <button data-act="move-down" title="Переместить слайд ниже">↓</button> |
| 511 | <button data-act="delete-slide" class="danger" title="Удалить слайд">Удалить</button> |
| 512 | </div> |
| 513 | |
| 514 | <div class="stage" id="stage"> |
| 515 | <div class="canvas-wrap" id="canvas-wrap"> |
| 516 | <div class="canvas" id="canvas"></div> |
| 517 | <div class="sel-box" id="sel-box" hidden> |
| 518 | <span class="resize" data-dir="nw"></span> |
| 519 | <span class="resize" data-dir="ne"></span> |
| 520 | <span class="resize" data-dir="sw"></span> |
| 521 | <span class="resize" data-dir="se"></span> |
| 522 | </div> |
| 523 | </div> |
| 524 | </div> |
| 525 | |
| 526 | <div class="graph-stage" id="graph-stage" hidden> |
| 527 | <div class="graph-toolbar"> |
| 528 | <span class="toolbar-label">Ноды</span> |
| 529 | <button data-graph-add="slide">+ Слайд</button> |
| 530 | <button data-graph-add="script">+ Код</button> |
| 531 | <button data-graph-add="audio">+ Аудио</button> |
| 532 | <button data-graph-add="variable">+ Переменная</button> |
| 533 | <button data-graph-add="transition">+ Переход</button> |
| 534 | <button data-graph-add="anim">+ Анимация</button> |
| 535 | <button data-act="tree-toggle" title="Показать/скрыть древо">🌳 Древо</button> |
| 536 | <button data-act="plugin-new" title="Создать Lua-плагин">+ Плагин</button> |
| 537 | <span class="spacer"></span> |
| 538 | <div class="graph-legend" id="graph-legend" title="Цвета связей"> |
| 539 | <span><i style="background:#60a5fa"></i>навигация</span> |
| 540 | <span><i style="background:#f59e0b"></i>кнопка</span> |
| 541 | <span><i style="background:#34d399"></i>данные</span> |
| 542 | <span><i style="background:#fbbf24"></i>аудио</span> |
| 543 | <span><i style="background:#e879f9"></i>код</span> |
| 544 | <span><i style="background:#22d3ee"></i>переход</span> |
| 545 | <span><i style="background:#fb7185"></i>анимация</span> |
| 546 | <span><i style="background:#f97316"></i>плагин</span> |
| 547 | </div> |
| 548 | </div> |
| 549 | <div class="graph-body"> |
| 550 | <aside class="tree-panel" id="tree-panel"> |
| 551 | <div class="tree-head"><span>Древо</span><button class="tree-collapse" data-act="tree-collapse" title="Свернуть древо">‹</button></div> |
| 552 | <div class="tree-tabs"> |
| 553 | <button data-tree-tab="base" class="active">База</button> |
| 554 | <button data-tree-tab="plugins">Плагины</button> |
| 555 | </div> |
| 556 | <input class="tree-search" id="tree-search" placeholder="Поиск по древу…" autocomplete="off"> |
| 557 | <div class="tree-scroll" id="tree-list"></div> |
| 558 | <div class="tree-legend"> |
| 559 | <span><i style="background:#60a5fa"></i>навигация</span> |
| 560 | <span><i style="background:#f59e0b"></i>кнопка</span> |
| 561 | <span><i style="background:#34d399"></i>данные</span> |
| 562 | <span><i style="background:#e879f9"></i>код</span> |
| 563 | <span><i style="background:#f97316"></i>плагин</span> |
| 564 | </div> |
| 565 | <div class="tree-foot"> |
| 566 | <button data-act="plugin-new">+ Плагин</button> |
| 567 | <button data-act="plugin-edit">Редактор</button> |
| 568 | </div> |
| 569 | </aside> |
| 570 | <div class="graph-scroll" id="graph-scroll"> |
| 571 | <div class="graph-world" id="graph-world"> |
| 572 | <svg class="graph-svg" id="graph-svg"></svg> |
| 573 | <div class="graph-nodes" id="graph-nodes"></div> |
| 574 | </div> |
| 575 | </div> |
| 576 | </div> |
| 577 | </div> |
| 578 | |
| 579 | <div class="statusbar"> |
| 580 | <span>Слайд <b id="slide-index">1</b> из <b id="slide-total">1</b></span> |
| 581 | <span class="hints" id="status-hint"> |
| 582 | <span><kbd>Ctrl+S</kbd> сохранить</span> |
| 583 | <span><kbd>Ctrl+Z</kbd> отменить</span> |
| 584 | <span><kbd>Ctrl+C/V</kbd> копировать элемент</span> |
| 585 | <span><kbd>↑↓←→</kbd> сдвиг элемента</span> |
| 586 | <span><kbd>Del</kbd> удалить</span> |
| 587 | </span> |
| 588 | </div> |
| 589 | </main> |
| 590 | |
| 591 | <aside class="inspector" id="inspector"></aside> |
| 592 | </div> |
| 593 | |
| 594 | <div class="modal" id="settings-modal" hidden> |
| 595 | <div class="modal-card"> |
| 596 | <div class="modal-head"> |
| 597 | <h2>Настройки презентации</h2> |
| 598 | <button id="close-settings" title="Закрыть">×</button> |
| 599 | </div> |
| 600 | <div class="modal-body"> |
| 601 | <section class="section"> |
| 602 | <h3>Глобальные переменные</h3> |
| 603 | <p class="hint">По одной на строку: <code>key = value</code>. Подставляются в тексты и подписи как <code>{{key}}</code>, доступны в Lua как <code>vars.key</code>. Общие для всех слайдов и зрителей.</p> |
| 604 | <textarea id="vars-input" rows="5" placeholder="score = 0 speaker_name = Иван"></textarea> |
| 605 | </section> |
| 606 | |
| 607 | <section class="section"> |
| 608 | <h3>Фоновая музыка</h3> |
| 609 | <label>URL аудиофайла |
| 610 | <input id="music-src" type="url" placeholder="https://example.com/background.mp3"> |
| 611 | </label> |
| 612 | <label>Начальная громкость |
| 613 | <span class="vol-line"> |
| 614 | <input id="music-volume" type="range" min="0" max="100" step="1" value="50"> |
| 615 | <output id="music-volume-out">50%</output> |
| 616 | </span> |
| 617 | </label> |
| 618 | <p class="hint">Играет на всех слайдах. Во время эффектов автоматически приглушается. Докладчик меняет громкость фона и эффектов отдельно.</p> |
| 619 | </section> |
| 620 | |
| 621 | <section class="section"> |
| 622 | <h3>Глобальный Lua</h3> |
| 623 | <p class="hint"> |
| 624 | Выполняется при старте демонстрации. API: |
| 625 | <code>app.go(n)</code>, <code>app.next()</code>, <code>app.prev()</code>, |
| 626 | <code>app.play(id)</code>, <code>app.stop(id)</code>, <code>app.music(src)</code>, |
| 627 | <code>app.musicPlay()</code>, <code>app.musicStop()</code>, <code>app.musicVolume(v)</code>, |
| 628 | <code>app.setVar(k, v)</code>, <code>app.getVar(k)</code>, <code>app.log(msg)</code>. |
| 629 | </p> |
| 630 | <textarea id="lua-input" rows="6" placeholder="vars.score = 0 app.log('Презентация готова')"></textarea> |
| 631 | </section> |
| 632 | </div> |
| 633 | <div class="modal-foot"> |
| 634 | <button class="ghost" id="cancel-settings">Отмена</button> |
| 635 | <button class="primary" id="save-settings">Сохранить</button> |
| 636 | </div> |
| 637 | </div> |
| 638 | </div> |
| 639 | |
| 640 | <div class="modal" id="commands-modal" hidden> |
| 641 | <div class="modal-card"> |
| 642 | <div class="modal-head"> |
| 643 | <h2>Консоль команд</h2> |
| 644 | <button id="close-commands" title="Закрыть">×</button> |
| 645 | </div> |
| 646 | <div class="modal-body"> |
| 647 | <p class="hint">Команды появятся у докладчика в консоли. Он выбирает нужную стрелками и запускает Enter. Каждая команда — Lua-код, который выполняется только у докладчика, а переменные синхронизируются со зрителями.</p> |
| 648 | <div id="commands-list"></div> |
| 649 | <button class="ghost" id="add-command">+ Добавить команду</button> |
| 650 | </div> |
| 651 | <div class="modal-foot"> |
| 652 | <button class="ghost" id="cancel-commands">Отмена</button> |
| 653 | <button class="primary" id="save-commands">Сохранить</button> |
| 654 | </div> |
| 655 | </div> |
| 656 | </div> |
| 657 | |
| 658 | <div class="modal" id="plugin-modal" hidden> |
| 659 | <div class="modal-card wide"> |
| 660 | <div class="modal-head"> |
| 661 | <h2>Редактор плагинов</h2> |
| 662 | <button id="close-plugin" title="Закрыть">×</button> |
| 663 | </div> |
| 664 | <div class="plugin-wrap"> |
| 665 | <aside class="plugin-side"> |
| 666 | <div class="plugin-side-head"> |
| 667 | <button class="ghost" id="plugin-new">+ Новый</button> |
| 668 | <button class="ghost" id="plugin-reload" title="Перечитать реестр с сервера">↻</button> |
| 669 | </div> |
| 670 | <div class="plugin-list" id="plugin-list"></div> |
| 671 | </aside> |
| 672 | <div class="plugin-main"> |
| 673 | <div class="plugin-meta"> |
| 674 | <label class="fld"><span class="label">Название</span><input id="plugin-name" placeholder="Например, Эффекты"></label> |
| 675 | <label class="fld"><span class="label">Цвет</span><input type="color" id="plugin-color" value="#f97316"></label> |
| 676 | </div> |
| 677 | <label class="fld"><span class="label">Описание</span><input id="plugin-desc" placeholder="Что делает плагин"></label> |
| 678 | <div class="fld"> |
| 679 | <span class="label">Lua-модуль · каждая функция становится нодой</span> |
| 680 | <div id="plugin-code"></div> |
| 681 | </div> |
| 682 | <div class="muted" id="plugin-status"></div> |
| 683 | <div class="plugin-nodes" id="plugin-nodes"></div> |
| 684 | <p class="hint">Комментарий <code>-- @node Заголовок</code> перед функцией задаёт имя ноды. Плагин хранится на диске: <code>server/data/plugins/<id>.lua</code>. В ноде плагина код — снимок модуля, поэтому показ не зависит от реестра.</p> |
| 685 | <div class="plugin-foot"> |
| 686 | <button class="ghost" id="plugin-delete">Удалить</button> |
| 687 | <span class="spacer"></span> |
| 688 | <button class="ghost" id="plugin-close">Закрыть</button> |
| 689 | <button class="primary" id="plugin-save">Сохранить</button> |
| 690 | </div> |
| 691 | </div> |
| 692 | </div> |
| 693 | </div> |
| 694 | </div> |
| 695 | |
| 696 | <div class="toast" id="toast"></div> |
| 697 | |
| 698 | <script src="vendor/fengari-web.js"></script> |
| 699 | <script src="js/lua-bridge.js"></script> |
| 700 | <script src="js/slide-view.js"></script> |
| 701 | <script> |
| 702 | const DEFAULT_GRADIENT = 'linear-gradient(135deg, #0f172a 0%, #1e1b4b 55%, #312e81 100%)'; |
| 703 | const GRADIENT_PRESETS = [ |
| 704 | 'linear-gradient(135deg, #0f172a 0%, #1e1b4b 55%, #312e81 100%)', |
| 705 | 'linear-gradient(135deg, #111827 0%, #3b0764 55%, #831843 100%)', |
| 706 | 'linear-gradient(135deg, #052e16 0%, #064e3b 50%, #0f766e 100%)', |
| 707 | 'linear-gradient(135deg, #1c1917 0%, #7c2d12 55%, #b45309 100%)', |
| 708 | 'linear-gradient(135deg, #0c0a1d 0%, #1e1b4b 45%, #0e7490 100%)', |
| 709 | 'linear-gradient(160deg, #020617 0%, #1e293b 60%, #334155 100%)', |
| 710 | 'linear-gradient(135deg, #450a0a 0%, #7f1d1d 55%, #b91c1c 100%)', |
| 711 | 'linear-gradient(135deg, #172554 0%, #1d4ed8 60%, #38bdf8 100%)', |
| 712 | 'linear-gradient(135deg, #faf5ff 0%, #e9d5ff 55%, #c4b5fd 100%)', |
| 713 | 'linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%)', |
| 714 | ]; |
| 715 | const SOLID_PRESETS = [ |
| 716 | '#0f172a', '#020617', '#1e1b4b', '#312e81', '#4c1d95', '#701a75', |
| 717 | '#881337', '#7f1d1d', '#7c2d12', '#713f12', '#14532d', '#064e3b', |
| 718 | '#0c4a6e', '#1e3a8a', '#f8fafc', '#e2e8f0', |
| 719 | ]; |
| 720 | const FONT_OPTIONS = [ |
| 721 | ['sans', 'Sans (системный)'], |
| 722 | ['serif', 'Serif (Georgia)'], |
| 723 | ['mono', 'Mono (консольный)'], |
| 724 | ['round', 'Round (скруглённый)'], |
| 725 | ]; |
| 726 | const SHAPE_OPTIONS = [ |
| 727 | ['rect', 'Прямоугольник'], |
| 728 | ['round', 'Скруглённый'], |
| 729 | ['ellipse', 'Эллипс'], |
| 730 | ['triangle', 'Треугольник'], |
| 731 | ['diamond', 'Ромб'], |
| 732 | ['hexagon', 'Шестиугольник'], |
| 733 | ['arrow', 'Стрелка'], |
| 734 | ['star', 'Звезда'], |
| 735 | ['line', 'Линия'], |
| 736 | ]; |
| 737 | const SHAPE_FILLS = [ |
| 738 | '#6366f1', '#8b5cf6', '#d946ef', '#ec4899', '#ef4444', '#f97316', |
| 739 | '#fbbf24', '#22c55e', '#14b8a6', '#0ea5e9', '#f8fafc', '#0f172a', |
| 740 | ]; |
| 741 | |
| 742 | const uid = () => (crypto.randomUUID ? crypto.randomUUID() : `id_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`); |
| 743 | const $ = (id) => document.getElementById(id); |
| 744 | const esc = (value) => |
| 745 | String(value ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); |
| 746 | const clamp = (value, min, max) => Math.max(min, Math.min(max, value)); |
| 747 | |
| 748 | function defaultBackground() { |
| 749 | return { type: 'gradient', color: '#0f172a', gradient: DEFAULT_GRADIENT, image: '' }; |
| 750 | } |
| 751 | |
| 752 | function newSlide() { |
| 753 | return { id: uid(), notes: '', transition: 'fade', background: defaultBackground(), lua: '', elements: [] }; |
| 754 | } |
| 755 | |
| 756 | // Шаблоны слайдов: фабрики элементов для быстрого старта. |
| 757 | function slideTemplates() { |
| 758 | const t = (over) => ({ |
| 759 | id: uid(), type: 'text', x: 8, y: 40, w: 84, h: 20, text: 'Текст', fontSize: 5, |
| 760 | color: '#f8fafc', weight: 700, align: 'center', bg: '', font: 'sans', |
| 761 | italic: false, shadow: false, lineHeight: 1.16, opacity: 1, rotate: 0, z: 2, ...over, |
| 762 | }); |
| 763 | const shape = (over) => ({ |
| 764 | id: uid(), type: 'shape', shape: 'rect', x: 10, y: 10, w: 30, h: 8, fill: '#6366f1', |
| 765 | borderColor: '', borderWidth: 0, radius: 10, shadow: false, opacity: 1, rotate: 0, z: 1, ...over, |
| 766 | }); |
| 767 | const img = (over) => ({ |
| 768 | id: uid(), type: 'image', x: 55, y: 18, w: 38, h: 64, src: '', fit: 'cover', |
| 769 | radius: 16, shadow: true, opacity: 1, rotate: 0, z: 2, ...over, |
| 770 | }); |
| 771 | return { |
| 772 | blank: () => [], |
| 773 | title: () => [ |
| 774 | shape({ shape: 'rect', x: 42, y: 63, w: 16, h: 1.2, fill: '#a855f7', radius: 99 }), |
| 775 | t({ y: 30, h: 22, fontSize: 9, weight: 800, text: 'Заголовок презентации' }), |
| 776 | t({ y: 55, h: 12, fontSize: 3.4, weight: 400, color: '#c7d2fe', text: 'подзаголовок · автор · дата' }), |
| 777 | ], |
| 778 | heading: () => [ |
| 779 | shape({ shape: 'rect', x: 8, y: 12, w: 1.4, h: 12, fill: '#818cf8', radius: 99 }), |
| 780 | t({ x: 11, y: 11, w: 80, h: 14, fontSize: 6, weight: 800, align: 'left', text: 'Заголовок слайда' }), |
| 781 | t({ x: 11, y: 30, w: 78, h: 55, fontSize: 3, weight: 400, align: 'left', color: '#e2e8f0', lineHeight: 1.5, text: 'Основной текст слайда.\nВторой абзац — здесь важна структура и воздух между блоками.' }), |
| 782 | ], |
| 783 | columns: () => [ |
| 784 | t({ y: 8, h: 12, fontSize: 5.4, weight: 800, text: 'Сравнение' }), |
| 785 | shape({ shape: 'round', x: 7, y: 26, w: 41, h: 62, fill: 'rgba(99,102,241,.16)', borderColor: 'rgba(129,140,248,.5)', borderWidth: 2, radius: 16 }), |
| 786 | shape({ shape: 'round', x: 52, y: 26, w: 41, h: 62, fill: 'rgba(217,70,239,.12)', borderColor: 'rgba(232,121,249,.45)', borderWidth: 2, radius: 16 }), |
| 787 | t({ x: 9, y: 30, w: 37, h: 10, fontSize: 3.4, weight: 700, color: '#a5b4fc', text: 'Было' }), |
| 788 | t({ x: 9, y: 42, w: 37, h: 42, fontSize: 2.4, weight: 400, align: 'left', color: '#cbd5e1', lineHeight: 1.5, text: '• пункт один\n• пункт два\n• пункт три' }), |
| 789 | t({ x: 54, y: 30, w: 37, h: 10, fontSize: 3.4, weight: 700, color: '#f0abfc', text: 'Стало' }), |
| 790 | t({ x: 54, y: 42, w: 37, h: 42, fontSize: 2.4, weight: 400, align: 'left', color: '#cbd5e1', lineHeight: 1.5, text: '• пункт один\n• пункт два\n• пункт три' }), |
| 791 | ], |
| 792 | image: () => [ |
| 793 | t({ x: 7, y: 20, w: 44, h: 14, fontSize: 5.2, weight: 800, align: 'left', text: 'Картинка и мысль' }), |
| 794 | t({ x: 7, y: 38, w: 44, h: 40, fontSize: 2.6, weight: 400, align: 'left', color: '#cbd5e1', lineHeight: 1.5, text: 'Описание того, что видно на изображении справа. Загрузите файл в инспекторе.' }), |
| 795 | img({}), |
| 796 | ], |
| 797 | quote: () => [ |
| 798 | t({ y: 12, h: 18, fontSize: 12, weight: 800, color: '#a855f7', text: '«' }), |
| 799 | t({ x: 14, y: 28, w: 72, h: 32, fontSize: 4.6, weight: 600, italic: true, align: 'center', lineHeight: 1.4, text: 'Простота — высшая форма сложности.' }), |
| 800 | t({ x: 14, y: 66, w: 72, h: 10, fontSize: 2.6, weight: 400, color: '#94a3b8', text: '— Леонардо да Винчи' }), |
| 801 | ], |
| 802 | stat: () => { |
| 803 | const cards = []; |
| 804 | const data = [['87%', 'рост конверсии'], ['2.4×', 'ускорение'], ['15 мин', 'экономия в день']]; |
| 805 | data.forEach((item, i) => { |
| 806 | const x = 7 + i * 30; |
| 807 | cards.push(shape({ shape: 'round', x, y: 26, w: 26, h: 48, fill: 'rgba(255,255,255,.05)', borderColor: 'rgba(129,140,248,.35)', borderWidth: 2, radius: 16 })); |
| 808 | cards.push(t({ x, y: 34, w: 26, h: 16, fontSize: 6.4, weight: 800, color: '#a5b4fc', text: item[0] })); |
| 809 | cards.push(t({ x, y: 54, w: 26, h: 12, fontSize: 2.2, weight: 400, color: '#94a3b8', text: item[1] })); |
| 810 | }); |
| 811 | return [t({ y: 8, h: 14, fontSize: 5.4, weight: 800, text: 'Ключевые показатели' }), ...cards]; |
| 812 | }, |
| 813 | section: () => [ |
| 814 | shape({ shape: 'ellipse', x: 43, y: 14, w: 14, h: 25, fill: 'rgba(168,85,247,.25)', borderColor: '#a855f7', borderWidth: 3 }), |
| 815 | t({ y: 18, h: 16, fontSize: 8, weight: 800, color: '#e9d5ff', text: '02' }), |
| 816 | t({ y: 44, h: 16, fontSize: 6.4, weight: 800, text: 'Название раздела' }), |
| 817 | t({ y: 64, h: 10, fontSize: 2.6, weight: 400, color: '#94a3b8', text: 'короткое описание раздела' }), |
| 818 | ], |
| 819 | }; |
| 820 | } |
| 821 | |
| 822 | function hydrateSlide(slide) { |
| 823 | const source = slide || {}; |
| 824 | return { |
| 825 | id: source.id || uid(), |
| 826 | notes: source.notes || '', |
| 827 | transition: source.transition || 'fade', |
| 828 | background: { ...defaultBackground(), ...(source.background || {}) }, |
| 829 | lua: source.lua || '', |
| 830 | elements: (source.elements || []).map((element) => ({ |
| 831 | ...element, |
| 832 | id: element.id || uid(), |
| 833 | action: element.type === 'button' |
| 834 | ? { type: 'next', slideIndex: 0, audioId: '', code: '', scriptNodeId: '', ...(element.action || {}) } |
| 835 | : element.action, |
| 836 | ...(element.type === 'lua' ? { |
| 837 | code: element.code || '', |
| 838 | label: element.label || 'Lua-элемент', |
| 839 | computed: { |
| 840 | style: (element.computed && element.computed.style) || {}, |
| 841 | css: (element.computed && element.computed.css) || '', |
| 842 | html: (element.computed && element.computed.html) || '', |
| 843 | text: (element.computed && element.computed.text) || '', |
| 844 | at: (element.computed && element.computed.at) || 0, |
| 845 | }, |
| 846 | } : {}), |
| 847 | })), |
| 848 | }; |
| 849 | } |
| 850 | |
| 851 | const state = { |
| 852 | id: null, |
| 853 | title: '', |
| 854 | slides: [newSlide()], |
| 855 | variables: {}, |
| 856 | music: { src: '', volume: 0.5 }, |
| 857 | lua: '', |
| 858 | commands: [], |
| 859 | graph: { positions: {}, scripts: [], audios: [], variables: [], transitions: [], anims: [], plugins: [], links: [], jumps: {} }, |
| 860 | view: 'canvas', |
| 861 | selectedNode: null, |
| 862 | selectedLink: null, |
| 863 | commandDraft: [], |
| 864 | windowTargets: [], |
| 865 | windowEndpoint: '', |
| 866 | selected: 0, |
| 867 | selectedEl: null, |
| 868 | saving: false, |
| 869 | pending: false, |
| 870 | dirty: false, |
| 871 | updatedAt: 0, |
| 872 | clipboard: null, |
| 873 | tree: { tab: 'base', query: '', collapsed: {}, plugins: {}, open: true }, |
| 874 | pluginRegistry: [], |
| 875 | pluginDraft: null, |
| 876 | }; |
| 877 | |
| 878 | // История для Ctrl+Z / Ctrl+Shift+Z: снимки всего документа. |
| 879 | const undoHistory = { stack: [], index: -1, limit: 60, lastPush: 0 }; |
| 880 | let restoringHistory = false; |
| 881 | |
| 882 | const titleInput = $('title'); |
| 883 | const thumbsEl = $('thumbs'); |
| 884 | const canvasWrap = $('canvas-wrap'); |
| 885 | const canvasEl = $('canvas'); |
| 886 | const selBox = $('sel-box'); |
| 887 | const inspectorEl = $('inspector'); |
| 888 | const saveStateEl = $('save-state'); |
| 889 | const liveChip = $('live-chip'); |
| 890 | const copyLinkBtn = $('copy-link'); |
| 891 | const settingsModal = $('settings-modal'); |
| 892 | const commandsModal = $('commands-modal'); |
| 893 | const stageEl = $('stage'); |
| 894 | const graphStage = $('graph-stage'); |
| 895 | const graphWorld = $('graph-world'); |
| 896 | const graphSvg = $('graph-svg'); |
| 897 | const graphNodesEl = $('graph-nodes'); |
| 898 | const graphScroll = $('graph-scroll'); |
| 899 | const treePanel = $('tree-panel'); |
| 900 | const treeListEl = $('tree-list'); |
| 901 | const treeSearchEl = $('tree-search'); |
| 902 | const pluginModal = $('plugin-modal'); |
| 903 | const pluginListEl = $('plugin-list'); |
| 904 | const pluginCodeEl = $('plugin-code'); |
| 905 | const commandsListEl = $('commands-list'); |
| 906 | |
| 907 | const LINK_COLORS = { |
| 908 | nav: '#60a5fa', |
| 909 | button: '#f59e0b', |
| 910 | data: '#34d399', |
| 911 | audio: '#fbbf24', |
| 912 | logic: '#e879f9', |
| 913 | transition: '#22d3ee', |
| 914 | anim: '#fb7185', |
| 915 | plugin: '#f97316', |
| 916 | }; |
| 917 | |
| 918 | const PASS_THROUGH_KINDS = new Set(['transition', 'anim', 'plugin']); |
| 919 | |
| 920 | function linkKind(link) { |
| 921 | const from = link.from || {}; |
| 922 | const to = link.to || {}; |
| 923 | if (from.kind === 'variable' || to.kind === 'variable') return 'data'; |
| 924 | if (from.kind === 'slide' && String(from.port || '').startsWith('btn:')) return 'button'; |
| 925 | if (from.kind === 'audio' || to.kind === 'audio') return 'audio'; |
| 926 | if (from.kind === 'script' || to.kind === 'script') return 'logic'; |
| 927 | if (from.kind === 'plugin' || to.kind === 'plugin') return 'plugin'; |
| 928 | if (from.kind === 'transition' || to.kind === 'transition') return 'transition'; |
| 929 | if (from.kind === 'anim' || to.kind === 'anim') return 'anim'; |
| 930 | return 'nav'; |
| 931 | } |
| 932 | |
| 933 | const currentSlide = () => state.slides[state.selected]; |
| 934 | |
| 935 | function selectedElement() { |
| 936 | if (!state.selectedEl) return null; |
| 937 | return (currentSlide().elements || []).find((element) => element.id === state.selectedEl) || null; |
| 938 | } |
| 939 | |
| 940 | // ==================== Граф ==================== |
| 941 | function graphDefaultPosition(index) { |
| 942 | return { x: 340 + (index % 4) * 320, y: 60 + Math.floor(index / 4) * 300 }; |
| 943 | } |
| 944 | |
| 945 | // Оценка габаритов нод для поиска свободного места без наложений. |
| 946 | function graphNodeBoxes(ignoreKind, ignoreId) { |
| 947 | const boxes = []; |
| 948 | state.slides.forEach((slide, index) => { |
| 949 | const p = state.graph.positions[slide.id] || graphDefaultPosition(index); |
| 950 | const ports = 3 + slideButtonPorts(slide).length + slideVarPorts(slide).length; |
| 951 | boxes.push({ kind: 'slide', id: slide.id, x: p.x, y: p.y, w: 250, h: 118 + ports * 21 }); |
| 952 | }); |
| 953 | state.graph.scripts.forEach((node) => boxes.push({ kind: 'script', id: node.id, x: node.x, y: node.y, w: 250, h: 150 })); |
| 954 | (state.graph.audios || []).forEach((node) => boxes.push({ kind: 'audio', id: node.id, x: node.x, y: node.y, w: 250, h: 130 })); |
| 955 | (state.graph.variables || []).forEach((node) => boxes.push({ kind: 'variable', id: node.id, x: node.x, y: node.y, w: 250, h: 130 })); |
| 956 | (state.graph.transitions || []).forEach((node) => boxes.push({ kind: 'transition', id: node.id, x: node.x, y: node.y, w: 250, h: 150 })); |
| 957 | (state.graph.anims || []).forEach((node) => boxes.push({ kind: 'anim', id: node.id, x: node.x, y: node.y, w: 250, h: 150 })); |
| 958 | (state.graph.plugins || []).forEach((node) => boxes.push({ kind: 'plugin', id: node.id, x: node.x, y: node.y, w: 250, h: 150 })); |
| 959 | return boxes.filter((box) => box.kind !== ignoreKind || box.id !== ignoreId); |
| 960 | } |
| 961 | |
| 962 | function findFreeNodeSpot(x, y, ignoreKind, ignoreId, size) { |
| 963 | const boxes = graphNodeBoxes(ignoreKind, ignoreId); |
| 964 | const w = (size && size.w) || 250; |
| 965 | const h = (size && size.h) || 150; |
| 966 | const overlaps = (box) => boxes.some((other) => |
| 967 | box.x < other.x + other.w + 18 |
| 968 | && box.x + box.w + 18 > other.x |
| 969 | && box.y < other.y + other.h + 18 |
| 970 | && box.y + box.h + 18 > other.y |
| 971 | ); |
| 972 | const fits = (cx, cy) => { |
| 973 | const candidate = { x: Math.max(20, cx), y: Math.max(20, cy), w, h }; |
| 974 | return overlaps(candidate) ? null : { x: candidate.x, y: candidate.y }; |
| 975 | }; |
| 976 | const exact = fits(x, y); |
| 977 | if (exact) return exact; |
| 978 | // Расходящаяся сетка: сначала ближние позиции, затем всё дальше. |
| 979 | const stepX = 320; |
| 980 | const stepY = 300; |
| 981 | const baseX = Math.round(x / stepX) * stepX; |
| 982 | const baseY = Math.round(y / stepY) * stepY; |
| 983 | for (let radius = 1; radius <= 12; radius += 1) { |
| 984 | for (let dx = -radius; dx <= radius; dx += 1) { |
| 985 | for (let dy = -radius; dy <= radius; dy += 1) { |
| 986 | if (Math.max(Math.abs(dx), Math.abs(dy)) !== radius) continue; |
| 987 | const spot = fits(baseX + dx * stepX, baseY + dy * stepY); |
| 988 | if (spot) return spot; |
| 989 | } |
| 990 | } |
| 991 | } |
| 992 | return { x: Math.max(20, x), y: Math.max(20, y) }; |
| 993 | } |
| 994 | |
| 995 | function findScriptNode(id) { |
| 996 | return state.graph.scripts.find((node) => node.id === id) || null; |
| 997 | } |
| 998 | |
| 999 | function findTransitionNode(id) { |
| 1000 | return (state.graph.transitions || []).find((node) => node.id === id) || null; |
| 1001 | } |
| 1002 | |
| 1003 | function findAnimNode(id) { |
| 1004 | return (state.graph.anims || []).find((node) => node.id === id) || null; |
| 1005 | } |
| 1006 | |
| 1007 | function findAudioNode(id) { |
| 1008 | return (state.graph.audios || []).find((node) => node.id === id) || null; |
| 1009 | } |
| 1010 | |
| 1011 | function findVariableNode(id) { |
| 1012 | return (state.graph.variables || []).find((node) => node.id === id) || null; |
| 1013 | } |
| 1014 | |
| 1015 | function findPluginNode(id) { |
| 1016 | return (state.graph.plugins || []).find((node) => node.id === id) || null; |
| 1017 | } |
| 1018 | |
| 1019 | function findNodeByKind(kind, id) { |
| 1020 | if (kind === 'slide') return state.slides.find((slide) => slide.id === id) || null; |
| 1021 | if (kind === 'script') return findScriptNode(id); |
| 1022 | if (kind === 'audio') return findAudioNode(id); |
| 1023 | if (kind === 'variable') return findVariableNode(id); |
| 1024 | if (kind === 'transition') return findTransitionNode(id); |
| 1025 | if (kind === 'anim') return findAnimNode(id); |
| 1026 | if (kind === 'plugin') return findPluginNode(id); |
| 1027 | return null; |
| 1028 | } |
| 1029 | |
| 1030 | function findVariableByName(name) { |
| 1031 | return (state.graph.variables || []).find((node) => node.name === name) || null; |
| 1032 | } |
| 1033 | |
| 1034 | function scriptNodeForElement(elementId) { |
| 1035 | return state.graph.scripts.find((node) => node.elementId === elementId) || null; |
| 1036 | } |
| 1037 | |
| 1038 | function findLinkedElement(node) { |
| 1039 | if (!node || !node.elementId) return null; |
| 1040 | for (const slide of state.slides) { |
| 1041 | const element = (slide.elements || []).find((item) => item.id === node.elementId); |
| 1042 | if (element) return { slide, element }; |
| 1043 | } |
| 1044 | return null; |
| 1045 | } |
| 1046 | |
| 1047 | function findAudioElement(id) { |
| 1048 | if (!id) return null; |
| 1049 | for (const slide of state.slides) { |
| 1050 | const element = (slide.elements || []).find((item) => item.type === 'audio' && item.id === id); |
| 1051 | if (element) return { slide, element }; |
| 1052 | } |
| 1053 | return null; |
| 1054 | } |
| 1055 | |
| 1056 | function nodeRef(kind, id) { |
| 1057 | if (kind === 'slide') { |
| 1058 | if (!state.graph.positions[id]) state.graph.positions[id] = { x: 0, y: 0 }; |
| 1059 | return state.graph.positions[id]; |
| 1060 | } |
| 1061 | if (kind === 'script') return findScriptNode(id); |
| 1062 | if (kind === 'audio') return findAudioNode(id); |
| 1063 | if (kind === 'variable') return findVariableNode(id); |
| 1064 | if (kind === 'transition') return findTransitionNode(id); |
| 1065 | if (kind === 'anim') return findAnimNode(id); |
| 1066 | if (kind === 'plugin') return findPluginNode(id); |
| 1067 | return null; |
| 1068 | } |
| 1069 | |
| 1070 | function slideVarPorts(slide) { |
| 1071 | const ports = []; |
| 1072 | const seen = new Set(); |
| 1073 | (slide.elements || []).forEach((element) => { |
| 1074 | if (element.type !== 'text') return; |
| 1075 | const matches = String(element.text || '').match(/\{\{\s*[\w.-]+\s*\}\}/g) || []; |
| 1076 | matches.forEach((raw) => { |
| 1077 | const name = raw.replace(/[{}]/g, '').trim(); |
| 1078 | if (!name) return; |
| 1079 | const key = `var:${element.id}:${name}`; |
| 1080 | if (seen.has(key)) return; |
| 1081 | seen.add(key); |
| 1082 | ports.push({ key, name, elementId: element.id }); |
| 1083 | }); |
| 1084 | }); |
| 1085 | return ports; |
| 1086 | } |
| 1087 | |
| 1088 | function slideButtonPorts(slide) { |
| 1089 | return (slide.elements || []) |
| 1090 | .filter((element) => element.type === 'button') |
| 1091 | .map((element) => ({ key: `btn:${element.id}`, label: element.label || 'Кнопка', elementId: element.id })); |
| 1092 | } |
| 1093 | |
| 1094 | const escapeRx = (value) => String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); |
| 1095 | |
| 1096 | function removeVarPlaceholder(elementId, name) { |
| 1097 | for (const slide of state.slides) { |
| 1098 | const element = (slide.elements || []).find((item) => item.id === elementId); |
| 1099 | if (!element || typeof element.text !== 'string') continue; |
| 1100 | element.text = element.text |
| 1101 | .replace(new RegExp(`\\{\\{\\s*${escapeRx(name)}\\s*\\}\\}`, 'g'), '') |
| 1102 | .trim(); |
| 1103 | return; |
| 1104 | } |
| 1105 | } |
| 1106 | |
| 1107 | function hasLink(from, to) { |
| 1108 | return state.graph.links.some((link) => |
| 1109 | link.from.kind === from.kind && link.from.id === from.id && link.from.port === from.port |
| 1110 | && link.to.kind === to.kind && link.to.id === to.id && link.to.port === to.port |
| 1111 | ); |
| 1112 | } |
| 1113 | |
| 1114 | function pushLink(from, to) { |
| 1115 | if (hasLink(from, to)) return null; |
| 1116 | const link = { |
| 1117 | id: uid(), |
| 1118 | from: { kind: from.kind, id: from.id, port: from.port }, |
| 1119 | to: { kind: to.kind, id: to.id, port: to.port }, |
| 1120 | }; |
| 1121 | state.graph.links.push(link); |
| 1122 | return link; |
| 1123 | } |
| 1124 | |
| 1125 | function ensureAudioNode(elementId, mode) { |
| 1126 | let node = state.graph.audios.find((item) => item.elementId === elementId); |
| 1127 | if (!node) { |
| 1128 | const found = findAudioElement(elementId); |
| 1129 | const slide = found ? found.slide : currentSlide(); |
| 1130 | const base = slide && state.graph.positions[slide.id] ? state.graph.positions[slide.id] : { x: 340, y: 60 }; |
| 1131 | const index = state.graph.audios.length; |
| 1132 | const spot = findFreeNodeSpot(base.x + 330, base.y + 200 + (index % 3) * 96, 'audio', ''); |
| 1133 | node = { |
| 1134 | id: uid(), |
| 1135 | name: found && found.element.label ? found.element.label : 'Аудио', |
| 1136 | elementId, |
| 1137 | mode: mode || 'play', |
| 1138 | x: spot.x, |
| 1139 | y: spot.y, |
| 1140 | }; |
| 1141 | state.graph.audios.push(node); |
| 1142 | } |
| 1143 | if (mode) node.mode = mode; |
| 1144 | return node; |
| 1145 | } |
| 1146 | |
| 1147 | function ensureVariableNode(name) { |
| 1148 | let node = findVariableByName(name); |
| 1149 | if (!node) { |
| 1150 | const anchor = state.slides[0] ? state.graph.positions[state.slides[0].id] : { x: 340, y: 60 }; |
| 1151 | const index = state.graph.variables.length; |
| 1152 | const spot = findFreeNodeSpot( |
| 1153 | Math.max(20, (anchor ? anchor.x : 340) - 300), |
| 1154 | (anchor ? anchor.y : 60) + 20 + (index % 6) * 120, |
| 1155 | 'variable', |
| 1156 | '' |
| 1157 | ); |
| 1158 | node = { |
| 1159 | id: uid(), |
| 1160 | name: name || `var${index + 1}`, |
| 1161 | x: spot.x, |
| 1162 | y: spot.y, |
| 1163 | }; |
| 1164 | state.graph.variables.push(node); |
| 1165 | } |
| 1166 | return node; |
| 1167 | } |
| 1168 | |
| 1169 | // Достраивает связи по действиям кнопок и вставкам {{переменная}}. |
| 1170 | function graphPortExists(kind, id, port) { |
| 1171 | if (kind === 'slide') { |
| 1172 | const slide = state.slides.find((item) => item.id === id); |
| 1173 | if (!slide) return false; |
| 1174 | if (port === 'in' || port === 'next' || port === 'prev') return true; |
| 1175 | if (port.startsWith('btn:')) { |
| 1176 | const elementId = port.slice(4); |
| 1177 | return (slide.elements || []).some((el) => el.type === 'button' && el.id === elementId); |
| 1178 | } |
| 1179 | if (port.startsWith('var:')) return slideVarPorts(slide).some((item) => item.key === port); |
| 1180 | return false; |
| 1181 | } |
| 1182 | if (kind === 'script') return !!findScriptNode(id) && port === 'in'; |
| 1183 | if (kind === 'audio') return !!findAudioNode(id) && port === 'in'; |
| 1184 | if (kind === 'variable') return !!findVariableNode(id) && port === 'value'; |
| 1185 | if (kind === 'transition') return !!findTransitionNode(id) && (port === 'in' || port === 'out'); |
| 1186 | if (kind === 'anim') return !!findAnimNode(id) && (port === 'in' || port === 'out'); |
| 1187 | if (kind === 'plugin') return !!findPluginNode(id) && (port === 'in' || port === 'out'); |
| 1188 | return false; |
| 1189 | } |
| 1190 | |
| 1191 | function pruneGraphLinks() { |
| 1192 | state.graph.links = state.graph.links.filter((link) => |
| 1193 | graphPortExists(link.from.kind, link.from.id, link.from.port) |
| 1194 | && graphPortExists(link.to.kind, link.to.id, link.to.port) |
| 1195 | ); |
| 1196 | } |
| 1197 | |
| 1198 | function ensureLinksFromModel() { |
| 1199 | pruneGraphLinks(); |
| 1200 | state.slides.forEach((slide) => { |
| 1201 | (slide.elements || []).forEach((element) => { |
| 1202 | if (element.type !== 'button' || !element.action) return; |
| 1203 | const action = element.action; |
| 1204 | const from = { kind: 'slide', id: slide.id, port: `btn:${element.id}` }; |
| 1205 | const exists = state.graph.links.some((link) => |
| 1206 | link.from.kind === from.kind && link.from.id === from.id && link.from.port === from.port |
| 1207 | ); |
| 1208 | if (exists) return; |
| 1209 | if (action.type === 'go') { |
| 1210 | const target = state.slides[Number(action.slideIndex) || 0]; |
| 1211 | if (target) pushLink(from, { kind: 'slide', id: target.id, port: 'in' }); |
| 1212 | } else if (action.type === 'lua') { |
| 1213 | const node = action.scriptNodeId ? findScriptNode(action.scriptNodeId) : scriptNodeForElement(element.id); |
| 1214 | if (node) pushLink(from, { kind: 'script', id: node.id, port: 'in' }); |
| 1215 | } else if ((action.type === 'play' || action.type === 'stop') && action.audioId) { |
| 1216 | const node = ensureAudioNode(action.audioId, action.type); |
| 1217 | pushLink(from, { kind: 'audio', id: node.id, port: 'in' }); |
| 1218 | } |
| 1219 | }); |
| 1220 | |
| 1221 | slideVarPorts(slide).forEach((port) => { |
| 1222 | const connected = state.graph.links.some((link) => |
| 1223 | link.to.kind === 'slide' && link.to.id === slide.id && link.to.port === port.key |
| 1224 | ); |
| 1225 | if (connected) return; |
| 1226 | const variable = ensureVariableNode(port.name); |
| 1227 | pushLink( |
| 1228 | { kind: 'variable', id: variable.id, port: 'value' }, |
| 1229 | { kind: 'slide', id: slide.id, port: port.key } |
| 1230 | ); |
| 1231 | }); |
| 1232 | }); |
| 1233 | } |
| 1234 | |
| 1235 | // Переходы «дальше/назад» выводятся из цепочки связей. |
| 1236 | // Цепь может проходить через переходы, анимации и ноды плагинов (порты in/out). |
| 1237 | function rebuildJumps() { |
| 1238 | const outgoing = new Map(); |
| 1239 | state.graph.links.forEach((link) => { |
| 1240 | const key = `${link.from.kind}|${link.from.id}`; |
| 1241 | if (!outgoing.has(key)) outgoing.set(key, []); |
| 1242 | outgoing.get(key).push(link); |
| 1243 | }); |
| 1244 | const jumps = {}; |
| 1245 | state.graph.links.forEach((link) => { |
| 1246 | if (link.from.kind !== 'slide' || (link.from.port !== 'next' && link.from.port !== 'prev')) return; |
| 1247 | const port = link.from.port; |
| 1248 | let current = link; |
| 1249 | const visited = new Set(); |
| 1250 | for (let step = 0; current && step < 32; step += 1) { |
| 1251 | const key = `${current.to.kind}|${current.to.id}`; |
| 1252 | if (visited.has(key)) break; |
| 1253 | visited.add(key); |
| 1254 | if (current.to.kind === 'slide' && current.to.port === 'in') { |
| 1255 | jumps[link.from.id] = jumps[link.from.id] || {}; |
| 1256 | if (!jumps[link.from.id][port]) jumps[link.from.id][port] = current.to.id; |
| 1257 | break; |
| 1258 | } |
| 1259 | if (PASS_THROUGH_KINDS.has(current.to.kind) && current.to.port === 'in') { |
| 1260 | current = (outgoing.get(key) || []).find((item) => item.from.port === 'out'); |
| 1261 | continue; |
| 1262 | } |
| 1263 | break; |
| 1264 | } |
| 1265 | }); |
| 1266 | state.graph.jumps = jumps; |
| 1267 | } |
| 1268 | |
| 1269 | function isNavLink(link) { |
| 1270 | return link.from.kind === 'slide' |
| 1271 | && (link.from.port === 'next' || link.from.port === 'prev') |
| 1272 | && (link.to.kind === 'slide' || PASS_THROUGH_KINDS.has(link.to.kind)); |
| 1273 | } |
| 1274 | |
| 1275 | function transitionForSlide(slideId) { |
| 1276 | return (state.graph.transitions || []).find((node) => node.slideId === slideId) || null; |
| 1277 | } |
| 1278 | |
| 1279 | // Нода перехода, через которую входят на слайд. Создаётся по требованию. |
| 1280 | function ensureTransitionNodeForSlide(slide) { |
| 1281 | if (!slide) return null; |
| 1282 | let node = transitionForSlide(slide.id); |
| 1283 | if (!node) { |
| 1284 | const index = state.slides.indexOf(slide); |
| 1285 | const base = state.graph.positions[slide.id] || graphDefaultPosition(Math.max(0, index)); |
| 1286 | const spot = findFreeNodeSpot(Math.max(20, base.x - 330), base.y + 40, 'transition', ''); |
| 1287 | node = { |
| 1288 | id: uid(), |
| 1289 | name: `Переход · слайд ${index + 1}`, |
| 1290 | code: DEFAULT_TRANSITION_LUA, |
| 1291 | slideId: slide.id, |
| 1292 | x: spot.x, |
| 1293 | y: spot.y, |
| 1294 | }; |
| 1295 | state.graph.transitions = state.graph.transitions || []; |
| 1296 | state.graph.transitions.push(node); |
| 1297 | } |
| 1298 | return node; |
| 1299 | } |
| 1300 | |
| 1301 | // Автоцепь: prev.next → transition.in, transition.out → next.in. |
| 1302 | // Ручную связь «Дальше» не перезаписываем. |
| 1303 | function chainSlides(fromSlide, toSlide) { |
| 1304 | if (!fromSlide || !toSlide || fromSlide.id === toSlide.id) return false; |
| 1305 | const hasNext = state.graph.links.some((link) => |
| 1306 | link.from.kind === 'slide' && link.from.id === fromSlide.id && link.from.port === 'next' |
| 1307 | ); |
| 1308 | if (hasNext) return false; |
| 1309 | const transition = ensureTransitionNodeForSlide(toSlide); |
| 1310 | if (!transition) return false; |
| 1311 | pushLink( |
| 1312 | { kind: 'slide', id: fromSlide.id, port: 'next' }, |
| 1313 | { kind: 'transition', id: transition.id, port: 'in' } |
| 1314 | ); |
| 1315 | pushLink( |
| 1316 | { kind: 'transition', id: transition.id, port: 'out' }, |
| 1317 | { kind: 'slide', id: toSlide.id, port: 'in' } |
| 1318 | ); |
| 1319 | return true; |
| 1320 | } |
| 1321 | |
| 1322 | function ensureSlideChain(force = false) { |
| 1323 | if (state.slides.length < 2) return; |
| 1324 | if (!force && state.graph.links.some(isNavLink)) return; |
| 1325 | for (let i = 0; i < state.slides.length - 1; i += 1) { |
| 1326 | chainSlides(state.slides[i], state.slides[i + 1]); |
| 1327 | } |
| 1328 | rebuildJumps(); |
| 1329 | } |
| 1330 | |
| 1331 | function findElementSlide(elementId) { |
| 1332 | for (const slide of state.slides) { |
| 1333 | if ((slide.elements || []).some((element) => element.id === elementId)) return slide; |
| 1334 | } |
| 1335 | return null; |
| 1336 | } |
| 1337 | |
| 1338 | // Действие кнопки из инспектора переносим в её выход в графе. |
| 1339 | function syncButtonLink(element) { |
| 1340 | if (!element || element.type !== 'button') return; |
| 1341 | const slide = findElementSlide(element.id); |
| 1342 | if (!slide) return; |
| 1343 | const port = `btn:${element.id}`; |
| 1344 | state.graph.links = state.graph.links.filter((link) => |
| 1345 | !(link.from.kind === 'slide' && link.from.id === slide.id && link.from.port === port) |
| 1346 | ); |
| 1347 | const action = element.action; |
| 1348 | const from = { kind: 'slide', id: slide.id, port }; |
| 1349 | if (action && action.type === 'go') { |
| 1350 | const target = state.slides[Number(action.slideIndex) || 0]; |
| 1351 | if (target) pushLink(from, { kind: 'slide', id: target.id, port: 'in' }); |
| 1352 | } else if (action && action.type === 'lua') { |
| 1353 | const node = action.scriptNodeId ? findScriptNode(action.scriptNodeId) : scriptNodeForElement(element.id); |
| 1354 | if (node) pushLink(from, { kind: 'script', id: node.id, port: 'in' }); |
| 1355 | } else if (action && (action.type === 'play' || action.type === 'stop') && action.audioId) { |
| 1356 | const node = ensureAudioNode(action.audioId, action.type); |
| 1357 | pushLink(from, { kind: 'audio', id: node.id, port: 'in' }); |
| 1358 | } |
| 1359 | rebuildJumps(); |
| 1360 | } |
| 1361 | |
| 1362 | // Переносит связи графа в модель: действия кнопок, переходы next/prev и переменные. |
| 1363 | function applyGraphLinks() { |
| 1364 | const byKey = new Map(); |
| 1365 | state.graph.links.forEach((link) => { |
| 1366 | byKey.set(`${link.from.kind}|${link.from.id}|${link.from.port}`, link); |
| 1367 | }); |
| 1368 | |
| 1369 | state.slides.forEach((slide) => { |
| 1370 | (slide.elements || []).forEach((element) => { |
| 1371 | if (element.type !== 'button') return; |
| 1372 | const link = byKey.get(`slide|${slide.id}|btn:${element.id}`); |
| 1373 | if (!link) return; |
| 1374 | if (link.to.kind === 'slide') { |
| 1375 | const index = state.slides.findIndex((item) => item.id === link.to.id); |
| 1376 | if (index >= 0) { |
| 1377 | element.action = { |
| 1378 | ...(element.action || {}), |
| 1379 | type: 'go', slideIndex: index, audioId: '', code: '', scriptNodeId: '', |
| 1380 | }; |
| 1381 | } |
| 1382 | } else if (link.to.kind === 'script') { |
| 1383 | const node = findScriptNode(link.to.id); |
| 1384 | if (node) { |
| 1385 | node.slideId = slide.id; |
| 1386 | node.elementId = element.id; |
| 1387 | element.action = { |
| 1388 | ...(element.action || {}), |
| 1389 | type: 'lua', slideIndex: 0, audioId: '', code: node.code, scriptNodeId: node.id, |
| 1390 | }; |
| 1391 | } |
| 1392 | } else if (link.to.kind === 'audio') { |
| 1393 | const node = findAudioNode(link.to.id); |
| 1394 | if (node && node.elementId) { |
| 1395 | element.action = { |
| 1396 | ...(element.action || {}), |
| 1397 | type: node.mode === 'stop' ? 'stop' : 'play', |
| 1398 | slideIndex: 0, audioId: node.elementId, code: '', scriptNodeId: '', |
| 1399 | }; |
| 1400 | } |
| 1401 | } |
| 1402 | }); |
| 1403 | }); |
| 1404 | |
| 1405 | // Переменная → порт текста: меняем имя в {{...}}, порт переименовываем. |
| 1406 | state.graph.links.forEach((link) => { |
| 1407 | if (link.from.kind !== 'variable' || link.to.kind !== 'slide') return; |
| 1408 | if (!link.to.port.startsWith('var:')) return; |
| 1409 | const parts = link.to.port.split(':'); |
| 1410 | if (parts.length < 3) return; |
| 1411 | const elementId = parts[1]; |
| 1412 | const oldName = parts.slice(2).join(':'); |
| 1413 | const variable = findVariableNode(link.from.id); |
| 1414 | const slide = state.slides.find((item) => item.id === link.to.id); |
| 1415 | const element = slide && (slide.elements || []).find((item) => item.id === elementId); |
| 1416 | if (!variable || !element || typeof element.text !== 'string' || variable.name === oldName) return; |
| 1417 | element.text = element.text.replace( |
| 1418 | new RegExp(`\\{\\{\\s*${escapeRx(oldName)}\\s*\\}\\}`, 'g'), |
| 1419 | `{{${variable.name}}}` |
| 1420 | ); |
| 1421 | link.to.port = `var:${elementId}:${variable.name}`; |
| 1422 | }); |
| 1423 | |
| 1424 | rebuildJumps(); |
| 1425 | } |
| 1426 | |
| 1427 | function renameVariableNode(node, name) { |
| 1428 | const oldName = node.name; |
| 1429 | const nextName = String(name || '').trim(); |
| 1430 | if (!nextName || nextName === oldName) return; |
| 1431 | node.name = nextName; |
| 1432 | state.graph.links.forEach((link) => { |
| 1433 | if (link.from.kind !== 'variable' || link.from.id !== node.id || link.to.kind !== 'slide') return; |
| 1434 | if (!link.to.port.startsWith('var:')) return; |
| 1435 | const parts = link.to.port.split(':'); |
| 1436 | if (parts.length < 3) return; |
| 1437 | const elementId = parts[1]; |
| 1438 | const oldInPort = parts.slice(2).join(':'); |
| 1439 | const slide = state.slides.find((item) => item.id === link.to.id); |
| 1440 | const element = slide && (slide.elements || []).find((item) => item.id === elementId); |
| 1441 | if (!element || typeof element.text !== 'string') return; |
| 1442 | if (oldInPort === oldName) { |
| 1443 | element.text = element.text.replace( |
| 1444 | new RegExp(`\\{\\{\\s*${escapeRx(oldName)}\\s*\\}\\}`, 'g'), |
| 1445 | `{{${nextName}}}` |
| 1446 | ); |
| 1447 | } |
| 1448 | link.to.port = `var:${elementId}:${nextName}`; |
| 1449 | }); |
| 1450 | } |
| 1451 | |
| 1452 | |
| 1453 | function ensureGraphPositions() { |
| 1454 | state.slides.forEach((slide, index) => { |
| 1455 | if (!state.graph.positions[slide.id]) state.graph.positions[slide.id] = graphDefaultPosition(index); |
| 1456 | }); |
| 1457 | } |
| 1458 | |
| 1459 | function ensureScriptNode(element, slide) { |
| 1460 | if (!element || element.type !== 'button') return null; |
| 1461 | if (!element.action) element.action = { type: 'lua', slideIndex: 0, audioId: '', code: '', scriptNodeId: '' }; |
| 1462 | const action = element.action; |
| 1463 | let node = action.scriptNodeId ? findScriptNode(action.scriptNodeId) : null; |
| 1464 | if (!node) node = scriptNodeForElement(element.id); |
| 1465 | if (!node) { |
| 1466 | const base = state.graph.positions[slide.id] || graphDefaultPosition(state.slides.indexOf(slide)); |
| 1467 | node = { |
| 1468 | id: uid(), |
| 1469 | name: `Lua · ${element.label || 'Кнопка'}`, |
| 1470 | code: action.code || '', |
| 1471 | x: base.x + 330, |
| 1472 | y: base.y + 20, |
| 1473 | slideId: slide.id, |
| 1474 | elementId: element.id, |
| 1475 | }; |
| 1476 | state.graph.scripts.push(node); |
| 1477 | } |
| 1478 | action.scriptNodeId = node.id; |
| 1479 | node.slideId = slide.id; |
| 1480 | node.elementId = element.id; |
| 1481 | if (node.code && node.code !== action.code) action.code = node.code; |
| 1482 | else if (!node.code && action.code) node.code = action.code; |
| 1483 | return node; |
| 1484 | } |
| 1485 | |
| 1486 | function hydrateGraph(graph) { |
| 1487 | const source = graph && typeof graph === 'object' ? graph : {}; |
| 1488 | const positions = {}; |
| 1489 | state.slides.forEach((slide, index) => { |
| 1490 | const p = (source.positions && source.positions[slide.id]) || {}; |
| 1491 | const fallback = graphDefaultPosition(index); |
| 1492 | positions[slide.id] = { |
| 1493 | x: Number.isFinite(Number(p.x)) ? Number(p.x) : fallback.x, |
| 1494 | y: Number.isFinite(Number(p.y)) ? Number(p.y) : fallback.y, |
| 1495 | }; |
| 1496 | }); |
| 1497 | const scripts = (Array.isArray(source.scripts) ? source.scripts : []).map((node, index) => ({ |
| 1498 | id: node.id || uid(), |
| 1499 | name: node.name || 'Lua-скрипт', |
| 1500 | code: node.code || '', |
| 1501 | x: Number.isFinite(Number(node.x)) ? Number(node.x) : 60 + (index % 3) * 320, |
| 1502 | y: Number.isFinite(Number(node.y)) ? Number(node.y) : 520 + Math.floor(index / 3) * 220, |
| 1503 | slideId: node.slideId || '', |
| 1504 | elementId: node.elementId || '', |
| 1505 | })); |
| 1506 | const audios = (Array.isArray(source.audios) ? source.audios : []).map((node, index) => ({ |
| 1507 | id: node.id || uid(), |
| 1508 | name: node.name || 'Аудио', |
| 1509 | elementId: node.elementId || '', |
| 1510 | mode: node.mode === 'stop' ? 'stop' : 'play', |
| 1511 | x: Number.isFinite(Number(node.x)) ? Number(node.x) : 60 + (index % 3) * 320, |
| 1512 | y: Number.isFinite(Number(node.y)) ? Number(node.y) : 840 + Math.floor(index / 3) * 110, |
| 1513 | })); |
| 1514 | const variables = (Array.isArray(source.variables) ? source.variables : []).map((node, index) => ({ |
| 1515 | id: node.id || uid(), |
| 1516 | name: String(node.name || `var${index + 1}`), |
| 1517 | x: Number.isFinite(Number(node.x)) ? Number(node.x) : 40, |
| 1518 | y: Number.isFinite(Number(node.y)) ? Number(node.y) : 520 + index * 96, |
| 1519 | })); |
| 1520 | const transitions = (Array.isArray(source.transitions) ? source.transitions : []).map((node, index) => ({ |
| 1521 | id: node.id || uid(), |
| 1522 | name: node.name || 'Переход', |
| 1523 | code: node.code || '', |
| 1524 | slideId: node.slideId || '', |
| 1525 | x: Number.isFinite(Number(node.x)) ? Number(node.x) : 60 + (index % 3) * 320, |
| 1526 | y: Number.isFinite(Number(node.y)) ? Number(node.y) : 1120 + Math.floor(index / 3) * 200, |
| 1527 | })); |
| 1528 | const anims = (Array.isArray(source.anims) ? source.anims : []).map((node, index) => ({ |
| 1529 | id: node.id || uid(), |
| 1530 | name: node.name || 'Анимация', |
| 1531 | code: node.code || '', |
| 1532 | slideId: node.slideId || '', |
| 1533 | elementId: node.elementId || '', |
| 1534 | x: Number.isFinite(Number(node.x)) ? Number(node.x) : 140 + (index % 3) * 320, |
| 1535 | y: Number.isFinite(Number(node.y)) ? Number(node.y) : 1320 + Math.floor(index / 3) * 200, |
| 1536 | })); |
| 1537 | const pluginNodes = (Array.isArray(source.plugins) ? source.plugins : []).map((node, index) => ({ |
| 1538 | id: node.id || uid(), |
| 1539 | pluginId: node.pluginId || '', |
| 1540 | fn: node.fn || '', |
| 1541 | name: node.name || 'Плагин', |
| 1542 | description: node.description || '', |
| 1543 | color: node.color || '#f97316', |
| 1544 | code: node.code || '', |
| 1545 | args: node.args || '', |
| 1546 | x: Number.isFinite(Number(node.x)) ? Number(node.x) : 60 + (index % 3) * 320, |
| 1547 | y: Number.isFinite(Number(node.y)) ? Number(node.y) : 1440 + Math.floor(index / 3) * 200, |
| 1548 | })); |
| 1549 | const links = (Array.isArray(source.links) ? source.links : []).map((link) => { |
| 1550 | const from = link && link.from ? link.from : {}; |
| 1551 | const to = link && link.to ? link.to : {}; |
| 1552 | const kinds = ['slide', 'script', 'audio', 'variable', 'transition', 'anim', 'plugin']; |
| 1553 | if (!kinds.includes(from.kind) || !kinds.includes(to.kind)) return null; |
| 1554 | if (!from.id || !to.id || !from.port || !to.port) return null; |
| 1555 | return { |
| 1556 | id: link.id || uid(), |
| 1557 | from: { kind: from.kind, id: String(from.id), port: String(from.port) }, |
| 1558 | to: { kind: to.kind, id: String(to.id), port: String(to.port) }, |
| 1559 | }; |
| 1560 | }).filter(Boolean); |
| 1561 | state.graph = { positions, scripts, audios, variables, transitions, anims, plugins: pluginNodes, links, jumps: {} }; |
| 1562 | state.slides.forEach((slide) => { |
| 1563 | (slide.elements || []).forEach((element) => { |
| 1564 | if (element.type === 'button' && element.action && element.action.type === 'lua') ensureScriptNode(element, slide); |
| 1565 | }); |
| 1566 | }); |
| 1567 | ensureLinksFromModel(); |
| 1568 | ensureSlideChain(); |
| 1569 | rebuildJumps(); |
| 1570 | } |
| 1571 | |
| 1572 | function applyScriptNodeToElement(node) { |
| 1573 | const linked = findLinkedElement(node); |
| 1574 | if (!linked) return; |
| 1575 | linked.element.action = { |
| 1576 | ...(linked.element.action || {}), |
| 1577 | type: 'lua', |
| 1578 | scriptNodeId: node.id, |
| 1579 | code: node.code, |
| 1580 | }; |
| 1581 | } |
| 1582 | |
| 1583 | function setStatus(cls, text) { |
| 1584 | saveStateEl.className = `save-state ${cls}`; |
| 1585 | saveStateEl.textContent = text; |
| 1586 | } |
| 1587 | |
| 1588 | let toastTimer = null; |
| 1589 | function toast(message) { |
| 1590 | const el = $('toast'); |
| 1591 | el.textContent = message; |
| 1592 | el.classList.add('visible'); |
| 1593 | clearTimeout(toastTimer); |
| 1594 | toastTimer = setTimeout(() => el.classList.remove('visible'), 2600); |
| 1595 | } |
| 1596 | |
| 1597 | // ==================== Lua-редактор: подсветка и автодополнение ==================== |
| 1598 | const LUA_KEYWORDS = new Set([ |
| 1599 | 'and', 'break', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', |
| 1600 | 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while', |
| 1601 | ]); |
| 1602 | const LUA_BUILTINS = new Set([ |
| 1603 | 'vars', 'app', 'anim', 'string', 'math', 'table', 'os', 'io', 'tostring', 'tonumber', |
| 1604 | 'ipairs', 'pairs', 'print', 'type', 'next', 'select', 'error', 'pcall', 'xpcall', 'require', |
| 1605 | 'setmetatable', 'getmetatable', 'rawget', 'rawset', 'unpack', 'assert', 'coroutine', |
| 1606 | ]); |
| 1607 | const LUA_COMPLETIONS = [ |
| 1608 | { insert: 'app.go(1)', label: 'app.go(index)', kind: 'навигация' }, |
| 1609 | { insert: 'app.next()', label: 'app.next()', kind: 'навигация' }, |
| 1610 | { insert: 'app.prev()', label: 'app.prev()', kind: 'навигация' }, |
| 1611 | { insert: 'app.play(id)', label: 'app.play(id)', kind: 'аудио' }, |
| 1612 | { insert: 'app.stop(id)', label: 'app.stop(id)', kind: 'аудио' }, |
| 1613 | { insert: 'app.music(src)', label: 'app.music(src)', kind: 'аудио' }, |
| 1614 | { insert: 'app.musicPlay()', label: 'app.musicPlay()', kind: 'аудио' }, |
| 1615 | { insert: 'app.musicStop()', label: 'app.musicStop()', kind: 'аудио' }, |
| 1616 | { insert: 'app.musicVolume(v)', label: 'app.musicVolume(v)', kind: 'аудио' }, |
| 1617 | { insert: 'app.setVar(k, v)', label: 'app.setVar(k, v)', kind: 'переменные' }, |
| 1618 | { insert: 'app.getVar(k)', label: 'app.getVar(k)', kind: 'переменные' }, |
| 1619 | { insert: 'app.log(msg)', label: 'app.log(msg)', kind: 'лог' }, |
| 1620 | { insert: 'anim.play(target, frames, opts)', label: 'anim.play(target, frames, opts)', kind: 'анимация' }, |
| 1621 | { insert: 'anim.fadeIn(target, duration, delay)', label: 'anim.fadeIn(target, duration, delay)', kind: 'анимация' }, |
| 1622 | { insert: 'anim.fadeOut(target, duration, delay)', label: 'anim.fadeOut(target, duration, delay)', kind: 'анимация' }, |
| 1623 | { insert: 'anim.clear(target)', label: 'anim.clear(target)', kind: 'анимация' }, |
| 1624 | { insert: 'sleep(ms)', label: 'sleep(ms)', kind: 'пауза' }, |
| 1625 | { insert: 'vars.', label: 'vars.<key>', kind: 'переменные' }, |
| 1626 | { insert: 'string.format(', label: 'string.format(fmt, …)', kind: 'string' }, |
| 1627 | { insert: 'string.gmatch(', label: 'string.gmatch(s, pattern)', kind: 'string' }, |
| 1628 | { insert: 'math.floor(', label: 'math.floor(x)', kind: 'math' }, |
| 1629 | { insert: 'table.insert(', label: 'table.insert(t, value)', kind: 'table' }, |
| 1630 | { insert: 'function ', label: 'function name(args) … end', kind: 'функция' }, |
| 1631 | { insert: 'for i = 1, n do\n \nend', label: 'for i = 1, n do … end', kind: 'цикл' }, |
| 1632 | { insert: 'if then\n \nend', label: 'if … then … end', kind: 'условие' }, |
| 1633 | { insert: '-- @node ', label: '-- @node Заголовок', kind: 'плагин' }, |
| 1634 | ]; |
| 1635 | |
| 1636 | function highlightLua(code) { |
| 1637 | const src = String(code || ''); |
| 1638 | let out = ''; |
| 1639 | let i = 0; |
| 1640 | const isWord = (ch) => /[A-Za-z0-9_]/.test(ch || ''); |
| 1641 | while (i < src.length) { |
| 1642 | const ch = src[i]; |
| 1643 | const rest = src.slice(i); |
| 1644 | if (rest.startsWith('--')) { |
| 1645 | let end; |
| 1646 | if (rest.startsWith('--[[')) { |
| 1647 | const close = src.indexOf(']]', i + 4); |
| 1648 | end = close < 0 ? src.length : close + 2; |
| 1649 | } else { |
| 1650 | const close = src.indexOf('\n', i); |
| 1651 | end = close < 0 ? src.length : close; |
| 1652 | } |
| 1653 | out += `<span class="tok-com">${esc(src.slice(i, end))}</span>`; |
| 1654 | i = end; |
| 1655 | continue; |
| 1656 | } |
| 1657 | if (rest.startsWith('[[')) { |
| 1658 | const close = src.indexOf(']]', i + 2); |
| 1659 | const end = close < 0 ? src.length : close + 2; |
| 1660 | out += `<span class="tok-str">${esc(src.slice(i, end))}</span>`; |
| 1661 | i = end; |
| 1662 | continue; |
| 1663 | } |
| 1664 | if (ch === '"' || ch === "'") { |
| 1665 | let j = i + 1; |
| 1666 | while (j < src.length) { |
| 1667 | if (src[j] === '\\') { j += 2; continue; } |
| 1668 | if (src[j] === ch) { j += 1; break; } |
| 1669 | j += 1; |
| 1670 | } |
| 1671 | out += `<span class="tok-str">${esc(src.slice(i, j))}</span>`; |
| 1672 | i = j; |
| 1673 | continue; |
| 1674 | } |
| 1675 | if (/[0-9]/.test(ch) && !isWord(src[i - 1])) { |
| 1676 | let j = i + 1; |
| 1677 | while (/[0-9a-fA-FxX._]/.test(src[j] || '')) j += 1; |
| 1678 | out += `<span class="tok-num">${esc(src.slice(i, j))}</span>`; |
| 1679 | i = j; |
| 1680 | continue; |
| 1681 | } |
| 1682 | if (/[A-Za-z_]/.test(ch)) { |
| 1683 | let j = i + 1; |
| 1684 | while (isWord(src[j])) j += 1; |
| 1685 | const word = src.slice(i, j); |
| 1686 | const after = src.slice(j).match(/^\s*\(/); |
| 1687 | let cls = ''; |
| 1688 | if (LUA_KEYWORDS.has(word)) cls = 'tok-kw'; |
| 1689 | else if (after) cls = 'tok-fn'; |
| 1690 | else if (LUA_BUILTINS.has(word)) cls = 'tok-api'; |
| 1691 | out += cls ? `<span class="${cls}">${esc(word)}</span>` : esc(word); |
| 1692 | i = j; |
| 1693 | continue; |
| 1694 | } |
| 1695 | if ('+-*/%=<>~#^&|'.includes(ch)) { |
| 1696 | out += `<span class="tok-op">${esc(ch)}</span>`; |
| 1697 | i += 1; |
| 1698 | continue; |
| 1699 | } |
| 1700 | out += esc(ch); |
| 1701 | i += 1; |
| 1702 | } |
| 1703 | return out + '\n'; |
| 1704 | } |
| 1705 | |
| 1706 | function luaEditorMarkup(options = {}) { |
| 1707 | const attrs = options.nodeProp |
| 1708 | ? ` data-node-prop="${esc(options.nodeProp)}"` |
| 1709 | : options.prop ? ` data-prop="${esc(options.prop)}"` : ''; |
| 1710 | return `<div class="lua-editor${options.compact ? ' compact' : ''}" data-lua-editor> |
| 1711 | <pre class="lua-highlight" aria-hidden="true"></pre> |
| 1712 | <textarea class="lua-code" rows="${Number(options.rows) || 8}" spellcheck="false"${attrs} placeholder="${esc(options.placeholder || '')}">${esc(options.value || '')}</textarea> |
| 1713 | <div class="lua-suggest" hidden></div> |
| 1714 | </div>`; |
| 1715 | } |
| 1716 | |
| 1717 | function createLuaEditor(wrapper, options = {}) { |
| 1718 | if (!wrapper) return null; |
| 1719 | const textarea = wrapper.querySelector('.lua-code'); |
| 1720 | const highlight = wrapper.querySelector('.lua-highlight'); |
| 1721 | const suggest = wrapper.querySelector('.lua-suggest'); |
| 1722 | if (!textarea || !highlight) return null; |
| 1723 | let suggestIndex = 0; |
| 1724 | let suggestItems = []; |
| 1725 | |
| 1726 | const sync = () => { |
| 1727 | highlight.innerHTML = highlightLua(textarea.value); |
| 1728 | highlight.scrollTop = textarea.scrollTop; |
| 1729 | highlight.scrollLeft = textarea.scrollLeft; |
| 1730 | }; |
| 1731 | const hideSuggest = () => { |
| 1732 | suggest.hidden = true; |
| 1733 | suggest.innerHTML = ''; |
| 1734 | suggestItems = []; |
| 1735 | }; |
| 1736 | const currentWord = () => { |
| 1737 | const pos = textarea.selectionStart; |
| 1738 | const before = textarea.value.slice(0, pos); |
| 1739 | const match = before.match(/[A-Za-z_][\w.]*$/); |
| 1740 | return match ? { word: match[0], start: pos - match[0].length } : null; |
| 1741 | }; |
| 1742 | const applyItem = (item) => { |
| 1743 | const token = currentWord(); |
| 1744 | const start = token ? token.start : textarea.selectionStart; |
| 1745 | const end = textarea.selectionStart; |
| 1746 | textarea.value = `${textarea.value.slice(0, start)}${item.insert}${textarea.value.slice(end)}`; |
| 1747 | const caret = start + item.insert.length; |
| 1748 | textarea.selectionStart = caret; |
| 1749 | textarea.selectionEnd = caret; |
| 1750 | hideSuggest(); |
| 1751 | sync(); |
| 1752 | textarea.dispatchEvent(new Event('input', { bubbles: true })); |
| 1753 | textarea.focus(); |
| 1754 | }; |
| 1755 | const paintSuggest = () => { |
| 1756 | suggest.innerHTML = suggestItems.map((item, index) => |
| 1757 | `<button type="button" data-sg-index="${index}" class="${index === suggestIndex ? 'active' : ''}"><span class="sg-name">${highlightLua(item.label || item.insert).replace(/^\s+|\n$/g, '')}</span><span class="sg-kind">${esc(item.kind || '')}</span></button>` |
| 1758 | ).join(''); |
| 1759 | suggest.hidden = !suggestItems.length; |
| 1760 | suggest.querySelectorAll('button').forEach((button) => { |
| 1761 | button.addEventListener('mousedown', (event) => event.preventDefault()); |
| 1762 | button.addEventListener('click', () => applyItem(suggestItems[Number(button.dataset.sgIndex)])); |
| 1763 | }); |
| 1764 | }; |
| 1765 | const showSuggest = (force = false) => { |
| 1766 | const token = currentWord(); |
| 1767 | const query = (token ? token.word : '').toLowerCase(); |
| 1768 | if (!force && (!query || query.length < 1)) { hideSuggest(); return; } |
| 1769 | suggestItems = LUA_COMPLETIONS |
| 1770 | .filter((item) => !query || item.insert.toLowerCase().startsWith(query) || item.label.toLowerCase().includes(query)) |
| 1771 | .slice(0, 12); |
| 1772 | suggestIndex = 0; |
| 1773 | paintSuggest(); |
| 1774 | }; |
| 1775 | |
| 1776 | textarea.addEventListener('input', () => { |
| 1777 | sync(); |
| 1778 | if (typeof options.onInput === 'function') options.onInput(textarea.value); |
| 1779 | showSuggest(); |
| 1780 | }); |
| 1781 | textarea.addEventListener('scroll', () => { |
| 1782 | highlight.scrollTop = textarea.scrollTop; |
| 1783 | highlight.scrollLeft = textarea.scrollLeft; |
| 1784 | }); |
| 1785 | textarea.addEventListener('keydown', (event) => { |
| 1786 | if (!suggest.hidden && suggestItems.length) { |
| 1787 | if (event.key === 'ArrowDown' || event.key === 'ArrowUp') { |
| 1788 | event.preventDefault(); |
| 1789 | suggestIndex = (suggestIndex + (event.key === 'ArrowDown' ? 1 : -1) + suggestItems.length) % suggestItems.length; |
| 1790 | paintSuggest(); |
| 1791 | return; |
| 1792 | } |
| 1793 | if (event.key === 'Enter' || event.key === 'Tab') { |
| 1794 | event.preventDefault(); |
| 1795 | applyItem(suggestItems[suggestIndex]); |
| 1796 | return; |
| 1797 | } |
| 1798 | if (event.key === 'Escape') { |
| 1799 | event.preventDefault(); |
| 1800 | hideSuggest(); |
| 1801 | return; |
| 1802 | } |
| 1803 | } |
| 1804 | if (event.key === 'Tab') { |
| 1805 | event.preventDefault(); |
| 1806 | const start = textarea.selectionStart; |
| 1807 | textarea.value = `${textarea.value.slice(0, start)} ${textarea.value.slice(textarea.selectionEnd)}`; |
| 1808 | textarea.selectionStart = textarea.selectionEnd = start + 2; |
| 1809 | sync(); |
| 1810 | } else if (event.key === ' ' && event.ctrlKey) { |
| 1811 | event.preventDefault(); |
| 1812 | showSuggest(true); |
| 1813 | } |
| 1814 | }); |
| 1815 | textarea.addEventListener('blur', () => { |
| 1816 | setTimeout(() => { if (document.activeElement !== textarea) hideSuggest(); }, 140); |
| 1817 | }); |
| 1818 | sync(); |
| 1819 | wrapper.dataset.luaReady = '1'; |
| 1820 | return { textarea, sync, showSuggest }; |
| 1821 | } |
| 1822 | |
| 1823 | function mountLuaEditor(host, options = {}) { |
| 1824 | if (!host) return null; |
| 1825 | host.innerHTML = luaEditorMarkup(options); |
| 1826 | return createLuaEditor(host.firstElementChild, options); |
| 1827 | } |
| 1828 | |
| 1829 | function enhanceLuaEditors(root) { |
| 1830 | if (!root) return; |
| 1831 | root.querySelectorAll('[data-lua-editor]').forEach((wrapper) => { |
| 1832 | if (wrapper.dataset.luaReady) return; |
| 1833 | createLuaEditor(wrapper, {}); |
| 1834 | }); |
| 1835 | } |
| 1836 | |
| 1837 | // ==================== Кастомный Lua-элемент ==================== |
| 1838 | const DEFAULT_LUA_ELEMENT = [ |
| 1839 | '-- Верните таблицу: style / css / html / text.', |
| 1840 | '-- Ключи style пишутся как в JS: backgroundColor, borderRadius, fontSize.', |
| 1841 | 'return {', |
| 1842 | " style = {", |
| 1843 | " background = 'rgba(15, 23, 42, .78)',", |
| 1844 | " border = '1px solid rgba(129, 140, 248, .5)',", |
| 1845 | " borderRadius = '20px',", |
| 1846 | " boxShadow = '0 24px 60px rgba(0, 0, 0, .4)',", |
| 1847 | " color = '#e2e8f0',", |
| 1848 | " padding = '22px',", |
| 1849 | " fontSize = '1.8cqw'", |
| 1850 | ' },', |
| 1851 | " html = '<b>Lua-элемент</b><br><span style=\"opacity:.7\">стили и HTML вычислены в Lua</span>'", |
| 1852 | '}', |
| 1853 | ].join('\n'); |
| 1854 | |
| 1855 | function computeLuaElement(element) { |
| 1856 | if (!element || element.type !== 'lua') return; |
| 1857 | if (!window.createLuaRuntime) { |
| 1858 | toast('Lua-рантайм не загружен'); |
| 1859 | return; |
| 1860 | } |
| 1861 | if (!String(element.code || '').trim()) { |
| 1862 | toast('Добавьте Lua-код, возвращающий таблицу стилей'); |
| 1863 | return; |
| 1864 | } |
| 1865 | let runtime; |
| 1866 | try { |
| 1867 | runtime = window.createLuaRuntime({ |
| 1868 | vars: { ...(state.variables || {}) }, |
| 1869 | log: (message) => console.log('[lua:element]', message), |
| 1870 | error: (message) => toast(String(message)), |
| 1871 | }); |
| 1872 | } catch (error) { |
| 1873 | toast('Не удалось запустить Lua'); |
| 1874 | return; |
| 1875 | } |
| 1876 | const result = runtime.eval(element.code, `Lua-элемент «${element.label || 'без названия'}»`); |
| 1877 | if (result === null || result === undefined) { |
| 1878 | toast('Lua вернул пустое значение'); |
| 1879 | return; |
| 1880 | } |
| 1881 | const style = {}; |
| 1882 | const pushStyle = (value) => { |
| 1883 | Object.entries(value && typeof value === 'object' ? value : {}).forEach(([key, item]) => { |
| 1884 | if (item === null || item === undefined || typeof item === 'object') return; |
| 1885 | style[key] = String(item); |
| 1886 | }); |
| 1887 | }; |
| 1888 | let html = ''; |
| 1889 | let text = ''; |
| 1890 | let css = ''; |
| 1891 | if (typeof result === 'string' || typeof result === 'number') { |
| 1892 | text = String(result); |
| 1893 | } else if (typeof result === 'object') { |
| 1894 | pushStyle(result.style); |
| 1895 | Object.entries(result).forEach(([key, value]) => { |
| 1896 | if (['style', 'css', 'html', 'text'].includes(key)) return; |
| 1897 | if (value !== null && value !== undefined && typeof value !== 'object') style[key] = String(value); |
| 1898 | }); |
| 1899 | html = typeof result.html === 'string' ? result.html : ''; |
| 1900 | text = typeof result.text === 'string' || typeof result.text === 'number' ? String(result.text) : ''; |
| 1901 | css = typeof result.css === 'string' ? result.css : ''; |
| 1902 | } |
| 1903 | element.computed = { style, css, html, text, at: Date.now() }; |
| 1904 | renderCanvas(); |
| 1905 | renderInspector(); |
| 1906 | scheduleThumbs(); |
| 1907 | scheduleSave(true); |
| 1908 | toast('Lua-элемент вычислен'); |
| 1909 | } |
| 1910 | |
| 1911 | // ==================== Древо ==================== |
| 1912 | const TREE_BASE_ELEMENTS = [ |
| 1913 | { kind: 'text', icon: 'Т', label: 'Текст' }, |
| 1914 | { kind: 'image', icon: '▧', label: 'Картинка' }, |
| 1915 | { kind: 'shape', icon: '◆', label: 'Фигура' }, |
| 1916 | { kind: 'button', icon: '▶', label: 'Кнопка' }, |
| 1917 | { kind: 'audio', icon: '♪', label: 'Аудио' }, |
| 1918 | { kind: 'video', icon: '▤', label: 'Видео' }, |
| 1919 | { kind: 'window', icon: '⧉', label: 'Окно Chrome' }, |
| 1920 | { kind: 'lua', icon: 'λ', label: 'Lua-элемент' }, |
| 1921 | ]; |
| 1922 | const TREE_BASE_NODES = [ |
| 1923 | { kind: 'slide', icon: '▭', label: 'Слайд' }, |
| 1924 | { kind: 'script', icon: 'λ', label: 'Код' }, |
| 1925 | { kind: 'transition', icon: '⇥', label: 'Переход' }, |
| 1926 | { kind: 'anim', icon: '✦', label: 'Анимация' }, |
| 1927 | { kind: 'variable', icon: '⌘', label: 'Переменная' }, |
| 1928 | { kind: 'audio', icon: '♪', label: 'Аудио-нода' }, |
| 1929 | ]; |
| 1930 | |
| 1931 | function treeGroup(id, label, itemsHtml, count) { |
| 1932 | const collapsed = !!state.tree.collapsed[id]; |
| 1933 | return `<div class="tree-group"> |
| 1934 | <button class="tree-group-head" data-tree-group="${esc(id)}"><span class="caret">${collapsed ? '▸' : '▾'}</span>${esc(label)}<span class="count">${count}</span></button> |
| 1935 | ${collapsed ? '' : `<div class="tree-items">${itemsHtml}</div>`} |
| 1936 | </div>`; |
| 1937 | } |
| 1938 | |
| 1939 | function treeItem(attrs, icon, name, meta, extra = '') { |
| 1940 | return `<div class="tree-item" draggable="true" ${attrs}> |
| 1941 | <span class="ti-ico">${icon}</span> |
| 1942 | <span class="ti-name">${esc(name)}</span> |
| 1943 | ${meta ? `<span class="ti-meta">${esc(meta)}</span>` : ''} |
| 1944 | ${extra} |
| 1945 | </div>`; |
| 1946 | } |
| 1947 | |
| 1948 | function renderTree() { |
| 1949 | if (!treeListEl) return; |
| 1950 | const query = String(state.tree.query || '').trim().toLowerCase(); |
| 1951 | const match = (text) => !query || String(text || '').toLowerCase().includes(query); |
| 1952 | const tabs = treePanel.querySelectorAll('[data-tree-tab]'); |
| 1953 | tabs.forEach((button) => button.classList.toggle('active', button.dataset.treeTab === state.tree.tab)); |
| 1954 | let html = ''; |
| 1955 | |
| 1956 | if (state.tree.tab === 'plugins') { |
| 1957 | const plugins = (state.pluginRegistry || []).filter((plugin) => { |
| 1958 | if (!query) return true; |
| 1959 | if (match(plugin.name) || match(plugin.description)) return true; |
| 1960 | return (plugin.nodes || []).some((node) => match(node.name) || match(node.fn) || match(node.description)); |
| 1961 | }); |
| 1962 | if (!plugins.length) { |
| 1963 | html = `<div class="tree-empty">${query ? 'Плагины не найдены.' : 'Реестр пуст. Создайте плагин — его функции появятся здесь как ноды.'}<br><br><button class="primary" data-act="plugin-new">+ Новый плагин</button></div>`; |
| 1964 | } else { |
| 1965 | html = plugins.map((plugin) => { |
| 1966 | const closed = !!state.tree.plugins[plugin.id]; |
| 1967 | const nodes = (plugin.nodes || []).filter((node) => !query || match(node.name) || match(node.fn) || match(node.description) || match(plugin.name)); |
| 1968 | const items = nodes.map((node) => treeItem( |
| 1969 | `data-tree-action="add-plugin" data-drag-kind="plugin" data-plugin-id="${esc(plugin.id)}" data-fn="${esc(node.fn)}"`, |
| 1970 | 'ƒ', |
| 1971 | node.name || node.fn, |
| 1972 | node.args ? `(${node.args})` : '', |
| 1973 | `<button class="ti-add" data-tree-action="add-plugin" data-plugin-id="${esc(plugin.id)}" data-fn="${esc(node.fn)}" title="Добавить ноду в граф">+</button>` |
| 1974 | )).join(''); |
| 1975 | return `<div class="tree-plugin"> |
| 1976 | <div class="tree-plugin-head"> |
| 1977 | <span class="ti-dot" style="background:${esc(plugin.color || '#f97316')}"></span> |
| 1978 | <span>${esc(plugin.name)}</span> |
| 1979 | <span class="ti-actions"> |
| 1980 | <button data-tree-action="toggle-plugin" data-plugin-id="${esc(plugin.id)}" title="Свернуть">${closed ? '▸' : '▾'}</button> |
| 1981 | <button data-tree-action="edit-plugin" data-plugin-id="${esc(plugin.id)}" title="Редактировать плагин">✎</button> |
| 1982 | </span> |
| 1983 | </div> |
| 1984 | <div class="tree-plugin-desc">${esc(plugin.description || 'Без описания')}</div> |
| 1985 | ${closed ? '' : `<div class="tree-items">${items || '<div class="tree-empty">В плагине нет функций.</div>'}</div>`} |
| 1986 | </div>`; |
| 1987 | }).join(''); |
| 1988 | } |
| 1989 | } else { |
| 1990 | // База: элементы холста, ноды графа, содержимое текущего слайда. |
| 1991 | const elementItems = TREE_BASE_ELEMENTS.filter((item) => match(item.label) || match(item.kind)).map((item) => |
| 1992 | treeItem(`data-tree-action="add-element" data-drag-kind="element" data-kind="${item.kind}"`, |
| 1993 | item.icon, item.label, 'на холст', |
| 1994 | `<button class="ti-add" data-tree-action="add-element" data-kind="${item.kind}" title="Добавить на слайд">+</button>`) |
| 1995 | ).join(''); |
| 1996 | if (elementItems) html += treeGroup('elements', 'Элементы холста', elementItems, TREE_BASE_ELEMENTS.length); |
| 1997 | |
| 1998 | const nodeItems = TREE_BASE_NODES.filter((item) => match(item.label) || match(item.kind)).map((item) => |
| 1999 | treeItem(`data-tree-action="add-node" data-drag-kind="node" data-node-kind="${item.kind}"`, |
| 2000 | item.icon, item.label, 'в граф', |
| 2001 | `<button class="ti-add" data-tree-action="add-node" data-node-kind="${item.kind}" title="Добавить ноду">+</button>`) |
| 2002 | ).join(''); |
| 2003 | if (nodeItems) html += treeGroup('nodes', 'Базовые ноды', nodeItems, TREE_BASE_NODES.length); |
| 2004 | |
| 2005 | const slide = currentSlide(); |
| 2006 | const elementNodes = (slide && slide.elements || []).filter((element) => match(element.label || element.text || element.type)).map((element) => { |
| 2007 | const label = element.label || (element.type === 'text' ? String(element.text || '').slice(0, 40) : element.type); |
| 2008 | return treeItem( |
| 2009 | `data-tree-action="select-element" data-slide-index="${state.selected}" data-element-id="${esc(element.id)}"`, |
| 2010 | element.type === 'lua' ? 'λ' : element.type === 'button' ? '▶' : element.type === 'text' ? 'Т' : '◆', |
| 2011 | label || element.type, |
| 2012 | element.type |
| 2013 | ); |
| 2014 | }).join(''); |
| 2015 | if (elementNodes) html += treeGroup('slide-elements', `Элементы слайда ${state.selected + 1}`, elementNodes, (slide && slide.elements || []).length); |
| 2016 | |
| 2017 | const slideItems = state.slides.filter((item, index) => match(`слайд ${index + 1}`)).map((item, index) => |
| 2018 | treeItem(`data-tree-action="select-slide" data-slide-id="${esc(item.id)}"`, '▭', |
| 2019 | `Слайд ${index + 1}`, |
| 2020 | item === currentSlide() ? 'текущий' : '', |
| 2021 | `<button class="ti-add" data-tree-action="select-slide" data-slide-id="${esc(item.id)}" title="Открыть слайд">→</button>`) |
| 2022 | ).join(''); |
| 2023 | if (slideItems) html += treeGroup('slides', 'Слайды', slideItems, state.slides.length); |
| 2024 | |
| 2025 | const activeNodes = []; |
| 2026 | (state.graph.scripts || []).forEach((node) => activeNodes.push({ type: 'script', id: node.id, icon: 'λ', name: node.name || 'Lua-скрипт', meta: 'код' })); |
| 2027 | (state.graph.transitions || []).forEach((node) => activeNodes.push({ type: 'transition', id: node.id, icon: '⇥', name: node.name || 'Переход', meta: 'переход' })); |
| 2028 | (state.graph.anims || []).forEach((node) => activeNodes.push({ type: 'anim', id: node.id, icon: '✦', name: node.name || 'Анимация', meta: 'анимация' })); |
| 2029 | (state.graph.plugins || []).forEach((node) => activeNodes.push({ type: 'plugin', id: node.id, icon: 'ƒ', name: node.name || 'Плагин', meta: node.fn || 'плагин' })); |
| 2030 | (state.graph.variables || []).forEach((node) => activeNodes.push({ type: 'variable', id: node.id, icon: '⌘', name: node.name || 'Переменная', meta: 'данные' })); |
| 2031 | const activeHtml = activeNodes.filter((node) => match(node.name) || match(node.meta)).map((node) => |
| 2032 | treeItem(`data-tree-action="select-node" data-node-type="${node.type}" data-node-id="${esc(node.id || '')}"`, node.icon, node.name, node.meta) |
| 2033 | ).join(''); |
| 2034 | if (activeHtml) html += treeGroup('active-nodes', 'Ноды графа', activeHtml, activeNodes.length); |
| 2035 | } |
| 2036 | if (!html) html = '<div class="tree-empty">Ничего не найдено.</div>'; |
| 2037 | treeListEl.innerHTML = html; |
| 2038 | } |
| 2039 | |
| 2040 | function setTreeOpen(open) { |
| 2041 | state.tree.open = !!open; |
| 2042 | if (treePanel) treePanel.classList.toggle('collapsed', !open); |
| 2043 | const button = treePanel && treePanel.querySelector('.tree-collapse'); |
| 2044 | if (button) button.textContent = open ? '‹' : '›'; |
| 2045 | } |
| 2046 | |
| 2047 | function applyTreeDrag(payload, point) { |
| 2048 | if (!payload) return; |
| 2049 | if (payload.kind === 'element') { |
| 2050 | addElement(payload.element, point); |
| 2051 | } else if (payload.kind === 'node') { |
| 2052 | const kind = payload.nodeKind; |
| 2053 | if (kind === 'slide') addSlide(); |
| 2054 | else if (kind === 'script') addScriptNode(); |
| 2055 | else if (kind === 'transition') addTransitionNode(); |
| 2056 | else if (kind === 'anim') addAnimNode(); |
| 2057 | else if (kind === 'variable') addVariableNode(); |
| 2058 | else if (kind === 'audio') addAudioNode(); |
| 2059 | if (point && state.selectedNode) { |
| 2060 | if (state.selectedNode.type === 'slide') { |
| 2061 | state.graph.positions[state.selectedNode.id] = { |
| 2062 | x: Math.max(20, point.x), |
| 2063 | y: Math.max(20, point.y), |
| 2064 | }; |
| 2065 | } else { |
| 2066 | const node = findNodeByKind(state.selectedNode.type, state.selectedNode.id); |
| 2067 | if (node) { |
| 2068 | node.x = Math.max(20, point.x); |
| 2069 | node.y = Math.max(20, point.y); |
| 2070 | } |
| 2071 | } |
| 2072 | renderAll(); |
| 2073 | scheduleSave(); |
| 2074 | } |
| 2075 | } else if (payload.kind === 'plugin') { |
| 2076 | addPluginNode(payload.pluginId, payload.fn, point); |
| 2077 | } |
| 2078 | } |
| 2079 | |
| 2080 | // ==================== Редактор плагинов ==================== |
| 2081 | const PLUGIN_TEMPLATE = [ |
| 2082 | '-- Promptly plugin: новый модуль', |
| 2083 | '-- Комментарий "-- @node Заголовок" задаёт имя ноды.', |
| 2084 | '', |
| 2085 | '-- @node Приветствие', |
| 2086 | 'function hello(target)', |
| 2087 | " target = target or 'slide'", |
| 2088 | " anim.fadeIn(target, 420)", |
| 2089 | " app.log('hello')", |
| 2090 | 'end', |
| 2091 | '', |
| 2092 | '-- @node Счётчик', |
| 2093 | 'function bump(key, amount)', |
| 2094 | " key = tostring(key or 'count')", |
| 2095 | ' amount = tonumber(amount) or 1', |
| 2096 | ' vars[key] = (tonumber(vars[key]) or 0) + amount', |
| 2097 | ' return { [key] = vars[key] }', |
| 2098 | 'end', |
| 2099 | ].join('\n'); |
| 2100 | |
| 2101 | function derivePluginNodesClient(code) { |
| 2102 | const source = String(code || ''); |
| 2103 | const nodes = []; |
| 2104 | const seen = new Set(); |
| 2105 | const re = /(?:^|\n)[ \t]*(?:local[ \t]+)?function[ \t]+([A-Za-z_][A-Za-z0-9_]*)[ \t]*\(([^)]*)\)/g; |
| 2106 | let match; |
| 2107 | while ((match = re.exec(source))) { |
| 2108 | const fn = match[1]; |
| 2109 | if (seen.has(fn)) continue; |
| 2110 | seen.add(fn); |
| 2111 | const before = source.slice(0, match.index).split('\n').slice(-6); |
| 2112 | const comments = []; |
| 2113 | for (let i = before.length - 1; i >= 0; i -= 1) { |
| 2114 | const line = before[i].trim(); |
| 2115 | if (!line.startsWith('--')) break; |
| 2116 | comments.unshift(line.replace(/^--\s?/, '').trim()); |
| 2117 | } |
| 2118 | let title = ''; |
| 2119 | const description = []; |
| 2120 | comments.forEach((line) => { |
| 2121 | if (/^@node\s+/i.test(line)) title = line.replace(/^@node\s+/i, '').trim(); |
| 2122 | else if (line) description.push(line); |
| 2123 | }); |
| 2124 | nodes.push({ |
| 2125 | fn, |
| 2126 | name: title || fn.replace(/_/g, ' '), |
| 2127 | description: description.join(' · '), |
| 2128 | args: match[2].trim(), |
| 2129 | }); |
| 2130 | } |
| 2131 | return nodes; |
| 2132 | } |
| 2133 | |
| 2134 | function newPluginDraft() { |
| 2135 | return { |
| 2136 | id: '', |
| 2137 | name: 'Новый плагин', |
| 2138 | description: '', |
| 2139 | color: '#f97316', |
| 2140 | code: PLUGIN_TEMPLATE, |
| 2141 | }; |
| 2142 | } |
| 2143 | |
| 2144 | async function loadPlugins() { |
| 2145 | try { |
| 2146 | const response = await fetch('/api/plugins'); |
| 2147 | if (!response.ok) throw new Error(`HTTP ${response.status}`); |
| 2148 | const data = await response.json(); |
| 2149 | state.pluginRegistry = Array.isArray(data.plugins) ? data.plugins : []; |
| 2150 | } catch (error) { |
| 2151 | state.pluginRegistry = state.pluginRegistry || []; |
| 2152 | toast('Не удалось загрузить реестр плагинов'); |
| 2153 | } |
| 2154 | renderTree(); |
| 2155 | if (!pluginModal.hidden && state.pluginDraft) renderPluginEditor(); |
| 2156 | return state.pluginRegistry; |
| 2157 | } |
| 2158 | |
| 2159 | function pluginDraftFrom(plugin) { |
| 2160 | if (!plugin) return newPluginDraft(); |
| 2161 | return { |
| 2162 | id: plugin.id, |
| 2163 | name: plugin.name || '', |
| 2164 | description: plugin.description || '', |
| 2165 | color: plugin.color || '#f97316', |
| 2166 | code: plugin.code || '', |
| 2167 | }; |
| 2168 | } |
| 2169 | |
| 2170 | function renderPluginEditor() { |
| 2171 | const draft = state.pluginDraft || newPluginDraft(); |
| 2172 | state.pluginDraft = draft; |
| 2173 | pluginListEl.innerHTML = (state.pluginRegistry || []).map((plugin) => ` |
| 2174 | <button class="plugin-list-item${plugin.id === draft.id ? ' active' : ''}" data-plugin-pick="${esc(plugin.id)}"> |
| 2175 | <span class="pl-dot" style="background:${esc(plugin.color || '#f97316')}"></span> |
| 2176 | <span class="pl-name">${esc(plugin.name)}</span> |
| 2177 | <span class="pl-count">${(plugin.nodes || []).length}</span> |
| 2178 | </button>`).join('') || '<div class="tree-empty">Плагинов пока нет.</div>'; |
| 2179 | $('plugin-name').value = draft.name || ''; |
| 2180 | $('plugin-desc').value = draft.description || ''; |
| 2181 | $('plugin-color').value = /^#[0-9a-f]{6}$/i.test(draft.color || '') ? draft.color : '#f97316'; |
| 2182 | $('plugin-delete').disabled = !draft.id; |
| 2183 | mountLuaEditor(pluginCodeEl, { |
| 2184 | value: draft.code, |
| 2185 | rows: 18, |
| 2186 | placeholder: PLUGIN_TEMPLATE, |
| 2187 | onInput: (value) => { |
| 2188 | draft.code = value; |
| 2189 | state.pluginDirty = true; |
| 2190 | renderPluginNodesPreview(); |
| 2191 | }, |
| 2192 | }); |
| 2193 | renderPluginNodesPreview(); |
| 2194 | } |
| 2195 | |
| 2196 | function renderPluginNodesPreview() { |
| 2197 | const draft = state.pluginDraft || newPluginDraft(); |
| 2198 | const nodes = draft.id |
| 2199 | ? ((state.pluginRegistry.find((plugin) => plugin.id === draft.id) || {}).nodes || derivePluginNodesClient(draft.code)) |
| 2200 | : derivePluginNodesClient(draft.code); |
| 2201 | const parsed = derivePluginNodesClient(draft.code); |
| 2202 | const list = parsed.length ? parsed : nodes; |
| 2203 | $('plugin-nodes').innerHTML = list.length |
| 2204 | ? list.map((node) => `<span class="plugin-node-chip">ƒ ${esc(node.name || node.fn)} <small>${esc(node.args || '')}</small></span>`).join('') |
| 2205 | : '<span class="muted">Функции не найдены — ноды не появятся.</span>'; |
| 2206 | $('plugin-status').innerHTML = `${draft.id ? `id: <code>${esc(draft.id)}</code>` : 'Новый плагин'} · функций-нод: <b>${list.length}</b>${state.pluginDirty ? ' · есть несохранённые правки' : ''}`; |
| 2207 | } |
| 2208 | |
| 2209 | async function openPluginEditor(id = null) { |
| 2210 | if (!(state.pluginRegistry || []).length) await loadPlugins(); |
| 2211 | let plugin = id ? (state.pluginRegistry || []).find((item) => item.id === id) : null; |
| 2212 | if (id && !plugin) { |
| 2213 | try { |
| 2214 | const response = await fetch(`/api/plugins/${encodeURIComponent(id)}`); |
| 2215 | if (response.ok) plugin = await response.json(); |
| 2216 | } catch (error) { |
| 2217 | /* плагин мог быть удалён */ |
| 2218 | } |
| 2219 | } |
| 2220 | state.pluginDraft = pluginDraftFrom(plugin); |
| 2221 | state.pluginDirty = false; |
| 2222 | pluginModal.hidden = false; |
| 2223 | renderPluginEditor(); |
| 2224 | } |
| 2225 | |
| 2226 | function closePluginEditor() { |
| 2227 | pluginModal.hidden = true; |
| 2228 | state.pluginDraft = null; |
| 2229 | state.pluginDirty = false; |
| 2230 | } |
| 2231 | |
| 2232 | function syncPluginNodes(plugin) { |
| 2233 | (state.graph.plugins || []).forEach((node) => { |
| 2234 | if (node.pluginId !== plugin.id) return; |
| 2235 | const fn = pluginFunction(plugin, node.fn); |
| 2236 | node.code = plugin.code || node.code; |
| 2237 | node.color = plugin.color || node.color; |
| 2238 | if (fn) { |
| 2239 | node.name = `${plugin.name} · ${fn.name || fn.fn}`; |
| 2240 | node.description = fn.description || plugin.description || ''; |
| 2241 | } |
| 2242 | }); |
| 2243 | } |
| 2244 | |
| 2245 | async function savePluginDraft() { |
| 2246 | const draft = state.pluginDraft; |
| 2247 | if (!draft) return; |
| 2248 | draft.name = $('plugin-name').value.trim() || 'Без названия'; |
| 2249 | draft.description = $('plugin-desc').value; |
| 2250 | draft.color = $('plugin-color').value; |
| 2251 | try { |
| 2252 | const response = await fetch(draft.id ? `/api/plugins/${encodeURIComponent(draft.id)}` : '/api/plugins', { |
| 2253 | method: draft.id ? 'PUT' : 'POST', |
| 2254 | headers: { 'Content-Type': 'application/json' }, |
| 2255 | body: JSON.stringify(draft), |
| 2256 | }); |
| 2257 | if (!response.ok) throw new Error(`HTTP ${response.status}`); |
| 2258 | const saved = await response.json(); |
| 2259 | state.pluginRegistry = (state.pluginRegistry || []).filter((plugin) => plugin.id !== saved.id); |
| 2260 | state.pluginRegistry.push(saved); |
| 2261 | state.pluginRegistry.sort((a, b) => String(a.name).localeCompare(String(b.name), 'ru')); |
| 2262 | state.pluginDraft = pluginDraftFrom(saved); |
| 2263 | state.pluginDirty = false; |
| 2264 | syncPluginNodes(saved); |
| 2265 | renderPluginEditor(); |
| 2266 | renderTree(); |
| 2267 | renderAll(); |
| 2268 | scheduleSave(true); |
| 2269 | toast(`Плагин «${saved.name}» сохранён на диск`); |
| 2270 | } catch (error) { |
| 2271 | toast('Не удалось сохранить плагин'); |
| 2272 | } |
| 2273 | } |
| 2274 | |
| 2275 | async function deletePluginDraft() { |
| 2276 | const draft = state.pluginDraft; |
| 2277 | if (!draft || !draft.id) return; |
| 2278 | const confirmed = typeof confirm === 'function' ? confirm(`Удалить плагин «${draft.name}»? Ноды в презентации сохранят снимок кода.`) : true; |
| 2279 | if (!confirmed) return; |
| 2280 | try { |
| 2281 | const response = await fetch(`/api/plugins/${encodeURIComponent(draft.id)}`, { method: 'DELETE' }); |
| 2282 | if (!response.ok) throw new Error(`HTTP ${response.status}`); |
| 2283 | state.pluginRegistry = (state.pluginRegistry || []).filter((plugin) => plugin.id !== draft.id); |
| 2284 | state.pluginDraft = newPluginDraft(); |
| 2285 | state.pluginDirty = false; |
| 2286 | renderPluginEditor(); |
| 2287 | renderTree(); |
| 2288 | toast('Плагин удалён с диска'); |
| 2289 | } catch (error) { |
| 2290 | toast('Не удалось удалить плагин'); |
| 2291 | } |
| 2292 | } |
| 2293 | |
| 2294 | // ==================== Рендер ==================== |
| 2295 | function renderCanvas() { |
| 2296 | SlideView.render(canvasEl, currentSlide(), { |
| 2297 | variables: state.variables, |
| 2298 | editable: true, |
| 2299 | selectedId: state.selectedEl, |
| 2300 | placeholder: 'Пустой слайд — добавьте элементы на панели сверху', |
| 2301 | }); |
| 2302 | renderSelection(); |
| 2303 | } |
| 2304 | |
| 2305 | function renderSelection() { |
| 2306 | const element = selectedElement(); |
| 2307 | if (!element) { |
| 2308 | selBox.hidden = true; |
| 2309 | return; |
| 2310 | } |
| 2311 | selBox.hidden = false; |
| 2312 | selBox.style.left = `${element.x}%`; |
| 2313 | selBox.style.top = `${element.y}%`; |
| 2314 | selBox.style.width = `${element.w}%`; |
| 2315 | selBox.style.height = `${element.h}%`; |
| 2316 | } |
| 2317 | |
| 2318 | let thumbsTimer = null; |
| 2319 | function scheduleThumbs() { |
| 2320 | clearTimeout(thumbsTimer); |
| 2321 | thumbsTimer = setTimeout(renderThumbs, 140); |
| 2322 | } |
| 2323 | |
| 2324 | function renderThumbs() { |
| 2325 | thumbsEl.innerHTML = ''; |
| 2326 | state.slides.forEach((slide, index) => { |
| 2327 | const button = document.createElement('button'); |
| 2328 | button.className = 'thumb' + (index === state.selected ? ' active' : ''); |
| 2329 | button.innerHTML = `<span class="num">${index + 1}</span><span class="thumb-canvas"></span>`; |
| 2330 | SlideView.render(button.querySelector('.thumb-canvas'), slide, { variables: state.variables, staticPreview: true }); |
| 2331 | button.addEventListener('click', () => selectSlide(index)); |
| 2332 | thumbsEl.appendChild(button); |
| 2333 | }); |
| 2334 | $('slide-count').textContent = String(state.slides.length); |
| 2335 | $('slide-total').textContent = String(state.slides.length); |
| 2336 | } |
| 2337 | |
| 2338 | function selectSlide(index) { |
| 2339 | state.selected = clamp(index, 0, state.slides.length - 1); |
| 2340 | state.selectedEl = null; |
| 2341 | const slide = currentSlide(); |
| 2342 | if (slide) state.selectedNode = { type: 'slide', id: slide.id }; |
| 2343 | renderAll(); |
| 2344 | } |
| 2345 | |
| 2346 | function renderAll() { |
| 2347 | ensureGraphPositions(); |
| 2348 | $('slide-index').textContent = String(state.selected + 1); |
| 2349 | $('slide-total').textContent = String(state.slides.length); |
| 2350 | renderThumbs(); |
| 2351 | renderCanvas(); |
| 2352 | renderInspector(); |
| 2353 | renderTree(); |
| 2354 | if (state.view === 'graph') renderGraph(); |
| 2355 | } |
| 2356 | |
| 2357 | function setView(view) { |
| 2358 | state.view = view === 'graph' ? 'graph' : 'canvas'; |
| 2359 | stageEl.hidden = state.view !== 'canvas'; |
| 2360 | graphStage.hidden = state.view !== 'graph'; |
| 2361 | document.querySelectorAll('[data-view]').forEach((button) => { |
| 2362 | button.classList.toggle('active', button.dataset.view === state.view); |
| 2363 | }); |
| 2364 | if (state.view === 'graph') { |
| 2365 | if (!state.selectedNode) { |
| 2366 | const slide = currentSlide(); |
| 2367 | if (slide) state.selectedNode = { type: 'slide', id: slide.id }; |
| 2368 | } |
| 2369 | ensureLinksFromModel(); |
| 2370 | rebuildJumps(); |
| 2371 | renderGraph(); |
| 2372 | } |
| 2373 | renderInspector(); |
| 2374 | renderTree(); |
| 2375 | } |
| 2376 | |
| 2377 | function renderGraph() { |
| 2378 | if (!graphNodesEl || state.view !== 'graph') return; |
| 2379 | ensureGraphPositions(); |
| 2380 | graphNodesEl.innerHTML = ''; |
| 2381 | |
| 2382 | let maxX = 1200; |
| 2383 | let maxY = 760; |
| 2384 | const track = (x, y, extraX, extraY) => { |
| 2385 | maxX = Math.max(maxX, Number(x) + (extraX || 300)); |
| 2386 | maxY = Math.max(maxY, Number(y) + (extraY || 280)); |
| 2387 | }; |
| 2388 | |
| 2389 | const selectedNode = state.selectedNode; |
| 2390 | const portHtml = (nodeKind, nodeId, portKey, dir, label, variant) => ` |
| 2391 | <div class="grow ${dir === 'out' ? 'out' : 'in'}${variant ? ` ${variant}` : ''}"> |
| 2392 | <span class="gport-label">${esc(label)}</span> |
| 2393 | <span class="gport ${dir}${variant ? ` ${variant}` : ''}" |
| 2394 | data-port-kind="${dir}" |
| 2395 | data-link-node-kind="${nodeKind}" |
| 2396 | data-link-node-id="${esc(nodeId)}" |
| 2397 | data-port-key="${esc(portKey)}"></span> |
| 2398 | </div>`; |
| 2399 | |
| 2400 | state.slides.forEach((slide, index) => { |
| 2401 | const p = state.graph.positions[slide.id] || graphDefaultPosition(index); |
| 2402 | track(p.x, p.y, 250, 320); |
| 2403 | const node = document.createElement('div'); |
| 2404 | const isSelected = selectedNode && selectedNode.type === 'slide' && selectedNode.id === slide.id; |
| 2405 | node.className = 'gnode slide' + (isSelected ? ' selected' : ''); |
| 2406 | node.dataset.nodeKind = 'slide'; |
| 2407 | node.dataset.nodeId = slide.id; |
| 2408 | node.style.left = `${p.x}px`; |
| 2409 | node.style.top = `${p.y}px`; |
| 2410 | |
| 2411 | const elements = slide.elements || []; |
| 2412 | const firstText = elements.find((el) => el.type === 'text' && String(el.text || '').trim()); |
| 2413 | const title = firstText ? String(firstText.text).trim().slice(0, 48) : `Слайд ${index + 1}`; |
| 2414 | const media = elements.filter((el) => el.type === 'video' || el.type === 'window').length; |
| 2415 | const meta = [`${elements.length} эл.`, media ? `${media} медиа` : ''].filter(Boolean).join(' · '); |
| 2416 | |
| 2417 | node.innerHTML = ` |
| 2418 | <div class="gnode-body"> |
| 2419 | <div class="gnode-head"> |
| 2420 | <span class="gnode-badge">Слайд ${index + 1}</span> |
| 2421 | <span class="gnode-kind"></span> |
| 2422 | </div> |
| 2423 | <div class="gnode-title"></div> |
| 2424 | <div class="gnode-sub"></div> |
| 2425 | <div class="gnode-bar"></div> |
| 2426 | </div> |
| 2427 | <div class="gnode-ports"> |
| 2428 | ${portHtml('slide', slide.id, 'in', 'in', 'вход')} |
| 2429 | ${slideVarPorts(slide).map((port) => portHtml('slide', slide.id, port.key, 'in', `⌘ ${port.name}`, 'data')).join('')} |
| 2430 | ${portHtml('slide', slide.id, 'next', 'out', 'Дальше')} |
| 2431 | ${portHtml('slide', slide.id, 'prev', 'out', 'Назад')} |
| 2432 | ${slideButtonPorts(slide).map((port) => portHtml('slide', slide.id, port.key, 'out', port.label)).join('')} |
| 2433 | </div>`; |
| 2434 | node.querySelector('.gnode-kind').textContent = meta; |
| 2435 | node.querySelector('.gnode-title').textContent = title; |
| 2436 | node.querySelector('.gnode-sub').textContent = slide.notes ? String(slide.notes).split('\n')[0].slice(0, 52) : 'без пометок'; |
| 2437 | const bg = slide.background || {}; |
| 2438 | node.querySelector('.gnode-bar').style.background = |
| 2439 | bg.type === 'gradient' && bg.gradient ? bg.gradient : bg.type === 'image' && bg.image ? `url("${bg.image}") center/cover` : (bg.color || '#6366f1'); |
| 2440 | bindGraphNode(node, 'slide', slide.id); |
| 2441 | node.addEventListener('dblclick', () => { |
| 2442 | state.selected = index; |
| 2443 | state.selectedEl = null; |
| 2444 | setView('canvas'); |
| 2445 | }); |
| 2446 | graphNodesEl.appendChild(node); |
| 2447 | bindPortEvents(node, 'slide', slide.id); |
| 2448 | }); |
| 2449 | |
| 2450 | state.graph.scripts.forEach((script) => { |
| 2451 | track(script.x, script.y, 250, 240); |
| 2452 | const node = document.createElement('div'); |
| 2453 | const isSelected = selectedNode && selectedNode.type === 'script' && selectedNode.id === script.id; |
| 2454 | node.className = 'gnode script' + (isSelected ? ' selected' : ''); |
| 2455 | node.dataset.nodeKind = 'script'; |
| 2456 | node.dataset.nodeId = script.id; |
| 2457 | node.style.left = `${script.x}px`; |
| 2458 | node.style.top = `${script.y}px`; |
| 2459 | const linked = findLinkedElement(script); |
| 2460 | node.innerHTML = ` |
| 2461 | <div class="gnode-body"> |
| 2462 | <div class="gnode-head"> |
| 2463 | <span class="gnode-badge">Lua</span> |
| 2464 | <span class="gnode-kind"></span> |
| 2465 | </div> |
| 2466 | <div class="gnode-title"></div> |
| 2467 | <pre class="gnode-code"></pre> |
| 2468 | </div> |
| 2469 | <div class="gnode-ports"> |
| 2470 | ${portHtml('script', script.id, 'in', 'in', 'запуск')} |
| 2471 | </div>`; |
| 2472 | node.querySelector('.gnode-kind').textContent = linked ? (linked.element.label || 'кнопка') : 'свободный код'; |
| 2473 | node.querySelector('.gnode-title').textContent = script.name || 'Lua-скрипт'; |
| 2474 | node.querySelector('.gnode-code').textContent = String(script.code || '').split('\n').slice(0, 2).join('\n') || '— пустой скрипт —'; |
| 2475 | bindGraphNode(node, 'script', script.id); |
| 2476 | graphNodesEl.appendChild(node); |
| 2477 | bindPortEvents(node, 'script', script.id); |
| 2478 | }); |
| 2479 | |
| 2480 | state.graph.audios.forEach((audioNode) => { |
| 2481 | track(audioNode.x, audioNode.y, 250, 220); |
| 2482 | const node = document.createElement('div'); |
| 2483 | const isSelected = selectedNode && selectedNode.type === 'audio' && selectedNode.id === audioNode.id; |
| 2484 | node.className = 'gnode audio' + (isSelected ? ' selected' : ''); |
| 2485 | node.dataset.nodeKind = 'audio'; |
| 2486 | node.dataset.nodeId = audioNode.id; |
| 2487 | node.style.left = `${audioNode.x}px`; |
| 2488 | node.style.top = `${audioNode.y}px`; |
| 2489 | const found = findAudioElement(audioNode.elementId); |
| 2490 | const fileName = found && found.element.src ? String(found.element.src).split('/').pop().slice(0, 34) : 'файл не выбран'; |
| 2491 | node.innerHTML = ` |
| 2492 | <div class="gnode-body"> |
| 2493 | <div class="gnode-head"> |
| 2494 | <span class="gnode-badge">Аудио</span> |
| 2495 | <span class="gnode-kind">${audioNode.mode === 'stop' ? 'STOP' : 'PLAY'}</span> |
| 2496 | </div> |
| 2497 | <div class="gnode-title"></div> |
| 2498 | <div class="gnode-sub"></div> |
| 2499 | </div> |
| 2500 | <div class="gnode-ports"> |
| 2501 | ${portHtml('audio', audioNode.id, 'in', 'in', 'запуск', 'audio')} |
| 2502 | </div>`; |
| 2503 | node.querySelector('.gnode-title').textContent = audioNode.name || 'Аудио'; |
| 2504 | node.querySelector('.gnode-sub').textContent = fileName; |
| 2505 | bindGraphNode(node, 'audio', audioNode.id); |
| 2506 | graphNodesEl.appendChild(node); |
| 2507 | bindPortEvents(node, 'audio', audioNode.id); |
| 2508 | }); |
| 2509 | |
| 2510 | state.graph.variables.forEach((variable) => { |
| 2511 | track(variable.x, variable.y, 220, 200); |
| 2512 | const node = document.createElement('div'); |
| 2513 | const isSelected = selectedNode && selectedNode.type === 'variable' && selectedNode.id === variable.id; |
| 2514 | node.className = 'gnode variable' + (isSelected ? ' selected' : ''); |
| 2515 | node.dataset.nodeKind = 'variable'; |
| 2516 | node.dataset.nodeId = variable.id; |
| 2517 | node.style.left = `${variable.x}px`; |
| 2518 | node.style.top = `${variable.y}px`; |
| 2519 | const value = Object.prototype.hasOwnProperty.call(state.variables, variable.name) |
| 2520 | ? state.variables[variable.name] |
| 2521 | : '—'; |
| 2522 | node.innerHTML = ` |
| 2523 | <div class="gnode-body"> |
| 2524 | <div class="gnode-head"> |
| 2525 | <span class="gnode-badge">Переменная</span> |
| 2526 | <span class="gnode-kind">${esc(String(value)).slice(0, 22)}</span> |
| 2527 | </div> |
| 2528 | <div class="gnode-title"></div> |
| 2529 | <div class="gnode-sub">соедините с ⌘-портом слайда</div> |
| 2530 | </div> |
| 2531 | <div class="gnode-ports"> |
| 2532 | ${portHtml('variable', variable.id, 'value', 'out', `{{${variable.name}}}`, 'data')} |
| 2533 | </div>`; |
| 2534 | node.querySelector('.gnode-title').textContent = variable.name; |
| 2535 | bindGraphNode(node, 'variable', variable.id); |
| 2536 | graphNodesEl.appendChild(node); |
| 2537 | bindPortEvents(node, 'variable', variable.id); |
| 2538 | }); |
| 2539 | |
| 2540 | (state.graph.transitions || []).forEach((transNode) => { |
| 2541 | track(transNode.x, transNode.y, 250, 240); |
| 2542 | const node = document.createElement('div'); |
| 2543 | const isSelected = selectedNode && selectedNode.type === 'transition' && selectedNode.id === transNode.id; |
| 2544 | node.className = 'gnode transition' + (isSelected ? ' selected' : ''); |
| 2545 | node.dataset.nodeKind = 'transition'; |
| 2546 | node.dataset.nodeId = transNode.id; |
| 2547 | node.style.left = `${transNode.x}px`; |
| 2548 | node.style.top = `${transNode.y}px`; |
| 2549 | const slideIndex = state.slides.findIndex((item) => item.id === transNode.slideId); |
| 2550 | node.innerHTML = ` |
| 2551 | <div class="gnode-body"> |
| 2552 | <div class="gnode-head"> |
| 2553 | <span class="gnode-badge">Переход</span> |
| 2554 | <span class="gnode-kind"></span> |
| 2555 | </div> |
| 2556 | <div class="gnode-title"></div> |
| 2557 | <pre class="gnode-code"></pre> |
| 2558 | </div> |
| 2559 | <div class="gnode-ports"> |
| 2560 | ${portHtml('transition', transNode.id, 'in', 'in', 'вход', 'transition')} |
| 2561 | ${portHtml('transition', transNode.id, 'out', 'out', 'выход', 'transition')} |
| 2562 | </div>`; |
| 2563 | node.querySelector('.gnode-kind').textContent = slideIndex >= 0 ? `слайд ${slideIndex + 1}` : 'не привязан'; |
| 2564 | node.querySelector('.gnode-title').textContent = transNode.name || 'Переход'; |
| 2565 | node.querySelector('.gnode-code').textContent = String(transNode.code || '').split('\n').slice(0, 2).join('\n') || '— пустой код —'; |
| 2566 | bindGraphNode(node, 'transition', transNode.id); |
| 2567 | graphNodesEl.appendChild(node); |
| 2568 | bindPortEvents(node, 'transition', transNode.id); |
| 2569 | }); |
| 2570 | |
| 2571 | (state.graph.anims || []).forEach((animNode) => { |
| 2572 | track(animNode.x, animNode.y, 250, 240); |
| 2573 | const node = document.createElement('div'); |
| 2574 | const isSelected = selectedNode && selectedNode.type === 'anim' && selectedNode.id === animNode.id; |
| 2575 | node.className = 'gnode anim' + (isSelected ? ' selected' : ''); |
| 2576 | node.dataset.nodeKind = 'anim'; |
| 2577 | node.dataset.nodeId = animNode.id; |
| 2578 | node.style.left = `${animNode.x}px`; |
| 2579 | node.style.top = `${animNode.y}px`; |
| 2580 | const slideIndex = state.slides.findIndex((item) => item.id === animNode.slideId); |
| 2581 | const linkedEl = slideIndex >= 0 |
| 2582 | ? (state.slides[slideIndex].elements || []).find((item) => item.id === animNode.elementId) |
| 2583 | : null; |
| 2584 | node.innerHTML = ` |
| 2585 | <div class="gnode-body"> |
| 2586 | <div class="gnode-head"> |
| 2587 | <span class="gnode-badge">Анимация</span> |
| 2588 | <span class="gnode-kind"></span> |
| 2589 | </div> |
| 2590 | <div class="gnode-title"></div> |
| 2591 | <pre class="gnode-code"></pre> |
| 2592 | </div> |
| 2593 | <div class="gnode-ports"> |
| 2594 | ${portHtml('anim', animNode.id, 'in', 'in', 'вход', 'anim')} |
| 2595 | ${portHtml('anim', animNode.id, 'out', 'out', 'выход', 'anim')} |
| 2596 | </div>`; |
| 2597 | node.querySelector('.gnode-kind').textContent = linkedEl |
| 2598 | ? `эл.: ${linkedEl.type}` |
| 2599 | : slideIndex >= 0 ? `слайд ${slideIndex + 1}` : 'не привязан'; |
| 2600 | node.querySelector('.gnode-title').textContent = animNode.name || 'Анимация'; |
| 2601 | node.querySelector('.gnode-code').textContent = String(animNode.code || '').split('\n').slice(0, 2).join('\n') || '— пустой код —'; |
| 2602 | bindGraphNode(node, 'anim', animNode.id); |
| 2603 | graphNodesEl.appendChild(node); |
| 2604 | bindPortEvents(node, 'anim', animNode.id); |
| 2605 | }); |
| 2606 | |
| 2607 | (state.graph.plugins || []).forEach((pluginNode) => { |
| 2608 | track(pluginNode.x, pluginNode.y, 250, 240); |
| 2609 | const node = document.createElement('div'); |
| 2610 | const isSelected = selectedNode && selectedNode.type === 'plugin' && selectedNode.id === pluginNode.id; |
| 2611 | node.className = 'gnode plugin' + (isSelected ? ' selected' : ''); |
| 2612 | node.dataset.nodeKind = 'plugin'; |
| 2613 | node.dataset.nodeId = pluginNode.id; |
| 2614 | node.style.left = `${pluginNode.x}px`; |
| 2615 | node.style.top = `${pluginNode.y}px`; |
| 2616 | const fn = pluginNode.fn || 'function'; |
| 2617 | node.innerHTML = ` |
| 2618 | <div class="gnode-body"> |
| 2619 | <div class="gnode-head"> |
| 2620 | <span class="gnode-badge">Плагин</span> |
| 2621 | <span class="gnode-kind"></span> |
| 2622 | </div> |
| 2623 | <div class="gnode-title"></div> |
| 2624 | <div class="gnode-sub"></div> |
| 2625 | <pre class="gnode-code"></pre> |
| 2626 | </div> |
| 2627 | <div class="gnode-ports"> |
| 2628 | ${portHtml('plugin', pluginNode.id, 'in', 'in', 'вход', 'plugin')} |
| 2629 | ${portHtml('plugin', pluginNode.id, 'out', 'out', 'выход', 'plugin')} |
| 2630 | </div>`; |
| 2631 | node.querySelector('.gnode-kind').textContent = pluginNode.pluginId ? 'Lua-модуль' : 'без плагина'; |
| 2632 | node.querySelector('.gnode-title').textContent = pluginNode.name || fn; |
| 2633 | node.querySelector('.gnode-sub').textContent = pluginNode.description || `${fn}() · ${pluginNode.args ? `аргументы: ${pluginNode.args}` : 'без аргументов'}`; |
| 2634 | node.querySelector('.gnode-code').textContent = `function ${fn}(…)`; |
| 2635 | bindGraphNode(node, 'plugin', pluginNode.id); |
| 2636 | graphNodesEl.appendChild(node); |
| 2637 | bindPortEvents(node, 'plugin', pluginNode.id); |
| 2638 | }); |
| 2639 | |
| 2640 | graphWorld.style.width = `${maxX}px`; |
| 2641 | graphWorld.style.height = `${maxY}px`; |
| 2642 | if (!state.slides.length) { |
| 2643 | const empty = document.createElement('div'); |
| 2644 | empty.className = 'graph-empty'; |
| 2645 | empty.textContent = 'Добавьте слайд, чтобы построить граф.'; |
| 2646 | graphNodesEl.appendChild(empty); |
| 2647 | } |
| 2648 | drawGraphEdges(); |
| 2649 | } |
| 2650 | |
| 2651 | function edgeGeometry(from, to) { |
| 2652 | const bend = Math.max(44, Math.abs(to.x - from.x) * 0.42); |
| 2653 | return `M ${from.x} ${from.y} C ${from.x + bend} ${from.y}, ${to.x - bend} ${to.y}, ${to.x} ${to.y}`; |
| 2654 | } |
| 2655 | |
| 2656 | function drawGraphEdges() { |
| 2657 | if (!graphSvg) return; |
| 2658 | const portMap = new Map(); |
| 2659 | graphNodesEl.querySelectorAll('.gport').forEach((el) => { |
| 2660 | portMap.set(`${el.dataset.linkNodeKind}|${el.dataset.linkNodeId}|${el.dataset.portKey}`, el); |
| 2661 | }); |
| 2662 | const worldRect = graphWorld.getBoundingClientRect(); |
| 2663 | const pointOf = (ref) => { |
| 2664 | const el = portMap.get(`${ref.kind}|${ref.id}|${ref.port}`); |
| 2665 | if (!el) return null; |
| 2666 | const rect = el.getBoundingClientRect(); |
| 2667 | return { |
| 2668 | x: rect.left - worldRect.left + rect.width / 2, |
| 2669 | y: rect.top - worldRect.top + rect.height / 2, |
| 2670 | }; |
| 2671 | }; |
| 2672 | |
| 2673 | const colors = LINK_COLORS; |
| 2674 | const defs = `<defs>${Object.entries(colors).map(([kind, color]) => ` |
| 2675 | <marker id="graph-arrow-${kind}" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"> |
| 2676 | <path d="M0,0 L10,5 L0,10 z" fill="${color}"></path> |
| 2677 | </marker>`).join('')}</defs>`; |
| 2678 | |
| 2679 | const paths = []; |
| 2680 | state.graph.links.forEach((link) => { |
| 2681 | const from = pointOf(link.from); |
| 2682 | const to = pointOf(link.to); |
| 2683 | if (!from || !to) return; |
| 2684 | const kind = linkKind(link); |
| 2685 | const color = colors[kind] || colors.nav; |
| 2686 | const selected = state.selectedLink === link.id; |
| 2687 | paths.push(`<path class="edge${selected ? ' selected' : ''}" data-link-id="${link.id}" d="${edgeGeometry(from, to)}" fill="none" stroke="${color}" stroke-width="${selected ? 2.8 : 1.7}" stroke-opacity="${selected ? 1 : 0.78}" marker-end="url(#graph-arrow-${kind})"></path>`); |
| 2688 | }); |
| 2689 | |
| 2690 | if (state.linkDraft) { |
| 2691 | const draft = state.linkDraft; |
| 2692 | const anchor = pointOf(draft.from); |
| 2693 | if (anchor) { |
| 2694 | const from = draft.from.dir === 'out' ? anchor : { x: draft.x, y: draft.y }; |
| 2695 | const to = draft.from.dir === 'out' ? { x: draft.x, y: draft.y } : anchor; |
| 2696 | const kind = draft.from.kind === 'variable' ? 'data' : 'nav'; |
| 2697 | 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>`); |
| 2698 | } |
| 2699 | } |
| 2700 | |
| 2701 | graphSvg.innerHTML = defs + paths.join(''); |
| 2702 | } |
| 2703 | |
| 2704 | let graphDrag = null; |
| 2705 | |
| 2706 | function bindGraphNode(nodeEl, kind, id) { |
| 2707 | nodeEl.addEventListener('pointerdown', (event) => { |
| 2708 | if (event.button !== 0) return; |
| 2709 | if (event.target.closest && event.target.closest('.gport')) return; |
| 2710 | event.preventDefault(); |
| 2711 | event.stopPropagation(); |
| 2712 | const point = nodeRef(kind, id); |
| 2713 | if (!point) return; |
| 2714 | graphDrag = { |
| 2715 | kind, |
| 2716 | id, |
| 2717 | point, |
| 2718 | startX: event.clientX, |
| 2719 | startY: event.clientY, |
| 2720 | originX: point.x, |
| 2721 | originY: point.y, |
| 2722 | moved: false, |
| 2723 | }; |
| 2724 | window.addEventListener('pointermove', onGraphPointerMove); |
| 2725 | window.addEventListener('pointerup', onGraphPointerUp); |
| 2726 | document.body.style.cursor = 'grabbing'; |
| 2727 | }); |
| 2728 | } |
| 2729 | |
| 2730 | function bindPortEvents(nodeEl, kind, id) { |
| 2731 | nodeEl.querySelectorAll('.gport').forEach((portEl) => { |
| 2732 | portEl.addEventListener('pointerdown', (event) => { |
| 2733 | if (event.button !== 0) return; |
| 2734 | event.preventDefault(); |
| 2735 | event.stopPropagation(); |
| 2736 | startLinkDrag({ |
| 2737 | kind, |
| 2738 | id, |
| 2739 | port: portEl.dataset.portKey, |
| 2740 | dir: portEl.dataset.portKind, |
| 2741 | }, event); |
| 2742 | }); |
| 2743 | portEl.addEventListener('click', (event) => event.stopPropagation()); |
| 2744 | }); |
| 2745 | } |
| 2746 | |
| 2747 | function startLinkDrag(from, event) { |
| 2748 | const rect = graphWorld.getBoundingClientRect(); |
| 2749 | state.linkDraft = { from, x: event.clientX - rect.left, y: event.clientY - rect.top }; |
| 2750 | graphWorld.classList.add('drafting'); |
| 2751 | document.body.style.cursor = 'crosshair'; |
| 2752 | drawGraphEdges(); |
| 2753 | window.addEventListener('pointermove', onLinkMove); |
| 2754 | window.addEventListener('pointerup', onLinkUp); |
| 2755 | } |
| 2756 | |
| 2757 | function onLinkMove(event) { |
| 2758 | if (!state.linkDraft) return; |
| 2759 | const rect = graphWorld.getBoundingClientRect(); |
| 2760 | state.linkDraft.x = event.clientX - rect.left; |
| 2761 | state.linkDraft.y = event.clientY - rect.top; |
| 2762 | drawGraphEdges(); |
| 2763 | } |
| 2764 | |
| 2765 | function canLink(out, inp) { |
| 2766 | if (out.dir !== 'out' || inp.dir !== 'in') return false; |
| 2767 | if (out.kind === 'variable') { |
| 2768 | return out.port === 'value' && inp.kind === 'slide' && String(inp.port).startsWith('var:'); |
| 2769 | } |
| 2770 | if (inp.kind === 'slide' && String(inp.port).startsWith('var:')) return false; |
| 2771 | if (out.kind === 'slide' && (out.port === 'next' || out.port === 'prev')) { |
| 2772 | return inp.port === 'in' && (inp.kind === 'slide' || PASS_THROUGH_KINDS.has(inp.kind)); |
| 2773 | } |
| 2774 | if (inp.kind === 'slide') return inp.port === 'in'; |
| 2775 | if (inp.kind === 'script' || inp.kind === 'audio') return inp.port === 'in'; |
| 2776 | if (PASS_THROUGH_KINDS.has(inp.kind)) return inp.port === 'in'; |
| 2777 | return false; |
| 2778 | } |
| 2779 | |
| 2780 | function onLinkUp(event) { |
| 2781 | window.removeEventListener('pointermove', onLinkMove); |
| 2782 | window.removeEventListener('pointerup', onLinkUp); |
| 2783 | graphWorld.classList.remove('drafting'); |
| 2784 | document.body.style.cursor = ''; |
| 2785 | const draft = state.linkDraft; |
| 2786 | state.linkDraft = null; |
| 2787 | if (!draft) return; |
| 2788 | const hit = document.elementFromPoint(event.clientX, event.clientY); |
| 2789 | const portEl = hit && hit.closest ? hit.closest('.gport') : null; |
| 2790 | if (!portEl) { drawGraphEdges(); return; } |
| 2791 | const target = { |
| 2792 | kind: portEl.dataset.linkNodeKind, |
| 2793 | id: portEl.dataset.linkNodeId, |
| 2794 | port: portEl.dataset.portKey, |
| 2795 | dir: portEl.dataset.portKind, |
| 2796 | }; |
| 2797 | if (target.kind === draft.from.kind && target.id === draft.from.id && target.port === draft.from.port) { |
| 2798 | drawGraphEdges(); |
| 2799 | return; |
| 2800 | } |
| 2801 | const out = draft.from.dir === 'out' ? draft.from : target; |
| 2802 | const inp = draft.from.dir === 'out' ? target : draft.from; |
| 2803 | if (!canLink(out, inp)) { |
| 2804 | toast('Соединяйте выход со входом: слайд, переход, анимация, плагин, код или аудио'); |
| 2805 | drawGraphEdges(); |
| 2806 | return; |
| 2807 | } |
| 2808 | addGraphLink(out, inp); |
| 2809 | } |
| 2810 | |
| 2811 | function addGraphLink(out, inp) { |
| 2812 | if (inp.kind === 'slide' && inp.port.startsWith('var:')) { |
| 2813 | state.graph.links = state.graph.links.filter((link) => |
| 2814 | !(link.to.kind === 'slide' && link.to.id === inp.id && link.to.port === inp.port) |
| 2815 | ); |
| 2816 | } |
| 2817 | // У навигационных и pass-through выходов может быть только одна ветка. |
| 2818 | const singleOut = (out.kind === 'slide' && (out.port === 'next' || out.port === 'prev')) |
| 2819 | || (PASS_THROUGH_KINDS.has(out.kind) && out.port === 'out'); |
| 2820 | if (singleOut) { |
| 2821 | state.graph.links = state.graph.links.filter((link) => |
| 2822 | !(link.from.kind === out.kind && link.from.id === out.id && link.from.port === out.port) |
| 2823 | ); |
| 2824 | } |
| 2825 | state.graph.links = state.graph.links.filter((link) => |
| 2826 | !(link.from.kind === out.kind && link.from.id === out.id && link.from.port === out.port |
| 2827 | && link.to.kind === inp.kind && link.to.id === inp.id && link.to.port === inp.port) |
| 2828 | ); |
| 2829 | state.graph.links.push({ |
| 2830 | id: uid(), |
| 2831 | from: { kind: out.kind, id: out.id, port: out.port }, |
| 2832 | to: { kind: inp.kind, id: inp.id, port: inp.port }, |
| 2833 | }); |
| 2834 | applyGraphLinks(); |
| 2835 | state.selectedLink = null; |
| 2836 | renderAll(); |
| 2837 | scheduleSave(); |
| 2838 | toast('Связь добавлена'); |
| 2839 | } |
| 2840 | |
| 2841 | function removeGraphLink(linkId) { |
| 2842 | const link = state.graph.links.find((item) => item.id === linkId); |
| 2843 | if (!link) return; |
| 2844 | if (link.from.kind === 'variable' && link.to.kind === 'slide' && link.to.port.startsWith('var:')) { |
| 2845 | const parts = link.to.port.split(':'); |
| 2846 | if (parts.length >= 3) removeVarPlaceholder(parts[1], parts.slice(2).join(':')); |
| 2847 | } |
| 2848 | state.graph.links = state.graph.links.filter((item) => item.id !== linkId); |
| 2849 | if (link.from.kind === 'slide' && link.from.port.startsWith('btn:')) { |
| 2850 | const elementId = link.from.port.slice(4); |
| 2851 | const slide = state.slides.find((item) => item.id === link.from.id); |
| 2852 | const button = slide && (slide.elements || []).find((item) => item.id === elementId); |
| 2853 | if (button) button.action = { type: 'none', slideIndex: 0, audioId: '', code: '', scriptNodeId: '' }; |
| 2854 | } |
| 2855 | applyGraphLinks(); |
| 2856 | state.selectedLink = null; |
| 2857 | renderAll(); |
| 2858 | scheduleSave(); |
| 2859 | toast('Связь удалена'); |
| 2860 | } |
| 2861 | |
| 2862 | function onGraphPointerMove(event) { |
| 2863 | if (!graphDrag) return; |
| 2864 | const dx = event.clientX - graphDrag.startX; |
| 2865 | const dy = event.clientY - graphDrag.startY; |
| 2866 | if (Math.abs(dx) > 3 || Math.abs(dy) > 3) graphDrag.moved = true; |
| 2867 | graphDrag.point.x = Math.max(0, graphDrag.originX + dx); |
| 2868 | graphDrag.point.y = Math.max(0, graphDrag.originY + dy); |
| 2869 | const node = graphNodesEl.querySelector( |
| 2870 | `[data-node-kind="${graphDrag.kind}"][data-node-id="${graphDrag.id}"]` |
| 2871 | ); |
| 2872 | if (node) { |
| 2873 | node.style.left = `${graphDrag.point.x}px`; |
| 2874 | node.style.top = `${graphDrag.point.y}px`; |
| 2875 | } |
| 2876 | drawGraphEdges(); |
| 2877 | } |
| 2878 | |
| 2879 | function onGraphPointerUp() { |
| 2880 | window.removeEventListener('pointermove', onGraphPointerMove); |
| 2881 | window.removeEventListener('pointerup', onGraphPointerUp); |
| 2882 | document.body.style.cursor = ''; |
| 2883 | if (!graphDrag) return; |
| 2884 | const dragState = graphDrag; |
| 2885 | graphDrag = null; |
| 2886 | if (dragState.moved) { |
| 2887 | scheduleSave(); |
| 2888 | renderGraph(); |
| 2889 | } else { |
| 2890 | selectGraphNode(dragState.kind, dragState.id); |
| 2891 | } |
| 2892 | } |
| 2893 | |
| 2894 | function selectGraphNode(kind, id) { |
| 2895 | if (kind === 'slide') { |
| 2896 | const index = state.slides.findIndex((slide) => slide.id === id); |
| 2897 | if (index < 0) return; |
| 2898 | state.selected = index; |
| 2899 | state.selectedEl = null; |
| 2900 | state.selectedNode = { type: 'slide', id }; |
| 2901 | } else if (kind === 'script') { |
| 2902 | const script = findScriptNode(id); |
| 2903 | if (!script) return; |
| 2904 | state.selectedNode = { type: 'script', id }; |
| 2905 | const linked = findLinkedElement(script); |
| 2906 | if (linked) { |
| 2907 | const index = state.slides.indexOf(linked.slide); |
| 2908 | if (index >= 0) { |
| 2909 | state.selected = index; |
| 2910 | state.selectedEl = linked.element.id; |
| 2911 | } |
| 2912 | } |
| 2913 | } else if (kind === 'audio') { |
| 2914 | if (!findAudioNode(id)) return; |
| 2915 | state.selectedNode = { type: 'audio', id }; |
| 2916 | } else if (kind === 'variable') { |
| 2917 | if (!findVariableNode(id)) return; |
| 2918 | state.selectedNode = { type: 'variable', id }; |
| 2919 | } else if (kind === 'transition') { |
| 2920 | if (!findTransitionNode(id)) return; |
| 2921 | state.selectedNode = { type: 'transition', id }; |
| 2922 | } else if (kind === 'anim') { |
| 2923 | if (!findAnimNode(id)) return; |
| 2924 | state.selectedNode = { type: 'anim', id }; |
| 2925 | } else if (kind === 'plugin') { |
| 2926 | if (!findPluginNode(id)) return; |
| 2927 | state.selectedNode = { type: 'plugin', id }; |
| 2928 | } |
| 2929 | state.selectedLink = null; |
| 2930 | renderAll(); |
| 2931 | } |
| 2932 | |
| 2933 | |
| 2934 | // ==================== Инспектор ==================== |
| 2935 | function option(value, label, current) { |
| 2936 | return `<option value="${esc(value)}"${value === current ? ' selected' : ''}>${esc(label)}</option>`; |
| 2937 | } |
| 2938 | |
| 2939 | function audioOptions(current) { |
| 2940 | const options = []; |
| 2941 | state.slides.forEach((slide, index) => { |
| 2942 | (slide.elements || []).forEach((element) => { |
| 2943 | if (element.type !== 'audio') return; |
| 2944 | const label = `${element.label || element.src || 'Аудио'} · слайд ${index + 1}`; |
| 2945 | options.push(option(element.id, label, current)); |
| 2946 | }); |
| 2947 | }); |
| 2948 | if (!options.length) return '<option value="">— нет аудио на слайдах —</option>'; |
| 2949 | return options.join(''); |
| 2950 | } |
| 2951 | |
| 2952 | function slideOptions(current) { |
| 2953 | return state.slides.map((_, index) => option(String(index), `Слайд ${index + 1}`, String(current))).join(''); |
| 2954 | } |
| 2955 | |
| 2956 | function geometryFields(element) { |
| 2957 | return ` |
| 2958 | <div class="row-4"> |
| 2959 | <label class="fld"><span class="label">X %</span><input type="number" data-prop="x" step="1" value="${Number(element.x) || 0}"></label> |
| 2960 | <label class="fld"><span class="label">Y %</span><input type="number" data-prop="y" step="1" value="${Number(element.y) || 0}"></label> |
| 2961 | <label class="fld"><span class="label">Ш %</span><input type="number" data-prop="w" step="1" min="2" value="${Number(element.w) || 10}"></label> |
| 2962 | <label class="fld"><span class="label">В %</span><input type="number" data-prop="h" step="1" min="2" value="${Number(element.h) || 10}"></label> |
| 2963 | </div>`; |
| 2964 | } |
| 2965 | |
| 2966 | function elementInspector(element) { |
| 2967 | const typeNames = { text: 'Текст', image: 'Картинка', shape: 'Фигура', button: 'Кнопка', audio: 'Аудио', video: 'Видео', window: 'Окно Chrome', lua: 'Lua-элемент' }; |
| 2968 | let fields = ''; |
| 2969 | |
| 2970 | if (element.type === 'text') { |
| 2971 | const textVars = [...String(element.text || '').matchAll(/\{\{\s*([\w.-]+)\s*\}\}/g)].map((match) => match[1]); |
| 2972 | const currentVar = textVars[0] || ''; |
| 2973 | const varNames = [...new Set([ |
| 2974 | ...(state.graph.variables || []).map((node) => node.name), |
| 2975 | ...Object.keys(state.variables || {}), |
| 2976 | ])].filter(Boolean); |
| 2977 | if (currentVar && !varNames.includes(currentVar)) varNames.unshift(currentVar); |
| 2978 | fields = ` |
| 2979 | <label class="fld"><span class="label">Текст</span> |
| 2980 | <textarea data-prop="text" rows="3" placeholder="Текст слайда">${esc(element.text || '')}</textarea> |
| 2981 | </label> |
| 2982 | <label class="fld"><span class="label">Переменная</span> |
| 2983 | <select data-var-bind="${esc(element.id)}"> |
| 2984 | <option value="">— без переменной —</option> |
| 2985 | ${varNames.map((name) => option(name, `{{${name}}} · ${state.variables[name] ?? '—'}`, currentVar)).join('')} |
| 2986 | </select> |
| 2987 | </label> |
| 2988 | <div class="row-2"> |
| 2989 | <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> |
| 2990 | <label class="fld"><span class="label">Цвет</span><input type="color" data-prop="color" value="${esc(element.color || '#f8fafc')}"></label> |
| 2991 | </div> |
| 2992 | <div class="row-2"> |
| 2993 | <label class="fld"><span class="label">Насыщенность</span> |
| 2994 | <select data-prop="weight"> |
| 2995 | ${option('300', 'Light', String(element.weight))} |
| 2996 | ${option('400', 'Regular', String(element.weight))} |
| 2997 | ${option('600', 'Semibold', String(element.weight))} |
| 2998 | ${option('700', 'Bold', String(element.weight))} |
| 2999 | ${option('800', 'Extra bold', String(element.weight))} |
| 3000 | </select> |
| 3001 | </label> |
| 3002 | <label class="fld"><span class="label">Выравнивание</span> |
| 3003 | <select data-prop="align"> |
| 3004 | ${option('left', 'Слева', element.align)} |
| 3005 | ${option('center', 'По центру', element.align)} |
| 3006 | ${option('right', 'Справа', element.align)} |
| 3007 | </select> |
| 3008 | </label> |
| 3009 | </div> |
| 3010 | <div class="row-2"> |
| 3011 | <label class="fld"><span class="label">Шрифт</span> |
| 3012 | <select data-prop="font"> |
| 3013 | ${FONT_OPTIONS.map(([value, label]) => option(value, label, element.font || 'sans')).join('')} |
| 3014 | </select> |
| 3015 | </label> |
| 3016 | <label class="fld"><span class="label">Межстрочный</span> |
| 3017 | <input type="number" data-prop="lineHeight" step="0.05" min="0.8" max="3" value="${Number(element.lineHeight) || 1.16}"> |
| 3018 | </label> |
| 3019 | </div> |
| 3020 | <div class="row-2"> |
| 3021 | <div class="fld"> |
| 3022 | <label class="checkline"><input type="checkbox" data-prop="italic" ${element.italic ? 'checked' : ''}> Курсив</label> |
| 3023 | <label class="checkline"><input type="checkbox" data-prop="shadow" ${element.shadow ? 'checked' : ''}> Тень текста</label> |
| 3024 | </div> |
| 3025 | <label class="fld"><span class="label">Подложка (CSS)</span> |
| 3026 | <input data-prop="bg" value="${esc(element.bg || '')}" placeholder="rgba(15, 23, 42, .6)"> |
| 3027 | </label> |
| 3028 | </div> |
| 3029 | <p class="hint">Переменные подставляются как <code>{{name}}</code>.</p>`; |
| 3030 | } else if (element.type === 'image') { |
| 3031 | fields = ` |
| 3032 | <label class="fld"><span class="label">URL изображения</span> |
| 3033 | <input type="url" data-prop="src" value="${esc(element.src || '')}" placeholder="https://images.unsplash.com/..."> |
| 3034 | </label> |
| 3035 | <div class="upload-line"> |
| 3036 | <button class="ghost" data-act="image-upload">Загрузить файл</button> |
| 3037 | <span class="file-name">${element.src ? esc(String(element.src).split('/').pop().slice(0, 30)) : 'файл не выбран'}</span> |
| 3038 | <input type="file" data-upload="image" accept="image/*" hidden> |
| 3039 | </div> |
| 3040 | <div class="row-2"> |
| 3041 | <label class="fld"><span class="label">Вписывание</span> |
| 3042 | <select data-prop="fit"> |
| 3043 | ${option('cover', 'Заполнить', element.fit)} |
| 3044 | ${option('contain', 'Вписать', element.fit)} |
| 3045 | </select> |
| 3046 | </label> |
| 3047 | <label class="fld"><span class="label">Скругление</span><input type="number" data-prop="radius" min="0" step="1" value="${Number(element.radius) || 0}"></label> |
| 3048 | </div> |
| 3049 | <label class="checkline"><input type="checkbox" data-prop="shadow" ${element.shadow ? 'checked' : ''}> Тень</label>`; |
| 3050 | } else if (element.type === 'shape') { |
| 3051 | fields = ` |
| 3052 | <label class="fld"><span class="label">Фигура</span> |
| 3053 | <select data-prop="shape"> |
| 3054 | ${SHAPE_OPTIONS.map(([value, label]) => option(value, label, element.shape)).join('')} |
| 3055 | </select> |
| 3056 | </label> |
| 3057 | <label class="fld"><span class="label">Заливка (цвет или rgba)</span> |
| 3058 | <div class="palette"> |
| 3059 | ${SHAPE_FILLS.map((color) => `<button class="p-swatch${element.fill === color ? ' active' : ''}" data-fill="${color}" style="background:${color}" title="${color}"></button>`).join('')} |
| 3060 | </div> |
| 3061 | <input data-prop="fill" value="${esc(element.fill || '#6366f1')}" placeholder="#6366f1 или rgba(99,102,241,.2)"> |
| 3062 | </label> |
| 3063 | <div class="row-2"> |
| 3064 | <label class="fld"><span class="label">Обводка (цвет/rgba)</span><input data-prop="borderColor" value="${esc(element.borderColor || '')}" placeholder="без обводки"></label> |
| 3065 | <label class="fld"><span class="label">Толщина обводки</span><input type="number" data-prop="borderWidth" min="0" max="20" step="0.5" value="${Number(element.borderWidth) || 0}"></label> |
| 3066 | </div> |
| 3067 | <div class="row-2"> |
| 3068 | <label class="fld"><span class="label">Скругление углов</span><input type="number" data-prop="radius" min="0" max="45" step="1" value="${Number(element.radius) || 0}"></label> |
| 3069 | <div class="fld"> |
| 3070 | <label class="checkline"><input type="checkbox" data-prop="shadow" ${element.shadow ? 'checked' : ''}> Тень</label> |
| 3071 | </div> |
| 3072 | </div> |
| 3073 | <p class="hint">Фигуры — быстрый способ строить схемы, плашки и акценты. В заливку и обводку можно писать <code>rgba(99,102,241,.2)</code> для полупрозрачности.</p>`; |
| 3074 | } else if (element.type === 'button') { |
| 3075 | const action = element.action || { type: 'next' }; |
| 3076 | let actionFields = ''; |
| 3077 | if (action.type === 'go') { |
| 3078 | actionFields = `<label class="fld"><span class="label">Целевой слайд</span><select data-prop="action.slideIndex">${slideOptions(Number(action.slideIndex) || 0)}</select></label>`; |
| 3079 | } else if (action.type === 'play' || action.type === 'stop') { |
| 3080 | actionFields = ` |
| 3081 | <label class="fld"><span class="label">Аудиоэлемент</span> |
| 3082 | <select data-prop="action.audioId"> |
| 3083 | ${action.type === 'stop' ? '<option value="">— остановить всё —</option>' : ''} |
| 3084 | ${audioOptions(action.audioId)} |
| 3085 | </select> |
| 3086 | </label>`; |
| 3087 | } else if (action.type === 'lua') { |
| 3088 | actionFields = ` |
| 3089 | <label class="fld"><span class="label">Lua-код</span> |
| 3090 | <textarea data-prop="action.code" rows="4" placeholder="vars.score = vars.score + 1 app.log(vars.score)">${esc(action.code || '')}</textarea> |
| 3091 | </label>`; |
| 3092 | } |
| 3093 | |
| 3094 | fields = ` |
| 3095 | <label class="fld"><span class="label">Подпись</span><input data-prop="label" value="${esc(element.label || '')}"></label> |
| 3096 | <div class="row-2"> |
| 3097 | <label class="fld"><span class="label">Фон</span><input type="color" data-prop="bg" value="${esc(element.bg || '#6366f1')}"></label> |
| 3098 | <label class="fld"><span class="label">Текст</span><input type="color" data-prop="color" value="${esc(element.color || '#ffffff')}"></label> |
| 3099 | </div> |
| 3100 | <div class="row-2"> |
| 3101 | <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> |
| 3102 | <label class="fld"><span class="label">Скругление</span><input type="number" data-prop="radius" min="0" step="1" value="${Number(element.radius) || 12}"></label> |
| 3103 | </div> |
| 3104 | <label class="fld"><span class="label">Действие кнопки</span> |
| 3105 | <select data-prop="action.type"> |
| 3106 | ${option('none', 'Без действия', action.type)} |
| 3107 | ${option('go', 'Перейти на слайд', action.type)} |
| 3108 | ${option('next', 'Следующий слайд', action.type)} |
| 3109 | ${option('prev', 'Предыдущий слайд', action.type)} |
| 3110 | ${option('play', 'Запустить аудио', action.type)} |
| 3111 | ${option('stop', 'Остановить аудио', action.type)} |
| 3112 | ${option('lua', 'Выполнить Lua', action.type)} |
| 3113 | </select> |
| 3114 | </label> |
| 3115 | ${actionFields} |
| 3116 | <p class="hint">Кнопки и аудио управляются докладчиком в режиме показа.</p>`; |
| 3117 | } else if (element.type === 'audio') { |
| 3118 | fields = ` |
| 3119 | <label class="fld"><span class="label">URL аудио</span> |
| 3120 | <input type="url" data-prop="src" value="${esc(element.src || '')}" placeholder="https://example.com/sound.mp3"> |
| 3121 | </label> |
| 3122 | <label class="fld"><span class="label">Подпись</span><input data-prop="label" value="${esc(element.label || '')}"></label> |
| 3123 | <div class="row-2"> |
| 3124 | <label class="fld"><span class="label">Громкость</span><input type="range" data-prop="volume" min="0" max="100" step="1" value="${Math.round(clamp01v(element.volume, 0.8) * 100)}"></label> |
| 3125 | <div class="fld"> |
| 3126 | <label class="checkline"><input type="checkbox" data-prop="loop" ${element.loop ? 'checked' : ''}> Повтор</label> |
| 3127 | <label class="checkline"><input type="checkbox" data-prop="visible" ${element.visible !== false ? 'checked' : ''}> Видно на слайде</label> |
| 3128 | </div> |
| 3129 | </div> |
| 3130 | <div class="field-actions"> |
| 3131 | <button data-act="audio-preview">▶ Прослушать</button> |
| 3132 | <button data-act="audio-to-music">Сделать фоновой</button> |
| 3133 | </div> |
| 3134 | <p class="hint">Скрытое аудио (без галочки «Видно») запускается только докладчиком с панели интерактива.</p>`; |
| 3135 | } else if (element.type === 'video') { |
| 3136 | fields = ` |
| 3137 | <label class="fld"><span class="label">Ссылка на видео</span> |
| 3138 | <input type="url" data-prop="src" value="${esc(element.src || '')}" placeholder="https://example.com/video.mp4"> |
| 3139 | </label> |
| 3140 | <div class="upload-line"> |
| 3141 | <button class="ghost" data-act="video-upload">Загрузить файл</button> |
| 3142 | <span class="file-name">${element.src ? esc(String(element.src).split('/').pop()) : 'файл не выбран'}</span> |
| 3143 | <input type="file" data-upload="video" accept="video/*" hidden> |
| 3144 | </div> |
| 3145 | <label class="fld"><span class="label">Постер (URL)</span> |
| 3146 | <input type="url" data-prop="poster" value="${esc(element.poster || '')}" placeholder="Необязательно"> |
| 3147 | </label> |
| 3148 | <label class="fld"><span class="label">Подпись</span><input data-prop="label" value="${esc(element.label || '')}"></label> |
| 3149 | <div class="row-2"> |
| 3150 | <label class="fld"><span class="label">Вписывание</span> |
| 3151 | <select data-prop="fit"> |
| 3152 | ${option('cover', 'Заполнить', element.fit)} |
| 3153 | ${option('contain', 'Вписать', element.fit)} |
| 3154 | </select> |
| 3155 | </label> |
| 3156 | <label class="fld"><span class="label">Скругление</span><input type="number" data-prop="radius" min="0" step="1" value="${Number(element.radius) || 0}"></label> |
| 3157 | </div> |
| 3158 | <div class="row-2"> |
| 3159 | <div class="fld"> |
| 3160 | <label class="checkline"><input type="checkbox" data-prop="autoplay" ${element.autoplay !== false ? 'checked' : ''}> Автозапуск</label> |
| 3161 | <label class="checkline"><input type="checkbox" data-prop="loop" ${element.loop ? 'checked' : ''}> Повтор</label> |
| 3162 | </div> |
| 3163 | <div class="fld"> |
| 3164 | <label class="checkline"><input type="checkbox" data-prop="muted" ${element.muted !== false ? 'checked' : ''}> Без звука</label> |
| 3165 | <label class="checkline"><input type="checkbox" data-prop="controls" ${element.controls !== false ? 'checked' : ''}> Управление</label> |
| 3166 | </div> |
| 3167 | </div> |
| 3168 | <p class="hint">Файл сохраняется на сервере в <code>public/uploads</code>. Докладчик управляет видео, зрители получают те же команды.</p>`; |
| 3169 | } else if (element.type === 'window') { |
| 3170 | const current = String(element.targetId || ''); |
| 3171 | const known = state.windowTargets.some((target) => target.id === current); |
| 3172 | const targetOptions = state.windowTargets.map((target) => |
| 3173 | option(target.id, `${target.title || 'Без названия'} — ${target.url || ''}`.slice(0, 90), current) |
| 3174 | ); |
| 3175 | if (current && !known) targetOptions.unshift(option(current, `Сохранённая цель · ${current.slice(0, 12)}`, current)); |
| 3176 | if (!targetOptions.length) targetOptions.push('<option value="">— окна Chrome не найдены —</option>'); |
| 3177 | fields = ` |
| 3178 | <label class="fld"><span class="label">Окно Chrome</span> |
| 3179 | <select data-prop="targetId" id="window-target-select">${targetOptions.join('')}</select> |
| 3180 | </label> |
| 3181 | <div class="field-actions"> |
| 3182 | <button data-act="window-refresh">↻ Обновить список окон</button> |
| 3183 | </div> |
| 3184 | <label class="fld"><span class="label">Подпись</span><input data-prop="label" value="${esc(element.label || '')}"></label> |
| 3185 | <div class="row-2"> |
| 3186 | <label class="fld"><span class="label">Скругление</span><input type="number" data-prop="radius" min="0" step="1" value="${Number(element.radius) || 0}"></label> |
| 3187 | <div class="fld"> |
| 3188 | <label class="checkline"><input type="checkbox" data-prop="autoStart" ${element.autoStart !== false ? 'checked' : ''}> Запускать сразу</label> |
| 3189 | </div> |
| 3190 | </div> |
| 3191 | <p class="hint">Запустите отдельный Chrome с <code>--remote-debugging-port=9222</code> и отдельным <code>--user-data-dir</code>. Клики по трансляции и пульт докладчика управляют этим окном. Произвольные нативные приложения браузер перехватывать не может.</p>`; |
| 3192 | } else if (element.type === 'lua') { |
| 3193 | const computed = element.computed || {}; |
| 3194 | const styleKeys = Object.keys(computed.style || {}); |
| 3195 | fields = ` |
| 3196 | <label class="fld"><span class="label">Подпись</span><input data-prop="label" value="${esc(element.label || '')}"></label> |
| 3197 | <div class="fld"> |
| 3198 | <span class="label">Lua-код · верните таблицу</span> |
| 3199 | ${luaEditorMarkup({ prop: 'code', value: element.code || DEFAULT_LUA_ELEMENT, rows: 12 })} |
| 3200 | </div> |
| 3201 | <p class="hint">Верните таблицу с полями <code>style</code>, <code>css</code>, <code>html</code>, <code>text</code>. Ключи стиля — как в JS: <code>backgroundColor</code>, <code>borderRadius</code>, <code>fontSize: '1.8cqw'</code>. Можно вернуть просто строку — она станет текстом.</p> |
| 3202 | <div class="field-actions"> |
| 3203 | <button class="primary" data-act="lua-compute">▶ Вычислить</button> |
| 3204 | <button data-act="lua-reset">Сбросить стили</button> |
| 3205 | </div> |
| 3206 | <div class="muted">Вычислено: ${computed.at ? new Date(computed.at).toLocaleString('ru-RU') : 'ещё нет'} · стилей: ${styleKeys.length}${computed.html ? ' · есть HTML' : ''}${computed.css ? ' · есть CSS' : ''}</div>`; |
| 3207 | } |
| 3208 | |
| 3209 | return ` |
| 3210 | <div class="insp-card"> |
| 3211 | <div class="insp-head"> |
| 3212 | <span class="insp-title">${typeNames[element.type] || 'Элемент'}</span> |
| 3213 | <div class="insp-btns"> |
| 3214 | <button data-act="el-front" title="На передний план">↑</button> |
| 3215 | <button data-act="el-back" title="На задний план">↓</button> |
| 3216 | <button data-act="el-duplicate" title="Дублировать (Ctrl+D)">⧉</button> |
| 3217 | <button data-act="el-delete" class="danger" title="Удалить (Del)">Удалить</button> |
| 3218 | </div> |
| 3219 | </div> |
| 3220 | ${geometryFields(element)} |
| 3221 | <div class="fld"> |
| 3222 | <span class="label">Выравнивание на слайде</span> |
| 3223 | <div class="align-row"> |
| 3224 | <button data-act="align-left" title="К левому краю">⫷</button> |
| 3225 | <button data-act="align-hcenter" title="По центру горизонтально">⇔</button> |
| 3226 | <button data-act="align-right" title="К правому краю">⫸</button> |
| 3227 | <button data-act="align-top" title="К верхнему краю">⤒</button> |
| 3228 | <button data-act="align-vcenter" title="По центру вертикально">⇕</button> |
| 3229 | <button data-act="align-bottom" title="К нижнему краю">⤓</button> |
| 3230 | </div> |
| 3231 | </div> |
| 3232 | <div class="row-2"> |
| 3233 | <label class="fld"><span class="label">Прозрачность</span> |
| 3234 | <input type="range" data-prop="opacity" min="0" max="100" step="1" value="${Math.round(clamp01v(element.opacity, 1) * 100)}"> |
| 3235 | </label> |
| 3236 | <label class="fld"><span class="label">Поворот, °</span> |
| 3237 | <input type="number" data-prop="rotate" step="1" min="-180" max="180" value="${Number(element.rotate) || 0}"> |
| 3238 | </label> |
| 3239 | </div> |
| 3240 | ${fields} |
| 3241 | </div>`; |
| 3242 | } |
| 3243 | |
| 3244 | const clamp01v = (value, fallback) => { |
| 3245 | const n = Number(value); |
| 3246 | return Number.isFinite(n) ? Math.max(0, Math.min(1, n)) : fallback; |
| 3247 | }; |
| 3248 | |
| 3249 | function backgroundInspector(slide) { |
| 3250 | const bg = slide.background || defaultBackground(); |
| 3251 | const type = bg.type || 'gradient'; |
| 3252 | let fields = ''; |
| 3253 | if (type === 'color') { |
| 3254 | fields = ` |
| 3255 | <label class="fld"><span class="label">Цвет фона</span><input type="color" data-prop="background.color" value="${esc(bg.color || '#0f172a')}"></label> |
| 3256 | <div class="palette"> |
| 3257 | ${SOLID_PRESETS.map((color) => `<button class="p-swatch${bg.color === color ? ' active' : ''}" data-bgcolor="${color}" style="background:${color}" title="${color}"></button>`).join('')} |
| 3258 | </div>`; |
| 3259 | } else if (type === 'gradient') { |
| 3260 | fields = ` |
| 3261 | <label class="fld"><span class="label">CSS-градиент</span> |
| 3262 | <input data-prop="background.gradient" value="${esc(bg.gradient || DEFAULT_GRADIENT)}"> |
| 3263 | </label> |
| 3264 | <div class="swatches"> |
| 3265 | ${GRADIENT_PRESETS.map((preset) => `<button class="swatch" data-bgpreset="${esc(preset)}" style="background:${esc(preset)}" title="Применить градиент"></button>`).join('')} |
| 3266 | </div>`; |
| 3267 | } else { |
| 3268 | fields = ` |
| 3269 | <label class="fld"><span class="label">URL фонового изображения</span> |
| 3270 | <input type="url" data-prop="background.image" value="${esc(bg.image || '')}" placeholder="https://images.unsplash.com/..."> |
| 3271 | </label> |
| 3272 | <div class="upload-line"> |
| 3273 | <button class="ghost" data-act="bg-upload">Загрузить файл</button> |
| 3274 | <span class="file-name">${bg.image ? esc(String(bg.image).split('/').pop().slice(0, 30)) : 'файл не выбран'}</span> |
| 3275 | <input type="file" data-upload="background" accept="image/*" hidden> |
| 3276 | </div>`; |
| 3277 | } |
| 3278 | |
| 3279 | return ` |
| 3280 | <div class="insp-card"> |
| 3281 | <div class="insp-head"> |
| 3282 | <span class="insp-title">Слайд ${state.selected + 1}</span> |
| 3283 | <span class="muted">${currentSlide().elements.length} эл.</span> |
| 3284 | </div> |
| 3285 | <div class="fld"> |
| 3286 | <span class="label">Фон</span> |
| 3287 | <div class="segmented"> |
| 3288 | <button data-bgtype="color" class="${type === 'color' ? 'active' : ''}">Цвет</button> |
| 3289 | <button data-bgtype="gradient" class="${type === 'gradient' ? 'active' : ''}">Градиент</button> |
| 3290 | <button data-bgtype="image" class="${type === 'image' ? 'active' : ''}">Картинка</button> |
| 3291 | </div> |
| 3292 | </div> |
| 3293 | ${fields} |
| 3294 | <label class="fld"><span class="label">Переход</span> |
| 3295 | <select data-prop="transition"> |
| 3296 | ${option('none', 'Без анимации', slide.transition)} |
| 3297 | ${option('fade', 'Плавное появление', slide.transition)} |
| 3298 | ${option('slide', 'Сдвиг', slide.transition)} |
| 3299 | ${option('zoom', 'Приближение', slide.transition)} |
| 3300 | ${option('flip', 'Переворот 3D', slide.transition)} |
| 3301 | ${option('rise', 'Всплытие', slide.transition)} |
| 3302 | </select> |
| 3303 | </label> |
| 3304 | <label class="fld"><span class="label">Пометки докладчика</span> |
| 3305 | <textarea data-prop="notes" rows="4" placeholder="Что сказать на этом слайде...">${esc(slide.notes || '')}</textarea> |
| 3306 | </label> |
| 3307 | <label class="fld"><span class="label">Lua этого слайда</span> |
| 3308 | <textarea data-prop="lua" rows="4" placeholder="Запускается при входе на слайд vars.count = (vars.count or 0) + 1">${esc(slide.lua || '')}</textarea> |
| 3309 | </label> |
| 3310 | <p class="hint">Lua выполняется у докладчика. Переменные синхронизируются со зрителями.</p> |
| 3311 | </div>`; |
| 3312 | } |
| 3313 | |
| 3314 | function buttonLinkOptions(node) { |
| 3315 | const current = node.slideId && node.elementId ? `${node.slideId}|${node.elementId}` : ''; |
| 3316 | let html = '<option value="">— не привязана —</option>'; |
| 3317 | state.slides.forEach((slide, index) => { |
| 3318 | (slide.elements || []).forEach((element) => { |
| 3319 | if (element.type !== 'button') return; |
| 3320 | const value = `${slide.id}|${element.id}`; |
| 3321 | html += option(value, `Кнопка «${element.label || 'без подписи'}» · слайд ${index + 1}`, current); |
| 3322 | }); |
| 3323 | }); |
| 3324 | return html; |
| 3325 | } |
| 3326 | |
| 3327 | function scriptNodeInspector(node) { |
| 3328 | const linked = findLinkedElement(node); |
| 3329 | return ` |
| 3330 | <div class="insp-card"> |
| 3331 | <div class="insp-head"> |
| 3332 | <span class="insp-title">Lua-нода</span> |
| 3333 | <div class="insp-btns"> |
| 3334 | <button data-act="node-delete" class="danger" title="Удалить ноду">Удалить</button> |
| 3335 | </div> |
| 3336 | </div> |
| 3337 | <label class="fld"><span class="label">Название</span> |
| 3338 | <input data-node-prop="name" value="${esc(node.name || '')}"> |
| 3339 | </label> |
| 3340 | <label class="fld"><span class="label">Lua-код</span> |
| 3341 | <textarea data-node-prop="code" rows="10" spellcheck="false" placeholder="vars.score = (vars.score or 0) + 1 app.log('score')">${esc(node.code || '')}</textarea> |
| 3342 | </label> |
| 3343 | <label class="fld"><span class="label">Привязать к кнопке</span> |
| 3344 | <select data-node-link>${buttonLinkOptions(node)}</select> |
| 3345 | </label> |
| 3346 | <div class="field-actions"> |
| 3347 | <button data-act="node-open-slide" ${linked ? '' : 'disabled'}>Открыть слайд</button> |
| 3348 | <button data-act="node-new-script">+ Ещё нода</button> |
| 3349 | </div> |
| 3350 | <p class="hint">Этот код синхронизирован с Lua-кнопкой: правки здесь сразу меняют кнопку и наоборот. Свободную ноду можно привязать к любой кнопке.</p> |
| 3351 | </div>`; |
| 3352 | } |
| 3353 | |
| 3354 | function graphSlideOptions(currentId) { |
| 3355 | return state.slides.map((slide, index) => { |
| 3356 | const firstText = (slide.elements || []).find((el) => el.type === 'text' && String(el.text || '').trim()); |
| 3357 | const label = firstText ? String(firstText.text).trim().slice(0, 26) : `Слайд ${index + 1}`; |
| 3358 | return `<option value="${esc(slide.id)}"${slide.id === currentId ? ' selected' : ''}>${index + 1}. ${esc(label)}</option>`; |
| 3359 | }).join(''); |
| 3360 | } |
| 3361 | |
| 3362 | function transitionNodeInspector(node) { |
| 3363 | return ` |
| 3364 | <div class="insp-card"> |
| 3365 | <div class="insp-head"> |
| 3366 | <span class="insp-title">Переход · Lua</span> |
| 3367 | <div class="insp-btns"> |
| 3368 | <button data-act="node-delete" class="danger" title="Удалить ноду">Удалить</button> |
| 3369 | </div> |
| 3370 | </div> |
| 3371 | <label class="fld"><span class="label">Название</span> |
| 3372 | <input data-node-prop="name" value="${esc(node.name || '')}"> |
| 3373 | </label> |
| 3374 | <label class="fld"><span class="label">Слайд</span> |
| 3375 | <select data-node-prop="slideId">${graphSlideOptions(node.slideId)}</select> |
| 3376 | </label> |
| 3377 | <label class="fld"><span class="label">Lua-код перехода</span> |
| 3378 | <textarea data-node-prop="code" rows="10" spellcheck="false" placeholder="anim.play('in', { opacity = {0, 1} }, { duration = 400 })">${esc(node.code || '')}</textarea> |
| 3379 | </label> |
| 3380 | <p class="hint">Выполняется вместо встроенного перехода при входе на слайд. Цели: <code>in</code> — новый слайд, <code>out</code> — старый, id элемента, <code>slide</code>. API: <code>anim.play / fadeIn / fadeOut / clear</code>, <code>sleep(мс)</code>, свойства: opacity, x, y, w, h, scale, rotate.</p> |
| 3381 | </div>`; |
| 3382 | } |
| 3383 | |
| 3384 | function animNodeInspector(node) { |
| 3385 | const slide = state.slides.find((item) => item.id === node.slideId); |
| 3386 | const elementOptions = (slide ? slide.elements || [] : []).map((el) => { |
| 3387 | const label = el.label || el.text ? String(el.label || el.text).trim().slice(0, 24) : el.type; |
| 3388 | return `<option value="${esc(el.id)}"${el.id === node.elementId ? ' selected' : ''}>${esc(label)}</option>`; |
| 3389 | }).join(''); |
| 3390 | return ` |
| 3391 | <div class="insp-card"> |
| 3392 | <div class="insp-head"> |
| 3393 | <span class="insp-title">Анимация · Lua</span> |
| 3394 | <div class="insp-btns"> |
| 3395 | <button data-act="node-delete" class="danger" title="Удалить ноду">Удалить</button> |
| 3396 | </div> |
| 3397 | </div> |
| 3398 | <label class="fld"><span class="label">Название</span> |
| 3399 | <input data-node-prop="name" value="${esc(node.name || '')}"> |
| 3400 | </label> |
| 3401 | <label class="fld"><span class="label">Слайд</span> |
| 3402 | <select data-node-prop="slideId">${graphSlideOptions(node.slideId)}</select> |
| 3403 | </label> |
| 3404 | <label class="fld"><span class="label">Элемент (подсказка)</span> |
| 3405 | <select data-node-prop="elementId"><option value="">— весь слайд —</option>${elementOptions}</select> |
| 3406 | </label> |
| 3407 | <label class="fld"><span class="label">Lua-код анимации</span> |
| 3408 | <textarea data-node-prop="code" rows="10" spellcheck="false" placeholder="anim.play('slide', { opacity = {0, 1} }, { duration = 400 })">${esc(node.code || '')}</textarea> |
| 3409 | </label> |
| 3410 | <p class="hint">Выполняется при входе на слайд после перехода. Внутри можно анимировать любые элементы по id: <code>anim.play(id, { y = {6, 0} }, { duration = 400, delay = 200 })</code>. Паузы — <code>sleep(мс)</code>.</p> |
| 3411 | </div>`; |
| 3412 | } |
| 3413 | |
| 3414 | function pluginNodeInspector(node) { |
| 3415 | const plugin = pluginById(node.pluginId); |
| 3416 | const functions = (plugin && plugin.nodes) || []; |
| 3417 | const pluginOptions = (state.pluginRegistry || []).map((item) => |
| 3418 | option(item.id, `${item.name} · ${(item.nodes || []).length} нод`, node.pluginId) |
| 3419 | ).join(''); |
| 3420 | const fnOptions = functions.map((item) => |
| 3421 | option(item.fn, `${item.name || item.fn}(${item.args || ''})`, node.fn) |
| 3422 | ).join(''); |
| 3423 | return ` |
| 3424 | <div class="insp-card"> |
| 3425 | <div class="insp-head"> |
| 3426 | <span class="insp-title">Плагин · нода</span> |
| 3427 | <div class="insp-btns"> |
| 3428 | <button data-act="plugin-edit" title="Открыть редактор плагинов">✎</button> |
| 3429 | <button data-act="node-delete" class="danger" title="Удалить ноду">Удалить</button> |
| 3430 | </div> |
| 3431 | </div> |
| 3432 | <label class="fld"><span class="label">Плагин</span> |
| 3433 | <select data-node-prop="pluginId"> |
| 3434 | <option value="">— не выбран —</option> |
| 3435 | ${pluginOptions} |
| 3436 | </select> |
| 3437 | </label> |
| 3438 | <label class="fld"><span class="label">Функция-нода</span> |
| 3439 | <select data-node-prop="fn"> |
| 3440 | <option value="">— выберите функцию —</option> |
| 3441 | ${fnOptions} |
| 3442 | </select> |
| 3443 | </label> |
| 3444 | <label class="fld"><span class="label">Название</span> |
| 3445 | <input data-node-prop="name" value="${esc(node.name || '')}"> |
| 3446 | </label> |
| 3447 | <label class="fld"><span class="label">Аргументы вызова (Lua)</span> |
| 3448 | <input data-node-prop="args" value="${esc(node.args || '')}" placeholder="'slide', 1.1"> |
| 3449 | </label> |
| 3450 | <div class="muted">${esc(node.description || 'Без описания')}</div> |
| 3451 | ${plugin ? '' : '<p class="hint">Плагин отсутствует в реестре: нода продолжит работать по снимку кода.</p>'} |
| 3452 | <div class="field-actions"> |
| 3453 | <button data-act="node-open-plugin">Открыть плагин</button> |
| 3454 | <button data-act="node-new-plugin">+ Ещё нода</button> |
| 3455 | </div> |
| 3456 | <p class="hint">Нода выполняется при проходе по цепи: вход → плагин → выход. Код модуля сохранён снимком, поэтому показ не зависит от загрузки реестра.</p> |
| 3457 | </div>`; |
| 3458 | } |
| 3459 | |
| 3460 | function graphHomeInspector() { |
| 3461 | return ` |
| 3462 | <div class="insp-card"> |
| 3463 | <div class="insp-head"><span class="insp-title">Граф</span></div> |
| 3464 | <p class="hint">Каждый слайд — нода с входом и выходами. Тяните от выхода «Дальше», «Назад» или кнопки к входу другого слайда, кода или аудио. Переменные — отдельные ноды: соедините выход с портом <code>⌘ имя</code>, и текст с <code>{{имя}}</code> обновится.</p> |
| 3465 | <div class="muted">Слайды: ${state.slides.length} · код: ${state.graph.scripts.length} · аудио: ${state.graph.audios.length} · переменные: ${state.graph.variables.length} · переходы: ${(state.graph.transitions || []).length} · анимации: ${(state.graph.anims || []).length} · плагины: ${(state.graph.plugins || []).length} · связи: ${state.graph.links.length}</div> |
| 3466 | <div class="field-actions"> |
| 3467 | <button data-act="graph-to-canvas">Открыть холст</button> |
| 3468 | <button data-act="graph-add-script">+ Код</button> |
| 3469 | <button data-act="graph-add-variable">+ Переменная</button> |
| 3470 | <button data-act="graph-add-transition">+ Переход</button> |
| 3471 | <button data-act="graph-add-anim">+ Анимация</button> |
| 3472 | <button data-act="plugin-edit">Плагины…</button> |
| 3473 | </div> |
| 3474 | </div>`; |
| 3475 | } |
| 3476 | |
| 3477 | function actionLabel(action) { |
| 3478 | if (!action) return 'нет действия'; |
| 3479 | if (action.type === 'go') return `→ слайд ${(Number(action.slideIndex) || 0) + 1}`; |
| 3480 | if (action.type === 'next') return '→ дальше'; |
| 3481 | if (action.type === 'prev') return '← назад'; |
| 3482 | if (action.type === 'play') return '▶ аудио'; |
| 3483 | if (action.type === 'stop') return '■ аудио'; |
| 3484 | if (action.type === 'lua') return 'Lua-код'; |
| 3485 | return 'без действия'; |
| 3486 | } |
| 3487 | |
| 3488 | function variableNodeInspector(node) { |
| 3489 | const bound = state.graph.links.filter((link) => link.from.kind === 'variable' && link.from.id === node.id).length; |
| 3490 | const value = state.variables[node.name]; |
| 3491 | return ` |
| 3492 | <div class="insp-card"> |
| 3493 | <div class="insp-head"> |
| 3494 | <span class="insp-title">Переменная</span> |
| 3495 | <div class="insp-btns"><button data-act="node-delete" class="danger" title="Удалить ноду">Удалить</button></div> |
| 3496 | </div> |
| 3497 | <label class="fld"><span class="label">Имя</span> |
| 3498 | <input data-node-prop="name" value="${esc(node.name || '')}" placeholder="score"> |
| 3499 | </label> |
| 3500 | <div class="muted">Текущее значение: <b>${esc(value === undefined ? '—' : String(value))}</b> · связей: ${bound}</div> |
| 3501 | <p class="hint">Выход соединяется с портом <code>⌘ имя</code> на ноде слайда. Вставка <code>{{${esc(node.name)}}}</code> в тексте обновится автоматически.</p> |
| 3502 | <div class="field-actions"> |
| 3503 | <button data-act="node-new-variable">+ Ещё переменная</button> |
| 3504 | </div> |
| 3505 | </div>`; |
| 3506 | } |
| 3507 | |
| 3508 | function audioNodeInspector(node) { |
| 3509 | const audios = []; |
| 3510 | state.slides.forEach((slide, index) => { |
| 3511 | (slide.elements || []).forEach((element) => { |
| 3512 | if (element.type === 'audio') audios.push({ element, index }); |
| 3513 | }); |
| 3514 | }); |
| 3515 | const current = node.elementId || ''; |
| 3516 | if (current && !audios.some((item) => item.element.id === current)) { |
| 3517 | audios.unshift({ element: { id: current, label: 'Сохранённый элемент' }, index: -1 }); |
| 3518 | } |
| 3519 | const options = audios.map((item) => |
| 3520 | option(item.element.id, `${item.element.label || 'Аудио'} · слайд ${item.index + 1}`, current) |
| 3521 | ).join(''); |
| 3522 | return ` |
| 3523 | <div class="insp-card"> |
| 3524 | <div class="insp-head"> |
| 3525 | <span class="insp-title">Аудио-нода</span> |
| 3526 | <div class="insp-btns"><button data-act="node-delete" class="danger" title="Удалить ноду">Удалить</button></div> |
| 3527 | </div> |
| 3528 | <label class="fld"><span class="label">Название</span> |
| 3529 | <input data-node-prop="name" value="${esc(node.name || '')}"> |
| 3530 | </label> |
| 3531 | <label class="fld"><span class="label">Аудиоэлемент</span> |
| 3532 | <select data-node-prop="elementId"> |
| 3533 | <option value="">— не выбран —</option> |
| 3534 | ${options} |
| 3535 | </select> |
| 3536 | </label> |
| 3537 | <label class="fld"><span class="label">Команда</span> |
| 3538 | <select data-node-prop="mode"> |
| 3539 | ${option('play', '▶ Запустить', node.mode === 'stop' ? 'stop' : 'play')} |
| 3540 | ${option('stop', '■ Остановить', node.mode === 'stop' ? 'stop' : 'play')} |
| 3541 | </select> |
| 3542 | </label> |
| 3543 | <p class="hint">Вход аудио-ноды соединяется с выходом кнопки. Кнопка получит действие «Запустить аудио».</p> |
| 3544 | <div class="field-actions"> |
| 3545 | <button data-act="node-new-audio">+ Ещё аудио</button> |
| 3546 | </div> |
| 3547 | </div>`; |
| 3548 | } |
| 3549 | |
| 3550 | function slideGraphInspector(slide) { |
| 3551 | const index = state.slides.indexOf(slide); |
| 3552 | const buttons = (slide.elements || []).filter((element) => element.type === 'button'); |
| 3553 | const vars = slideVarPorts(slide); |
| 3554 | const jumps = state.graph.jumps[slide.id] || {}; |
| 3555 | const targetTitle = (id) => { |
| 3556 | const at = state.slides.findIndex((item) => item.id === id); |
| 3557 | return at >= 0 ? `слайд ${at + 1}` : '—'; |
| 3558 | }; |
| 3559 | return ` |
| 3560 | <div class="insp-card"> |
| 3561 | <div class="insp-head"> |
| 3562 | <span class="insp-title">Слайд ${index + 1} · граф</span> |
| 3563 | <div class="insp-btns"><button data-act="node-open-canvas">Открыть холст</button></div> |
| 3564 | </div> |
| 3565 | <div class="muted">Дальше: ${jumps.next ? targetTitle(jumps.next) : 'по порядку'} · Назад: ${jumps.prev ? targetTitle(jumps.prev) : 'по порядку'}</div> |
| 3566 | ${buttons.length ? `<div class="graph-bind-list">${buttons.map((button) => ` |
| 3567 | <div class="graph-bind"><span>▸ ${esc(button.label || 'Кнопка')}</span><span class="gdim">${esc(actionLabel(button.action))}</span></div>`).join('')}</div>` : '<p class="hint">На слайде нет кнопок. Выходы «Дальше» и «Назад» работают с клавиатуры.</p>'} |
| 3568 | ${vars.length ? `<div class="muted">Переменные: ${vars.map((port) => `{{${esc(port.name)}}}`).join(', ')}</div>` : ''} |
| 3569 | <p class="hint">Тяните от порта «Дальше», «Назад» или кнопки к входу другого слайда. Клик по связи и Delete удаляют её.</p> |
| 3570 | </div>`; |
| 3571 | } |
| 3572 | |
| 3573 | function renderInspector() { |
| 3574 | if (state.view === 'graph') { |
| 3575 | const selected = state.selectedNode; |
| 3576 | if (selected && selected.type === 'script') { |
| 3577 | const node = findScriptNode(selected.id); |
| 3578 | inspectorEl.innerHTML = node ? scriptNodeInspector(node) : graphHomeInspector(); |
| 3579 | } else if (selected && selected.type === 'transition') { |
| 3580 | const node = findTransitionNode(selected.id); |
| 3581 | inspectorEl.innerHTML = node ? transitionNodeInspector(node) : graphHomeInspector(); |
| 3582 | } else if (selected && selected.type === 'anim') { |
| 3583 | const node = findAnimNode(selected.id); |
| 3584 | inspectorEl.innerHTML = node ? animNodeInspector(node) : graphHomeInspector(); |
| 3585 | } else if (selected && selected.type === 'variable') { |
| 3586 | const node = findVariableNode(selected.id); |
| 3587 | inspectorEl.innerHTML = node ? variableNodeInspector(node) : graphHomeInspector(); |
| 3588 | } else if (selected && selected.type === 'audio') { |
| 3589 | const node = findAudioNode(selected.id); |
| 3590 | inspectorEl.innerHTML = node ? audioNodeInspector(node) : graphHomeInspector(); |
| 3591 | } else if (selected && selected.type === 'plugin') { |
| 3592 | const node = findPluginNode(selected.id); |
| 3593 | inspectorEl.innerHTML = node ? pluginNodeInspector(node) : graphHomeInspector(); |
| 3594 | } else if (selected && selected.type === 'slide') { |
| 3595 | const slide = state.slides.find((item) => item.id === selected.id) || currentSlide(); |
| 3596 | inspectorEl.innerHTML = slideGraphInspector(slide) + backgroundInspector(slide); |
| 3597 | } else { |
| 3598 | inspectorEl.innerHTML = graphHomeInspector() + backgroundInspector(currentSlide()); |
| 3599 | } |
| 3600 | return; |
| 3601 | } |
| 3602 | const element = selectedElement(); |
| 3603 | inspectorEl.innerHTML = (element ? elementInspector(element) : '') + backgroundInspector(currentSlide()); |
| 3604 | enhanceLuaEditors(inspectorEl); |
| 3605 | if (element && element.type === 'window') loadWindowTargets(false); |
| 3606 | } |
| 3607 | |
| 3608 | let lastTargetsFetch = 0; |
| 3609 | async function loadWindowTargets(notify) { |
| 3610 | // Не дёргаем CDP чаще раза в 4 секунды, если не просят принудительно. |
| 3611 | if (!notify && Date.now() - lastTargetsFetch < 4000 && state.windowTargets.length) return; |
| 3612 | lastTargetsFetch = Date.now(); |
| 3613 | try { |
| 3614 | const response = await fetch('/api/windows'); |
| 3615 | const data = await response.json(); |
| 3616 | state.windowTargets = Array.isArray(data.targets) ? data.targets : []; |
| 3617 | state.windowEndpoint = data.endpoint || ''; |
| 3618 | const select = inspectorEl.querySelector('#window-target-select'); |
| 3619 | const element = selectedElement(); |
| 3620 | if (select && element && element.type === 'window') { |
| 3621 | const current = String(element.targetId || ''); |
| 3622 | const items = state.windowTargets.map((target) => |
| 3623 | option(target.id, `${target.title || 'Без названия'} — ${target.url || ''}`.slice(0, 90), current) |
| 3624 | ); |
| 3625 | if (current && !state.windowTargets.some((target) => target.id === current)) { |
| 3626 | items.unshift(option(current, `Сохранённая цель · ${current.slice(0, 12)}`, current)); |
| 3627 | } |
| 3628 | if (!items.length) items.push('<option value="">— окна Chrome не найдены —</option>'); |
| 3629 | select.innerHTML = items.join(''); |
| 3630 | } |
| 3631 | if (notify) { |
| 3632 | toast(state.windowTargets.length |
| 3633 | ? `Найдено окон: ${state.windowTargets.length}` |
| 3634 | : `Chrome не найден на ${state.windowEndpoint || '127.0.0.1:9222'}`); |
| 3635 | } |
| 3636 | } catch (error) { |
| 3637 | if (notify) toast('Не удалось получить список окон'); |
| 3638 | } |
| 3639 | } |
| 3640 | |
| 3641 | // ==================== Элементы ==================== |
| 3642 | function defaultElement(type) { |
| 3643 | const base = { |
| 3644 | id: uid(), type, opacity: 1, rotate: 0, |
| 3645 | z: Math.max(0, ...(currentSlide().elements || []).map((el) => Number(el.z) || 0)) + 1, |
| 3646 | }; |
| 3647 | if (type === 'text') { |
| 3648 | return { ...base, x: 10, y: 38, w: 80, h: 24, text: 'Новый текст', fontSize: 6, color: '#f8fafc', weight: 700, align: 'center', bg: '', font: 'sans', italic: false, shadow: false, lineHeight: 1.16 }; |
| 3649 | } |
| 3650 | if (type === 'image') { |
| 3651 | return { ...base, x: 30, y: 18, w: 40, h: 50, src: '', fit: 'cover', radius: 14, shadow: false }; |
| 3652 | } |
| 3653 | if (type === 'shape') { |
| 3654 | return { ...base, x: 32, y: 30, w: 36, h: 40, shape: 'rect', fill: '#6366f1', borderColor: '', borderWidth: 0, radius: 12, shadow: false }; |
| 3655 | } |
| 3656 | if (type === 'button') { |
| 3657 | return { ...base, x: 35, y: 62, w: 30, h: 11, label: 'Кнопка', bg: '#6366f1', color: '#ffffff', fontSize: 2.4, radius: 12, shadow: true, action: { type: 'next', slideIndex: 0, audioId: '', code: '', scriptNodeId: '' } }; |
| 3658 | } |
| 3659 | if (type === 'video') { |
| 3660 | 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: 'Видео' }; |
| 3661 | } |
| 3662 | if (type === 'window') { |
| 3663 | return { ...base, x: 12, y: 14, w: 62, h: 58, targetId: '', targetTitle: '', radius: 12, autoStart: true, label: 'Окно Chrome' }; |
| 3664 | } |
| 3665 | if (type === 'lua') { |
| 3666 | return { |
| 3667 | ...base, x: 26, y: 24, w: 48, h: 36, |
| 3668 | label: 'Lua-элемент', |
| 3669 | code: typeof DEFAULT_LUA_ELEMENT === 'string' ? DEFAULT_LUA_ELEMENT : '', |
| 3670 | computed: { style: {}, css: '', html: '', text: '', at: 0 }, |
| 3671 | }; |
| 3672 | } |
| 3673 | return { ...base, x: 30, y: 82, w: 40, h: 8, src: '', loop: false, visible: true, volume: 0.8, label: 'Аудио' }; |
| 3674 | } |
| 3675 | |
| 3676 | function addElement(type, point) { |
| 3677 | pushHistory(true); |
| 3678 | const element = defaultElement(type); |
| 3679 | if (point) { |
| 3680 | element.x = clamp(Number(point.x) || 0, 0, 100 - (Number(element.w) || 10)); |
| 3681 | element.y = clamp(Number(point.y) || 0, 0, 100 - (Number(element.h) || 10)); |
| 3682 | } |
| 3683 | currentSlide().elements.push(element); |
| 3684 | state.selectedEl = element.id; |
| 3685 | renderCanvas(); |
| 3686 | renderInspector(); |
| 3687 | scheduleThumbs(); |
| 3688 | scheduleSave(true); |
| 3689 | } |
| 3690 | |
| 3691 | function selectElement(id) { |
| 3692 | if (state.selectedEl === id) return; |
| 3693 | state.selectedEl = id; |
| 3694 | renderCanvas(); |
| 3695 | renderInspector(); |
| 3696 | } |
| 3697 | |
| 3698 | function addSlide(template = 'blank') { |
| 3699 | pushHistory(true); |
| 3700 | const slide = newSlide(); |
| 3701 | const factory = slideTemplates()[template] || slideTemplates().blank; |
| 3702 | slide.elements = factory(); |
| 3703 | const previous = currentSlide(); |
| 3704 | state.slides.push(slide); |
| 3705 | state.graph.positions[slide.id] = graphDefaultPosition(state.slides.length - 1); |
| 3706 | chainSlides(previous, slide); |
| 3707 | rebuildJumps(); |
| 3708 | state.selected = state.slides.length - 1; |
| 3709 | state.selectedEl = null; |
| 3710 | state.selectedNode = { type: 'slide', id: slide.id }; |
| 3711 | renderAll(); |
| 3712 | scheduleSave(true); |
| 3713 | } |
| 3714 | |
| 3715 | function duplicateSelectedElement() { |
| 3716 | const element = selectedElement(); |
| 3717 | if (!element) return; |
| 3718 | pushHistory(true); |
| 3719 | const copy = { ...element, id: uid(), x: clamp(element.x + 3, 0, 100 - element.w), y: clamp(element.y + 3, 0, 100 - element.h) }; |
| 3720 | if (element.action) copy.action = { ...element.action }; |
| 3721 | if (element.type === 'button' && element.action && element.action.type === 'lua') { |
| 3722 | const original = element.action.scriptNodeId |
| 3723 | ? findScriptNode(element.action.scriptNodeId) |
| 3724 | : scriptNodeForElement(element.id); |
| 3725 | if (original) { |
| 3726 | const spot = findFreeNodeSpot(original.x + 320, original.y + 40, 'script', ''); |
| 3727 | const node = { |
| 3728 | ...original, |
| 3729 | id: uid(), |
| 3730 | x: spot.x, |
| 3731 | y: spot.y, |
| 3732 | slideId: currentSlide().id, |
| 3733 | elementId: copy.id, |
| 3734 | }; |
| 3735 | state.graph.scripts.push(node); |
| 3736 | copy.action.scriptNodeId = node.id; |
| 3737 | copy.action.code = node.code; |
| 3738 | } |
| 3739 | } |
| 3740 | currentSlide().elements.push(copy); |
| 3741 | ensureLinksFromModel(); |
| 3742 | rebuildJumps(); |
| 3743 | state.selectedEl = copy.id; |
| 3744 | renderCanvas(); |
| 3745 | renderInspector(); |
| 3746 | scheduleThumbs(); |
| 3747 | scheduleSave(true); |
| 3748 | } |
| 3749 | |
| 3750 | function pasteElement() { |
| 3751 | if (!state.clipboard) { toast('Буфер обмена пуст'); return; } |
| 3752 | pushHistory(true); |
| 3753 | const copy = JSON.parse(JSON.stringify(state.clipboard)); |
| 3754 | copy.id = uid(); |
| 3755 | copy.x = clamp((Number(copy.x) || 0) + 3, 0, 96); |
| 3756 | copy.y = clamp((Number(copy.y) || 0) + 3, 0, 96); |
| 3757 | copy.z = Math.max(0, ...(currentSlide().elements || []).map((el) => Number(el.z) || 0)) + 1; |
| 3758 | if (copy.type === 'button' && copy.action && copy.action.type === 'lua' && copy.action.scriptNodeId) { |
| 3759 | const original = findScriptNode(copy.action.scriptNodeId); |
| 3760 | if (original) { |
| 3761 | const spot = findFreeNodeSpot((Number(original.x) || 60) + 320, (Number(original.y) || 60) + 40, 'script', ''); |
| 3762 | const node = { ...original, id: uid(), x: spot.x, y: spot.y, slideId: currentSlide().id, elementId: copy.id }; |
| 3763 | state.graph.scripts.push(node); |
| 3764 | copy.action.scriptNodeId = node.id; |
| 3765 | copy.action.code = node.code; |
| 3766 | } |
| 3767 | } |
| 3768 | currentSlide().elements.push(copy); |
| 3769 | ensureLinksFromModel(); |
| 3770 | rebuildJumps(); |
| 3771 | state.selectedEl = copy.id; |
| 3772 | renderCanvas(); |
| 3773 | renderInspector(); |
| 3774 | scheduleThumbs(); |
| 3775 | scheduleSave(true); |
| 3776 | toast('Элемент вставлен'); |
| 3777 | } |
| 3778 | |
| 3779 | function nudgeSelected(dx, dy) { |
| 3780 | const element = selectedElement(); |
| 3781 | if (!element) return; |
| 3782 | element.x = clamp((Number(element.x) || 0) + dx, -40, 130); |
| 3783 | element.y = clamp((Number(element.y) || 0) + dy, -40, 130); |
| 3784 | applyElementStyles(element); |
| 3785 | scheduleThumbs(); |
| 3786 | scheduleSave(); |
| 3787 | } |
| 3788 | |
| 3789 | function duplicateSlide() { |
| 3790 | pushHistory(true); |
| 3791 | const source = currentSlide(); |
| 3792 | const copyId = uid(); |
| 3793 | const copy = { |
| 3794 | ...source, |
| 3795 | id: copyId, |
| 3796 | background: { ...(source.background || {}) }, |
| 3797 | elements: (source.elements || []).map((element) => { |
| 3798 | const nextElement = { ...element, id: uid() }; |
| 3799 | if (element.action) nextElement.action = { ...element.action }; |
| 3800 | if (element.type === 'button' && element.action && element.action.type === 'lua') { |
| 3801 | const original = element.action.scriptNodeId |
| 3802 | ? findScriptNode(element.action.scriptNodeId) |
| 3803 | : scriptNodeForElement(element.id); |
| 3804 | if (original) { |
| 3805 | const spot = findFreeNodeSpot(original.x + 320, original.y + 40, 'script', ''); |
| 3806 | const node = { |
| 3807 | ...original, |
| 3808 | id: uid(), |
| 3809 | x: spot.x, |
| 3810 | y: spot.y, |
| 3811 | slideId: copyId, |
| 3812 | elementId: nextElement.id, |
| 3813 | }; |
| 3814 | state.graph.scripts.push(node); |
| 3815 | nextElement.action.scriptNodeId = node.id; |
| 3816 | nextElement.action.code = node.code; |
| 3817 | } |
| 3818 | } |
| 3819 | return nextElement; |
| 3820 | }), |
| 3821 | }; |
| 3822 | const sourcePos = state.graph.positions[source.id] || graphDefaultPosition(state.selected); |
| 3823 | const copyPos = findFreeNodeSpot(sourcePos.x, sourcePos.y + 300, 'slide', copyId, { w: 250, h: 300 }); |
| 3824 | state.graph.positions[copy.id] = copyPos; |
| 3825 | state.slides.splice(state.selected + 1, 0, copy); |
| 3826 | ensureLinksFromModel(); |
| 3827 | rebuildJumps(); |
| 3828 | state.selected += 1; |
| 3829 | state.selectedEl = null; |
| 3830 | state.selectedNode = { type: 'slide', id: copy.id }; |
| 3831 | renderAll(); |
| 3832 | scheduleSave(true); |
| 3833 | } |
| 3834 | |
| 3835 | function deleteSlide() { |
| 3836 | if (state.slides.length <= 1) { |
| 3837 | toast('Нельзя удалить единственный слайд'); |
| 3838 | return; |
| 3839 | } |
| 3840 | pushHistory(true); |
| 3841 | const removed = currentSlide(); |
| 3842 | state.graph.scripts.forEach((node) => { |
| 3843 | if (node.slideId === removed.id) { |
| 3844 | node.slideId = ''; |
| 3845 | node.elementId = ''; |
| 3846 | } |
| 3847 | }); |
| 3848 | cleanupSlideLinks(removed); |
| 3849 | state.slides.splice(state.selected, 1); |
| 3850 | state.selected = Math.min(state.selected, state.slides.length - 1); |
| 3851 | state.selectedEl = null; |
| 3852 | const slide = currentSlide(); |
| 3853 | state.selectedNode = { type: 'slide', id: slide.id }; |
| 3854 | renderAll(); |
| 3855 | scheduleSave(true); |
| 3856 | } |
| 3857 | |
| 3858 | function moveSlide(delta) { |
| 3859 | const target = state.selected + delta; |
| 3860 | if (target < 0 || target >= state.slides.length) return; |
| 3861 | pushHistory(true); |
| 3862 | const [slide] = state.slides.splice(state.selected, 1); |
| 3863 | state.slides.splice(target, 0, slide); |
| 3864 | state.selected = target; |
| 3865 | state.selectedEl = null; |
| 3866 | renderAll(); |
| 3867 | scheduleSave(true); |
| 3868 | } |
| 3869 | |
| 3870 | // ==================== Перетаскивание ==================== |
| 3871 | let drag = null; |
| 3872 | |
| 3873 | function elementNode(id) { |
| 3874 | return canvasEl.querySelector(`[data-el="${id}"]`); |
| 3875 | } |
| 3876 | |
| 3877 | function applyElementStyles(element) { |
| 3878 | const node = elementNode(element.id); |
| 3879 | if (node) { |
| 3880 | node.style.left = `${element.x}%`; |
| 3881 | node.style.top = `${element.y}%`; |
| 3882 | node.style.width = `${element.w}%`; |
| 3883 | node.style.height = `${element.h}%`; |
| 3884 | } |
| 3885 | renderSelection(); |
| 3886 | } |
| 3887 | |
| 3888 | canvasWrap.addEventListener('pointerdown', (event) => { |
| 3889 | if (event.button !== 0) return; |
| 3890 | const handle = event.target.closest('.resize'); |
| 3891 | const node = event.target.closest('.sv-el'); |
| 3892 | |
| 3893 | if (handle) { |
| 3894 | const element = selectedElement(); |
| 3895 | if (!element) return; |
| 3896 | event.preventDefault(); |
| 3897 | drag = { |
| 3898 | mode: 'resize', |
| 3899 | dir: handle.dataset.dir, |
| 3900 | element, |
| 3901 | startX: event.clientX, |
| 3902 | startY: event.clientY, |
| 3903 | rect: canvasEl.getBoundingClientRect(), |
| 3904 | original: { x: element.x, y: element.y, w: element.w, h: element.h }, |
| 3905 | }; |
| 3906 | startDragListeners(); |
| 3907 | return; |
| 3908 | } |
| 3909 | |
| 3910 | if (!node) { |
| 3911 | selectElement(null); |
| 3912 | return; |
| 3913 | } |
| 3914 | |
| 3915 | event.preventDefault(); |
| 3916 | selectElement(node.dataset.el); |
| 3917 | const element = selectedElement(); |
| 3918 | if (!element) return; |
| 3919 | drag = { |
| 3920 | mode: 'move', |
| 3921 | element, |
| 3922 | startX: event.clientX, |
| 3923 | startY: event.clientY, |
| 3924 | rect: canvasEl.getBoundingClientRect(), |
| 3925 | original: { x: element.x, y: element.y, w: element.w, h: element.h }, |
| 3926 | }; |
| 3927 | startDragListeners(); |
| 3928 | }); |
| 3929 | |
| 3930 | function startDragListeners() { |
| 3931 | window.addEventListener('pointermove', onDragMove); |
| 3932 | window.addEventListener('pointerup', onDragEnd); |
| 3933 | document.body.style.cursor = drag.mode === 'move' ? 'grabbing' : 'nwse-resize'; |
| 3934 | } |
| 3935 | |
| 3936 | function onDragMove(event) { |
| 3937 | if (!drag) return; |
| 3938 | const rect = drag.rect; |
| 3939 | const dx = ((event.clientX - drag.startX) / rect.width) * 100; |
| 3940 | const dy = ((event.clientY - drag.startY) / rect.height) * 100; |
| 3941 | const original = drag.original; |
| 3942 | const element = drag.element; |
| 3943 | |
| 3944 | if (drag.mode === 'move') { |
| 3945 | element.x = clamp(original.x + dx, 0, 100 - element.w); |
| 3946 | element.y = clamp(original.y + dy, 0, 100 - element.h); |
| 3947 | } else { |
| 3948 | let x = original.x; |
| 3949 | let y = original.y; |
| 3950 | let w = original.w; |
| 3951 | let h = original.h; |
| 3952 | if (drag.dir.includes('e')) w = original.w + dx; |
| 3953 | if (drag.dir.includes('s')) h = original.h + dy; |
| 3954 | if (drag.dir.includes('w')) { |
| 3955 | w = original.w - dx; |
| 3956 | x = original.x + dx; |
| 3957 | } |
| 3958 | if (drag.dir.includes('n')) { |
| 3959 | h = original.h - dy; |
| 3960 | y = original.y + dy; |
| 3961 | } |
| 3962 | w = clamp(w, 2, 100); h = clamp(h, 2, 100); |
| 3963 | x = clamp(x, 0, 100 - w); y = clamp(y, 0, 100 - h); |
| 3964 | if (drag.dir.includes('w') && x + w > 100) w = 100 - x; |
| 3965 | if (drag.dir.includes('n') && y + h > 100) h = 100 - y; |
| 3966 | element.x = x; element.y = y; element.w = w; element.h = h; |
| 3967 | } |
| 3968 | applyElementStyles(element); |
| 3969 | } |
| 3970 | |
| 3971 | function onDragEnd() { |
| 3972 | window.removeEventListener('pointermove', onDragMove); |
| 3973 | window.removeEventListener('pointerup', onDragEnd); |
| 3974 | document.body.style.cursor = ''; |
| 3975 | if (!drag) return; |
| 3976 | drag = null; |
| 3977 | renderSelection(); |
| 3978 | renderInspector(); |
| 3979 | scheduleThumbs(); |
| 3980 | scheduleSave(); |
| 3981 | } |
| 3982 | |
| 3983 | // ==================== Инспектор: ввод ==================== |
| 3984 | function setPath(target, path, value) { |
| 3985 | const parts = path.split('.'); |
| 3986 | let cursor = target; |
| 3987 | for (let i = 0; i < parts.length - 1; i += 1) { |
| 3988 | if (!cursor[parts[i]] || typeof cursor[parts[i]] !== 'object') cursor[parts[i]] = {}; |
| 3989 | cursor = cursor[parts[i]]; |
| 3990 | } |
| 3991 | cursor[parts[parts.length - 1]] = value; |
| 3992 | } |
| 3993 | |
| 3994 | function handleInspectorInput(input, commit) { |
| 3995 | const prop = input.dataset.prop; |
| 3996 | if (!prop) return; |
| 3997 | const slide = currentSlide(); |
| 3998 | const target = prop.startsWith('background.') || ['notes', 'lua', 'transition'].includes(prop) |
| 3999 | ? slide |
| 4000 | : selectedElement(); |
| 4001 | if (!target) return; |
| 4002 | |
| 4003 | let value; |
| 4004 | if (input.type === 'checkbox') value = input.checked; |
| 4005 | else if (input.type === 'number' || input.type === 'range') { |
| 4006 | if (input.value === '') return; |
| 4007 | value = Number(input.value); |
| 4008 | } else value = input.value; |
| 4009 | |
| 4010 | if (prop === 'volume') value = clamp(Number(value) / 100, 0, 1); |
| 4011 | if (prop === 'opacity') value = clamp(Number(value) / 100, 0, 1); |
| 4012 | if (prop === 'action.slideIndex') value = Number(value) || 0; |
| 4013 | |
| 4014 | setPath(target, prop, value); |
| 4015 | if (prop === 'action.type') { |
| 4016 | if (value === 'lua') ensureScriptNode(target, currentSlide()); |
| 4017 | if (target && target.type === 'button' && target.action) { |
| 4018 | if (value === 'go') { |
| 4019 | target.action.audioId = ''; |
| 4020 | target.action.code = ''; |
| 4021 | target.action.scriptNodeId = ''; |
| 4022 | } else if (value === 'play' || value === 'stop') { |
| 4023 | target.action.code = ''; |
| 4024 | target.action.scriptNodeId = ''; |
| 4025 | } else if (value === 'lua') { |
| 4026 | target.action.audioId = ''; |
| 4027 | } else { |
| 4028 | target.action.audioId = ''; |
| 4029 | target.action.code = ''; |
| 4030 | target.action.scriptNodeId = ''; |
| 4031 | } |
| 4032 | } |
| 4033 | } |
| 4034 | if (target && target.type === 'button' && ['action.type', 'action.slideIndex', 'action.audioId'].includes(prop)) { |
| 4035 | syncButtonLink(target); |
| 4036 | } |
| 4037 | if (prop === 'action.code' && target && target.type === 'button') { |
| 4038 | const node = target.action && target.action.scriptNodeId |
| 4039 | ? findScriptNode(target.action.scriptNodeId) |
| 4040 | : scriptNodeForElement(target.id); |
| 4041 | if (node) node.code = value; |
| 4042 | } |
| 4043 | if (prop === 'targetId') { |
| 4044 | const found = state.windowTargets.find((item) => item.id === value); |
| 4045 | target.targetTitle = found ? found.title : ''; |
| 4046 | } |
| 4047 | if (prop === 'label' && target && target.type === 'button' && target.action && target.action.scriptNodeId) { |
| 4048 | const node = findScriptNode(target.action.scriptNodeId); |
| 4049 | if (node && /^Lua · /.test(node.name || '')) node.name = `Lua · ${value || 'Кнопка'}`; |
| 4050 | } |
| 4051 | renderCanvas(); |
| 4052 | scheduleThumbs(); |
| 4053 | scheduleSave(); |
| 4054 | if (commit) { |
| 4055 | if (prop === 'action.type' || prop === 'background.type' || prop === 'text') renderInspector(); |
| 4056 | } |
| 4057 | } |
| 4058 | |
| 4059 | function handleNodeInput(input, commit) { |
| 4060 | const selected = state.selectedNode; |
| 4061 | if (!selected) return; |
| 4062 | const prop = input.dataset.nodeProp; |
| 4063 | |
| 4064 | if (selected.type === 'script') { |
| 4065 | const node = findScriptNode(selected.id); |
| 4066 | if (!node) return; |
| 4067 | if (prop === 'name') node.name = input.value; |
| 4068 | if (prop === 'code') { |
| 4069 | node.code = input.value; |
| 4070 | applyScriptNodeToElement(node); |
| 4071 | renderCanvas(); |
| 4072 | scheduleThumbs(); |
| 4073 | } |
| 4074 | if (commit) renderGraph(); |
| 4075 | } else if (selected.type === 'variable') { |
| 4076 | const node = findVariableNode(selected.id); |
| 4077 | if (!node) return; |
| 4078 | if (prop === 'name') { |
| 4079 | renameVariableNode(node, input.value); |
| 4080 | applyGraphLinks(); |
| 4081 | renderCanvas(); |
| 4082 | scheduleThumbs(); |
| 4083 | } |
| 4084 | if (commit) renderAll(); |
| 4085 | } else if (selected.type === 'transition') { |
| 4086 | const node = findTransitionNode(selected.id); |
| 4087 | if (!node) return; |
| 4088 | if (prop === 'name') node.name = input.value; |
| 4089 | if (prop === 'code') node.code = input.value; |
| 4090 | if (prop === 'slideId') node.slideId = input.value; |
| 4091 | if (commit) renderGraph(); |
| 4092 | } else if (selected.type === 'anim') { |
| 4093 | const node = findAnimNode(selected.id); |
| 4094 | if (!node) return; |
| 4095 | if (prop === 'name') node.name = input.value; |
| 4096 | if (prop === 'code') node.code = input.value; |
| 4097 | if (prop === 'slideId') node.slideId = input.value; |
| 4098 | if (prop === 'elementId') node.elementId = input.value; |
| 4099 | if (commit) renderGraph(); |
| 4100 | } else if (selected.type === 'audio') { |
| 4101 | const node = findAudioNode(selected.id); |
| 4102 | if (!node) return; |
| 4103 | if (prop === 'name') node.name = input.value; |
| 4104 | if (prop === 'elementId') { |
| 4105 | node.elementId = input.value; |
| 4106 | const found = findAudioElement(input.value); |
| 4107 | if (found) node.name = found.element.label || node.name; |
| 4108 | } |
| 4109 | if (prop === 'mode') node.mode = input.value === 'stop' ? 'stop' : 'play'; |
| 4110 | applyGraphLinks(); |
| 4111 | if (commit) renderAll(); |
| 4112 | } else if (selected.type === 'plugin') { |
| 4113 | const node = findPluginNode(selected.id); |
| 4114 | if (!node) return; |
| 4115 | if (prop === 'name') node.name = input.value; |
| 4116 | if (prop === 'args') node.args = input.value; |
| 4117 | if (prop === 'pluginId') { |
| 4118 | const plugin = pluginById(input.value); |
| 4119 | node.pluginId = input.value; |
| 4120 | if (plugin) { |
| 4121 | const fn = pluginFunction(plugin, node.fn) || (plugin.nodes || [])[0]; |
| 4122 | node.fn = fn ? fn.fn : ''; |
| 4123 | node.name = fn ? `${plugin.name} · ${fn.name || fn.fn}` : plugin.name; |
| 4124 | node.description = (fn && fn.description) || plugin.description || ''; |
| 4125 | node.color = plugin.color || node.color; |
| 4126 | node.code = plugin.code || ''; |
| 4127 | } |
| 4128 | } |
| 4129 | if (prop === 'fn') { |
| 4130 | const plugin = pluginById(node.pluginId); |
| 4131 | const fn = pluginFunction(plugin, input.value); |
| 4132 | node.fn = input.value; |
| 4133 | if (fn) { |
| 4134 | node.name = `${plugin.name} · ${fn.name || fn.fn}`; |
| 4135 | node.description = fn.description || plugin.description || ''; |
| 4136 | } |
| 4137 | } |
| 4138 | if (commit) renderAll(); |
| 4139 | } |
| 4140 | scheduleSave(); |
| 4141 | } |
| 4142 | |
| 4143 | function attachScriptToButton(node, value) { |
| 4144 | const previous = findLinkedElement(node); |
| 4145 | if (previous) { |
| 4146 | previous.element.action = { ...(previous.element.action || {}), scriptNodeId: '' }; |
| 4147 | } |
| 4148 | if (!value) { |
| 4149 | node.slideId = ''; |
| 4150 | node.elementId = ''; |
| 4151 | renderAll(); |
| 4152 | scheduleSave(); |
| 4153 | return; |
| 4154 | } |
| 4155 | const [slideId, elementId] = value.split('|'); |
| 4156 | const slide = state.slides.find((item) => item.id === slideId); |
| 4157 | const element = slide && (slide.elements || []).find((item) => item.id === elementId); |
| 4158 | if (!element) return; |
| 4159 | const otherId = element.action && element.action.scriptNodeId; |
| 4160 | if (otherId && otherId !== node.id) { |
| 4161 | const other = findScriptNode(otherId); |
| 4162 | if (other) { |
| 4163 | other.slideId = ''; |
| 4164 | other.elementId = ''; |
| 4165 | } |
| 4166 | } |
| 4167 | if (!String(node.code || '').trim() && element.action && element.action.code) { |
| 4168 | node.code = element.action.code; |
| 4169 | } |
| 4170 | node.slideId = slide.id; |
| 4171 | node.elementId = element.id; |
| 4172 | element.action = { |
| 4173 | ...(element.action || {}), |
| 4174 | type: 'lua', |
| 4175 | scriptNodeId: node.id, |
| 4176 | code: node.code, |
| 4177 | }; |
| 4178 | syncButtonLink(element); |
| 4179 | renderAll(); |
| 4180 | scheduleSave(); |
| 4181 | } |
| 4182 | |
| 4183 | function cleanupElementLinks(elementId) { |
| 4184 | state.graph.links = state.graph.links.filter((link) => { |
| 4185 | if (link.from.kind === 'slide' && link.from.port === `btn:${elementId}`) return false; |
| 4186 | if (link.to.kind === 'slide' && link.to.port.startsWith(`var:${elementId}:`)) return false; |
| 4187 | return true; |
| 4188 | }); |
| 4189 | const audioNodes = state.graph.audios.filter((node) => node.elementId === elementId); |
| 4190 | audioNodes.forEach((node) => { |
| 4191 | state.graph.links = state.graph.links.filter((link) => |
| 4192 | !(link.from.kind === 'audio' && link.from.id === node.id) |
| 4193 | && !(link.to.kind === 'audio' && link.to.id === node.id) |
| 4194 | ); |
| 4195 | }); |
| 4196 | state.graph.audios = state.graph.audios.filter((node) => node.elementId !== elementId); |
| 4197 | rebuildJumps(); |
| 4198 | } |
| 4199 | |
| 4200 | function cleanupSlideLinks(slide) { |
| 4201 | if (!slide) return; |
| 4202 | (slide.elements || []).forEach((element) => cleanupElementLinks(element.id)); |
| 4203 | state.graph.links = state.graph.links.filter((link) => |
| 4204 | !(link.from.kind === 'slide' && link.from.id === slide.id) |
| 4205 | && !(link.to.kind === 'slide' && link.to.id === slide.id) |
| 4206 | ); |
| 4207 | delete state.graph.positions[slide.id]; |
| 4208 | rebuildJumps(); |
| 4209 | } |
| 4210 | |
| 4211 | function deleteTransitionNode(node) { |
| 4212 | state.graph.links = state.graph.links.filter((link) => |
| 4213 | !(link.from.kind === 'transition' && link.from.id === node.id) |
| 4214 | && !(link.to.kind === 'transition' && link.to.id === node.id) |
| 4215 | ); |
| 4216 | state.graph.transitions = (state.graph.transitions || []).filter((item) => item.id !== node.id); |
| 4217 | const slide = currentSlide(); |
| 4218 | state.selectedNode = slide ? { type: 'slide', id: slide.id } : null; |
| 4219 | rebuildJumps(); |
| 4220 | renderAll(); |
| 4221 | scheduleSave(true); |
| 4222 | toast('Нода перехода удалена'); |
| 4223 | } |
| 4224 | |
| 4225 | function deleteAnimNode(node) { |
| 4226 | state.graph.links = state.graph.links.filter((link) => |
| 4227 | !(link.from.kind === 'anim' && link.from.id === node.id) |
| 4228 | && !(link.to.kind === 'anim' && link.to.id === node.id) |
| 4229 | ); |
| 4230 | state.graph.anims = (state.graph.anims || []).filter((item) => item.id !== node.id); |
| 4231 | const slide = currentSlide(); |
| 4232 | state.selectedNode = slide ? { type: 'slide', id: slide.id } : null; |
| 4233 | rebuildJumps(); |
| 4234 | renderAll(); |
| 4235 | scheduleSave(true); |
| 4236 | toast('Нода анимации удалена'); |
| 4237 | } |
| 4238 | |
| 4239 | function deleteScriptNode(node) { |
| 4240 | const linked = findLinkedElement(node); |
| 4241 | if (linked) { |
| 4242 | linked.element.action = { ...(linked.element.action || {}), type: 'none', scriptNodeId: '', code: '' }; |
| 4243 | } |
| 4244 | state.graph.links = state.graph.links.filter((link) => |
| 4245 | !(link.to.kind === 'script' && link.to.id === node.id) |
| 4246 | && !(linked && link.from.kind === 'slide' && link.from.port === `btn:${linked.element.id}`) |
| 4247 | ); |
| 4248 | state.graph.scripts = state.graph.scripts.filter((item) => item.id !== node.id); |
| 4249 | const slide = currentSlide(); |
| 4250 | state.selectedNode = slide ? { type: 'slide', id: slide.id } : null; |
| 4251 | renderAll(); |
| 4252 | scheduleSave(); |
| 4253 | toast('Нода удалена'); |
| 4254 | } |
| 4255 | |
| 4256 | function addScriptNode() { |
| 4257 | const base = state.graph.positions[currentSlide().id] || graphDefaultPosition(state.selected); |
| 4258 | const spot = findFreeNodeSpot(base.x + 320, base.y + 140, 'script', ''); |
| 4259 | const node = { |
| 4260 | id: uid(), |
| 4261 | name: 'Lua-скрипт', |
| 4262 | code: '', |
| 4263 | x: spot.x, |
| 4264 | y: spot.y, |
| 4265 | slideId: '', |
| 4266 | elementId: '', |
| 4267 | }; |
| 4268 | state.graph.scripts.push(node); |
| 4269 | state.selectedNode = { type: 'script', id: node.id }; |
| 4270 | if (state.view !== 'graph') setView('graph'); |
| 4271 | else renderAll(); |
| 4272 | scheduleSave(); |
| 4273 | toast('Добавлена нода кода'); |
| 4274 | } |
| 4275 | |
| 4276 | const DEFAULT_TRANSITION_LUA = [ |
| 4277 | '-- Кастомный переход: in — новый слайд, out — старый', |
| 4278 | "anim.play('out', { opacity = {1, 0}, scale = {1, 1.05} }, { duration = 320 })", |
| 4279 | "anim.play('in', { opacity = {0, 1}, y = {5, 0} }, { duration = 520, delay = 100 })", |
| 4280 | ].join('\n'); |
| 4281 | const DEFAULT_ANIM_LUA = [ |
| 4282 | '-- Анимация при входе на слайд. Цели: id элемента, slide, in, out', |
| 4283 | "anim.play('slide', { opacity = {0, 1}, scale = {0.97, 1} }, { duration = 450 })", |
| 4284 | '-- sleep(200) — пауза между шагами', |
| 4285 | ].join('\n'); |
| 4286 | |
| 4287 | function addTransitionNode() { |
| 4288 | const slide = currentSlide(); |
| 4289 | const base = (slide && state.graph.positions[slide.id]) || graphDefaultPosition(state.selected); |
| 4290 | const spot = findFreeNodeSpot(base.x + 320, base.y + 330, 'transition', ''); |
| 4291 | const node = { |
| 4292 | id: uid(), |
| 4293 | name: 'Переход', |
| 4294 | code: DEFAULT_TRANSITION_LUA, |
| 4295 | slideId: slide ? slide.id : '', |
| 4296 | x: spot.x, |
| 4297 | y: spot.y, |
| 4298 | }; |
| 4299 | state.graph.transitions.push(node); |
| 4300 | state.selectedNode = { type: 'transition', id: node.id }; |
| 4301 | if (state.view !== 'graph') setView('graph'); |
| 4302 | else renderAll(); |
| 4303 | scheduleSave(true); |
| 4304 | toast('Добавлена нода перехода'); |
| 4305 | } |
| 4306 | |
| 4307 | function addAnimNode() { |
| 4308 | const slide = currentSlide(); |
| 4309 | const base = (slide && state.graph.positions[slide.id]) || graphDefaultPosition(state.selected); |
| 4310 | const spot = findFreeNodeSpot(base.x + 320, base.y + 500, 'anim', ''); |
| 4311 | const node = { |
| 4312 | id: uid(), |
| 4313 | name: 'Анимация', |
| 4314 | code: DEFAULT_ANIM_LUA, |
| 4315 | slideId: slide ? slide.id : '', |
| 4316 | elementId: state.selectedEl || '', |
| 4317 | x: spot.x, |
| 4318 | y: spot.y, |
| 4319 | }; |
| 4320 | state.graph.anims.push(node); |
| 4321 | state.selectedNode = { type: 'anim', id: node.id }; |
| 4322 | if (state.view !== 'graph') setView('graph'); |
| 4323 | else renderAll(); |
| 4324 | scheduleSave(true); |
| 4325 | toast('Добавлена нода анимации'); |
| 4326 | } |
| 4327 | |
| 4328 | function pluginById(id) { |
| 4329 | return (state.pluginRegistry || []).find((plugin) => plugin.id === id) || null; |
| 4330 | } |
| 4331 | |
| 4332 | function pluginFunction(plugin, fn) { |
| 4333 | return ((plugin && plugin.nodes) || []).find((node) => node.fn === fn) || null; |
| 4334 | } |
| 4335 | |
| 4336 | // Создаёт экземпляр ноды плагина. В ноду кладём снимок кода модуля. |
| 4337 | function addPluginNode(pluginId, fn, position) { |
| 4338 | const plugin = pluginById(pluginId); |
| 4339 | if (!plugin) { |
| 4340 | toast('Плагин не найден в реестре'); |
| 4341 | return null; |
| 4342 | } |
| 4343 | const functions = plugin.nodes || []; |
| 4344 | const selected = pluginFunction(plugin, fn) || functions[0]; |
| 4345 | if (!selected) { |
| 4346 | toast('В плагине нет функций-нод'); |
| 4347 | return null; |
| 4348 | } |
| 4349 | const base = (currentSlide() && state.graph.positions[currentSlide().id]) || graphDefaultPosition(state.selected); |
| 4350 | const x = position ? position.x : base.x + 360; |
| 4351 | const y = position ? position.y : base.y + 180 + state.graph.plugins.length * 20; |
| 4352 | const spot = findFreeNodeSpot(x, y, 'plugin', ''); |
| 4353 | const node = { |
| 4354 | id: uid(), |
| 4355 | pluginId: plugin.id, |
| 4356 | fn: selected.fn, |
| 4357 | name: `${plugin.name} · ${selected.name || selected.fn}`, |
| 4358 | description: selected.description || plugin.description || '', |
| 4359 | color: plugin.color || '#f97316', |
| 4360 | code: plugin.code || '', |
| 4361 | args: '', |
| 4362 | x: spot.x, |
| 4363 | y: spot.y, |
| 4364 | }; |
| 4365 | state.graph.plugins = state.graph.plugins || []; |
| 4366 | state.graph.plugins.push(node); |
| 4367 | state.selectedNode = { type: 'plugin', id: node.id }; |
| 4368 | if (state.view !== 'graph') setView('graph'); |
| 4369 | else renderAll(); |
| 4370 | scheduleSave(true); |
| 4371 | toast(`Нода плагина «${selected.name || selected.fn}» добавлена`); |
| 4372 | return node; |
| 4373 | } |
| 4374 | |
| 4375 | function deletePluginNode(node) { |
| 4376 | state.graph.links = state.graph.links.filter((link) => |
| 4377 | !(link.from.kind === 'plugin' && link.from.id === node.id) |
| 4378 | && !(link.to.kind === 'plugin' && link.to.id === node.id) |
| 4379 | ); |
| 4380 | state.graph.plugins = (state.graph.plugins || []).filter((item) => item.id !== node.id); |
| 4381 | const slide = currentSlide(); |
| 4382 | state.selectedNode = slide ? { type: 'slide', id: slide.id } : null; |
| 4383 | rebuildJumps(); |
| 4384 | renderAll(); |
| 4385 | scheduleSave(); |
| 4386 | toast('Нода плагина удалена'); |
| 4387 | } |
| 4388 | |
| 4389 | function addVariableNode() { |
| 4390 | const base = currentSlide() ? state.graph.positions[currentSlide().id] : { x: 340, y: 60 }; |
| 4391 | let index = state.graph.variables.length + 1; |
| 4392 | let name = `var${index}`; |
| 4393 | while (findVariableByName(name)) { |
| 4394 | index += 1; |
| 4395 | name = `var${index}`; |
| 4396 | } |
| 4397 | const spot = findFreeNodeSpot( |
| 4398 | Math.max(20, (base ? base.x : 340) - 300), |
| 4399 | (base ? base.y : 60) + 20 + state.graph.variables.length * 120, |
| 4400 | 'variable', |
| 4401 | '' |
| 4402 | ); |
| 4403 | const node = { |
| 4404 | id: uid(), |
| 4405 | name, |
| 4406 | x: spot.x, |
| 4407 | y: spot.y, |
| 4408 | }; |
| 4409 | state.graph.variables.push(node); |
| 4410 | const element = selectedElement(); |
| 4411 | if (element && element.type === 'text') { |
| 4412 | bindElementVariable(element.id, name); |
| 4413 | } else if (state.view !== 'graph') { |
| 4414 | setView('graph'); |
| 4415 | } else { |
| 4416 | renderAll(); |
| 4417 | } |
| 4418 | state.selectedNode = { type: 'variable', id: node.id }; |
| 4419 | renderAll(); |
| 4420 | scheduleSave(); |
| 4421 | toast('Добавлена нода переменной'); |
| 4422 | } |
| 4423 | |
| 4424 | function addAudioNode() { |
| 4425 | const found = []; |
| 4426 | state.slides.forEach((slide) => (slide.elements || []).forEach((element) => { |
| 4427 | if (element.type === 'audio') found.push(element); |
| 4428 | })); |
| 4429 | if (!found.length) { |
| 4430 | toast('Сначала добавьте аудио-элемент на слайд'); |
| 4431 | return; |
| 4432 | } |
| 4433 | const node = ensureAudioNode(found[0].id, 'play'); |
| 4434 | const base = state.graph.positions[currentSlide().id] || { x: 340, y: 60 }; |
| 4435 | const spot = findFreeNodeSpot(base.x + 330, base.y + 200 + (state.graph.audios.length % 3) * 96, 'audio', node.id); |
| 4436 | node.x = spot.x; |
| 4437 | node.y = spot.y; |
| 4438 | state.selectedNode = { type: 'audio', id: node.id }; |
| 4439 | if (state.view !== 'graph') setView('graph'); |
| 4440 | else renderAll(); |
| 4441 | scheduleSave(); |
| 4442 | toast('Добавлена аудио-нода'); |
| 4443 | } |
| 4444 | |
| 4445 | function bindElementVariable(elementId, name) { |
| 4446 | const slide = currentSlide(); |
| 4447 | const element = slide && (slide.elements || []).find((item) => item.id === elementId); |
| 4448 | if (!element) return; |
| 4449 | const varName = String(name || '').trim(); |
| 4450 | state.graph.links = state.graph.links.filter((link) => |
| 4451 | !(link.to.kind === 'slide' && link.to.id === slide.id && link.to.port.startsWith(`var:${elementId}:`)) |
| 4452 | ); |
| 4453 | if (!varName) { |
| 4454 | element.text = String(element.text || '').replace(/\{\{\s*[\w.-]+\s*\}\}/g, '').trim(); |
| 4455 | renderAll(); |
| 4456 | scheduleThumbs(); |
| 4457 | scheduleSave(); |
| 4458 | return; |
| 4459 | } |
| 4460 | const text = String(element.text || ''); |
| 4461 | if (/\{\{\s*[\w.-]+\s*\}\}/.test(text)) { |
| 4462 | element.text = text.replace(/\{\{\s*[\w.-]+\s*\}\}/g, `{{${varName}}}`); |
| 4463 | } else { |
| 4464 | element.text = `${text}${text ? ' ' : ''}{{${varName}}}`; |
| 4465 | } |
| 4466 | const variable = ensureVariableNode(varName); |
| 4467 | pushLink( |
| 4468 | { kind: 'variable', id: variable.id, port: 'value' }, |
| 4469 | { kind: 'slide', id: slide.id, port: `var:${elementId}:${varName}` } |
| 4470 | ); |
| 4471 | renderAll(); |
| 4472 | scheduleThumbs(); |
| 4473 | scheduleSave(); |
| 4474 | toast(`Текст привязан к {{${varName}}}`); |
| 4475 | } |
| 4476 | |
| 4477 | function deleteAudioNode(node) { |
| 4478 | state.graph.links = state.graph.links.filter((link) => |
| 4479 | !(link.from.kind === 'audio' && link.from.id === node.id) && !(link.to.kind === 'audio' && link.to.id === node.id) |
| 4480 | ); |
| 4481 | state.graph.audios = state.graph.audios.filter((item) => item.id !== node.id); |
| 4482 | if (node.elementId) { |
| 4483 | state.slides.forEach((slide) => { |
| 4484 | (slide.elements || []).forEach((element) => { |
| 4485 | if (element.type !== 'button' || !element.action) return; |
| 4486 | if ((element.action.type === 'play' || element.action.type === 'stop') && element.action.audioId === node.elementId) { |
| 4487 | element.action = { ...element.action, type: 'none', audioId: '', scriptNodeId: '' }; |
| 4488 | } |
| 4489 | }); |
| 4490 | }); |
| 4491 | } |
| 4492 | const slide = currentSlide(); |
| 4493 | state.selectedNode = slide ? { type: 'slide', id: slide.id } : null; |
| 4494 | renderAll(); |
| 4495 | scheduleSave(); |
| 4496 | toast('Аудио-нода удалена'); |
| 4497 | } |
| 4498 | |
| 4499 | function deleteVariableNode(node) { |
| 4500 | state.graph.links |
| 4501 | .filter((link) => link.from.kind === 'variable' && link.from.id === node.id) |
| 4502 | .forEach((link) => { |
| 4503 | if (link.to.kind !== 'slide' || !link.to.port.startsWith('var:')) return; |
| 4504 | const parts = link.to.port.split(':'); |
| 4505 | if (parts.length >= 3) removeVarPlaceholder(parts[1], parts.slice(2).join(':')); |
| 4506 | }); |
| 4507 | state.graph.links = state.graph.links.filter((link) => |
| 4508 | !(link.from.kind === 'variable' && link.from.id === node.id) && !(link.to.kind === 'variable' && link.to.id === node.id) |
| 4509 | ); |
| 4510 | state.graph.variables = state.graph.variables.filter((item) => item.id !== node.id); |
| 4511 | const slide = currentSlide(); |
| 4512 | state.selectedNode = slide ? { type: 'slide', id: slide.id } : null; |
| 4513 | renderAll(); |
| 4514 | scheduleThumbs(); |
| 4515 | scheduleSave(); |
| 4516 | toast('Нода переменной удалена'); |
| 4517 | } |
| 4518 | |
| 4519 | inspectorEl.addEventListener('input', (event) => { |
| 4520 | const input = event.target; |
| 4521 | if (input.dataset && input.dataset.nodeProp) handleNodeInput(input); |
| 4522 | else if (input.dataset && input.dataset.prop) handleInspectorInput(input, false); |
| 4523 | }); |
| 4524 | |
| 4525 | inspectorEl.addEventListener('change', (event) => { |
| 4526 | const input = event.target; |
| 4527 | if (input.dataset && input.dataset.nodeProp) { |
| 4528 | handleNodeInput(input, true); |
| 4529 | return; |
| 4530 | } |
| 4531 | if (input.dataset && input.dataset.varBind) { |
| 4532 | bindElementVariable(input.dataset.varBind, input.value); |
| 4533 | return; |
| 4534 | } |
| 4535 | if (input.matches('[data-upload="video"]')) { |
| 4536 | const file = input.files && input.files[0]; |
| 4537 | if (file) uploadVideo(file); |
| 4538 | return; |
| 4539 | } |
| 4540 | if (input.matches('[data-upload="image"]')) { |
| 4541 | const file = input.files && input.files[0]; |
| 4542 | if (file) uploadImage(file); |
| 4543 | return; |
| 4544 | } |
| 4545 | if (input.matches('[data-upload="background"]')) { |
| 4546 | const file = input.files && input.files[0]; |
| 4547 | if (file) uploadBackground(file); |
| 4548 | return; |
| 4549 | } |
| 4550 | if (input.matches('[data-node-link]')) { |
| 4551 | const node = state.selectedNode && state.selectedNode.type === 'script' |
| 4552 | ? findScriptNode(state.selectedNode.id) |
| 4553 | : null; |
| 4554 | if (node) attachScriptToButton(node, input.value); |
| 4555 | return; |
| 4556 | } |
| 4557 | if (input.dataset && input.dataset.prop) handleInspectorInput(input, true); |
| 4558 | }); |
| 4559 | |
| 4560 | async function uploadFile(file) { |
| 4561 | const response = await fetch(`/api/uploads?name=${encodeURIComponent(file.name)}`, { |
| 4562 | method: 'POST', |
| 4563 | headers: { 'Content-Type': file.type || 'application/octet-stream' }, |
| 4564 | body: file, |
| 4565 | }); |
| 4566 | if (!response.ok) throw new Error(`HTTP ${response.status}`); |
| 4567 | return response.json(); |
| 4568 | } |
| 4569 | |
| 4570 | async function uploadVideo(file) { |
| 4571 | const element = selectedElement(); |
| 4572 | if (!element || element.type !== 'video') return; |
| 4573 | toast(`Загрузка «${file.name}»…`); |
| 4574 | try { |
| 4575 | const data = await uploadFile(file); |
| 4576 | element.src = data.url; |
| 4577 | renderCanvas(); |
| 4578 | renderInspector(); |
| 4579 | scheduleThumbs(); |
| 4580 | scheduleSave(); |
| 4581 | const mb = Math.round(((data.size || 0) / 1024 / 1024) * 10) / 10; |
| 4582 | toast(`Видео загружено · ${mb} МБ`); |
| 4583 | } catch (error) { |
| 4584 | toast('Не удалось загрузить видео'); |
| 4585 | } |
| 4586 | } |
| 4587 | |
| 4588 | async function uploadImage(file) { |
| 4589 | const element = selectedElement(); |
| 4590 | if (!element || element.type !== 'image') return; |
| 4591 | toast(`Загрузка «${file.name}»…`); |
| 4592 | try { |
| 4593 | const data = await uploadFile(file); |
| 4594 | element.src = data.url; |
| 4595 | renderCanvas(); |
| 4596 | renderInspector(); |
| 4597 | scheduleThumbs(); |
| 4598 | scheduleSave(); |
| 4599 | toast('Изображение загружено'); |
| 4600 | } catch (error) { |
| 4601 | toast('Не удалось загрузить изображение'); |
| 4602 | } |
| 4603 | } |
| 4604 | |
| 4605 | async function uploadBackground(file) { |
| 4606 | const slide = currentSlide(); |
| 4607 | toast(`Загрузка «${file.name}»…`); |
| 4608 | try { |
| 4609 | const data = await uploadFile(file); |
| 4610 | slide.background = slide.background || defaultBackground(); |
| 4611 | slide.background.type = 'image'; |
| 4612 | slide.background.image = data.url; |
| 4613 | renderCanvas(); |
| 4614 | renderInspector(); |
| 4615 | scheduleThumbs(); |
| 4616 | scheduleSave(); |
| 4617 | toast('Фон загружен'); |
| 4618 | } catch (error) { |
| 4619 | toast('Не удалось загрузить фон'); |
| 4620 | } |
| 4621 | } |
| 4622 | |
| 4623 | inspectorEl.addEventListener('click', (event) => { |
| 4624 | const bgType = event.target.closest('[data-bgtype]'); |
| 4625 | if (bgType) { |
| 4626 | const slide = currentSlide(); |
| 4627 | slide.background = slide.background || defaultBackground(); |
| 4628 | slide.background.type = bgType.dataset.bgtype; |
| 4629 | if (slide.background.type === 'gradient' && !slide.background.gradient) slide.background.gradient = DEFAULT_GRADIENT; |
| 4630 | renderCanvas(); |
| 4631 | renderInspector(); |
| 4632 | scheduleThumbs(); |
| 4633 | scheduleSave(); |
| 4634 | return; |
| 4635 | } |
| 4636 | |
| 4637 | const preset = event.target.closest('[data-bgpreset]'); |
| 4638 | if (preset) { |
| 4639 | const slide = currentSlide(); |
| 4640 | slide.background = slide.background || defaultBackground(); |
| 4641 | slide.background.type = 'gradient'; |
| 4642 | slide.background.gradient = preset.dataset.bgpreset; |
| 4643 | renderCanvas(); |
| 4644 | renderInspector(); |
| 4645 | scheduleThumbs(); |
| 4646 | scheduleSave(); |
| 4647 | return; |
| 4648 | } |
| 4649 | |
| 4650 | const fillSwatch = event.target.closest('[data-fill]'); |
| 4651 | if (fillSwatch) { |
| 4652 | const element = selectedElement(); |
| 4653 | if (element && element.type === 'shape') { |
| 4654 | element.fill = fillSwatch.dataset.fill; |
| 4655 | renderCanvas(); |
| 4656 | renderInspector(); |
| 4657 | scheduleThumbs(); |
| 4658 | scheduleSave(); |
| 4659 | } |
| 4660 | return; |
| 4661 | } |
| 4662 | |
| 4663 | const bgColor = event.target.closest('[data-bgcolor]'); |
| 4664 | if (bgColor) { |
| 4665 | const slide = currentSlide(); |
| 4666 | slide.background = slide.background || defaultBackground(); |
| 4667 | slide.background.type = 'color'; |
| 4668 | slide.background.color = bgColor.dataset.bgcolor; |
| 4669 | renderCanvas(); |
| 4670 | renderInspector(); |
| 4671 | scheduleThumbs(); |
| 4672 | scheduleSave(); |
| 4673 | return; |
| 4674 | } |
| 4675 | |
| 4676 | const actionBtn = event.target.closest('[data-act]'); |
| 4677 | if (!actionBtn) return; |
| 4678 | const act = actionBtn.dataset.act; |
| 4679 | const element = selectedElement(); |
| 4680 | const selected = state.selectedNode; |
| 4681 | const scriptNode = selected && selected.type === 'script' ? findScriptNode(selected.id) : null; |
| 4682 | const variableNode = selected && selected.type === 'variable' ? findVariableNode(selected.id) : null; |
| 4683 | const audioNode = selected && selected.type === 'audio' ? findAudioNode(selected.id) : null; |
| 4684 | const transitionNode = selected && selected.type === 'transition' ? findTransitionNode(selected.id) : null; |
| 4685 | const animNode = selected && selected.type === 'anim' ? findAnimNode(selected.id) : null; |
| 4686 | const pluginNode = selected && selected.type === 'plugin' ? findPluginNode(selected.id) : null; |
| 4687 | |
| 4688 | // Выравнивание выбранного элемента по слайду |
| 4689 | if (act.startsWith('align-') && element) { |
| 4690 | pushHistory(true); |
| 4691 | if (act === 'align-left') element.x = 4; |
| 4692 | if (act === 'align-right') element.x = 96 - element.w; |
| 4693 | if (act === 'align-hcenter') element.x = (100 - element.w) / 2; |
| 4694 | if (act === 'align-top') element.y = 4; |
| 4695 | if (act === 'align-bottom') element.y = 96 - element.h; |
| 4696 | if (act === 'align-vcenter') element.y = (100 - element.h) / 2; |
| 4697 | renderCanvas(); |
| 4698 | renderInspector(); |
| 4699 | scheduleThumbs(); |
| 4700 | scheduleSave(true); |
| 4701 | return; |
| 4702 | } |
| 4703 | |
| 4704 | if (act === 'video-upload') { |
| 4705 | const input = inspectorEl.querySelector('[data-upload="video"]'); |
| 4706 | if (input) input.click(); |
| 4707 | } else if (act === 'image-upload') { |
| 4708 | const input = inspectorEl.querySelector('[data-upload="image"]'); |
| 4709 | if (input) input.click(); |
| 4710 | } else if (act === 'bg-upload') { |
| 4711 | const input = inspectorEl.querySelector('[data-upload="background"]'); |
| 4712 | if (input) input.click(); |
| 4713 | } else if (act === 'window-refresh') { |
| 4714 | loadWindowTargets(true); |
| 4715 | } else if (act === 'graph-to-canvas' || act === 'node-open-canvas') { |
| 4716 | setView('canvas'); |
| 4717 | } else if (act === 'graph-add-script' || act === 'node-new-script') { |
| 4718 | addScriptNode(); |
| 4719 | } else if (act === 'graph-add-variable' || act === 'node-new-variable') { |
| 4720 | addVariableNode(); |
| 4721 | } else if (act === 'node-new-audio') { |
| 4722 | addAudioNode(); |
| 4723 | } else if (act === 'node-delete') { |
| 4724 | if (scriptNode) deleteScriptNode(scriptNode); |
| 4725 | else if (variableNode) deleteVariableNode(variableNode); |
| 4726 | else if (audioNode) deleteAudioNode(audioNode); |
| 4727 | else if (transitionNode) deleteTransitionNode(transitionNode); |
| 4728 | else if (animNode) deleteAnimNode(animNode); |
| 4729 | else if (pluginNode) deletePluginNode(pluginNode); |
| 4730 | } else if (act === 'plugin-new') { |
| 4731 | openPluginEditor(null); |
| 4732 | } else if (act === 'plugin-edit' || act === 'node-open-plugin') { |
| 4733 | openPluginEditor(pluginNode ? pluginNode.pluginId : null); |
| 4734 | } else if (act === 'node-new-plugin') { |
| 4735 | if (pluginNode) addPluginNode(pluginNode.pluginId, pluginNode.fn); |
| 4736 | else openPluginEditor(null); |
| 4737 | } else if (act === 'tree-toggle') { |
| 4738 | setTreeOpen(!state.tree.open || treePanel.classList.contains('collapsed')); |
| 4739 | } else if (act === 'tree-collapse') { |
| 4740 | setTreeOpen(false); |
| 4741 | } else if (act === 'open-tree') { |
| 4742 | setView('graph'); |
| 4743 | setTreeOpen(true); |
| 4744 | } else if (act === 'lua-compute' && element && element.type === 'lua') { |
| 4745 | computeLuaElement(element); |
| 4746 | } else if (act === 'lua-reset' && element && element.type === 'lua') { |
| 4747 | element.computed = { style: {}, css: '', html: '', text: '', at: 0 }; |
| 4748 | renderCanvas(); |
| 4749 | renderInspector(); |
| 4750 | scheduleThumbs(); |
| 4751 | scheduleSave(true); |
| 4752 | } else if (act === 'graph-add-transition') { |
| 4753 | addTransitionNode(); |
| 4754 | } else if (act === 'graph-add-anim') { |
| 4755 | addAnimNode(); |
| 4756 | } else if (act === 'node-open-slide' && scriptNode) { |
| 4757 | const linked = findLinkedElement(scriptNode); |
| 4758 | if (linked) { |
| 4759 | state.selected = state.slides.indexOf(linked.slide); |
| 4760 | state.selectedEl = linked.element.id; |
| 4761 | } |
| 4762 | setView('canvas'); |
| 4763 | renderAll(); |
| 4764 | } else if (act === 'el-delete' && element) { |
| 4765 | const node = element.action && element.action.scriptNodeId |
| 4766 | ? findScriptNode(element.action.scriptNodeId) |
| 4767 | : scriptNodeForElement(element.id); |
| 4768 | if (node) { |
| 4769 | node.slideId = ''; |
| 4770 | node.elementId = ''; |
| 4771 | } |
| 4772 | cleanupElementLinks(element.id); |
| 4773 | pushHistory(true); |
| 4774 | currentSlide().elements = currentSlide().elements.filter((item) => item.id !== element.id); |
| 4775 | state.selectedEl = null; |
| 4776 | renderCanvas(); |
| 4777 | renderInspector(); |
| 4778 | scheduleThumbs(); |
| 4779 | scheduleSave(true); |
| 4780 | } else if (act === 'el-duplicate' && element) { |
| 4781 | duplicateSelectedElement(); |
| 4782 | } else if (act === 'el-front' && element) { |
| 4783 | element.z = Math.max(0, ...currentSlide().elements.map((item) => Number(item.z) || 0)) + 1; |
| 4784 | renderCanvas(); |
| 4785 | scheduleThumbs(); |
| 4786 | scheduleSave(); |
| 4787 | } else if (act === 'el-back' && element) { |
| 4788 | element.z = Math.min(0, ...currentSlide().elements.map((item) => Number(item.z) || 0)) - 1; |
| 4789 | renderCanvas(); |
| 4790 | scheduleThumbs(); |
| 4791 | scheduleSave(); |
| 4792 | } else if (act === 'audio-preview' && element) { |
| 4793 | if (!element.src) { toast('Укажите URL аудио'); return; } |
| 4794 | if (window._previewAudio) { window._previewAudio.pause(); window._previewAudio = null; } |
| 4795 | const preview = new Audio(element.src); |
| 4796 | preview.volume = clamp(Number(element.volume) || 0.8, 0, 1); |
| 4797 | window._previewAudio = preview; |
| 4798 | preview.play().catch(() => toast('Не удалось воспроизвести аудио')); |
| 4799 | } else if (act === 'audio-to-music' && element) { |
| 4800 | if (!element.src) { toast('Укажите URL аудио'); return; } |
| 4801 | state.music.src = element.src; |
| 4802 | toast('Аудио назначено фоновой музыкой'); |
| 4803 | scheduleSave(); |
| 4804 | } |
| 4805 | }); |
| 4806 | |
| 4807 | // ==================== Верхняя панель / слайды ==================== |
| 4808 | document.querySelector('.toolbar').addEventListener('click', (event) => { |
| 4809 | const view = event.target.closest('[data-view]'); |
| 4810 | if (view) { setView(view.dataset.view); return; } |
| 4811 | const add = event.target.closest('[data-add]'); |
| 4812 | if (add) { addElement(add.dataset.add); return; } |
| 4813 | const action = event.target.closest('[data-act]'); |
| 4814 | if (!action) return; |
| 4815 | if (action.dataset.act === 'duplicate-slide') duplicateSlide(); |
| 4816 | if (action.dataset.act === 'move-up') moveSlide(-1); |
| 4817 | if (action.dataset.act === 'move-down') moveSlide(1); |
| 4818 | if (action.dataset.act === 'delete-slide') deleteSlide(); |
| 4819 | if (action.dataset.act === 'undo') undo(); |
| 4820 | if (action.dataset.act === 'redo') redo(); |
| 4821 | if (action.dataset.act === 'open-tree') { |
| 4822 | setView('graph'); |
| 4823 | setTreeOpen(true); |
| 4824 | } |
| 4825 | }); |
| 4826 | |
| 4827 | document.querySelector('.graph-toolbar').addEventListener('click', (event) => { |
| 4828 | const add = event.target.closest('[data-graph-add]'); |
| 4829 | if (add) { |
| 4830 | if (add.dataset.graphAdd === 'slide') addSlide(); |
| 4831 | if (add.dataset.graphAdd === 'script') addScriptNode(); |
| 4832 | if (add.dataset.graphAdd === 'audio') addAudioNode(); |
| 4833 | if (add.dataset.graphAdd === 'variable') addVariableNode(); |
| 4834 | if (add.dataset.graphAdd === 'transition') addTransitionNode(); |
| 4835 | if (add.dataset.graphAdd === 'anim') addAnimNode(); |
| 4836 | return; |
| 4837 | } |
| 4838 | const action = event.target.closest('[data-act]'); |
| 4839 | if (!action) return; |
| 4840 | if (action.dataset.act === 'plugin-new') openPluginEditor(null); |
| 4841 | if (action.dataset.act === 'plugin-edit') openPluginEditor(null); |
| 4842 | if (action.dataset.act === 'tree-toggle') setTreeOpen(!state.tree.open || treePanel.classList.contains('collapsed')); |
| 4843 | }); |
| 4844 | |
| 4845 | if (treePanel) { |
| 4846 | treePanel.addEventListener('click', (event) => { |
| 4847 | const tab = event.target.closest('[data-tree-tab]'); |
| 4848 | if (tab) { |
| 4849 | state.tree.tab = tab.dataset.treeTab === 'plugins' ? 'plugins' : 'base'; |
| 4850 | renderTree(); |
| 4851 | return; |
| 4852 | } |
| 4853 | const group = event.target.closest('[data-tree-group]'); |
| 4854 | if (group) { |
| 4855 | const id = group.dataset.treeGroup; |
| 4856 | state.tree.collapsed[id] = !state.tree.collapsed[id]; |
| 4857 | renderTree(); |
| 4858 | return; |
| 4859 | } |
| 4860 | const action = event.target.closest('[data-tree-action]'); |
| 4861 | if (!action) { |
| 4862 | const panelAction = event.target.closest('[data-act]'); |
| 4863 | if (panelAction) { |
| 4864 | if (panelAction.dataset.act === 'plugin-new') openPluginEditor(null); |
| 4865 | if (panelAction.dataset.act === 'plugin-edit') openPluginEditor(null); |
| 4866 | if (panelAction.dataset.act === 'tree-collapse') setTreeOpen(false); |
| 4867 | } |
| 4868 | return; |
| 4869 | } |
| 4870 | const act = action.dataset.treeAction; |
| 4871 | if (act === 'add-element') { |
| 4872 | addElement(action.dataset.kind); |
| 4873 | } else if (act === 'add-node') { |
| 4874 | applyTreeDrag({ kind: 'node', nodeKind: action.dataset.nodeKind }); |
| 4875 | } else if (act === 'add-plugin') { |
| 4876 | addPluginNode(action.dataset.pluginId, action.dataset.fn); |
| 4877 | } else if (act === 'toggle-plugin') { |
| 4878 | const id = action.dataset.pluginId; |
| 4879 | state.tree.plugins[id] = !state.tree.plugins[id]; |
| 4880 | renderTree(); |
| 4881 | } else if (act === 'edit-plugin') { |
| 4882 | openPluginEditor(action.dataset.pluginId); |
| 4883 | } else if (act === 'select-slide') { |
| 4884 | const index = state.slides.findIndex((slide) => slide.id === action.dataset.slideId); |
| 4885 | if (index >= 0) { |
| 4886 | state.selected = index; |
| 4887 | state.selectedEl = null; |
| 4888 | const slide = currentSlide(); |
| 4889 | state.selectedNode = slide ? { type: 'slide', id: slide.id } : null; |
| 4890 | renderAll(); |
| 4891 | } |
| 4892 | } else if (act === 'select-element') { |
| 4893 | const index = Number(action.dataset.slideIndex) || 0; |
| 4894 | state.selected = clamp(index, 0, state.slides.length - 1); |
| 4895 | state.selectedEl = action.dataset.elementId; |
| 4896 | setView('canvas'); |
| 4897 | renderAll(); |
| 4898 | } else if (act === 'select-node') { |
| 4899 | state.selectedNode = { type: action.dataset.nodeType, id: action.dataset.nodeId }; |
| 4900 | state.selectedLink = null; |
| 4901 | if (state.view !== 'graph') setView('graph'); |
| 4902 | else renderAll(); |
| 4903 | } |
| 4904 | }); |
| 4905 | } |
| 4906 | |
| 4907 | if (treeSearchEl) { |
| 4908 | treeSearchEl.addEventListener('input', () => { |
| 4909 | state.tree.query = treeSearchEl.value; |
| 4910 | renderTree(); |
| 4911 | }); |
| 4912 | } |
| 4913 | |
| 4914 | // Drag-and-drop из древа на холст и в граф. |
| 4915 | function treeDragPayload(event) { |
| 4916 | const item = event.target.closest('[data-drag-kind]'); |
| 4917 | if (!item) return null; |
| 4918 | const kind = item.dataset.dragKind; |
| 4919 | if (kind === 'element') return { kind, element: item.dataset.kind }; |
| 4920 | if (kind === 'node') return { kind, nodeKind: item.dataset.nodeKind }; |
| 4921 | if (kind === 'plugin') return { kind, pluginId: item.dataset.pluginId, fn: item.dataset.fn }; |
| 4922 | return null; |
| 4923 | } |
| 4924 | |
| 4925 | document.addEventListener('dragstart', (event) => { |
| 4926 | const payload = treeDragPayload(event); |
| 4927 | if (!payload) return; |
| 4928 | event.dataTransfer.effectAllowed = 'copy'; |
| 4929 | event.dataTransfer.setData('application/x-promptly', JSON.stringify(payload)); |
| 4930 | event.dataTransfer.setData('text/plain', JSON.stringify(payload)); |
| 4931 | }); |
| 4932 | |
| 4933 | function readDragPayload(event) { |
| 4934 | try { |
| 4935 | const raw = event.dataTransfer.getData('application/x-promptly') || event.dataTransfer.getData('text/plain'); |
| 4936 | if (raw) return JSON.parse(raw); |
| 4937 | } catch (error) { /* не наш drag */ } |
| 4938 | return null; |
| 4939 | } |
| 4940 | |
| 4941 | if (canvasWrap) { |
| 4942 | canvasWrap.addEventListener('dragover', (event) => { |
| 4943 | if (!readDragPayload(event) && !(event.dataTransfer && event.dataTransfer.types.includes('application/x-promptly'))) return; |
| 4944 | event.preventDefault(); |
| 4945 | event.dataTransfer.dropEffect = 'copy'; |
| 4946 | canvasWrap.classList.add('tree-drop'); |
| 4947 | }); |
| 4948 | canvasWrap.addEventListener('dragleave', () => canvasWrap.classList.remove('tree-drop')); |
| 4949 | canvasWrap.addEventListener('drop', (event) => { |
| 4950 | const payload = readDragPayload(event); |
| 4951 | canvasWrap.classList.remove('tree-drop'); |
| 4952 | if (!payload) return; |
| 4953 | event.preventDefault(); |
| 4954 | let point = null; |
| 4955 | if (payload.kind === 'element') { |
| 4956 | const rect = canvasEl.getBoundingClientRect(); |
| 4957 | point = { |
| 4958 | x: clamp(((event.clientX - rect.left) / rect.width) * 100, 0, 92), |
| 4959 | y: clamp(((event.clientY - rect.top) / rect.height) * 100, 0, 92), |
| 4960 | }; |
| 4961 | } |
| 4962 | if (state.view !== 'canvas') setView('canvas'); |
| 4963 | applyTreeDrag(payload, point); |
| 4964 | }); |
| 4965 | } |
| 4966 | |
| 4967 | if (graphScroll) { |
| 4968 | graphScroll.addEventListener('dragover', (event) => { |
| 4969 | event.preventDefault(); |
| 4970 | event.dataTransfer.dropEffect = 'copy'; |
| 4971 | graphScroll.classList.add('dragover'); |
| 4972 | }); |
| 4973 | graphScroll.addEventListener('dragleave', (event) => { |
| 4974 | if (event.target === graphScroll || !graphScroll.contains(event.relatedTarget)) graphScroll.classList.remove('dragover'); |
| 4975 | }); |
| 4976 | graphScroll.addEventListener('drop', (event) => { |
| 4977 | const payload = readDragPayload(event); |
| 4978 | graphScroll.classList.remove('dragover'); |
| 4979 | if (!payload) return; |
| 4980 | event.preventDefault(); |
| 4981 | const rect = graphWorld.getBoundingClientRect(); |
| 4982 | const point = { |
| 4983 | x: Math.max(20, event.clientX - rect.left - 60), |
| 4984 | y: Math.max(20, event.clientY - rect.top - 20), |
| 4985 | }; |
| 4986 | if (payload.kind === 'element') { |
| 4987 | // Элемент из древа на граф: добавляем на текущий слайд, без координат графа. |
| 4988 | applyTreeDrag(payload, null); |
| 4989 | } else { |
| 4990 | applyTreeDrag(payload, point); |
| 4991 | } |
| 4992 | }); |
| 4993 | } |
| 4994 | |
| 4995 | // ==================== Редактор плагинов: события ==================== |
| 4996 | if (pluginModal) { |
| 4997 | $('close-plugin').addEventListener('click', closePluginEditor); |
| 4998 | $('plugin-close').addEventListener('click', closePluginEditor); |
| 4999 | pluginModal.addEventListener('click', (event) => { |
| 5000 | if (event.target === pluginModal) closePluginEditor(); |
| 5001 | }); |
| 5002 | $('plugin-new').addEventListener('click', () => { |
| 5003 | state.pluginDraft = newPluginDraft(); |
| 5004 | state.pluginDirty = false; |
| 5005 | renderPluginEditor(); |
| 5006 | const input = $('plugin-name'); |
| 5007 | if (input) input.focus(); |
| 5008 | }); |
| 5009 | $('plugin-reload').addEventListener('click', async () => { |
| 5010 | await loadPlugins(); |
| 5011 | toast('Реестр плагинов перечитан'); |
| 5012 | }); |
| 5013 | $('plugin-save').addEventListener('click', savePluginDraft); |
| 5014 | $('plugin-delete').addEventListener('click', deletePluginDraft); |
| 5015 | pluginListEl.addEventListener('click', (event) => { |
| 5016 | const pick = event.target.closest('[data-plugin-pick]'); |
| 5017 | if (!pick) return; |
| 5018 | const plugin = (state.pluginRegistry || []).find((item) => item.id === pick.dataset.pluginPick); |
| 5019 | if (!plugin) return; |
| 5020 | state.pluginDraft = pluginDraftFrom(plugin); |
| 5021 | state.pluginDirty = false; |
| 5022 | renderPluginEditor(); |
| 5023 | }); |
| 5024 | ['plugin-name', 'plugin-desc'].forEach((id) => { |
| 5025 | const input = $(id); |
| 5026 | if (input) input.addEventListener('input', () => { state.pluginDirty = true; }); |
| 5027 | }); |
| 5028 | const colorInput = $('plugin-color'); |
| 5029 | if (colorInput) colorInput.addEventListener('input', () => { state.pluginDirty = true; }); |
| 5030 | } |
| 5031 | |
| 5032 | if (graphSvg) { |
| 5033 | graphSvg.addEventListener('click', (event) => { |
| 5034 | const edge = event.target.closest('path.edge'); |
| 5035 | if (!edge) return; |
| 5036 | state.selectedLink = edge.dataset.linkId; |
| 5037 | drawGraphEdges(); |
| 5038 | }); |
| 5039 | } |
| 5040 | |
| 5041 | const tplMenu = $('tpl-menu'); |
| 5042 | $('add-slide').addEventListener('click', (event) => { |
| 5043 | event.stopPropagation(); |
| 5044 | tplMenu.hidden = !tplMenu.hidden; |
| 5045 | }); |
| 5046 | tplMenu.addEventListener('click', (event) => { |
| 5047 | const button = event.target.closest('[data-tpl]'); |
| 5048 | if (!button) return; |
| 5049 | tplMenu.hidden = true; |
| 5050 | addSlide(button.dataset.tpl); |
| 5051 | toast('Слайд добавлен из шаблона'); |
| 5052 | }); |
| 5053 | document.addEventListener('click', (event) => { |
| 5054 | if (!tplMenu.hidden && !event.target.closest('#tpl-menu') && !event.target.closest('#add-slide')) { |
| 5055 | tplMenu.hidden = true; |
| 5056 | } |
| 5057 | }); |
| 5058 | |
| 5059 | titleInput.addEventListener('input', () => { |
| 5060 | state.title = titleInput.value; |
| 5061 | scheduleSave(); |
| 5062 | }); |
| 5063 | |
| 5064 | // ==================== Сохранение ==================== |
| 5065 | let saveTimer = null; |
| 5066 | function scheduleSave(discrete = false) { |
| 5067 | if (!restoringHistory) pushHistory(discrete); |
| 5068 | state.dirty = true; |
| 5069 | setStatus('dirty', 'Изменения не сохранены'); |
| 5070 | clearTimeout(saveTimer); |
| 5071 | saveTimer = setTimeout(save, 700); |
| 5072 | } |
| 5073 | |
| 5074 | // ------- История (undo/redo) ------- |
| 5075 | function docSnapshot() { |
| 5076 | return JSON.stringify({ |
| 5077 | title: state.title, |
| 5078 | slides: state.slides, |
| 5079 | variables: state.variables, |
| 5080 | music: state.music, |
| 5081 | lua: state.lua, |
| 5082 | commands: state.commands, |
| 5083 | graph: state.graph, |
| 5084 | }); |
| 5085 | } |
| 5086 | |
| 5087 | function pushHistory(force = false) { |
| 5088 | const snap = docSnapshot(); |
| 5089 | if (undoHistory.index >= 0 && undoHistory.stack[undoHistory.index] === snap) return; |
| 5090 | const now = Date.now(); |
| 5091 | // Непрерывный ввод (печать, ползунки) склеиваем в один шаг за 450 мс. |
| 5092 | if (!force && undoHistory.index >= 0 && now - undoHistory.lastPush < 450) return; |
| 5093 | undoHistory.lastPush = now; |
| 5094 | undoHistory.stack = undoHistory.stack.slice(0, undoHistory.index + 1); |
| 5095 | undoHistory.stack.push(snap); |
| 5096 | if (undoHistory.stack.length > undoHistory.limit) undoHistory.stack.shift(); |
| 5097 | undoHistory.index = undoHistory.stack.length - 1; |
| 5098 | } |
| 5099 | |
| 5100 | function restoreSnapshot(snap) { |
| 5101 | const data = JSON.parse(snap); |
| 5102 | restoringHistory = true; |
| 5103 | try { |
| 5104 | state.title = data.title || ''; |
| 5105 | titleInput.value = state.title; |
| 5106 | state.slides = (data.slides || []).map(hydrateSlide); |
| 5107 | if (!state.slides.length) state.slides = [newSlide()]; |
| 5108 | state.variables = data.variables || {}; |
| 5109 | state.music = data.music || { src: '', volume: 0.5 }; |
| 5110 | state.lua = data.lua || ''; |
| 5111 | state.commands = Array.isArray(data.commands) ? data.commands : []; |
| 5112 | hydrateGraph(data.graph); |
| 5113 | state.selected = clamp(state.selected, 0, state.slides.length - 1); |
| 5114 | state.selectedEl = null; |
| 5115 | state.selectedNode = { type: 'slide', id: state.slides[state.selected].id }; |
| 5116 | renderAll(); |
| 5117 | scheduleSave(); |
| 5118 | } finally { |
| 5119 | restoringHistory = false; |
| 5120 | } |
| 5121 | } |
| 5122 | |
| 5123 | function undo() { |
| 5124 | if (undoHistory.index <= 0) { toast('Нечего отменять'); return; } |
| 5125 | undoHistory.index -= 1; |
| 5126 | restoreSnapshot(undoHistory.stack[undoHistory.index]); |
| 5127 | toast('Шаг отменён'); |
| 5128 | } |
| 5129 | |
| 5130 | function redo() { |
| 5131 | if (undoHistory.index >= undoHistory.stack.length - 1) { toast('Нечего повторять'); return; } |
| 5132 | undoHistory.index += 1; |
| 5133 | restoreSnapshot(undoHistory.stack[undoHistory.index]); |
| 5134 | toast('Шаг повторён'); |
| 5135 | } |
| 5136 | |
| 5137 | async function save() { |
| 5138 | if (state.saving) { state.pending = true; return; } |
| 5139 | state.saving = true; |
| 5140 | setStatus('saving', 'Сохранение…'); |
| 5141 | const payload = { |
| 5142 | title: state.title.trim() || 'Без названия', |
| 5143 | slides: state.slides, |
| 5144 | variables: state.variables, |
| 5145 | music: state.music, |
| 5146 | lua: state.lua, |
| 5147 | commands: state.commands, |
| 5148 | graph: state.graph, |
| 5149 | }; |
| 5150 | const url = state.id ? `/api/presentations/${state.id}` : '/api/presentations'; |
| 5151 | const method = state.id ? 'PUT' : 'POST'; |
| 5152 | try { |
| 5153 | const response = await fetch(url, { |
| 5154 | method, |
| 5155 | headers: { 'Content-Type': 'application/json' }, |
| 5156 | body: JSON.stringify(payload), |
| 5157 | }); |
| 5158 | if (!response.ok) throw new Error(`HTTP ${response.status}`); |
| 5159 | const presentation = await response.json(); |
| 5160 | if (!state.id) { |
| 5161 | state.id = presentation.id; |
| 5162 | undoHistory.stack = []; |
| 5163 | undoHistory.index = -1; |
| 5164 | pushHistory(true); |
| 5165 | history.replaceState(null, '', `editor.html?id=${presentation.id}`); |
| 5166 | } |
| 5167 | state.updatedAt = presentation.updatedAt || Date.now(); |
| 5168 | state.dirty = false; |
| 5169 | copyLinkBtn.disabled = false; |
| 5170 | $('export-btn').disabled = false; |
| 5171 | state.saving = false; |
| 5172 | setStatus('saved', 'Сохранено'); |
| 5173 | if (state.pending) { |
| 5174 | state.pending = false; |
| 5175 | save(); |
| 5176 | } |
| 5177 | } catch (error) { |
| 5178 | state.saving = false; |
| 5179 | setStatus('dirty', 'Ошибка сохранения'); |
| 5180 | } |
| 5181 | } |
| 5182 | |
| 5183 | // Дожимаем несохранённые правки при закрытии вкладки. |
| 5184 | window.addEventListener('pagehide', () => { |
| 5185 | if (!state.dirty || !saveTimer) return; |
| 5186 | clearTimeout(saveTimer); |
| 5187 | saveTimer = null; |
| 5188 | const payload = JSON.stringify({ |
| 5189 | title: state.title.trim() || 'Без названия', |
| 5190 | slides: state.slides, |
| 5191 | variables: state.variables, |
| 5192 | music: state.music, |
| 5193 | lua: state.lua, |
| 5194 | commands: state.commands, |
| 5195 | graph: state.graph, |
| 5196 | }); |
| 5197 | if (state.id && navigator.sendBeacon) { |
| 5198 | navigator.sendBeacon( |
| 5199 | `/api/presentations/${state.id}`, |
| 5200 | new Blob([payload], { type: 'application/json' }) |
| 5201 | ); |
| 5202 | } |
| 5203 | }); |
| 5204 | |
| 5205 | function audienceUrl() { |
| 5206 | const url = new URL('viewer.html', location.href); |
| 5207 | url.searchParams.set('id', state.id); |
| 5208 | url.searchParams.set('mode', 'audience'); |
| 5209 | return url.toString(); |
| 5210 | } |
| 5211 | |
| 5212 | copyLinkBtn.addEventListener('click', async () => { |
| 5213 | if (!state.id) return; |
| 5214 | const original = copyLinkBtn.innerHTML; |
| 5215 | try { |
| 5216 | await navigator.clipboard.writeText(audienceUrl()); |
| 5217 | copyLinkBtn.textContent = 'Скопировано'; |
| 5218 | } catch (error) { |
| 5219 | window.prompt('Ссылка для зрителей:', audienceUrl()); |
| 5220 | } |
| 5221 | setTimeout(() => (copyLinkBtn.innerHTML = original), 1600); |
| 5222 | }); |
| 5223 | |
| 5224 | $('demo-btn').addEventListener('click', async () => { |
| 5225 | clearTimeout(saveTimer); |
| 5226 | await save(); |
| 5227 | if (state.id) window.open(`viewer.html?id=${state.id}&mode=speaker`, '_blank'); |
| 5228 | }); |
| 5229 | |
| 5230 | document.addEventListener('keydown', (event) => { |
| 5231 | const target = event.target; |
| 5232 | const isField = !!(target && target.matches && target.matches('input, textarea, select')) |
| 5233 | || !!(target && target.isContentEditable); |
| 5234 | const mod = event.ctrlKey || event.metaKey; |
| 5235 | if (mod && event.key.toLowerCase() === 's') { |
| 5236 | event.preventDefault(); |
| 5237 | clearTimeout(saveTimer); |
| 5238 | save(); |
| 5239 | } |
| 5240 | if (mod && event.key.toLowerCase() === 'z') { |
| 5241 | event.preventDefault(); |
| 5242 | if (event.shiftKey) redo(); else undo(); |
| 5243 | return; |
| 5244 | } |
| 5245 | if (mod && event.key.toLowerCase() === 'y') { |
| 5246 | event.preventDefault(); |
| 5247 | redo(); |
| 5248 | return; |
| 5249 | } |
| 5250 | if (mod && event.key.toLowerCase() === 'c' && !isField && state.view === 'canvas' && state.selectedEl) { |
| 5251 | const el = selectedElement(); |
| 5252 | if (el) { |
| 5253 | state.clipboard = JSON.parse(JSON.stringify(el)); |
| 5254 | toast('Элемент скопирован · Ctrl+V — вставить'); |
| 5255 | } |
| 5256 | return; |
| 5257 | } |
| 5258 | if (mod && event.key.toLowerCase() === 'v' && !isField && state.view === 'canvas' && state.clipboard) { |
| 5259 | event.preventDefault(); |
| 5260 | pasteElement(); |
| 5261 | return; |
| 5262 | } |
| 5263 | if (mod && event.key.toLowerCase() === 'd' && !isField && state.view === 'canvas' && state.selectedEl) { |
| 5264 | event.preventDefault(); |
| 5265 | duplicateSelectedElement(); |
| 5266 | return; |
| 5267 | } |
| 5268 | // Тонкая подводка выбранного элемента стрелками (Shift — шаг крупнее) |
| 5269 | if (!isField && !mod && state.view === 'canvas' && state.selectedEl && event.key.startsWith('Arrow')) { |
| 5270 | const step = event.shiftKey ? 2.5 : 0.5; |
| 5271 | if (event.key === 'ArrowLeft') { event.preventDefault(); nudgeSelected(-step, 0); return; } |
| 5272 | if (event.key === 'ArrowRight') { event.preventDefault(); nudgeSelected(step, 0); return; } |
| 5273 | if (event.key === 'ArrowUp') { event.preventDefault(); nudgeSelected(0, -step); return; } |
| 5274 | if (event.key === 'ArrowDown') { event.preventDefault(); nudgeSelected(0, step); return; } |
| 5275 | } |
| 5276 | if (event.key === 'Delete' && state.view === 'graph' && !isField) { |
| 5277 | if (state.selectedLink) { |
| 5278 | removeGraphLink(state.selectedLink); |
| 5279 | return; |
| 5280 | } |
| 5281 | const selected = state.selectedNode; |
| 5282 | if (selected && selected.type === 'variable') { |
| 5283 | const node = findVariableNode(selected.id); |
| 5284 | if (node) deleteVariableNode(node); |
| 5285 | return; |
| 5286 | } |
| 5287 | if (selected && selected.type === 'audio') { |
| 5288 | const node = findAudioNode(selected.id); |
| 5289 | if (node) deleteAudioNode(node); |
| 5290 | return; |
| 5291 | } |
| 5292 | if (selected && selected.type === 'script') { |
| 5293 | const node = findScriptNode(selected.id); |
| 5294 | if (node) deleteScriptNode(node); |
| 5295 | return; |
| 5296 | } |
| 5297 | if (selected && selected.type === 'transition') { |
| 5298 | const node = findTransitionNode(selected.id); |
| 5299 | if (node) deleteTransitionNode(node); |
| 5300 | return; |
| 5301 | } |
| 5302 | if (selected && selected.type === 'anim') { |
| 5303 | const node = findAnimNode(selected.id); |
| 5304 | if (node) deleteAnimNode(node); |
| 5305 | return; |
| 5306 | } |
| 5307 | if (selected && selected.type === 'plugin') { |
| 5308 | const node = findPluginNode(selected.id); |
| 5309 | if (node) deletePluginNode(node); |
| 5310 | return; |
| 5311 | } |
| 5312 | } |
| 5313 | if (event.key === 'Delete' && state.view === 'canvas' && state.selectedEl && !isField) { |
| 5314 | const element = selectedElement(); |
| 5315 | if (!element) return; |
| 5316 | const node = element.action && element.action.scriptNodeId |
| 5317 | ? findScriptNode(element.action.scriptNodeId) |
| 5318 | : scriptNodeForElement(element.id); |
| 5319 | if (node) { |
| 5320 | node.slideId = ''; |
| 5321 | node.elementId = ''; |
| 5322 | } |
| 5323 | cleanupElementLinks(element.id); |
| 5324 | pushHistory(true); |
| 5325 | currentSlide().elements = currentSlide().elements.filter((item) => item.id !== element.id); |
| 5326 | state.selectedEl = null; |
| 5327 | renderCanvas(); |
| 5328 | renderInspector(); |
| 5329 | scheduleThumbs(); |
| 5330 | scheduleSave(true); |
| 5331 | } |
| 5332 | if (event.key === 'Escape') { |
| 5333 | selectElement(null); |
| 5334 | state.selectedLink = null; |
| 5335 | settingsModal.hidden = true; |
| 5336 | commandsModal.hidden = true; |
| 5337 | if (tplMenu) tplMenu.hidden = true; |
| 5338 | } |
| 5339 | }); |
| 5340 | |
| 5341 | // ==================== Настройки презентации ==================== |
| 5342 | function varsToText(variables) { |
| 5343 | return Object.entries(variables || {}) |
| 5344 | .map(([key, value]) => `${key} = ${value}`) |
| 5345 | .join('\n'); |
| 5346 | } |
| 5347 | |
| 5348 | function parseVars(text) { |
| 5349 | const result = {}; |
| 5350 | String(text || '').split('\n').forEach((line) => { |
| 5351 | const trimmed = line.trim(); |
| 5352 | if (!trimmed || trimmed.startsWith('#')) return; |
| 5353 | const index = trimmed.indexOf('='); |
| 5354 | if (index <= 0) return; |
| 5355 | const key = trimmed.slice(0, index).trim(); |
| 5356 | let value = trimmed.slice(index + 1).trim(); |
| 5357 | if (!key) return; |
| 5358 | if (value === 'true') value = true; |
| 5359 | else if (value === 'false') value = false; |
| 5360 | else if (/^-?\d+(\.\d+)?$/.test(value)) value = Number(value); |
| 5361 | else if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) { |
| 5362 | value = value.slice(1, -1); |
| 5363 | } |
| 5364 | result[key] = value; |
| 5365 | }); |
| 5366 | return result; |
| 5367 | } |
| 5368 | |
| 5369 | function openSettings() { |
| 5370 | $('vars-input').value = varsToText(state.variables); |
| 5371 | $('music-src').value = state.music.src || ''; |
| 5372 | $('music-volume').value = String(Math.round((state.music.volume ?? 0.5) * 100)); |
| 5373 | $('music-volume-out').textContent = `${Math.round((state.music.volume ?? 0.5) * 100)}%`; |
| 5374 | $('lua-input').value = state.lua || ''; |
| 5375 | settingsModal.hidden = false; |
| 5376 | } |
| 5377 | |
| 5378 | $('settings-btn').addEventListener('click', openSettings); |
| 5379 | $('close-settings').addEventListener('click', () => (settingsModal.hidden = true)); |
| 5380 | $('cancel-settings').addEventListener('click', () => (settingsModal.hidden = true)); |
| 5381 | settingsModal.addEventListener('click', (event) => { |
| 5382 | if (event.target === settingsModal) settingsModal.hidden = true; |
| 5383 | }); |
| 5384 | |
| 5385 | $('music-volume').addEventListener('input', () => { |
| 5386 | $('music-volume-out').textContent = `${$('music-volume').value}%`; |
| 5387 | }); |
| 5388 | |
| 5389 | $('save-settings').addEventListener('click', () => { |
| 5390 | state.variables = parseVars($('vars-input').value); |
| 5391 | state.music = { |
| 5392 | src: $('music-src').value.trim(), |
| 5393 | volume: clamp(Number($('music-volume').value) / 100, 0, 1), |
| 5394 | }; |
| 5395 | state.lua = $('lua-input').value; |
| 5396 | settingsModal.hidden = true; |
| 5397 | renderCanvas(); |
| 5398 | renderThumbs(); |
| 5399 | scheduleSave(); |
| 5400 | toast('Настройки сохранены'); |
| 5401 | }); |
| 5402 | |
| 5403 | // ==================== Команды ==================== |
| 5404 | function renderCommandsEditor() { |
| 5405 | commandsListEl.innerHTML = ''; |
| 5406 | if (!state.commandDraft.length) { |
| 5407 | commandsListEl.innerHTML = '<p class="hint">Пока нет команд. Добавьте первую — например, «Следующий раздел» с вызовом <code>app.next()</code>.</p>'; |
| 5408 | return; |
| 5409 | } |
| 5410 | state.commandDraft.forEach((command, index) => { |
| 5411 | const item = document.createElement('div'); |
| 5412 | item.className = 'command-item'; |
| 5413 | item.innerHTML = ` |
| 5414 | <div class="command-item-head"> |
| 5415 | <input data-command="label" placeholder="Название команды"> |
| 5416 | <button class="danger" data-command-delete="${index}" title="Удалить">Удалить</button> |
| 5417 | </div> |
| 5418 | <input data-command="description" placeholder="Короткое описание для докладчика"> |
| 5419 | <textarea data-command="code" rows="4" spellcheck="false" placeholder="vars.step = (vars.step or 0) + 1 app.log(vars.step)"></textarea>`; |
| 5420 | item.querySelector('[data-command="label"]').value = command.label || ''; |
| 5421 | item.querySelector('[data-command="description"]').value = command.description || ''; |
| 5422 | item.querySelector('[data-command="code"]').value = command.code || ''; |
| 5423 | commandsListEl.appendChild(item); |
| 5424 | }); |
| 5425 | } |
| 5426 | |
| 5427 | commandsListEl.addEventListener('input', (event) => { |
| 5428 | const field = event.target.dataset.command; |
| 5429 | if (!field) return; |
| 5430 | const item = event.target.closest('.command-item'); |
| 5431 | const index = [...commandsListEl.querySelectorAll('.command-item')].indexOf(item); |
| 5432 | if (index < 0 || !state.commandDraft[index]) return; |
| 5433 | state.commandDraft[index][field] = event.target.value; |
| 5434 | }); |
| 5435 | |
| 5436 | commandsListEl.addEventListener('click', (event) => { |
| 5437 | const remove = event.target.closest('[data-command-delete]'); |
| 5438 | if (!remove) return; |
| 5439 | state.commandDraft.splice(Number(remove.dataset.commandDelete), 1); |
| 5440 | renderCommandsEditor(); |
| 5441 | }); |
| 5442 | |
| 5443 | $('add-command').addEventListener('click', () => { |
| 5444 | state.commandDraft.push({ |
| 5445 | id: uid(), |
| 5446 | label: `Команда ${state.commandDraft.length + 1}`, |
| 5447 | description: '', |
| 5448 | code: '', |
| 5449 | }); |
| 5450 | renderCommandsEditor(); |
| 5451 | const fields = commandsListEl.querySelectorAll('[data-command="label"]'); |
| 5452 | if (fields.length) fields[fields.length - 1].focus(); |
| 5453 | }); |
| 5454 | |
| 5455 | function openCommands() { |
| 5456 | state.commandDraft = state.commands.map((command) => ({ ...command })); |
| 5457 | renderCommandsEditor(); |
| 5458 | commandsModal.hidden = false; |
| 5459 | } |
| 5460 | |
| 5461 | $('commands-btn').addEventListener('click', openCommands); |
| 5462 | $('close-commands').addEventListener('click', () => (commandsModal.hidden = true)); |
| 5463 | $('cancel-commands').addEventListener('click', () => (commandsModal.hidden = true)); |
| 5464 | commandsModal.addEventListener('click', (event) => { |
| 5465 | if (event.target === commandsModal) commandsModal.hidden = true; |
| 5466 | }); |
| 5467 | $('save-commands').addEventListener('click', () => { |
| 5468 | state.commands = state.commandDraft |
| 5469 | .map((command) => ({ |
| 5470 | id: command.id || uid(), |
| 5471 | label: String(command.label || '').trim() || 'Команда', |
| 5472 | description: String(command.description || '').trim(), |
| 5473 | code: command.code || '', |
| 5474 | })) |
| 5475 | .filter((command) => String(command.code).trim() || command.label !== 'Команда'); |
| 5476 | commandsModal.hidden = true; |
| 5477 | scheduleSave(); |
| 5478 | toast(`Команд в консоли: ${state.commands.length}`); |
| 5479 | }); |
| 5480 | |
| 5481 | // ==================== Живой статус и синхронизация между окнами ==================== |
| 5482 | function applyRemote(presentation) { |
| 5483 | state.updatedAt = Number(presentation.updatedAt) || state.updatedAt; |
| 5484 | state.title = presentation.title || ''; |
| 5485 | titleInput.value = state.title; |
| 5486 | state.slides = (presentation.slides || []).map(hydrateSlide); |
| 5487 | if (!state.slides.length) state.slides = [newSlide()]; |
| 5488 | state.variables = presentation.variables || {}; |
| 5489 | state.music = presentation.music || { src: '', volume: 0.5 }; |
| 5490 | state.lua = presentation.lua || ''; |
| 5491 | state.commands = Array.isArray(presentation.commands) ? presentation.commands : []; |
| 5492 | hydrateGraph(presentation.graph); |
| 5493 | state.selected = clamp(state.selected, 0, state.slides.length - 1); |
| 5494 | state.selectedEl = null; |
| 5495 | renderAll(); |
| 5496 | undoHistory.stack = []; |
| 5497 | undoHistory.index = -1; |
| 5498 | pushHistory(true); |
| 5499 | toast('Презентация обновлена из другого окна'); |
| 5500 | } |
| 5501 | |
| 5502 | function connectLiveStatus() { |
| 5503 | let ws; |
| 5504 | const wsProto = () => (location.protocol === 'https:' ? 'wss' : 'ws'); |
| 5505 | const connect = () => { |
| 5506 | ws = new WebSocket(`${wsProto()}://${location.host}/`); |
| 5507 | ws.onmessage = (event) => { |
| 5508 | let message; |
| 5509 | try { message = JSON.parse(event.data); } catch (error) { return; } |
| 5510 | if (message.type === 'sessions' && state.id) { |
| 5511 | const session = message.sessions.find((item) => item.presentationId === state.id); |
| 5512 | if (session) { |
| 5513 | liveChip.hidden = false; |
| 5514 | liveChip.textContent = `● Демонстрация · ${session.viewers} зр.`; |
| 5515 | } else { |
| 5516 | liveChip.hidden = true; |
| 5517 | } |
| 5518 | } |
| 5519 | // Совместное редактирование: если документ изменился в другом окне |
| 5520 | // и у нас нет несохранённых правок — подтягиваем свежую версию. |
| 5521 | if (message.type === 'presentations' && state.id && !state.dirty) { |
| 5522 | const fresh = (message.presentations || []).find((item) => item.id === state.id); |
| 5523 | if (fresh && Number(fresh.updatedAt) > Number(state.updatedAt)) applyRemote(fresh); |
| 5524 | } |
| 5525 | if (message.type === 'plugins' && Array.isArray(message.plugins)) { |
| 5526 | state.pluginRegistry = message.plugins; |
| 5527 | renderTree(); |
| 5528 | if (!pluginModal.hidden && state.pluginDraft && !state.pluginDirty) { |
| 5529 | const fresh = message.plugins.find((plugin) => plugin.id === state.pluginDraft.id); |
| 5530 | if (fresh) { |
| 5531 | state.pluginDraft = pluginDraftFrom(fresh); |
| 5532 | renderPluginEditor(); |
| 5533 | } |
| 5534 | } |
| 5535 | } |
| 5536 | }; |
| 5537 | ws.onclose = () => setTimeout(connect, 2000); |
| 5538 | ws.onerror = () => ws.close(); |
| 5539 | }; |
| 5540 | connect(); |
| 5541 | } |
| 5542 | |
| 5543 | // ==================== Загрузка ==================== |
| 5544 | async function init() { |
| 5545 | const id = new URLSearchParams(location.search).get('id'); |
| 5546 | if (id) { |
| 5547 | try { |
| 5548 | const response = await fetch(`/api/presentations/${encodeURIComponent(id)}`); |
| 5549 | if (response.ok) { |
| 5550 | const presentation = await response.json(); |
| 5551 | state.id = presentation.id; |
| 5552 | state.title = presentation.title || ''; |
| 5553 | state.variables = presentation.variables || {}; |
| 5554 | state.music = presentation.music || { src: '', volume: 0.5 }; |
| 5555 | state.lua = presentation.lua || ''; |
| 5556 | state.commands = Array.isArray(presentation.commands) ? presentation.commands : []; |
| 5557 | state.slides = (presentation.slides || []).map(hydrateSlide); |
| 5558 | if (!state.slides.length) state.slides = [newSlide()]; |
| 5559 | hydrateGraph(presentation.graph); |
| 5560 | titleInput.value = state.title; |
| 5561 | state.updatedAt = Number(presentation.updatedAt) || Date.now(); |
| 5562 | copyLinkBtn.disabled = false; |
| 5563 | $('export-btn').disabled = false; |
| 5564 | setStatus('saved', 'Загружено'); |
| 5565 | } else { |
| 5566 | history.replaceState(null, '', 'editor.html'); |
| 5567 | setStatus('dirty', 'Презентация не найдена — создаётся новая'); |
| 5568 | } |
| 5569 | } catch (error) { |
| 5570 | setStatus('dirty', 'Ошибка загрузки'); |
| 5571 | } |
| 5572 | } |
| 5573 | await loadPlugins(); |
| 5574 | renderAll(); |
| 5575 | pushHistory(true); // базовый снимок для Ctrl+Z |
| 5576 | connectLiveStatus(); |
| 5577 | } |
| 5578 | |
| 5579 | // ==================== Экспорт / импорт ==================== |
| 5580 | $('export-btn').addEventListener('click', async () => { |
| 5581 | clearTimeout(saveTimer); |
| 5582 | await save(); |
| 5583 | const payload = { |
| 5584 | app: 'promptly', |
| 5585 | version: 2, |
| 5586 | exportedAt: new Date().toISOString(), |
| 5587 | title: state.title, |
| 5588 | slides: state.slides, |
| 5589 | variables: state.variables, |
| 5590 | music: state.music, |
| 5591 | lua: state.lua, |
| 5592 | commands: state.commands, |
| 5593 | graph: state.graph, |
| 5594 | }; |
| 5595 | const blob = new Blob([JSON.stringify(payload, null, 2)], { type: 'application/json' }); |
| 5596 | const link = document.createElement('a'); |
| 5597 | const safeTitle = String(state.title || 'presentation').replace(/[^\wа-яёА-ЯЁ -]+/gi, '').trim().slice(0, 48) || 'presentation'; |
| 5598 | link.href = URL.createObjectURL(blob); |
| 5599 | link.download = `${safeTitle}.promptly.json`; |
| 5600 | link.click(); |
| 5601 | setTimeout(() => URL.revokeObjectURL(link.href), 4000); |
| 5602 | toast('JSON-файл презентации скачан'); |
| 5603 | }); |
| 5604 | |
| 5605 | $('import-btn').addEventListener('click', () => $('import-file').click()); |
| 5606 | $('import-file').addEventListener('change', async (event) => { |
| 5607 | const file = event.target.files && event.target.files[0]; |
| 5608 | event.target.value = ''; |
| 5609 | if (!file) return; |
| 5610 | try { |
| 5611 | const data = JSON.parse(await file.text()); |
| 5612 | if (!data || !Array.isArray(data.slides)) throw new Error('bad format'); |
| 5613 | const response = await fetch('/api/presentations', { |
| 5614 | method: 'POST', |
| 5615 | headers: { 'Content-Type': 'application/json' }, |
| 5616 | body: JSON.stringify(data), |
| 5617 | }); |
| 5618 | if (!response.ok) throw new Error(`HTTP ${response.status}`); |
| 5619 | const created = await response.json(); |
| 5620 | toast('Презентация импортирована'); |
| 5621 | location.href = `editor.html?id=${encodeURIComponent(created.id)}`; |
| 5622 | } catch (error) { |
| 5623 | toast('Не удалось импортировать: проверьте JSON-файл'); |
| 5624 | } |
| 5625 | }); |
| 5626 | |
| 5627 | init(); |
| 5628 | </script> |
| 5629 | </body> |
| 5630 | </html> |