1738 lines
78 KiB
HTML
1738 lines
78 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="ru">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||
<title>Promptly — демонстрация</title>
|
||
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Ctext y='.9em' font-size='90'%3E%F0%9F%8E%A4%3C/text%3E%3C/svg%3E">
|
||
<style>
|
||
:root {
|
||
--bg: #101014;
|
||
--panel: rgba(30, 30, 30, .5);
|
||
--panel-strong: rgba(30, 30, 30, .68);
|
||
--border: rgba(255, 255, 255, .08);
|
||
--accent: #4cc2ff;
|
||
--accent-2: #7fd4ff;
|
||
--text: #e5e5e5;
|
||
--muted: #aaa;
|
||
}
|
||
* { box-sizing: border-box; }
|
||
html, body { margin: 0; height: 100%; }
|
||
body {
|
||
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
||
background: var(--bg); color: var(--text); overflow: hidden;
|
||
}
|
||
button { border: none; border-radius: 11px; padding: 9px 14px; font: inherit; cursor: pointer; transition: .16s; background: rgba(255,255,255,.08); color: var(--text); }
|
||
button:hover:not(:disabled) { background: rgba(255,255,255,.16); }
|
||
button:disabled { opacity: .3; cursor: default; }
|
||
input, select, textarea { font: inherit; }
|
||
.mode { display: none; }
|
||
body.mode-audience .mode.audience { display: flex; }
|
||
body.mode-speaker .mode.speaker { display: flex; }
|
||
|
||
.live { display: inline-flex; align-items: center; gap: 7px; font-size: 12px; color: #8fdcff; letter-spacing: .4px; font-weight: 600; }
|
||
.live .dot { width: 8px; height: 8px; border-radius: 50%; background: #7fd4ff; box-shadow: 0 0 10px #7fd4ff; animation: pulse 1.2s infinite; }
|
||
@keyframes pulse { 50% { opacity: .25; } }
|
||
|
||
/* ==================== ЗРИТЕЛЬ ==================== */
|
||
#audience {
|
||
position: fixed; inset: 0; align-items: center; justify-content: center; padding: 2.4vmin;
|
||
background:
|
||
radial-gradient(1000px 560px at 50% -20%, rgba(99, 102, 241, .22), transparent 62%),
|
||
radial-gradient(760px 460px at 105% 115%, rgba(217, 70, 239, .14), transparent 60%);
|
||
}
|
||
.audience-frame {
|
||
position: relative; overflow: hidden; border-radius: 16px;
|
||
width: min(100%, calc((100vh - 4.8vmin) * 16 / 9));
|
||
aspect-ratio: 16 / 9;
|
||
box-shadow: 0 30px 90px rgba(0, 0, 0, .65), 0 0 0 1px rgba(255, 255, 255, .07);
|
||
}
|
||
.audience-progress {
|
||
position: absolute; left: 0; right: 0; bottom: 0; height: 3px; z-index: 40;
|
||
background: rgba(255, 255, 255, .08); pointer-events: none;
|
||
}
|
||
.audience-progress > div {
|
||
height: 100%; width: 0; border-radius: 0 3px 3px 0;
|
||
background: linear-gradient(90deg, #1795d8, #7fd4ff);
|
||
box-shadow: 0 0 10px rgba(232, 121, 249, .8);
|
||
transition: width .4s cubic-bezier(.2, .7, .3, 1);
|
||
}
|
||
.audience-frame .sv-button { cursor: default; }
|
||
.audience-frame .sv-button:hover { filter: none; }
|
||
.audience-frame .sv-button:active { transform: none; }
|
||
.audience-frame .sv-audio { cursor: default; pointer-events: none; }
|
||
|
||
.hud {
|
||
position: fixed; bottom: 18px; left: 50%; transform: translateX(-50%) translateY(8px);
|
||
display: flex; gap: 16px; align-items: center;
|
||
background: rgba(10, 14, 28, .78); border: 1px solid var(--border);
|
||
padding: 8px 10px 8px 20px; border-radius: 999px; font-size: 13px; color: #cbd5e1;
|
||
opacity: 0; pointer-events: none; transition: opacity .3s, transform .3s; backdrop-filter: blur(14px);
|
||
z-index: 60;
|
||
}
|
||
.hud.visible { opacity: 1; transform: translateX(-50%) translateY(0); pointer-events: auto; }
|
||
.hud .hud-title { max-width: 360px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-weight: 600; color: #e2e8f0; }
|
||
.hud .hud-counter { font-variant-numeric: tabular-nums; color: var(--muted); }
|
||
.hud button { padding: 6px 11px; border-radius: 999px; font-size: 13px; }
|
||
|
||
/* ==================== ДОКЛАДЧИК ==================== */
|
||
#speaker { flex-direction: column; height: 100vh; overflow: hidden; }
|
||
.speaker-head {
|
||
display: flex; align-items: center; gap: 14px; padding: 11px 18px;
|
||
background: rgba(10, 14, 28, .75); border-bottom: 1px solid var(--border);
|
||
}
|
||
.brand { display: flex; align-items: center; gap: 9px; font-weight: 700; font-size: 15px; min-width: 0; }
|
||
.brand .brand-mark { font-size: 18px; }
|
||
.brand span { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 34vw; }
|
||
.head-meta { display: flex; align-items: center; gap: 14px; margin-left: auto; flex-shrink: 0; }
|
||
.timer { font-variant-numeric: tabular-nums; font-weight: 700; color: #9fd8ff; font-size: 15px; }
|
||
.counter { font-size: 13px; color: var(--muted); font-variant-numeric: tabular-nums; }
|
||
.head-actions { display: flex; gap: 8px; flex-shrink: 0; }
|
||
.head-actions button { padding: 8px 13px; font-size: 13px; }
|
||
.head-actions .icon { padding: 8px 11px; }
|
||
|
||
.speaker-main {
|
||
flex: 1; min-height: 0; display: grid; grid-template-columns: minmax(0, 1fr) 390px;
|
||
gap: 14px; padding: 14px 16px;
|
||
}
|
||
.notes-card {
|
||
display: flex; flex-direction: column; min-height: 0; padding: 20px 24px;
|
||
background: linear-gradient(160deg, rgba(99, 102, 241, .13), rgba(12, 17, 33, .72) 55%);
|
||
border: 1px solid rgba(129, 140, 248, .22); border-radius: 20px;
|
||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .05);
|
||
}
|
||
.card-label { display: flex; align-items: center; gap: 8px; font-size: 11px; text-transform: uppercase; letter-spacing: 1.3px; font-weight: 800; color: var(--accent); margin-bottom: 12px; }
|
||
.card-label .spacer { flex: 1; }
|
||
.slide-pill { font-size: 11px; letter-spacing: .3px; text-transform: none; color: #bfe7ff; background: rgba(99, 102, 241, .2); border: 1px solid rgba(129, 140, 248, .3); border-radius: 999px; padding: 3px 9px; }
|
||
.notes-body { flex: 1; overflow-y: auto; font-size: clamp(19px, 2.05vw, 31px); line-height: 1.48; color: #e2e8f0; white-space: pre-wrap; padding-right: 6px; }
|
||
.notes-body:empty::before { content: 'Нет пометок к этому слайду'; color: #475569; }
|
||
.left-col { display: flex; flex-direction: column; gap: 14px; min-height: 0; }
|
||
.left-col .notes-card { flex: 1; min-height: 0; }
|
||
|
||
/* Консоль команд */
|
||
.console-card {
|
||
display: flex; flex-direction: column; min-height: 0; height: clamp(190px, 27vh, 300px); flex-shrink: 0;
|
||
padding: 12px 14px; background: rgba(7, 10, 20, .82);
|
||
border: 1px solid rgba(129, 140, 248, .22); border-radius: 16px;
|
||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .04);
|
||
}
|
||
.console-card .card-label { margin-bottom: 8px; }
|
||
.console-card .card-label a { color: #bfe7ff; font-size: 10px; text-decoration: none; border: 1px solid rgba(129,140,248,.35); border-radius: 999px; padding: 2px 8px; }
|
||
.console-list { flex: 1; min-height: 0; overflow-y: auto; display: flex; flex-direction: column; gap: 5px; outline: none; padding-right: 2px; }
|
||
.console-list:focus-visible { box-shadow: 0 0 0 2px rgba(129, 140, 248, .45); border-radius: 8px; }
|
||
.console-item { display: flex; align-items: flex-start; gap: 9px; width: 100%; text-align: left; padding: 7px 9px; border-radius: 9px; background: rgba(255,255,255,.035); border: 1px solid transparent; flex-shrink: 0; }
|
||
.console-item:hover { background: rgba(255,255,255,.09); }
|
||
.console-item.active { background: rgba(99, 102, 241, .18); border-color: rgba(129, 140, 248, .55); }
|
||
.console-idx { font-size: 10px; font-weight: 700; color: #9fd8ff; background: rgba(99,102,241,.22); border-radius: 5px; padding: 1px 6px; margin-top: 2px; font-variant-numeric: tabular-nums; }
|
||
.console-meta { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 1px; }
|
||
.console-meta b { font-size: 12.5px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||
.console-meta small { font-size: 10.5px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||
.console-item .run { font-size: 10px; color: #bfe7ff; padding: 2px 7px; border-radius: 999px; border: 1px solid rgba(129,140,248,.35); flex-shrink: 0; }
|
||
.console-empty { color: #64748b; font-size: 12px; line-height: 1.5; padding: 6px 2px; }
|
||
.console-log { flex-shrink: 0; margin-top: 6px; padding-top: 6px; border-top: 1px solid rgba(255,255,255,.07); max-height: 52px; overflow-y: auto; font-family: ui-monospace, 'SFMono-Regular', Consolas, monospace; font-size: 10.5px; line-height: 1.45; color: #8ea0bd; white-space: pre-wrap; }
|
||
.console-log:empty::before { content: 'Готово. ↑ ↓ — выбор, Enter — запуск.'; color: #475569; }
|
||
|
||
/* Окно Chrome / видео */
|
||
.window-row, .video-row { display: flex; align-items: center; gap: 8px; background: rgba(255,255,255,.04); border: 1px solid rgba(255,255,255,.06); border-radius: 10px; padding: 7px 8px; }
|
||
.window-row + .window-row, .video-row + .video-row { margin-top: 6px; }
|
||
.window-meta, .video-meta { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 1px; }
|
||
.window-meta b, .video-meta b { font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||
.window-meta small, .video-meta small { font-size: 10.5px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||
.window-row button, .video-row button { padding: 5px 8px; font-size: 11px; border-radius: 8px; flex-shrink: 0; }
|
||
.window-status { width: 7px; height: 7px; border-radius: 50%; background: #475569; flex-shrink: 0; }
|
||
.window-status.on { background: #4ade80; box-shadow: 0 0 8px rgba(74, 222, 128, .8); }
|
||
.window-select { margin-bottom: 7px; }
|
||
.window-select select { width: 100%; padding: 6px 8px; font-size: 12px; border-radius: 8px; background: rgba(255,255,255,.05); border: 1px solid var(--border); color: var(--text); }
|
||
.window-hint { margin: 6px 0 0; font-size: 10.5px; line-height: 1.4; color: #64748b; }
|
||
.window-hint code { color: #9fd8ff; }
|
||
|
||
.side { min-height: 0; overflow-y: auto; display: flex; flex-direction: column; gap: 12px; padding-right: 3px; }
|
||
.card { background: var(--panel); border: 1px solid var(--border); border-radius: 16px; padding: 12px; flex-shrink: 0; }
|
||
.card .card-label { margin-bottom: 9px; font-size: 10px; }
|
||
.preview-frame { position: relative; aspect-ratio: 16 / 9; border-radius: 10px; overflow: hidden; background: #0b1020; border: 1px solid rgba(255,255,255,.06); }
|
||
.preview-frame .sv-button { cursor: pointer; }
|
||
.preview-next { opacity: .82; }
|
||
|
||
.interact-list { display: flex; flex-direction: column; gap: 7px; max-height: 210px; overflow-y: auto; }
|
||
.interact-empty { color: #64748b; font-size: 12px; line-height: 1.4; padding: 2px 0; }
|
||
.interact-item { display: flex; align-items: center; gap: 9px; background: rgba(255,255,255,.045); border: 1px solid rgba(255,255,255,.06); border-radius: 10px; padding: 6px 8px; }
|
||
.interact-icon { width: 26px; height: 26px; flex-shrink: 0; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 12px; background: rgba(99, 102, 241, .22); color: #bfe7ff; }
|
||
.interact-meta { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 1px; }
|
||
.interact-meta b { font-size: 12px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||
.interact-meta small { font-size: 10.5px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||
.interact-item button { padding: 5px 9px; font-size: 11px; border-radius: 8px; flex-shrink: 0; }
|
||
.interact-item.playing { border-color: rgba(129, 140, 248, .5); background: rgba(99, 102, 241, .12); }
|
||
.badge-hidden { font-size: 9.5px; color: #fbbf24; border: 1px solid rgba(251, 191, 36, .35); border-radius: 999px; padding: 1px 6px; }
|
||
|
||
.audio-card .audio-row { display: flex; align-items: center; gap: 10px; font-size: 12px; color: #cbd5e1; margin-bottom: 8px; }
|
||
.audio-row span { width: 62px; flex-shrink: 0; }
|
||
.audio-row input[type="range"] { flex: 1; min-width: 0; accent-color: #4cc2ff; height: 4px; }
|
||
.audio-row output { width: 34px; text-align: right; font-variant-numeric: tabular-nums; color: var(--muted); font-size: 11px; }
|
||
.music-state { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-top: 4px; padding-top: 9px; border-top: 1px solid rgba(255,255,255,.06); }
|
||
.music-state .music-name { font-size: 11.5px; color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||
.music-state button { padding: 6px 10px; font-size: 11.5px; border-radius: 9px; }
|
||
.music-state button.on { background: rgba(99, 102, 241, .35); color: #fff; }
|
||
|
||
.viewers-card { display: flex; align-items: center; justify-content: space-between; font-size: 13px; color: #cbd5e1; }
|
||
.viewers-card strong { font-size: 22px; color: #8fdcff; font-variant-numeric: tabular-nums; }
|
||
|
||
.controls {
|
||
display: flex; align-items: center; gap: 14px; padding: 12px 18px;
|
||
background: rgba(10, 14, 28, .75); border-top: 1px solid var(--border);
|
||
}
|
||
.controls .nav {
|
||
font-size: 15px; font-weight: 700; padding: 13px 26px; border-radius: 13px;
|
||
background: linear-gradient(90deg, #1795d8, #38bdf8); color: #fff; flex-shrink: 0;
|
||
}
|
||
.controls .nav:hover:not(:disabled) { filter: brightness(1.12); background: linear-gradient(90deg, #1795d8, #38bdf8); }
|
||
.dots { flex: 1; display: flex; gap: 6px; overflow-x: auto; padding: 4px; align-items: center; justify-content: center; }
|
||
.dots .dot { padding: 6px 10px; border-radius: 8px; font-size: 12px; background: rgba(255,255,255,.06); color: var(--muted); min-width: 30px; flex-shrink: 0; font-variant-numeric: tabular-nums; }
|
||
.dots .dot.active { background: linear-gradient(90deg, #1795d8, #38bdf8); color: #fff; font-weight: 700; }
|
||
|
||
/* ==================== ОВЕРЛЕЙ / КНОПКА ЗВУКА / ТОСТ ==================== */
|
||
.unlock-audio {
|
||
position: fixed; right: 22px; bottom: 22px; z-index: 150;
|
||
display: flex; align-items: center; gap: 9px; padding: 13px 20px; border-radius: 999px;
|
||
background: linear-gradient(90deg, #1795d8, #38bdf8); color: #fff; font-weight: 700; font-size: 14px;
|
||
box-shadow: 0 14px 40px rgba(99, 102, 241, .45); animation: unlockPulse 1.8s infinite;
|
||
}
|
||
.unlock-audio[hidden] { display: none; }
|
||
@keyframes unlockPulse { 50% { box-shadow: 0 14px 54px rgba(168, 85, 247, .7); } }
|
||
|
||
.overlay { position: fixed; inset: 0; display: flex; align-items: center; justify-content: center; background: rgba(5, 7, 15, .88); backdrop-filter: blur(10px); z-index: 200; }
|
||
.overlay[hidden] { display: none; }
|
||
.overlay-card { background: #111827; border: 1px solid rgba(255,255,255,.1); border-radius: 22px; padding: 36px 44px; text-align: center; max-width: 480px; box-shadow: 0 30px 80px rgba(0,0,0,.6); }
|
||
.overlay-card h2 { margin: 0 0 10px; font-size: 23px; }
|
||
.overlay-card p { color: var(--muted); margin: 0 0 24px; line-height: 1.5; }
|
||
.overlay-card button { background: linear-gradient(90deg, #1795d8, #38bdf8); font-size: 15px; padding: 12px 24px; }
|
||
|
||
/* Пульт окна Chrome */
|
||
.window-remote { position: fixed; inset: 0; z-index: 220; display: flex; align-items: center; justify-content: center; background: rgba(4, 6, 14, .86); backdrop-filter: blur(10px); padding: 18px; }
|
||
.window-remote[hidden] { display: none; }
|
||
.window-remote-card { width: min(980px, 100%); max-height: 94vh; display: flex; flex-direction: column; gap: 12px; background: #0c1120; border: 1px solid rgba(255,255,255,.1); border-radius: 20px; padding: 14px; box-shadow: 0 30px 90px rgba(0,0,0,.7); }
|
||
.window-remote-head { display: flex; align-items: center; gap: 10px; }
|
||
.window-remote-head h3 { margin: 0; font-size: 15px; flex: 1; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||
.window-remote-head .live { font-size: 10.5px; }
|
||
.window-remote-stage { position: relative; flex: 1; min-height: 0; aspect-ratio: 16 / 9; max-height: 62vh; background: #02040a; border: 1px solid rgba(255,255,255,.08); border-radius: 12px; overflow: hidden; cursor: crosshair; }
|
||
.window-remote-stage img { width: 100%; height: 100%; object-fit: fill; display: block; }
|
||
.window-remote-stage .remote-empty { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; color: #64748b; font-size: 13px; text-align: center; padding: 20px; }
|
||
.window-remote-keys { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
|
||
.window-remote-keys button { padding: 7px 10px; font-size: 12px; border-radius: 8px; }
|
||
.window-remote-text { display: flex; gap: 8px; }
|
||
.window-remote-text input { flex: 1; padding: 8px 10px; border-radius: 9px; border: 1px solid var(--border); background: rgba(255,255,255,.05); color: var(--text); font: inherit; }
|
||
.window-remote-text button { padding: 8px 14px; }
|
||
|
||
.restart-btn { background: linear-gradient(90deg, #1795d8, #38bdf8); color: #fff; font-weight: 650; }
|
||
.restart-btn:hover { filter: brightness(1.12); }
|
||
.toast {
|
||
position: fixed; left: 50%; bottom: 26px; transform: translateX(-50%) translateY(12px);
|
||
background: rgba(127, 29, 29, .92); border: 1px solid rgba(248, 113, 113, .5); color: #fee2e2;
|
||
padding: 10px 18px; border-radius: 12px; font-size: 13px; z-index: 180; max-width: 70vw;
|
||
opacity: 0; pointer-events: none; transition: .25s;
|
||
}
|
||
.toast.visible { opacity: 1; transform: translateX(-50%) translateY(0); }
|
||
|
||
@media (max-width: 980px) {
|
||
.speaker-main { grid-template-columns: 1fr; overflow-y: auto; }
|
||
.side { overflow: visible; flex-direction: row; flex-wrap: wrap; }
|
||
.side .card { flex: 1; min-width: 160px; }
|
||
.notes-card { min-height: 240px; }
|
||
.console-card { height: 230px; }
|
||
.head-actions .label { display: none; }
|
||
.window-remote-stage { max-height: 52vh; }
|
||
.window-remote-card { padding: 10px; }
|
||
}
|
||
@media (max-width: 700px) {
|
||
.speaker-head { flex-wrap: wrap; row-gap: 8px; padding: 10px 12px; }
|
||
.brand { font-size: 14px; }
|
||
.brand span { max-width: 42vw; }
|
||
.head-meta { gap: 10px; }
|
||
.side { flex-direction: column; flex-wrap: nowrap; }
|
||
.side .card { flex: 0 0 auto; min-width: 0; }
|
||
.speaker-main { padding: 10px; gap: 10px; }
|
||
.notes-card { padding: 16px 18px; min-height: 200px; }
|
||
.notes-body { font-size: 19px; }
|
||
.console-card { height: 210px; padding: 10px 11px; }
|
||
.console-meta b { font-size: 12px; }
|
||
.controls { padding: 10px 12px; gap: 9px; }
|
||
.controls .nav { padding: 11px 16px; font-size: 13px; }
|
||
}
|
||
|
||
body { background: #101014 url('/img/bipfr-bg.png') center / cover fixed no-repeat; }
|
||
.speaker-head { background: rgba(30, 30, 30, .62); backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px); }
|
||
.notes-card, .console-card, .side .card { background: rgba(20, 20, 25, .6); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); border-color: rgba(255,255,255,.08); }
|
||
.brand-mark { width: 12px; height: 12px; border-radius: 4px; background: #4cc2ff; box-shadow: 0 0 10px rgba(76,194,255,.7); display: inline-block; flex-shrink: 0; }
|
||
button { touch-action: manipulation; }
|
||
@media (max-width: 700px) {
|
||
body.mode-speaker { overflow: auto; }
|
||
.speaker-head button, .controls button { min-height: 40px; }
|
||
.brand span { max-width: 52vw; }
|
||
}
|
||
|
||
</style>
|
||
</head>
|
||
<body class="mode-audience">
|
||
<!-- ============ РЕЖИМ ЗРИТЕЛЯ ============ -->
|
||
<div id="audience" class="mode audience">
|
||
<div class="audience-frame" id="audience-frame">
|
||
<div class="audience-progress" id="audience-progress"><div></div></div>
|
||
</div>
|
||
<div class="hud" id="hud">
|
||
<span class="hud-title" id="a-title"></span>
|
||
<span class="hud-counter" id="a-counter">0 / 0</span>
|
||
<button id="a-exit" title="Выйти">×</button>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- ============ РЕЖИМ ДОКЛАДЧИКА ============ -->
|
||
<div id="speaker" class="mode speaker">
|
||
<header class="speaker-head">
|
||
<div class="brand"><span class="brand-mark"></span><span id="s-title">Загрузка…</span></div>
|
||
<div class="head-meta">
|
||
<span class="live"><span class="dot"></span> LIVE</span>
|
||
<span class="timer" id="timer">00:00</span>
|
||
<span class="counter" id="s-counter">0 / 0</span>
|
||
</div>
|
||
<div class="head-actions">
|
||
<button id="docs-link" title="Справочник Lua"><span class="label">Lua</span></button>
|
||
<button id="copy-link" title="Скопировать ссылку для зрителей"><span class="label">Зрителям</span></button>
|
||
<button id="open-audience" title="Открыть окно зрителя"><span class="label">Открыть</span></button>
|
||
<button class="icon" id="fullscreen" title="Полный экран">⤢</button>
|
||
<button class="icon" id="s-exit" title="Выйти">×</button>
|
||
</div>
|
||
</header>
|
||
|
||
<main class="speaker-main">
|
||
<div class="left-col">
|
||
<section class="notes-card">
|
||
<div class="card-label">
|
||
Пометки докладчика
|
||
<span class="spacer"></span>
|
||
<span class="slide-pill" id="notes-slide">Слайд 1</span>
|
||
</div>
|
||
<div class="notes-body" id="s-notes"></div>
|
||
</section>
|
||
|
||
<section class="console-card">
|
||
<div class="card-label">
|
||
Консоль команд
|
||
<span class="spacer"></span>
|
||
<span class="slide-pill" id="console-count">0</span>
|
||
<a href="docs.html" target="_blank" rel="noopener">Lua API</a>
|
||
</div>
|
||
<div class="console-list" id="console-list" tabindex="0"></div>
|
||
<div class="console-log" id="console-log"></div>
|
||
</section>
|
||
</div>
|
||
|
||
<aside class="side">
|
||
<div class="card">
|
||
<div class="card-label">Текущий слайд</div>
|
||
<div class="preview-frame" id="current-preview"></div>
|
||
</div>
|
||
|
||
<div class="card">
|
||
<div class="card-label">Следующий</div>
|
||
<div class="preview-frame preview-next" id="next-preview"></div>
|
||
</div>
|
||
|
||
<div class="card" id="window-card" hidden>
|
||
<div class="card-label">
|
||
Окно Chrome
|
||
<span class="spacer"></span>
|
||
<button id="window-refresh" title="Обновить список окон" style="padding:2px 7px;font-size:11px;border-radius:6px;">↻</button>
|
||
</div>
|
||
<div class="window-select">
|
||
<select id="window-select"></select>
|
||
</div>
|
||
<div id="window-list"></div>
|
||
<p class="window-hint" id="window-hint"></p>
|
||
</div>
|
||
|
||
<div class="card" id="video-card" hidden>
|
||
<div class="card-label">Видео на слайде</div>
|
||
<div id="video-list"></div>
|
||
</div>
|
||
|
||
<div class="card">
|
||
<div class="card-label">
|
||
Интерактив слайда
|
||
<span class="spacer"></span>
|
||
<span class="slide-pill">только докладчик</span>
|
||
</div>
|
||
<div class="interact-list" id="interact"></div>
|
||
</div>
|
||
|
||
<div class="card audio-card">
|
||
<div class="card-label">Звук</div>
|
||
<div class="audio-row">
|
||
<span>Фон</span>
|
||
<input type="range" id="bgm-vol" min="0" max="100" step="1" value="50">
|
||
<output id="bgm-out">50%</output>
|
||
</div>
|
||
<div class="audio-row">
|
||
<span>Эффекты</span>
|
||
<input type="range" id="sfx-vol" min="0" max="100" step="1" value="80">
|
||
<output id="sfx-out">80%</output>
|
||
</div>
|
||
<div class="music-state">
|
||
<span class="music-name" id="music-name">Фоновая музыка не задана</span>
|
||
<button id="music-toggle" disabled>Включить</button>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="card viewers-card">
|
||
<span>Зрителей</span>
|
||
<strong id="audience-count">0</strong>
|
||
</div>
|
||
</aside>
|
||
</main>
|
||
|
||
<footer class="controls">
|
||
<button id="prev" class="nav" disabled>← Назад</button>
|
||
<div class="dots" id="dots"></div>
|
||
<button id="next" class="nav" disabled>Вперёд →</button>
|
||
</footer>
|
||
</div>
|
||
|
||
<button class="unlock-audio" id="unlock-audio" hidden>Включить звук</button>
|
||
|
||
<div class="toast" id="toast"></div>
|
||
|
||
<div class="overlay" id="overlay" hidden>
|
||
<div class="overlay-card">
|
||
<h2 id="overlay-title">Демонстрация остановлена</h2>
|
||
<p id="overlay-text">Организатор завершил показ.</p>
|
||
<div style="display:flex;gap:8px;justify-content:center;flex-wrap:wrap">
|
||
<button id="overlay-restart" class="restart-btn" hidden>Начать заново</button>
|
||
<button onclick="location.href = 'index.html'">На главную</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="window-remote" id="window-remote" hidden>
|
||
<div class="window-remote-card">
|
||
<div class="window-remote-head">
|
||
<span class="live"><span class="dot"></span> LIVE</span>
|
||
<h3 id="window-remote-title">Окно Chrome</h3>
|
||
<button id="window-remote-close" title="Закрыть">×</button>
|
||
</div>
|
||
<div class="window-remote-stage" id="window-remote-stage">
|
||
<img id="window-remote-frame" alt="">
|
||
<div class="remote-empty" id="window-remote-empty">Нажмите «Транслировать» в панели окна</div>
|
||
</div>
|
||
<div class="window-remote-keys">
|
||
<button data-key="Escape">Esc</button>
|
||
<button data-key="Tab">Tab</button>
|
||
<button data-key="Enter">Enter</button>
|
||
<button data-key="Backspace">⌫</button>
|
||
<button data-key="ArrowLeft">←</button>
|
||
<button data-key="ArrowUp">↑</button>
|
||
<button data-key="ArrowDown">↓</button>
|
||
<button data-key="ArrowRight">→</button>
|
||
<button data-key="PageUp">PgUp</button>
|
||
<button data-key="PageDown">PgDn</button>
|
||
</div>
|
||
<div class="window-remote-text">
|
||
<input id="window-remote-text" placeholder="Текст для ввода в окно…" autocomplete="off">
|
||
<button id="window-remote-send">Ввести</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<script src="vendor/fengari-web.js"></script>
|
||
<script src="js/lua-bridge.js"></script>
|
||
<script src="js/slide-view.js"></script>
|
||
<script src="js/audio-controller.js"></script>
|
||
<script>
|
||
const params = new URLSearchParams(location.search);
|
||
const presentationId = params.get('id');
|
||
const mode = params.get('mode') === 'speaker' ? 'speaker' : 'audience';
|
||
document.body.className = `mode-${mode}`;
|
||
|
||
const state = {
|
||
title: '',
|
||
slides: [],
|
||
slideIndex: 0,
|
||
variables: {},
|
||
vars: {},
|
||
music: { src: '', volume: 0.5 },
|
||
lua: '',
|
||
commands: [],
|
||
commandsLoaded: false,
|
||
graph: { positions: {}, scripts: [], audios: [], variables: [], links: [], jumps: {} },
|
||
media: {},
|
||
windowStates: {},
|
||
windowFrames: {},
|
||
windowTargets: [],
|
||
windowEndpoint: '',
|
||
activeWindow: null,
|
||
consoleIndex: 0,
|
||
consoleLines: [],
|
||
ready: false,
|
||
ended: false,
|
||
startedAt: Date.now(),
|
||
};
|
||
|
||
let ws = null;
|
||
let reconnecting = false;
|
||
let luaRuntime = null;
|
||
let lastVarsSent = '';
|
||
let lastSlideIndex = null;
|
||
|
||
// ---------- Lua-анимации: слои перехода и Web Animations ----------
|
||
const luaLayers = { in: null, out: null };
|
||
let outRemoveTimer = null;
|
||
let luaAnimEnd = 0;
|
||
|
||
function escapeSelector(value) {
|
||
return window.CSS && CSS.escape ? CSS.escape(value) : String(value);
|
||
}
|
||
|
||
function resolveAnimTarget(target) {
|
||
const key = String(target == null ? '' : target);
|
||
if (key === 'in') return luaLayers.in || audienceFrame.querySelector('.sv-root');
|
||
if (key === 'out') return luaLayers.out;
|
||
const root = luaLayers.in || audienceFrame.querySelector('.sv-root');
|
||
if (key === '' || key === 'slide') return root;
|
||
if (root) {
|
||
const inner = root.querySelector(`[data-el="${escapeSelector(key)}"]`);
|
||
if (inner) return inner;
|
||
}
|
||
return audienceFrame.querySelector(`[data-el="${escapeSelector(key)}"]`);
|
||
}
|
||
|
||
// Кадры из Lua: { opacity = {0, 1}, y = {6, 0}, scale = 1.2 } → keyframes WAAPI.
|
||
// x/y — относительные смещения в % от размера холста (transform), w/h — абсолютные %.
|
||
function buildKeyframes(frames, rootEl) {
|
||
const entries = Object.entries(frames || {}).filter(([, value]) => value !== null && value !== undefined);
|
||
if (!entries.length) return [];
|
||
const norm = entries.map(([prop, value]) => [prop, Array.isArray(value) ? value : [value]]);
|
||
const count = Math.max(...norm.map(([, values]) => values.length));
|
||
const baseW = (rootEl && rootEl.clientWidth) || 1280;
|
||
const baseH = (rootEl && rootEl.clientHeight) || 720;
|
||
const keys = [];
|
||
for (let i = 0; i < count; i += 1) {
|
||
const key = {};
|
||
const parts = [];
|
||
for (const [prop, values] of norm) {
|
||
const raw = values[Math.min(i, values.length - 1)];
|
||
const n = Number(raw);
|
||
if (prop === 'opacity') key.opacity = Number.isFinite(n) ? n : raw;
|
||
else if (prop === 'x') parts.push(`translateX(${Number.isFinite(n) ? (n / 100) * baseW : 0}px)`);
|
||
else if (prop === 'y') parts.push(`translateY(${Number.isFinite(n) ? (n / 100) * baseH : 0}px)`);
|
||
else if (prop === 'w') key.width = `${n}%`;
|
||
else if (prop === 'h') key.height = `${n}%`;
|
||
else if (prop === 'scale') parts.push(`scale(${Number.isFinite(n) ? n : 1})`);
|
||
else if (prop === 'rotate') parts.push(`rotate(${Number.isFinite(n) ? n : 0}deg)`);
|
||
else key[prop] = raw;
|
||
}
|
||
if (parts.length) key.transform = parts.join(' ');
|
||
keys.push(key);
|
||
}
|
||
return keys;
|
||
}
|
||
|
||
function animateTarget(target, frames, opts = {}) {
|
||
const node = resolveAnimTarget(target);
|
||
if (!node || typeof node.animate !== 'function') return;
|
||
const rootEl = node.closest ? (node.closest('.sv-root') || node) : node;
|
||
const keyframes = buildKeyframes(frames, rootEl);
|
||
if (!keyframes.length) return;
|
||
const duration = Math.min(Math.max(Number(opts.duration) || 500, 16), 10000);
|
||
const delay = Math.min(Math.max(Number(opts.delay) || 0, 0), 10000);
|
||
const fill = ['forwards', 'backwards', 'both'].includes(opts.fill) ? opts.fill : 'both';
|
||
const animation = node.animate(keyframes, {
|
||
duration,
|
||
delay,
|
||
easing: String(opts.easing || 'cubic-bezier(.2, .7, .3, 1)'),
|
||
fill,
|
||
});
|
||
node._luaAnims = node._luaAnims || [];
|
||
node._luaAnims.push(animation);
|
||
luaAnimEnd = Math.max(luaAnimEnd, Date.now() + duration + delay + 60);
|
||
if (animation.finished && typeof animation.finished.catch === 'function') animation.finished.catch(() => {});
|
||
}
|
||
|
||
function clearAnimTarget(target) {
|
||
const node = resolveAnimTarget(target);
|
||
if (!node) return;
|
||
(node._luaAnims || []).forEach((item) => {
|
||
try { item.cancel(); } catch (error) { /* уже завершена */ }
|
||
});
|
||
node._luaAnims = [];
|
||
}
|
||
|
||
function transitionNodeFor(slide) {
|
||
if (!slide || !luaRuntime) return null;
|
||
const list = (state.graph && state.graph.transitions) || [];
|
||
return list.find((node) => node.slideId === slide.id && String(node.code || '').trim()) || null;
|
||
}
|
||
|
||
function runEnterAnims(slide) {
|
||
if (!luaRuntime || !slide) return;
|
||
const list = ((state.graph && state.graph.anims) || [])
|
||
.filter((node) => node.slideId === slide.id && String(node.code || '').trim());
|
||
list.forEach((node) => {
|
||
state.vars = luaRuntime.run(node.code, `анимация «${node.name || 'без названия'}»`);
|
||
});
|
||
if (list.length) syncVars();
|
||
}
|
||
|
||
function findPluginInstance(id) {
|
||
return ((state.graph && state.graph.plugins) || []).find((node) => node.id === id) || null;
|
||
}
|
||
|
||
// Исполняет ноду плагина: модуль-снимок + вызов выбранной функции.
|
||
// Функция может быть локальной — вызов дописывается в тот же чанк.
|
||
function runPluginNode(node) {
|
||
if (!luaRuntime || !node || !node.fn || !String(node.code || '').trim()) return;
|
||
const args = String(node.args || '').trim();
|
||
const code = `${node.code}\n\nreturn ${node.fn}(${args})`;
|
||
state.vars = luaRuntime.run(code, `плагин «${node.name || node.fn}»`);
|
||
syncVars();
|
||
}
|
||
|
||
// Проходит цепь от выхода слайда через переходы, анимации и плагины.
|
||
// Переходы и анимации слайда исполняются отдельно, здесь — только ноды плагинов.
|
||
function runChainNodes(fromSlide, port) {
|
||
if (mode !== 'speaker' || !luaRuntime || !fromSlide) return;
|
||
const links = (state.graph && state.graph.links) || [];
|
||
const outgoing = new Map();
|
||
links.forEach((link) => {
|
||
const key = `${link.from.kind}|${link.from.id}`;
|
||
if (!outgoing.has(key)) outgoing.set(key, []);
|
||
outgoing.get(key).push(link);
|
||
});
|
||
let current = (outgoing.get(`slide|${fromSlide.id}`) || []).find((link) => link.from.port === port);
|
||
const visited = new Set();
|
||
for (let step = 0; current && step < 32; step += 1) {
|
||
const to = current.to;
|
||
if (!to || to.kind === 'slide') break;
|
||
const key = `${to.kind}|${to.id}`;
|
||
if (visited.has(key)) break;
|
||
visited.add(key);
|
||
if (to.kind === 'plugin') runPluginNode(findPluginInstance(to.id));
|
||
current = (outgoing.get(key) || []).find((link) => link.from.port === 'out');
|
||
}
|
||
}
|
||
|
||
const $ = (id) => document.getElementById(id);
|
||
const audienceFrame = $('audience-frame');
|
||
const currentPreview = $('current-preview');
|
||
const nextPreview = $('next-preview');
|
||
const interactEl = $('interact');
|
||
const notesEl = $('s-notes');
|
||
const dotsEl = $('dots');
|
||
const prevBtn = $('prev');
|
||
const nextBtn = $('next');
|
||
const timerEl = $('timer');
|
||
const audienceCountEl = $('audience-count');
|
||
const overlay = $('overlay');
|
||
const unlockBtn = $('unlock-audio');
|
||
const toastEl = $('toast');
|
||
const bgmSlider = $('bgm-vol');
|
||
const sfxSlider = $('sfx-vol');
|
||
const musicToggle = $('music-toggle');
|
||
const musicName = $('music-name');
|
||
const consoleListEl = $('console-list');
|
||
const consoleLogEl = $('console-log');
|
||
const windowCard = $('window-card');
|
||
const windowListEl = $('window-list');
|
||
const windowSelectEl = $('window-select');
|
||
const windowHintEl = $('window-hint');
|
||
const videoCard = $('video-card');
|
||
const videoListEl = $('video-list');
|
||
const windowRemote = $('window-remote');
|
||
const windowRemoteFrame = $('window-remote-frame');
|
||
const windowRemoteEmpty = $('window-remote-empty');
|
||
const windowRemoteTitle = $('window-remote-title');
|
||
|
||
// ---------- Аудио ----------
|
||
const audio = window.createAudioController({
|
||
onBlocked: () => {
|
||
unlockBtn.hidden = false;
|
||
},
|
||
onState: () => updateAudioPanel(),
|
||
onEnded: () => {
|
||
if (mode === 'speaker') renderSpeaker();
|
||
},
|
||
});
|
||
|
||
function clamp01(value) {
|
||
return Math.max(0, Math.min(1, Number(value) || 0));
|
||
}
|
||
|
||
function currentSlide() {
|
||
return state.slides[state.slideIndex] || { elements: [], notes: '', background: {} };
|
||
}
|
||
|
||
function isAudioPlaying(id) {
|
||
return audio.getPlayingEffectIds().includes(id);
|
||
}
|
||
|
||
function findAudio(id) {
|
||
if (!id) return null;
|
||
for (const slide of state.slides) {
|
||
const found = (slide.elements || []).find((el) => el.type === 'audio' && el.id === id);
|
||
if (found) return found;
|
||
}
|
||
return null;
|
||
}
|
||
|
||
function sendAudio(command) {
|
||
audio.applyCommand(command);
|
||
if (ws && ws.readyState === WebSocket.OPEN) {
|
||
ws.send(JSON.stringify({ type: 'audio', command }));
|
||
}
|
||
updateAudioPanel();
|
||
if (['play', 'stop', 'music', 'musicStop'].includes(command.action)) refreshSlides();
|
||
}
|
||
|
||
function playAudioById(id) {
|
||
const element = findAudio(id);
|
||
if (!element) {
|
||
showToast(`Аудио ${id} не найдено`);
|
||
return;
|
||
}
|
||
sendAudio({ action: 'play', id: element.id, src: element.src, loop: !!element.loop, volume: element.volume });
|
||
}
|
||
|
||
function stopAudioById(id) {
|
||
sendAudio({ action: 'stop', id: id || '*' });
|
||
}
|
||
|
||
function startMusic(src) {
|
||
const nextSrc = src || audio.getState().musicSrc || state.music.src;
|
||
if (!nextSrc) {
|
||
showToast('Не задан источник фоновой музыки (настройки презентации)');
|
||
return;
|
||
}
|
||
sendAudio({ action: 'music', src: nextSrc, play: true });
|
||
}
|
||
|
||
function updateAudioPanel() {
|
||
const snapshot = audio.getState();
|
||
if (document.activeElement !== bgmSlider) {
|
||
bgmSlider.value = String(Math.round(snapshot.bgm * 100));
|
||
}
|
||
if (document.activeElement !== sfxSlider) {
|
||
sfxSlider.value = String(Math.round(snapshot.sfx * 100));
|
||
}
|
||
$('bgm-out').textContent = `${Math.round(snapshot.bgm * 100)}%`;
|
||
$('sfx-out').textContent = `${Math.round(snapshot.sfx * 100)}%`;
|
||
const src = snapshot.musicSrc || state.music.src;
|
||
musicName.textContent = src ? (src.split('/').pop() || src).slice(0, 40) : 'Фоновая музыка не задана';
|
||
musicName.title = src || '';
|
||
musicToggle.disabled = !src && !snapshot.musicPlaying;
|
||
musicToggle.classList.toggle('on', snapshot.musicPlaying);
|
||
musicToggle.textContent = snapshot.musicPlaying ? 'Пауза' : 'Включить';
|
||
}
|
||
|
||
// ---------- Видео ----------
|
||
function findSlideElements(type) {
|
||
const result = [];
|
||
state.slides.forEach((slide, index) => {
|
||
(slide.elements || []).forEach((element) => {
|
||
if (element.type === type) result.push({ element, slide, index });
|
||
});
|
||
});
|
||
return result;
|
||
}
|
||
|
||
function applyMediaCommand(command) {
|
||
if (!command || !command.elementId) return;
|
||
state.media[command.elementId] = command;
|
||
document.querySelectorAll(`video[data-media-id="${command.elementId}"]`).forEach((video) => {
|
||
video._applyingRemote = true;
|
||
try {
|
||
if (command.action === 'videoPlay') video.play().catch(() => {});
|
||
else if (command.action === 'videoPause') video.pause();
|
||
else if (command.action === 'videoRestart') {
|
||
video.currentTime = 0;
|
||
video.play().catch(() => {});
|
||
} else if (command.action === 'videoSeek') {
|
||
video.currentTime = Number(command.time) || 0;
|
||
}
|
||
} catch (error) {
|
||
/* видео ещё не готово */
|
||
}
|
||
setTimeout(() => {
|
||
video._applyingRemote = false;
|
||
}, 80);
|
||
});
|
||
}
|
||
|
||
function sendMedia(command) {
|
||
applyMediaCommand(command);
|
||
if (mode === 'speaker' && ws && ws.readyState === WebSocket.OPEN) {
|
||
ws.send(JSON.stringify({ type: 'media', command }));
|
||
}
|
||
}
|
||
|
||
function videoEvent(element, type, video) {
|
||
if (mode !== 'speaker') return;
|
||
if (type === 'play') sendMedia({ action: 'videoPlay', elementId: element.id, time: video.currentTime });
|
||
else if (type === 'pause') sendMedia({ action: 'videoPause', elementId: element.id, time: video.currentTime });
|
||
else if (type === 'seek') sendMedia({ action: 'videoSeek', elementId: element.id, time: video.currentTime });
|
||
}
|
||
|
||
function renderVideoPanel() {
|
||
videoCard.hidden = mode !== 'speaker';
|
||
const videos = currentSlide().elements ? currentSlide().elements.filter((el) => el.type === 'video') : [];
|
||
videoCard.hidden = mode !== 'speaker' || !videos.length;
|
||
if (videoCard.hidden) return;
|
||
videoListEl.innerHTML = '';
|
||
videos.forEach((element) => {
|
||
const row = document.createElement('div');
|
||
row.className = 'video-row';
|
||
row.innerHTML = `<div class="video-meta"><b></b><small></small></div>
|
||
<button data-media="videoPlay">Пуск</button>
|
||
<button data-media="videoPause">Пауза</button>
|
||
<button data-media="videoRestart">↺</button>`;
|
||
row.querySelector('b').textContent = element.label || (element.src ? element.src.split('/').pop() : 'Видео');
|
||
row.querySelector('small').textContent = element.src ? 'синхронизируется со зрителями' : 'не задан источник';
|
||
row.querySelectorAll('[data-media]').forEach((button) => {
|
||
button.disabled = !element.src;
|
||
button.addEventListener('click', () => {
|
||
sendMedia({ action: button.dataset.media, elementId: element.id });
|
||
});
|
||
});
|
||
videoListEl.appendChild(row);
|
||
});
|
||
}
|
||
|
||
// ---------- Окно Chrome ----------
|
||
function windowElements() {
|
||
return currentSlide().elements ? currentSlide().elements.filter((el) => el.type === 'window') : [];
|
||
}
|
||
|
||
function windowState(id) {
|
||
return state.windowStates[id] || { elementId: id, active: false, targetTitle: '', error: '' };
|
||
}
|
||
|
||
function sendWindow(type, payload = {}) {
|
||
if (mode !== 'speaker' || !ws || ws.readyState !== WebSocket.OPEN) return false;
|
||
ws.send(JSON.stringify({ type, ...payload }));
|
||
return true;
|
||
}
|
||
|
||
function dataUrl(data) {
|
||
if (!data) return '';
|
||
return /^data:/.test(data) ? data : `data:image/jpeg;base64,${data}`;
|
||
}
|
||
|
||
function updateWindowFrameDom(elementId, data) {
|
||
state.windowFrames[elementId] = data;
|
||
const src = dataUrl(data);
|
||
document.querySelectorAll(`.sv-window[data-window-id="${elementId}"]`).forEach((wrap) => {
|
||
const img = wrap.querySelector('img.sv-window-frame');
|
||
if (!img) return;
|
||
const placeholder = wrap.querySelector('.sv-window-placeholder');
|
||
if (placeholder) placeholder.remove();
|
||
img.src = src;
|
||
wrap.dataset.live = '1';
|
||
if (!wrap.querySelector('.sv-window-live')) {
|
||
const badge = document.createElement('span');
|
||
badge.className = 'sv-window-live';
|
||
badge.innerHTML = '<i></i>LIVE';
|
||
wrap.appendChild(badge);
|
||
}
|
||
});
|
||
if (state.activeWindow === elementId) {
|
||
windowRemoteFrame.src = src;
|
||
windowRemoteEmpty.hidden = true;
|
||
}
|
||
}
|
||
|
||
function renderWindowPanel() {
|
||
const windows = windowElements();
|
||
windowCard.hidden = mode !== 'speaker' || !windows.length;
|
||
if (windowCard.hidden) return;
|
||
|
||
const options = state.windowTargets.map((target) =>
|
||
`<option value="${String(target.id).replace(/"/g, '"')}">${String(target.title || target.url || target.id).replace(/[<>&]/g, '')}</option>`
|
||
);
|
||
const currentTarget = windows[0] && windows[0].targetId;
|
||
windowSelectEl.innerHTML = options.length
|
||
? options.join('')
|
||
: '<option value="">— нет доступных окон —</option>';
|
||
if (currentTarget && state.windowTargets.some((t) => t.id === currentTarget)) {
|
||
windowSelectEl.value = currentTarget;
|
||
}
|
||
windowHintEl.innerHTML = state.windowTargets.length
|
||
? 'Клик по трансляции в слайде управляет окном. <code>Пульт</code> — клавиши и ввод текста.'
|
||
: `Chrome не найден на <code>${state.windowEndpoint || '127.0.0.1:9222'}</code>. Запустите браузер с <code>--remote-debugging-port=9222</code>.`;
|
||
|
||
windowListEl.innerHTML = '';
|
||
windows.forEach((element) => {
|
||
const info = windowState(element.id);
|
||
const row = document.createElement('div');
|
||
row.className = 'window-row';
|
||
row.innerHTML = `<span class="window-status${info.active ? ' on' : ''}"></span>
|
||
<div class="window-meta"><b></b><small></small></div>
|
||
<button data-window-act="start" title="Транслировать">Пуск</button>
|
||
<button data-window-act="remote" title="Пульт управления">Пульт</button>
|
||
<button data-window-act="stop" title="Остановить">Стоп</button>`;
|
||
row.querySelector('b').textContent = element.label || 'Окно Chrome';
|
||
row.querySelector('small').textContent = info.error
|
||
? info.error.slice(0, 60)
|
||
: info.active
|
||
? (info.targetTitle || 'трансляция активна')
|
||
: 'не запущено';
|
||
row.querySelectorAll('[data-window-act]').forEach((button) => {
|
||
button.addEventListener('click', () => {
|
||
const act = button.dataset.windowAct;
|
||
if (act === 'start') {
|
||
const targetId = windowSelectEl.value || element.targetId || '';
|
||
if (!sendWindow('window-start', { elementId: element.id, targetId })) {
|
||
showToast('Нет соединения с сервером');
|
||
}
|
||
} else if (act === 'stop') {
|
||
sendWindow('window-stop', { elementId: element.id });
|
||
} else if (act === 'remote') {
|
||
openWindowRemote(element.id);
|
||
}
|
||
});
|
||
});
|
||
windowListEl.appendChild(row);
|
||
});
|
||
}
|
||
|
||
function openWindowRemote(elementId) {
|
||
state.activeWindow = elementId;
|
||
const element = windowElements().find((item) => item.id === elementId);
|
||
windowRemoteTitle.textContent = (element && element.label) || (windowState(elementId).targetTitle) || 'Окно Chrome';
|
||
const data = state.windowFrames[elementId];
|
||
windowRemoteFrame.src = data ? dataUrl(data) : '';
|
||
windowRemoteEmpty.hidden = !!data;
|
||
windowRemote.hidden = false;
|
||
}
|
||
|
||
function closeWindowRemote() {
|
||
windowRemote.hidden = true;
|
||
state.activeWindow = null;
|
||
}
|
||
|
||
function sendWindowInput(input) {
|
||
if (!state.activeWindow) return;
|
||
sendWindow('window-input', { elementId: state.activeWindow, input });
|
||
}
|
||
|
||
function maybeAutoStartWindows() {
|
||
if (mode !== 'speaker') return;
|
||
windowElements().forEach((element) => {
|
||
if (!state.windowStates[element.id]) {
|
||
state.windowStates[element.id] = { elementId: element.id, active: false, targetTitle: '', error: '' };
|
||
}
|
||
if (element.autoStart && !state.windowStates[element.id].active) {
|
||
sendWindow('window-start', { elementId: element.id, targetId: element.targetId || '' });
|
||
}
|
||
});
|
||
}
|
||
|
||
// ---------- Консоль команд ----------
|
||
function logConsole(line) {
|
||
const time = new Date();
|
||
const stamp = `${String(time.getHours()).padStart(2, '0')}:${String(time.getMinutes()).padStart(2, '0')}:${String(time.getSeconds()).padStart(2, '0')}`;
|
||
state.consoleLines.push(`${stamp} ${line}`);
|
||
if (state.consoleLines.length > 60) state.consoleLines.shift();
|
||
consoleLogEl.textContent = state.consoleLines.slice(-6).join('\n');
|
||
consoleLogEl.scrollTop = consoleLogEl.scrollHeight;
|
||
}
|
||
|
||
function renderConsole() {
|
||
if (mode !== 'speaker') return;
|
||
$('console-count').textContent = String(state.commands.length);
|
||
consoleListEl.innerHTML = '';
|
||
if (!state.commands.length) {
|
||
consoleListEl.innerHTML = '<div class="console-empty">Список команд пуст. Добавьте их в редакторе: «Команды». Каждая команда — это Lua-код, который запускается у докладчика.</div>';
|
||
return;
|
||
}
|
||
state.commands.forEach((command, index) => {
|
||
const item = document.createElement('button');
|
||
item.className = 'console-item' + (index === state.consoleIndex ? ' active' : '');
|
||
item.innerHTML = `<span class="console-idx">${index + 1}</span>
|
||
<span class="console-meta"><b></b><small></small></span>
|
||
<span class="run">▶</span>`;
|
||
item.querySelector('b').textContent = command.label || 'Команда';
|
||
item.querySelector('small').textContent = command.description || 'Lua-код';
|
||
item.addEventListener('click', () => {
|
||
state.consoleIndex = index;
|
||
renderConsole();
|
||
runCommand(command);
|
||
});
|
||
consoleListEl.appendChild(item);
|
||
});
|
||
}
|
||
|
||
function runCommand(command) {
|
||
if (mode !== 'speaker' || !command) return;
|
||
logConsole(`▸ ${command.label || 'Команда'}`);
|
||
if (!String(command.code || '').trim()) {
|
||
logConsole('пустой код команды');
|
||
return;
|
||
}
|
||
runLua(command.code, `команда «${command.label || 'без названия'}»`);
|
||
}
|
||
|
||
function setConsoleIndex(next) {
|
||
if (!state.commands.length) return;
|
||
const total = state.commands.length;
|
||
state.consoleIndex = ((next % total) + total) % total;
|
||
renderConsole();
|
||
const items = consoleListEl.querySelectorAll('.console-item');
|
||
if (items[state.consoleIndex]) items[state.consoleIndex].scrollIntoView({ block: 'nearest' });
|
||
}
|
||
|
||
// ---------- Рендер ----------
|
||
function renderAudience(animate) {
|
||
const slide = currentSlide();
|
||
$('a-title').textContent = state.title || 'Презентация';
|
||
$('a-counter').textContent = `${state.slides.length ? state.slideIndex + 1 : 0} / ${state.slides.length}`;
|
||
const progress = state.slides.length ? ((state.slideIndex + 1) / state.slides.length) * 100 : 0;
|
||
$('audience-progress').firstElementChild.style.width = `${progress}%`;
|
||
|
||
const luaTrans = animate ? transitionNodeFor(slide) : null;
|
||
if (luaTrans) {
|
||
// Lua-переход: старый слайд остаётся слоем «out», новый — «in»; скрипт управляет обоими.
|
||
const oldRoot = audienceFrame.querySelector('.sv-root');
|
||
if (oldRoot) oldRoot.remove();
|
||
SlideView.render(audienceFrame, slide, {
|
||
variables: state.vars,
|
||
animate: false,
|
||
isAudioPlaying,
|
||
windowFrames: state.windowFrames,
|
||
});
|
||
const newRoot = audienceFrame.querySelector('.sv-root');
|
||
luaLayers.in = newRoot;
|
||
luaLayers.out = oldRoot || null;
|
||
if (oldRoot) {
|
||
oldRoot.classList.add('sv-layer-out');
|
||
audienceFrame.appendChild(oldRoot);
|
||
}
|
||
clearTimeout(outRemoveTimer);
|
||
luaAnimEnd = 0;
|
||
state.vars = luaRuntime.run(luaTrans.code, `переход на слайд ${state.slideIndex + 1}`);
|
||
syncVars();
|
||
const ttl = Math.max(900, Math.min(luaAnimEnd - Date.now() + 250, 8000));
|
||
outRemoveTimer = setTimeout(() => {
|
||
if (luaLayers.out) {
|
||
luaLayers.out.remove();
|
||
luaLayers.out = null;
|
||
}
|
||
}, ttl);
|
||
} else {
|
||
if (luaLayers.out) {
|
||
luaLayers.out.remove();
|
||
luaLayers.out = null;
|
||
}
|
||
SlideView.render(audienceFrame, slide, {
|
||
variables: state.vars,
|
||
animate: !!animate,
|
||
isAudioPlaying,
|
||
windowFrames: state.windowFrames,
|
||
});
|
||
luaLayers.in = audienceFrame.querySelector('.sv-root');
|
||
}
|
||
if (animate) runEnterAnims(slide);
|
||
}
|
||
|
||
function renderSpeaker() {
|
||
const slide = currentSlide();
|
||
const total = state.slides.length;
|
||
const counterText = `${total ? state.slideIndex + 1 : 0} / ${total}`;
|
||
|
||
$('s-title').textContent = state.title || 'Презентация';
|
||
$('s-counter').textContent = counterText;
|
||
$('notes-slide').textContent = `Слайд ${state.slideIndex + 1} из ${total}`;
|
||
notesEl.textContent = slide.notes || '';
|
||
|
||
SlideView.render(currentPreview, slide, {
|
||
variables: state.vars,
|
||
isAudioPlaying,
|
||
onAction: executeAction,
|
||
windowFrames: state.windowFrames,
|
||
onWindowInput: (element, input) => sendWindow('window-input', { elementId: element.id, input }),
|
||
onVideoEvent: videoEvent,
|
||
});
|
||
const nextIndex = stepIndex(1);
|
||
SlideView.render(nextPreview, state.slides[nextIndex] || { elements: [] }, {
|
||
variables: state.vars,
|
||
windowFrames: state.windowFrames,
|
||
staticPreview: true,
|
||
});
|
||
|
||
renderInteract(slide);
|
||
renderDots();
|
||
renderVideoPanel();
|
||
renderWindowPanel();
|
||
|
||
const hasNext = jumpTarget(1) !== null;
|
||
const hasPrev = jumpTarget(-1) !== null;
|
||
prevBtn.disabled = state.ended || (!hasPrev && state.slideIndex <= 0);
|
||
nextBtn.disabled = state.ended || (!hasNext && state.slideIndex >= total - 1);
|
||
updateAudioPanel();
|
||
}
|
||
|
||
function renderDots() {
|
||
dotsEl.innerHTML = '';
|
||
state.slides.forEach((_, index) => {
|
||
const button = document.createElement('button');
|
||
button.className = 'dot' + (index === state.slideIndex ? ' active' : '');
|
||
button.textContent = index + 1;
|
||
button.disabled = state.ended;
|
||
button.addEventListener('click', () => navigate(index));
|
||
dotsEl.appendChild(button);
|
||
});
|
||
}
|
||
|
||
function actionDescription(action) {
|
||
if (!action) return 'без действия';
|
||
switch (action.type) {
|
||
case 'go': return `переход → слайд ${Number(action.slideIndex) + 1}`;
|
||
case 'next': return 'следующий слайд';
|
||
case 'prev': return 'предыдущий слайд';
|
||
case 'play': {
|
||
const element = findAudio(action.audioId);
|
||
return `аудио: ${element ? element.label || element.src : action.audioId || '—'}`;
|
||
}
|
||
case 'stop': return 'остановить аудио';
|
||
case 'lua': return 'Lua-скрипт';
|
||
default: return action.type;
|
||
}
|
||
}
|
||
|
||
function renderInteract(slide) {
|
||
interactEl.innerHTML = '';
|
||
const elements = slide.elements || [];
|
||
const buttons = elements.filter((el) => el.type === 'button');
|
||
const audios = elements.filter((el) => el.type === 'audio');
|
||
|
||
if (!buttons.length && !audios.length) {
|
||
interactEl.innerHTML = '<div class="interact-empty">На этом слайде нет кнопок и аудио.<br>Добавьте их в редакторе.</div>';
|
||
return;
|
||
}
|
||
|
||
buttons.forEach((element) => {
|
||
const row = document.createElement('div');
|
||
row.className = 'interact-item';
|
||
row.innerHTML = `
|
||
<span class="interact-icon">▶</span>
|
||
<div class="interact-meta">
|
||
<b></b>
|
||
<small></small>
|
||
</div>
|
||
<button>Запустить</button>`;
|
||
row.querySelector('b').textContent = element.label || 'Кнопка';
|
||
row.querySelector('small').textContent = actionDescription(element.action);
|
||
row.querySelector('button').addEventListener('click', () => executeAction(element.action, element));
|
||
interactEl.appendChild(row);
|
||
});
|
||
|
||
audios.forEach((element) => {
|
||
const playing = isAudioPlaying(element.id);
|
||
const row = document.createElement('div');
|
||
row.className = 'interact-item' + (playing ? ' playing' : '');
|
||
row.innerHTML = `
|
||
<span class="interact-icon">${playing ? 'играет' : 'звук'}</span>
|
||
<div class="interact-meta">
|
||
<b></b>
|
||
<small></small>
|
||
</div>
|
||
<button class="toggle">${playing ? 'Стоп' : 'Играть'}</button>`;
|
||
row.querySelector('b').textContent = element.label || element.src || 'Аудио';
|
||
row.querySelector('small').textContent = element.visible === false ? 'скрытое аудио' : 'видно на слайде';
|
||
row.querySelector('button').addEventListener('click', () => {
|
||
if (playing) stopAudioById(element.id);
|
||
else playAudioById(element.id);
|
||
});
|
||
interactEl.appendChild(row);
|
||
});
|
||
}
|
||
|
||
function refreshSlides() {
|
||
renderAudience(false);
|
||
if (mode === 'speaker') renderSpeaker();
|
||
}
|
||
|
||
// ---------- Lua ----------
|
||
function initLuaRuntime() {
|
||
if (!window.createLuaRuntime) {
|
||
console.warn('Lua runtime недоступен');
|
||
return;
|
||
}
|
||
luaRuntime = window.createLuaRuntime({
|
||
vars: state.vars,
|
||
go: (index) => navigate(index),
|
||
next: () => go(1),
|
||
prev: () => go(-1),
|
||
play: (id) => playAudioById(id),
|
||
stop: (id) => stopAudioById(id),
|
||
volume: (id, value) => sendAudio({ action: 'effectVolume', id, volume: clamp01(value) }),
|
||
music: (src) => startMusic(src),
|
||
musicPlay: () => startMusic(),
|
||
musicStop: () => sendAudio({ action: 'musicStop' }),
|
||
musicVolume: (value) => {
|
||
const snapshot = audio.getState();
|
||
sendAudio({ action: 'volumes', bgm: clamp01(value), sfx: snapshot.sfx });
|
||
},
|
||
videoPlay: (id) => sendMedia({ action: 'videoPlay', elementId: id }),
|
||
videoPause: (id) => sendMedia({ action: 'videoPause', elementId: id }),
|
||
videoRestart: (id) => sendMedia({ action: 'videoRestart', elementId: id }),
|
||
videoSeek: (id, seconds) => sendMedia({ action: 'videoSeek', elementId: id, time: Number(seconds) || 0 }),
|
||
currentSlide: () => state.slideIndex + 1,
|
||
animate: (target, frames, opts) => animateTarget(target, frames, opts),
|
||
animateClear: (target) => clearAnimTarget(target),
|
||
log: (message) => {
|
||
console.log('[lua]', message);
|
||
logConsole(String(message));
|
||
},
|
||
error: (message) => {
|
||
console.error('[lua]', message);
|
||
logConsole(`Ошибка Lua: ${message}`);
|
||
showToast(message);
|
||
},
|
||
});
|
||
luaRuntime.setVars(state.vars);
|
||
if (state.lua && state.lua.trim()) {
|
||
state.vars = luaRuntime.run(state.lua, 'скрипт презентации');
|
||
}
|
||
}
|
||
|
||
function runLua(code, label) {
|
||
if (!luaRuntime || !code || !String(code).trim()) return;
|
||
state.vars = luaRuntime.run(code, label);
|
||
syncVars();
|
||
refreshSlides();
|
||
}
|
||
|
||
function syncVars() {
|
||
if (mode !== 'speaker') return;
|
||
const payload = JSON.stringify(state.vars || {});
|
||
if (payload === lastVarsSent) return;
|
||
lastVarsSent = payload;
|
||
if (ws && ws.readyState === WebSocket.OPEN) {
|
||
ws.send(JSON.stringify({ type: 'vars', vars: state.vars }));
|
||
}
|
||
}
|
||
|
||
// ---------- Действия ----------
|
||
function executeAction(action, element) {
|
||
if (!action) return;
|
||
switch (action.type) {
|
||
case 'go':
|
||
navigate(Number(action.slideIndex) || 0);
|
||
break;
|
||
case 'next':
|
||
go(1);
|
||
break;
|
||
case 'prev':
|
||
go(-1);
|
||
break;
|
||
case 'play':
|
||
playAudioById(action.audioId);
|
||
break;
|
||
case 'stop':
|
||
stopAudioById(action.audioId);
|
||
break;
|
||
case 'lua':
|
||
runLua(action.code, `кнопка «${element && element.label ? element.label : 'без имени'}»`);
|
||
break;
|
||
default:
|
||
break;
|
||
}
|
||
}
|
||
|
||
function onSlideEnter(first) {
|
||
if (mode !== 'speaker') return;
|
||
const slide = currentSlide();
|
||
const previous = state.slides[lastSlideIndex];
|
||
if (!first && previous && previous.id !== slide.id) {
|
||
runChainNodes(previous, state.slideIndex >= lastSlideIndex ? 'next' : 'prev');
|
||
}
|
||
if (luaRuntime && slide.lua && slide.lua.trim()) {
|
||
state.vars = luaRuntime.run(slide.lua, `слайд ${state.slideIndex + 1}`);
|
||
syncVars();
|
||
}
|
||
lastSlideIndex = state.slideIndex;
|
||
}
|
||
|
||
function stopEffectsAndBroadcast() {
|
||
const ids = audio.getPlayingEffectIds();
|
||
audio.stopAllEffects();
|
||
if (mode === 'speaker' && ws && ws.readyState === WebSocket.OPEN) {
|
||
ids.forEach((id) => ws.send(JSON.stringify({ type: 'audio', command: { action: 'stop', id } })));
|
||
}
|
||
}
|
||
|
||
// ---------- Навигация ----------
|
||
function navigate(index) {
|
||
if (state.ended) return;
|
||
const next = Math.max(0, Math.min(Number(index) || 0, state.slides.length - 1));
|
||
if (next === state.slideIndex) return;
|
||
if (ws && ws.readyState === WebSocket.OPEN) {
|
||
ws.send(JSON.stringify({ type: 'navigate', slideIndex: next }));
|
||
} else {
|
||
state.slideIndex = next;
|
||
renderAll(true);
|
||
}
|
||
}
|
||
|
||
function go(delta) {
|
||
navigate(stepIndex(delta));
|
||
}
|
||
|
||
// Связи «Дальше»/«Назад» из графа имеют приоритет над порядком слайдов.
|
||
function jumpTarget(delta) {
|
||
const slide = state.slides[state.slideIndex];
|
||
if (!slide) return null;
|
||
const jumps = state.graph && state.graph.jumps ? state.graph.jumps : {};
|
||
const port = delta > 0 ? 'next' : 'prev';
|
||
const targetId = jumps[slide.id] && jumps[slide.id][port];
|
||
if (!targetId) return null;
|
||
const index = state.slides.findIndex((item) => item.id === targetId);
|
||
return index >= 0 ? index : null;
|
||
}
|
||
|
||
function stepIndex(delta) {
|
||
const jump = jumpTarget(delta);
|
||
if (jump !== null) return jump;
|
||
return state.slideIndex + delta;
|
||
}
|
||
|
||
// ---------- Сообщения сервера ----------
|
||
function applySync(message) {
|
||
const previousIndex = state.slideIndex;
|
||
const first = !state.ready;
|
||
|
||
state.title = message.title || 'Без названия';
|
||
state.slides = Array.isArray(message.slides) ? message.slides : [];
|
||
state.slideIndex = Math.max(0, Math.min(Number(message.slideIndex) || 0, Math.max(state.slides.length - 1, 0)));
|
||
state.music = message.music || { src: '', volume: 0.5 };
|
||
state.lua = message.lua || '';
|
||
if (message.graph) state.graph = message.graph;
|
||
if (Array.isArray(message.commands)) state.commands = message.commands;
|
||
|
||
if (first) {
|
||
state.vars = { ...(message.variables || {}) };
|
||
} else if (message.variables) {
|
||
state.vars = { ...message.variables, ...state.vars };
|
||
}
|
||
if (mode === 'speaker' && luaRuntime) luaRuntime.setVars(state.vars);
|
||
|
||
state.ready = true;
|
||
const slideChanged = first || state.slideIndex !== previousIndex;
|
||
|
||
if (first) {
|
||
audio.setBgmLevel(state.music.volume);
|
||
// Lua-рантайм нужен и зрителям: переходы и анимации выполняются на каждой странице
|
||
initLuaRuntime();
|
||
if (mode === 'speaker') {
|
||
if (state.music.src) {
|
||
setTimeout(() => {
|
||
if (!audio.getState().musicPlaying) startMusic(state.music.src);
|
||
}, 450);
|
||
}
|
||
}
|
||
}
|
||
|
||
if (slideChanged) stopEffectsAndBroadcast();
|
||
if (mode === 'speaker' && slideChanged) onSlideEnter(first);
|
||
renderAudience(slideChanged);
|
||
if (mode === 'speaker') {
|
||
renderSpeaker();
|
||
renderConsole();
|
||
if (slideChanged) {
|
||
maybeAutoStartWindows();
|
||
if (first) sendWindow('window-targets');
|
||
}
|
||
}
|
||
document.title = `${state.title} — Promptly`;
|
||
}
|
||
|
||
function applyVars(vars) {
|
||
if (!vars || typeof vars !== 'object') return;
|
||
state.vars = { ...state.vars, ...vars };
|
||
if (mode === 'speaker' && luaRuntime) luaRuntime.setVars(state.vars);
|
||
refreshSlides();
|
||
}
|
||
|
||
function connect() {
|
||
const wsProto = location.protocol === 'https:' ? 'wss' : 'ws';
|
||
ws = new WebSocket(`${wsProto}://${location.host}/?id=${encodeURIComponent(presentationId)}&role=${mode}`);
|
||
|
||
ws.onmessage = (event) => {
|
||
let message;
|
||
try {
|
||
message = JSON.parse(event.data);
|
||
} catch (error) {
|
||
return;
|
||
}
|
||
|
||
if (message.type === 'sync') {
|
||
applySync(message);
|
||
} else if (message.type === 'vars') {
|
||
applyVars(message.vars);
|
||
} else if (message.type === 'audio') {
|
||
audio.applyCommand(message.command);
|
||
updateAudioPanel();
|
||
if (['play', 'stop', 'music', 'musicStop'].includes(message.command && message.command.action)) {
|
||
refreshSlides();
|
||
}
|
||
} else if (message.type === 'audio-state') {
|
||
const snapshot = message.state || {};
|
||
audio.applyVolumes(snapshot.bgm, snapshot.sfx);
|
||
if (snapshot.musicSrc || snapshot.musicPlaying) {
|
||
audio.applyCommand({ action: 'music', src: snapshot.musicSrc || '', play: !!snapshot.musicPlaying });
|
||
refreshSlides();
|
||
}
|
||
} else if (message.type === 'media') {
|
||
applyMediaCommand(message.command);
|
||
if (mode === 'speaker') renderVideoPanel();
|
||
} else if (message.type === 'media-state') {
|
||
(message.states || []).forEach(applyMediaCommand);
|
||
if (mode === 'speaker') renderVideoPanel();
|
||
} else if (message.type === 'window-state') {
|
||
const stateInfo = message.state || {};
|
||
if (stateInfo.elementId) {
|
||
state.windowStates[stateInfo.elementId] = {
|
||
...(state.windowStates[stateInfo.elementId] || {}),
|
||
...stateInfo,
|
||
};
|
||
if (mode === 'speaker') {
|
||
renderWindowPanel();
|
||
if (state.activeWindow === stateInfo.elementId && stateInfo.targetTitle) {
|
||
windowRemoteTitle.textContent = stateInfo.targetTitle;
|
||
}
|
||
}
|
||
}
|
||
} else if (message.type === 'window-frame') {
|
||
if (message.elementId) updateWindowFrameDom(message.elementId, message.data);
|
||
} else if (message.type === 'window-stop') {
|
||
if (message.elementId) {
|
||
state.windowStates[message.elementId] = {
|
||
...(state.windowStates[message.elementId] || { elementId: message.elementId }),
|
||
active: false,
|
||
};
|
||
delete state.windowFrames[message.elementId];
|
||
refreshSlides();
|
||
if (state.activeWindow === message.elementId) {
|
||
windowRemoteFrame.src = '';
|
||
windowRemoteEmpty.hidden = false;
|
||
}
|
||
}
|
||
} else if (message.type === 'window-error') {
|
||
if (message.elementId) {
|
||
state.windowStates[message.elementId] = {
|
||
...(state.windowStates[message.elementId] || { elementId: message.elementId }),
|
||
active: false,
|
||
error: message.message || '',
|
||
};
|
||
showToast(`Окно: ${message.message || 'ошибка трансляции'}`);
|
||
if (mode === 'speaker') renderWindowPanel();
|
||
}
|
||
} else if (message.type === 'window-starting') {
|
||
if (message.elementId) {
|
||
state.windowStates[message.elementId] = {
|
||
...(state.windowStates[message.elementId] || { elementId: message.elementId }),
|
||
active: true,
|
||
error: '',
|
||
};
|
||
if (mode === 'speaker') renderWindowPanel();
|
||
}
|
||
} else if (message.type === 'window-targets') {
|
||
state.windowTargets = Array.isArray(message.targets) ? message.targets : [];
|
||
state.windowEndpoint = message.endpoint || '';
|
||
if (mode === 'speaker') renderWindowPanel();
|
||
} else if (message.type === 'sessions') {
|
||
const session = message.sessions.find((item) => item.presentationId === presentationId);
|
||
if (session) {
|
||
audienceCountEl.textContent = session.viewers;
|
||
if (session.startedAt && session.startedAt < state.startedAt) state.startedAt = session.startedAt;
|
||
}
|
||
} else if (message.type === 'session-ended') {
|
||
state.ended = true;
|
||
audio.stopAllEffects();
|
||
audio.stopMusic();
|
||
if (mode === 'speaker') renderSpeaker();
|
||
showOverlay('Демонстрация остановлена', 'Организатор завершил показ.');
|
||
} else if (message.type === 'error') {
|
||
state.ended = true;
|
||
audio.stopAllEffects();
|
||
audio.stopMusic();
|
||
showOverlay('Презентация не найдена', 'Возможно, её удалили.');
|
||
}
|
||
};
|
||
|
||
ws.onclose = (event) => {
|
||
if (state.ended) return;
|
||
if (event.code === 4004) {
|
||
state.ended = true;
|
||
showOverlay('Презентация не найдена', 'Возможно, её удалили.');
|
||
return;
|
||
}
|
||
if (reconnecting) return;
|
||
reconnecting = true;
|
||
setTimeout(() => {
|
||
reconnecting = false;
|
||
connect();
|
||
}, 1500);
|
||
};
|
||
|
||
ws.onerror = () => ws.close();
|
||
}
|
||
|
||
function renderAll(animate) {
|
||
renderAudience(animate);
|
||
if (mode === 'speaker') renderSpeaker();
|
||
}
|
||
|
||
function showOverlay(title, message) {
|
||
$('overlay-title').textContent = title;
|
||
$('overlay-text').textContent = message;
|
||
overlay.hidden = false;
|
||
const restart = $('overlay-restart');
|
||
// Перезапуск имеет смысл, только если презентация цела и это окно докладчика.
|
||
restart.hidden = !(mode === 'speaker');
|
||
restart.onclick = () => location.reload();
|
||
}
|
||
|
||
let toastTimer = null;
|
||
function showToast(message) {
|
||
toastEl.textContent = message;
|
||
toastEl.classList.add('visible');
|
||
clearTimeout(toastTimer);
|
||
toastTimer = setTimeout(() => toastEl.classList.remove('visible'), 4200);
|
||
}
|
||
|
||
function updateTimer() {
|
||
if (state.ended) return;
|
||
const seconds = Math.floor((Date.now() - state.startedAt) / 1000);
|
||
const hours = Math.floor(seconds / 3600);
|
||
const minutes = Math.floor((seconds % 3600) / 60);
|
||
const rest = seconds % 60;
|
||
const pad = (value) => String(value).padStart(2, '0');
|
||
timerEl.textContent = hours > 0 ? `${hours}:${pad(minutes)}:${pad(rest)}` : `${pad(minutes)}:${pad(rest)}`;
|
||
}
|
||
setInterval(updateTimer, 1000);
|
||
|
||
// ---------- UI события ----------
|
||
prevBtn.addEventListener('click', () => go(-1));
|
||
nextBtn.addEventListener('click', () => go(1));
|
||
$('s-exit').addEventListener('click', () => (location.href = 'index.html'));
|
||
$('a-exit').addEventListener('click', () => (location.href = 'index.html'));
|
||
|
||
const audienceUrl = () =>
|
||
`${location.origin}${location.pathname}?id=${encodeURIComponent(presentationId)}&mode=audience`;
|
||
|
||
$('copy-link').addEventListener('click', async (event) => {
|
||
const button = event.currentTarget;
|
||
const original = button.innerHTML;
|
||
try {
|
||
await navigator.clipboard.writeText(audienceUrl());
|
||
button.textContent = 'Скопировано';
|
||
} catch (error) {
|
||
window.prompt('Ссылка для зрителей:', audienceUrl());
|
||
}
|
||
setTimeout(() => (button.innerHTML = original), 1600);
|
||
});
|
||
|
||
$('open-audience').addEventListener('click', () => window.open(audienceUrl(), '_blank'));
|
||
|
||
$('fullscreen').addEventListener('click', () => {
|
||
if (!document.fullscreenElement) document.documentElement.requestFullscreen?.();
|
||
else document.exitFullscreen?.();
|
||
});
|
||
|
||
unlockBtn.addEventListener('click', () => {
|
||
audio.unlock();
|
||
unlockBtn.hidden = true;
|
||
updateAudioPanel();
|
||
});
|
||
|
||
bgmSlider.addEventListener('input', () => {
|
||
const value = clamp01(Number(bgmSlider.value) / 100);
|
||
const snapshot = audio.getState();
|
||
sendAudio({ action: 'volumes', bgm: value, sfx: snapshot.sfx });
|
||
});
|
||
|
||
sfxSlider.addEventListener('input', () => {
|
||
const value = clamp01(Number(sfxSlider.value) / 100);
|
||
const snapshot = audio.getState();
|
||
sendAudio({ action: 'volumes', bgm: snapshot.bgm, sfx: value });
|
||
});
|
||
|
||
musicToggle.addEventListener('click', () => {
|
||
if (audio.getState().musicPlaying) sendAudio({ action: 'musicStop' });
|
||
else startMusic();
|
||
});
|
||
|
||
$('docs-link').addEventListener('click', () => window.open('docs.html', '_blank'));
|
||
|
||
// ---------- Консоль ----------
|
||
consoleListEl.addEventListener('keydown', (event) => {
|
||
if (!state.commands.length) return;
|
||
if (event.key === 'ArrowDown') {
|
||
event.preventDefault();
|
||
setConsoleIndex(state.consoleIndex + 1);
|
||
} else if (event.key === 'ArrowUp') {
|
||
event.preventDefault();
|
||
setConsoleIndex(state.consoleIndex - 1);
|
||
} else if (event.key === 'Enter') {
|
||
event.preventDefault();
|
||
runCommand(state.commands[state.consoleIndex]);
|
||
} else if (event.key === 'Home') {
|
||
event.preventDefault();
|
||
setConsoleIndex(0);
|
||
} else if (event.key === 'End') {
|
||
event.preventDefault();
|
||
setConsoleIndex(state.commands.length - 1);
|
||
}
|
||
});
|
||
consoleListEl.addEventListener('click', () => consoleListEl.focus());
|
||
|
||
// ---------- Окно Chrome ----------
|
||
$('window-refresh').addEventListener('click', () => {
|
||
if (!sendWindow('window-targets')) {
|
||
fetch('/api/windows')
|
||
.then((response) => response.json())
|
||
.then((data) => {
|
||
state.windowTargets = data.targets || [];
|
||
state.windowEndpoint = data.endpoint || '';
|
||
renderWindowPanel();
|
||
})
|
||
.catch(() => showToast('Сервер недоступен'));
|
||
}
|
||
});
|
||
|
||
const remoteStage = $('window-remote-stage');
|
||
function remotePoint(event) {
|
||
const rect = remoteStage.getBoundingClientRect();
|
||
if (!rect.width || !rect.height) return null;
|
||
return {
|
||
x: Math.max(0, Math.min(1, (event.clientX - rect.left) / rect.width)),
|
||
y: Math.max(0, Math.min(1, (event.clientY - rect.top) / rect.height)),
|
||
};
|
||
}
|
||
remoteStage.addEventListener('click', (event) => {
|
||
if (!state.activeWindow) return;
|
||
const point = remotePoint(event);
|
||
if (point) sendWindowInput({ kind: 'click', ...point });
|
||
});
|
||
remoteStage.addEventListener(
|
||
'wheel',
|
||
(event) => {
|
||
if (!state.activeWindow) return;
|
||
event.preventDefault();
|
||
const point = remotePoint(event);
|
||
if (point) {
|
||
sendWindowInput({ kind: 'wheel', ...point, deltaX: event.deltaX, deltaY: event.deltaY });
|
||
}
|
||
},
|
||
{ passive: false }
|
||
);
|
||
|
||
document.querySelectorAll('[data-key]').forEach((button) => {
|
||
button.addEventListener('click', () => sendWindowInput({ kind: 'key', key: button.dataset.key }));
|
||
});
|
||
|
||
$('window-remote-send').addEventListener('click', () => {
|
||
const input = $('window-remote-text');
|
||
if (!input.value) return;
|
||
sendWindowInput({ kind: 'text', text: input.value });
|
||
input.value = '';
|
||
input.focus();
|
||
});
|
||
$('window-remote-text').addEventListener('keydown', (event) => {
|
||
if (event.key !== 'Enter') return;
|
||
event.preventDefault();
|
||
const text = event.currentTarget.value;
|
||
if (text) sendWindowInput({ kind: 'text', text });
|
||
event.currentTarget.value = '';
|
||
});
|
||
$('window-remote-close').addEventListener('click', closeWindowRemote);
|
||
windowRemote.addEventListener('click', (event) => {
|
||
if (event.target === windowRemote) closeWindowRemote();
|
||
});
|
||
|
||
// HUD зрителя появляется при движении мыши
|
||
let hudTimer = null;
|
||
document.addEventListener('mousemove', () => {
|
||
if (mode !== 'audience') return;
|
||
const hud = $('hud');
|
||
hud.classList.add('visible');
|
||
clearTimeout(hudTimer);
|
||
hudTimer = setTimeout(() => hud.classList.remove('visible'), 2200);
|
||
});
|
||
|
||
document.addEventListener('dblclick', () => {
|
||
if (mode !== 'audience') return;
|
||
if (!document.fullscreenElement) document.documentElement.requestFullscreen?.();
|
||
else document.exitFullscreen?.();
|
||
});
|
||
|
||
window.addEventListener('keydown', (event) => {
|
||
if (mode !== 'speaker' || state.ended) return;
|
||
if (!windowRemote.hidden) {
|
||
if (event.key === 'Escape') {
|
||
event.preventDefault();
|
||
closeWindowRemote();
|
||
}
|
||
return;
|
||
}
|
||
if (event.target.matches('input, textarea, select')) return;
|
||
if (['ArrowRight', 'ArrowDown', ' ', 'PageDown'].includes(event.key)) {
|
||
event.preventDefault();
|
||
go(1);
|
||
} else if (['ArrowLeft', 'ArrowUp', 'Backspace', 'PageUp'].includes(event.key)) {
|
||
event.preventDefault();
|
||
go(-1);
|
||
} else if (event.key === 'Home') {
|
||
event.preventDefault();
|
||
navigate(0);
|
||
} else if (event.key === 'End') {
|
||
event.preventDefault();
|
||
navigate(state.slides.length - 1);
|
||
} else if (event.key.toLowerCase() === 'f') {
|
||
if (!document.fullscreenElement) document.documentElement.requestFullscreen?.();
|
||
else document.exitFullscreen?.();
|
||
}
|
||
});
|
||
|
||
// ---------- Инициализация ----------
|
||
async function init() {
|
||
if (!presentationId) {
|
||
showOverlay('Презентация не найдена', 'В ссылке нет идентификатора презентации.');
|
||
return;
|
||
}
|
||
updateAudioPanel();
|
||
try {
|
||
const response = await fetch(`/api/presentations/${encodeURIComponent(presentationId)}`);
|
||
if (!response.ok) {
|
||
showOverlay('Презентация не найдена', 'Возможно, её удалили.');
|
||
return;
|
||
}
|
||
const presentation = await response.json();
|
||
state.title = presentation.title;
|
||
state.slides = presentation.slides || [];
|
||
state.slideIndex = presentation.currentSlide || 0;
|
||
state.music = presentation.music || { src: '', volume: 0.5 };
|
||
state.lua = presentation.lua || '';
|
||
state.graph = presentation.graph || state.graph;
|
||
state.vars = { ...(presentation.variables || {}) };
|
||
state.commands = Array.isArray(presentation.commands) ? presentation.commands : [];
|
||
state.ready = false;
|
||
renderAll(false);
|
||
renderConsole();
|
||
connect();
|
||
} catch (error) {
|
||
showOverlay('Ошибка загрузки', 'Не удалось загрузить презентацию. Проверьте соединение.');
|
||
}
|
||
}
|
||
|
||
init();
|
||
</script>
|
||
</body>
|
||
</html>
|