Promptly: node graph presentation studio
This commit is contained in:
commit
143ad3f6fa
19 files changed
+8778
No files matched your search
@@ -0,0 +1,8 @@
|
||||
node_modules/
|
||||
npm-debug.log*
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
.DS_Store
|
||||
*.log
|
||||
.idea/
|
||||
@@ -0,0 +1,199 @@
|
||||
# Promptly
|
||||
|
||||
Личная студия презентаций: свободный холст, живые кнопки, Lua-сценарии, управляемый звук и видео, трансляция окна Chrome и синхронизация между докладчиком и зрителями без перезагрузок.
|
||||
|
||||
## Запуск
|
||||
|
||||
```bash
|
||||
npm install # также копирует движок Lua в public/vendor
|
||||
npm start # или: npm run dev (с авто-перезапуском)
|
||||
```
|
||||
|
||||
По умолчанию сервер слушает порт **3045**. Если он занят, задайте свой:
|
||||
|
||||
```bash
|
||||
PORT=3001 npm run dev
|
||||
```
|
||||
|
||||
## Что умеет
|
||||
|
||||
- **Свободный холст.** Фон: цвет, CSS-градиент или изображение. Текст, картинки, кнопки, аудио, видео и окна размещаются в любом месте слайда и перетаскиваются мышью.
|
||||
- **Переходы.** Плавное появление, сдвиг, приближение или без анимации — отдельно для каждого слайда.
|
||||
- **Кнопки-переходы.** Кнопка ведёт на любой слайд, листает вперёд/назад, запускает или останавливает аудио либо выполняет Lua-код.
|
||||
- **Lua.** Глобальный скрипт презентации, скрипты слайдов, кнопок и команды докладчика. Переменные общие для всех слайдов и синхронизируются со зрителями. В текстах доступна подстановка `{{имя}}`.
|
||||
- **Звук.** Фоновая музыка играет постоянно, эффекты запускаются кнопками. Во время эффекта фон плавно приглушается (ducking), затем возвращается. Докладчик отдельно меняет громкость фона и эффектов на лету.
|
||||
- **Видео.** Ссылка или загрузка файла на сервер. Докладчик управляет воспроизведением, зрители получают те же команды; позиция и пауза синхронизированы.
|
||||
- **Окно Chrome.** Живая трансляция другой вкладки/окна и удалённые клики, клавиши и ввод текста через Chrome DevTools Protocol.
|
||||
- **Консоль команд.** Заранее заготовленные Lua-команды с названием и описанием. Докладчик листает список стрелками и запускает Enter.
|
||||
- **Граф презентации.** Нодовый редактор в духе Unity Shader Graph: слайды, код, аудио и переменные — отдельные ноды с портами. Связи создаются вручную, «Дальше»/«Назад» и запуск аудио вынесены в отдельные выходы, переменные подключаются к портам `⌘ имя`.
|
||||
- **Два режима показа.** Зритель видит только слайд. Докладчик — пометки, превью, консоль, панели окна/видео, таймер и управление звуком.
|
||||
- **Всё живьём.** Изменения в редакторе и действия докладчика приходят через WebSocket без перезагрузки.
|
||||
|
||||
## Страницы
|
||||
|
||||
| Страница | Назначение |
|
||||
| --- | --- |
|
||||
| `/` | Дашборд: презентации с миниатюрами и активные демонстрации |
|
||||
| `/editor.html` | Конструктор новой презентации |
|
||||
| `/editor.html?id=<id>` | Редактор существующей презентации (автосохранение, `Ctrl+S`) |
|
||||
| `/viewer.html?id=<id>&mode=audience` | Режим зрителя: только слайд |
|
||||
| `/viewer.html?id=<id>&mode=speaker` | Режим докладчика: пометки, превью, консоль, окно, видео, звук |
|
||||
| `/docs.html` | Полный справочник Lua API |
|
||||
|
||||
## Редактор
|
||||
|
||||
- Слева — миниатюры слайдов, добавление, дублирование и порядок.
|
||||
- По центру — холст 16:9 и переключатель **Холст / Граф**.
|
||||
- Сверху — добавление текста, картинки, кнопки, аудио, видео и окна.
|
||||
- Справа — инспектор элемента (координаты, размер, стиль, действие кнопки) и настройки слайда (фон, переход, пометки, Lua).
|
||||
- **⌘ Команды** — список команд для консоли докладчика.
|
||||
- **⚙ Настройки** — глобальные переменные, фоновая музыка, общий Lua.
|
||||
- **Граф** — ноды слайдов, кода, аудио и переменных. Потяните от выхода к входу, чтобы создать связь. «Дальше» и «Назад» — отдельные выходы слайда, кнопки — свои выходы, аудио и переменные — отдельные ноды. Клик по линии и `Delete` удаляют связь; двойной клик по слайду открывает холст.
|
||||
- **Переменные в графе.** Вставка `{{score}}` создаёт на слайде порт `⌘ score`. Подключите к нему ноду переменной `rank` — текст станет `{{rank}}`, и инспектор текста покажет новую привязку.
|
||||
|
||||
## Lua API
|
||||
|
||||
Полная документация — [`/docs.html`](public/docs.html). Кратко:
|
||||
|
||||
```lua
|
||||
-- Переменные (общие, синхронизируются со зрителями)
|
||||
vars.score = (vars.score or 0) + 1
|
||||
app.setVar('score', vars.score)
|
||||
local name = app.getVar('name')
|
||||
|
||||
-- Навигация
|
||||
app.go(3) -- слайд 3 (нумерация с 1)
|
||||
app.next()
|
||||
app.prev()
|
||||
app.slide() -- номер текущего слайда
|
||||
|
||||
-- Аудио
|
||||
app.play('audio_id')
|
||||
app.stop('audio_id')
|
||||
app.volume('audio_id', 0.6)
|
||||
app.music('https://.../music.mp3')
|
||||
app.musicPlay()
|
||||
app.musicStop()
|
||||
app.musicVolume(0.4)
|
||||
|
||||
-- Видео
|
||||
app.videoPlay('video_id')
|
||||
app.videoPause('video_id')
|
||||
app.videoRestart('video_id')
|
||||
app.videoSeek('video_id', 12)
|
||||
|
||||
app.log('готово')
|
||||
```
|
||||
|
||||
## Трансляция окна Chrome
|
||||
|
||||
Браузер не может нажимать кнопки в произвольных нативных приложениях. Трансляция и ввод работают для Chrome/Chromium/Electron с включённым remote debugging:
|
||||
|
||||
```bash
|
||||
google-chrome --remote-debugging-port=9222 \
|
||||
--user-data-dir=/tmp/promptly-chrome
|
||||
```
|
||||
|
||||
1. Откройте в этом Chrome нужную страницу.
|
||||
2. В редакторе добавьте элемент **Окно**, обновите список и выберите цель.
|
||||
3. В окне докладчика нажмите **▶ Транслировать**. Клик по трансляции передаёт клик, **Пульт** — клавиши и текст.
|
||||
|
||||
Адрес CDP задаётся переменной окружения `CHROME_DEBUG_URL` (по умолчанию `http://127.0.0.1:9222`).
|
||||
|
||||
## Загрузка видео
|
||||
|
||||
В инспекторе видео нажмите **⬆ Загрузить файл**. Файл уходит на `POST /api/uploads` и сохраняется в `public/uploads`, после чего доступен по локальному URL. Ограничение тела запроса — 512 МБ.
|
||||
|
||||
## REST API
|
||||
|
||||
- `GET /api/presentations` — список презентаций
|
||||
- `POST /api/presentations` — создать `{ title, slides, variables, music, lua, commands, graph }`
|
||||
- `GET /api/presentations/:id` — получить презентацию
|
||||
- `PUT /api/presentations/:id` — обновить презентацию
|
||||
- `POST /api/presentations/:id/duplicate` — дублировать
|
||||
- `DELETE /api/presentations/:id` — удалить (останавливает демонстрацию)
|
||||
- `GET /api/sessions` — активные демонстрации
|
||||
- `DELETE /api/sessions/:presentationId` — остановить демонстрацию удалённо
|
||||
- `POST /api/uploads?name=<file>` — загрузить файл сырым телом, ответ `{ url, name, size }`
|
||||
- `GET /api/windows` — список целей Chrome и адрес CDP
|
||||
|
||||
## WebSocket
|
||||
|
||||
- `ws://host/` — глобальный канал: снапшоты `presentations` и `sessions`.
|
||||
- `ws://host/?id=<presentationId>&role=speaker|audience` — комната демонстрации:
|
||||
- сервер → клиент: `sync { title, slides, slideIndex, variables, music, lua, commands, graph }`, `vars`, `audio`, `audio-state`, `media`, `media-state`, `window-state`, `window-frame`, `window-starting`, `window-targets`, `window-error`, `sessions`, `session-ended`
|
||||
- клиент → сервер: `navigate`, `audio`, `vars`, `media { command }`, `window-start`, `window-stop`, `window-input`, `window-targets`
|
||||
|
||||
Аудио-команды: `{ action: 'music', src, play }`, `{ action: 'musicStop' }`, `{ action: 'play', id, src, loop, volume }`, `{ action: 'stop', id }`, `{ action: 'effectVolume', id, volume }`, `{ action: 'volumes', bgm, sfx }`.
|
||||
|
||||
Медиа-команды: `{ action: 'videoPlay' | 'videoPause' | 'videoRestart' | 'videoSeek', elementId, time }`.
|
||||
|
||||
Ввод в окно: `{ kind: 'click' | 'move' | 'wheel', x, y, deltaX, deltaY }`, `{ kind: 'key', key }`, `{ kind: 'text', text }`; координаты нормализованы `0..1`. Поздние зрители получают актуальное аудио/видео/окно-состояние и последний кадр при подключении.
|
||||
|
||||
## Модель слайда
|
||||
|
||||
```js
|
||||
{
|
||||
id, notes, transition: 'none' | 'fade' | 'slide' | 'zoom', lua,
|
||||
background: { type: 'color' | 'gradient' | 'image', color, gradient, image },
|
||||
elements: [
|
||||
{ id, type: 'text', x, y, w, h, z, text, fontSize, color, weight, align, bg },
|
||||
{ id, type: 'image', x, y, w, h, z, src, fit, radius },
|
||||
{ id, type: 'button', x, y, w, h, z, label, bg, color, fontSize, radius, action },
|
||||
{ id, type: 'audio', x, y, w, h, z, src, loop, visible, volume, label },
|
||||
{ id, type: 'video', x, y, w, h, z, src, poster, fit, radius, autoplay, loop, muted, controls, label },
|
||||
{ id, type: 'window', x, y, w, h, z, targetId, targetTitle, radius, autoStart, label }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
`x/y/w/h` — проценты от размера слайда, `fontSize` — в `cqw` (1% ширины слайда). Действие кнопки: `{ type: 'go' | 'next' | 'prev' | 'play' | 'stop' | 'lua', slideIndex, audioId, code, scriptNodeId }`.
|
||||
|
||||
Презентация дополнительно хранит:
|
||||
|
||||
```js
|
||||
{
|
||||
variables: { key: 'value' },
|
||||
music: { src, volume },
|
||||
lua: '...',
|
||||
commands: [{ id, label, description, code }],
|
||||
graph: {
|
||||
positions: { [slideId]: { x, y } },
|
||||
scripts: [{ id, name, code, x, y, slideId, elementId }],
|
||||
audios: [{ id, name, elementId, mode: 'play' | 'stop', x, y }],
|
||||
variables: [{ id, name, x, y }],
|
||||
links: [{ id, from: { kind, id, port }, to: { kind, id, port } }],
|
||||
jumps: { [slideId]: { next: slideId, prev: slideId } }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`kind` в связях — `slide`, `script`, `audio` или `variable`. Порты слайда: `in`, `next`, `prev`, `btn:<elementId>`, `var:<elementId>:<name>`. У кода и аудио — `in`, у переменной — `value`. `jumps` вычисляется сервером из связей `next`/`prev` → `in` и используется окном показа для навигации.
|
||||
|
||||
## Структура
|
||||
|
||||
```
|
||||
server.js — точка входа (Express + WebSocket)
|
||||
server/store.js — in-memory хранилище и нормализация модели
|
||||
server/hub.js — комнаты, сессии, переменные, аудио/видео/окно-состояние
|
||||
server/routes.js — REST API, загрузка файлов, список окон
|
||||
server/ws.js — обработка WS-сообщений
|
||||
server/cdp.js — трансляция и ввод через Chrome DevTools Protocol
|
||||
public/index.html — дашборд
|
||||
public/editor.html — холст-редактор, граф и команды
|
||||
public/viewer.html — режимы зрителя и докладчика
|
||||
public/docs.html — справочник Lua
|
||||
public/js/slide-view.js — общий рендерер слайдов
|
||||
public/js/audio-controller.js — музыка, эффекты, ducking, громкости
|
||||
public/js/lua-bridge.js — мост Lua ↔ приложение
|
||||
public/vendor/fengari-web.js — движок Lua для браузера
|
||||
public/uploads/ — загруженные видеофайлы
|
||||
```
|
||||
|
||||
## Ограничения
|
||||
|
||||
- Данные хранятся в памяти: после перезапуска сервера презентации исчезают. Загруженные файлы в `public/uploads` остаются.
|
||||
- Lua выполняется только в окне докладчика. Закрытое окно докладчика останавливает скрипты.
|
||||
- Переменные должны быть плоскими: строка, число, boolean.
|
||||
- Трансляция и клики по чужому окну работают только через Chrome DevTools Protocol; нативные приложения не поддерживаются.
|
||||
- Для CDP нужен отдельный экземпляр Chrome с `--remote-debugging-port` и своим `--user-data-dir`.
|
||||
Generated
+840
@@ -0,0 +1,840 @@
|
||||
{
|
||||
"name": "promptly",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "promptly",
|
||||
"version": "1.0.0",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"express": "^4.21.2",
|
||||
"fengari": "^0.1.5",
|
||||
"fengari-web": "^0.1.4",
|
||||
"ws": "^8.18.0"
|
||||
}
|
||||
},
|
||||
"node_modules/accepts": {
|
||||
"version": "1.3.8",
|
||||
"resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",
|
||||
"integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==",
|
||||
"dependencies": {
|
||||
"mime-types": "~2.1.34",
|
||||
"negotiator": "0.6.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/array-flatten": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
|
||||
"integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg=="
|
||||
},
|
||||
"node_modules/body-parser": {
|
||||
"version": "1.20.9",
|
||||
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.9.tgz",
|
||||
"integrity": "sha512-FISIQxV5u91Y9gvuFq3q/tA/qTqLJn3AhRcEvyozyhJTh5OBFFtv827AdHU7Rbyct4r+Ba1/99oFa1Y3yuFsdw==",
|
||||
"dependencies": {
|
||||
"bytes": "~3.1.2",
|
||||
"content-type": "~1.0.5",
|
||||
"debug": "2.6.9",
|
||||
"depd": "2.0.0",
|
||||
"destroy": "~1.2.0",
|
||||
"http-errors": "~2.0.1",
|
||||
"iconv-lite": "~0.4.24",
|
||||
"on-finished": "~2.4.1",
|
||||
"qs": "~6.16.0",
|
||||
"raw-body": "~2.5.3",
|
||||
"type-is": "~1.6.18",
|
||||
"unpipe": "~1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8",
|
||||
"npm": "1.2.8000 || >= 1.4.16"
|
||||
}
|
||||
},
|
||||
"node_modules/bytes": {
|
||||
"version": "3.1.2",
|
||||
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
|
||||
"integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/call-bind-apply-helpers": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
|
||||
"integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
|
||||
"dependencies": {
|
||||
"es-errors": "^1.3.0",
|
||||
"function-bind": "^1.1.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/call-bound": {
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",
|
||||
"integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",
|
||||
"dependencies": {
|
||||
"call-bind-apply-helpers": "^1.0.2",
|
||||
"get-intrinsic": "^1.3.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/content-disposition": {
|
||||
"version": "0.5.4",
|
||||
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
|
||||
"integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==",
|
||||
"dependencies": {
|
||||
"safe-buffer": "5.2.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/content-type": {
|
||||
"version": "1.0.5",
|
||||
"resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",
|
||||
"integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/cookie": {
|
||||
"version": "0.7.2",
|
||||
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
|
||||
"integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/cookie-signature": {
|
||||
"version": "1.0.7",
|
||||
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz",
|
||||
"integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA=="
|
||||
},
|
||||
"node_modules/debug": {
|
||||
"version": "2.6.9",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
|
||||
"integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
|
||||
"dependencies": {
|
||||
"ms": "2.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/depd": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
|
||||
"integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/destroy": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz",
|
||||
"integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==",
|
||||
"engines": {
|
||||
"node": ">= 0.8",
|
||||
"npm": "1.2.8000 || >= 1.4.16"
|
||||
}
|
||||
},
|
||||
"node_modules/dunder-proto": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
|
||||
"integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
|
||||
"dependencies": {
|
||||
"call-bind-apply-helpers": "^1.0.1",
|
||||
"es-errors": "^1.3.0",
|
||||
"gopd": "^1.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/ee-first": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
|
||||
"integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="
|
||||
},
|
||||
"node_modules/encodeurl": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
|
||||
"integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/es-define-property": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
|
||||
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/es-errors": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
|
||||
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/es-object-atoms": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz",
|
||||
"integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==",
|
||||
"dependencies": {
|
||||
"es-errors": "^1.3.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/escape-html": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
|
||||
"integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow=="
|
||||
},
|
||||
"node_modules/etag": {
|
||||
"version": "1.8.1",
|
||||
"resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
|
||||
"integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/express": {
|
||||
"version": "4.22.3",
|
||||
"resolved": "https://registry.npmjs.org/express/-/express-4.22.3.tgz",
|
||||
"integrity": "sha512-Bdcs4+3qlpVlx2NRn6fgX2Ue2/gGRaPeawebgclM0ERSCqDpA+owF1fdPwjJUTAJWMTuAaxjDf+hzb0/4eKvvw==",
|
||||
"dependencies": {
|
||||
"accepts": "~1.3.8",
|
||||
"array-flatten": "1.1.1",
|
||||
"body-parser": "~1.20.5",
|
||||
"content-disposition": "~0.5.4",
|
||||
"content-type": "~1.0.4",
|
||||
"cookie": "~0.7.1",
|
||||
"cookie-signature": "~1.0.6",
|
||||
"debug": "2.6.9",
|
||||
"depd": "2.0.0",
|
||||
"encodeurl": "~2.0.0",
|
||||
"escape-html": "~1.0.3",
|
||||
"etag": "~1.8.1",
|
||||
"finalhandler": "~1.3.1",
|
||||
"fresh": "~0.5.2",
|
||||
"http-errors": "~2.0.0",
|
||||
"merge-descriptors": "1.0.3",
|
||||
"methods": "~1.1.2",
|
||||
"on-finished": "~2.4.1",
|
||||
"parseurl": "~1.3.3",
|
||||
"path-to-regexp": "~0.1.13",
|
||||
"proxy-addr": "~2.0.7",
|
||||
"qs": "~6.16.0",
|
||||
"range-parser": "~1.2.1",
|
||||
"safe-buffer": "5.2.1",
|
||||
"send": "~0.19.0",
|
||||
"serve-static": "~1.16.2",
|
||||
"setprototypeof": "1.2.0",
|
||||
"statuses": "~2.0.1",
|
||||
"type-is": "~1.6.18",
|
||||
"utils-merge": "1.0.1",
|
||||
"vary": "~1.1.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.10.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/fengari": {
|
||||
"version": "0.1.5",
|
||||
"resolved": "https://registry.npmjs.org/fengari/-/fengari-0.1.5.tgz",
|
||||
"integrity": "sha512-0DS4Nn4rV8qyFlQCpKK8brT61EUtswynrpfFTcgLErcilBIBskSMQ86fO2WVuybr14ywyKdRjv91FiRZwnEuvQ==",
|
||||
"dependencies": {
|
||||
"readline-sync": "^1.4.10",
|
||||
"sprintf-js": "^1.1.3",
|
||||
"tmp": "^0.2.5"
|
||||
}
|
||||
},
|
||||
"node_modules/fengari-interop": {
|
||||
"version": "0.1.4",
|
||||
"resolved": "https://registry.npmjs.org/fengari-interop/-/fengari-interop-0.1.4.tgz",
|
||||
"integrity": "sha512-4/CW/3PJUo3ebD4ACgE1g/3NGEYSq7OQAyETyypsAl/WeySDBbxExikkayNkZzbpgyC9GyJp8v1DU2VOXxNq7Q==",
|
||||
"peerDependencies": {
|
||||
"fengari": "^0.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/fengari-web": {
|
||||
"version": "0.1.4",
|
||||
"resolved": "https://registry.npmjs.org/fengari-web/-/fengari-web-0.1.4.tgz",
|
||||
"integrity": "sha512-f+W/Csx9VNyKttxYjZnk6290+Pcs7w7noDVhkuPEt0e51GWoD32vSNHFXhZYzTe8Ni/bhbk5VocNV1RBIgO5iA==",
|
||||
"dependencies": {
|
||||
"fengari": "^0.1.4",
|
||||
"fengari-interop": "^0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/finalhandler": {
|
||||
"version": "1.3.2",
|
||||
"resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz",
|
||||
"integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==",
|
||||
"dependencies": {
|
||||
"debug": "2.6.9",
|
||||
"encodeurl": "~2.0.0",
|
||||
"escape-html": "~1.0.3",
|
||||
"on-finished": "~2.4.1",
|
||||
"parseurl": "~1.3.3",
|
||||
"statuses": "~2.0.2",
|
||||
"unpipe": "~1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/forwarded": {
|
||||
"version": "0.2.0",
|
||||
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
|
||||
"integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/fresh": {
|
||||
"version": "0.5.2",
|
||||
"resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",
|
||||
"integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/function-bind": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
|
||||
"integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/get-intrinsic": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
|
||||
"integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
|
||||
"dependencies": {
|
||||
"call-bind-apply-helpers": "^1.0.2",
|
||||
"es-define-property": "^1.0.1",
|
||||
"es-errors": "^1.3.0",
|
||||
"es-object-atoms": "^1.1.1",
|
||||
"function-bind": "^1.1.2",
|
||||
"get-proto": "^1.0.1",
|
||||
"gopd": "^1.2.0",
|
||||
"has-symbols": "^1.1.0",
|
||||
"hasown": "^2.0.2",
|
||||
"math-intrinsics": "^1.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/get-proto": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
|
||||
"integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
|
||||
"dependencies": {
|
||||
"dunder-proto": "^1.0.1",
|
||||
"es-object-atoms": "^1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/gopd": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
|
||||
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/has-symbols": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
|
||||
"integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/hasown": {
|
||||
"version": "2.0.4",
|
||||
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",
|
||||
"integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==",
|
||||
"dependencies": {
|
||||
"function-bind": "^1.1.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/http-errors": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
|
||||
"integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",
|
||||
"dependencies": {
|
||||
"depd": "~2.0.0",
|
||||
"inherits": "~2.0.4",
|
||||
"setprototypeof": "~1.2.0",
|
||||
"statuses": "~2.0.2",
|
||||
"toidentifier": "~1.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/iconv-lite": {
|
||||
"version": "0.4.24",
|
||||
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz",
|
||||
"integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==",
|
||||
"dependencies": {
|
||||
"safer-buffer": ">= 2.1.2 < 3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/inherits": {
|
||||
"version": "2.0.4",
|
||||
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
|
||||
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="
|
||||
},
|
||||
"node_modules/ipaddr.js": {
|
||||
"version": "1.9.1",
|
||||
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
|
||||
"integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",
|
||||
"engines": {
|
||||
"node": ">= 0.10"
|
||||
}
|
||||
},
|
||||
"node_modules/math-intrinsics": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
|
||||
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/media-typer": {
|
||||
"version": "0.3.0",
|
||||
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
|
||||
"integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/merge-descriptors": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz",
|
||||
"integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/methods": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz",
|
||||
"integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/mime": {
|
||||
"version": "1.6.0",
|
||||
"resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz",
|
||||
"integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==",
|
||||
"bin": {
|
||||
"mime": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/mime-db": {
|
||||
"version": "1.52.0",
|
||||
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
|
||||
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/mime-types": {
|
||||
"version": "2.1.35",
|
||||
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
|
||||
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
|
||||
"dependencies": {
|
||||
"mime-db": "1.52.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/ms": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
|
||||
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="
|
||||
},
|
||||
"node_modules/negotiator": {
|
||||
"version": "0.6.3",
|
||||
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",
|
||||
"integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/object-inspect": {
|
||||
"version": "1.13.4",
|
||||
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
|
||||
"integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/on-finished": {
|
||||
"version": "2.4.2",
|
||||
"resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.2.tgz",
|
||||
"integrity": "sha512-ATWUv387i+nLD49EiDoOft5scf32Vsdz3ktrQJG9bi7jRFmaXTssvyvj1EmeKVVgvesbqUtvQQvaS2TpTukAZQ==",
|
||||
"dependencies": {
|
||||
"ee-first": "1.1.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/parseurl": {
|
||||
"version": "1.3.3",
|
||||
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
|
||||
"integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/path-to-regexp": {
|
||||
"version": "0.1.13",
|
||||
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.13.tgz",
|
||||
"integrity": "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA=="
|
||||
},
|
||||
"node_modules/proxy-addr": {
|
||||
"version": "2.0.8",
|
||||
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz",
|
||||
"integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==",
|
||||
"dependencies": {
|
||||
"forwarded": "0.2.0",
|
||||
"ipaddr.js": "1.9.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.10"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/qs": {
|
||||
"version": "6.16.2",
|
||||
"resolved": "https://registry.npmjs.org/qs/-/qs-6.16.2.tgz",
|
||||
"integrity": "sha512-VYdnB5S7/0IeXzBacUtwNAaM6d7Y/PgYnNC7bJCI6meqA/OgnsQbZMtVW8Dt2D1PHgbHGtYmhSoEIgvt7xZ2ZA==",
|
||||
"dependencies": {
|
||||
"es-define-property": "^1.0.1",
|
||||
"side-channel": "^1.1.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.6"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/range-parser": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
|
||||
"integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/raw-body": {
|
||||
"version": "2.5.3",
|
||||
"resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz",
|
||||
"integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==",
|
||||
"dependencies": {
|
||||
"bytes": "~3.1.2",
|
||||
"http-errors": "~2.0.1",
|
||||
"iconv-lite": "~0.4.24",
|
||||
"unpipe": "~1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/readline-sync": {
|
||||
"version": "1.4.10",
|
||||
"resolved": "https://registry.npmjs.org/readline-sync/-/readline-sync-1.4.10.tgz",
|
||||
"integrity": "sha512-gNva8/6UAe8QYepIQH/jQ2qn91Qj0B9sYjMBBs3QOB8F2CXcKgLxQaJRP76sWVRQt+QU+8fAkCbCvjjMFu7Ycw==",
|
||||
"engines": {
|
||||
"node": ">= 0.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/safe-buffer": {
|
||||
"version": "5.2.1",
|
||||
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
|
||||
"integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
]
|
||||
},
|
||||
"node_modules/safer-buffer": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
|
||||
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="
|
||||
},
|
||||
"node_modules/send": {
|
||||
"version": "0.19.2",
|
||||
"resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz",
|
||||
"integrity": "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==",
|
||||
"dependencies": {
|
||||
"debug": "2.6.9",
|
||||
"depd": "2.0.0",
|
||||
"destroy": "1.2.0",
|
||||
"encodeurl": "~2.0.0",
|
||||
"escape-html": "~1.0.3",
|
||||
"etag": "~1.8.1",
|
||||
"fresh": "~0.5.2",
|
||||
"http-errors": "~2.0.1",
|
||||
"mime": "1.6.0",
|
||||
"ms": "2.1.3",
|
||||
"on-finished": "~2.4.1",
|
||||
"range-parser": "~1.2.1",
|
||||
"statuses": "~2.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/send/node_modules/ms": {
|
||||
"version": "2.1.3",
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
|
||||
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="
|
||||
},
|
||||
"node_modules/serve-static": {
|
||||
"version": "1.16.3",
|
||||
"resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.3.tgz",
|
||||
"integrity": "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==",
|
||||
"dependencies": {
|
||||
"encodeurl": "~2.0.0",
|
||||
"escape-html": "~1.0.3",
|
||||
"parseurl": "~1.3.3",
|
||||
"send": "~0.19.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/setprototypeof": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
|
||||
"integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw=="
|
||||
},
|
||||
"node_modules/side-channel": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz",
|
||||
"integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==",
|
||||
"dependencies": {
|
||||
"es-errors": "^1.3.0",
|
||||
"object-inspect": "^1.13.4",
|
||||
"side-channel-list": "^1.0.1",
|
||||
"side-channel-map": "^1.0.1",
|
||||
"side-channel-weakmap": "^1.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/side-channel-list": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz",
|
||||
"integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==",
|
||||
"dependencies": {
|
||||
"es-errors": "^1.3.0",
|
||||
"object-inspect": "^1.13.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/side-channel-map": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",
|
||||
"integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",
|
||||
"dependencies": {
|
||||
"call-bound": "^1.0.2",
|
||||
"es-errors": "^1.3.0",
|
||||
"get-intrinsic": "^1.2.5",
|
||||
"object-inspect": "^1.13.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/side-channel-weakmap": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",
|
||||
"integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",
|
||||
"dependencies": {
|
||||
"call-bound": "^1.0.2",
|
||||
"es-errors": "^1.3.0",
|
||||
"get-intrinsic": "^1.2.5",
|
||||
"object-inspect": "^1.13.3",
|
||||
"side-channel-map": "^1.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/sprintf-js": {
|
||||
"version": "1.1.3",
|
||||
"resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz",
|
||||
"integrity": "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA=="
|
||||
},
|
||||
"node_modules/statuses": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
|
||||
"integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/tmp": {
|
||||
"version": "0.2.7",
|
||||
"resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.7.tgz",
|
||||
"integrity": "sha512-e0votIpp4Uo2AJYSzVHV6xCcawuiez3DzqDAbrTc3YxBkplN6e+dM13ZeIcZnDg/QpSuU2zfZ3rzwY8ukEnaXw==",
|
||||
"engines": {
|
||||
"node": ">=14.14"
|
||||
}
|
||||
},
|
||||
"node_modules/toidentifier": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
|
||||
"integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
|
||||
"engines": {
|
||||
"node": ">=0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/type-is": {
|
||||
"version": "1.6.18",
|
||||
"resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
|
||||
"integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==",
|
||||
"dependencies": {
|
||||
"media-typer": "0.3.0",
|
||||
"mime-types": "~2.1.24"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/unpipe": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
|
||||
"integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/utils-merge": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
|
||||
"integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==",
|
||||
"engines": {
|
||||
"node": ">= 0.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/vary": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
|
||||
"integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/ws": {
|
||||
"version": "8.22.0",
|
||||
"resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz",
|
||||
"integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==",
|
||||
"engines": {
|
||||
"node": ">=10.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"bufferutil": "^4.0.1",
|
||||
"utf-8-validate": ">=5.0.2"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"bufferutil": {
|
||||
"optional": true
|
||||
},
|
||||
"utf-8-validate": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "promptly",
|
||||
"version": "1.1.0",
|
||||
"description": "Interactive real-time presentations with a freeform slide editor, Lua scripting and managed audio",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
"start": "node server.js",
|
||||
"dev": "node --watch server.js",
|
||||
"vendor": "node -e \"require('fs').mkdirSync('public/vendor',{recursive:true});require('fs').copyFileSync('node_modules/fengari-web/dist/fengari-web.js','public/vendor/fengari-web.js')\"",
|
||||
"postinstall": "npm run vendor"
|
||||
},
|
||||
"dependencies": {
|
||||
"express": "^4.21.2",
|
||||
"fengari": "^0.1.5",
|
||||
"fengari-web": "^0.1.4",
|
||||
"ws": "^8.18.0"
|
||||
},
|
||||
"license": "ISC"
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Lua API — 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: #070a15;
|
||||
--panel: rgba(255,255,255,.035);
|
||||
--panel-2: rgba(255,255,255,.06);
|
||||
--border: rgba(255,255,255,.09);
|
||||
--accent: #818cf8;
|
||||
--accent-2: #e879f9;
|
||||
--text: #e8ecf6;
|
||||
--muted: #94a3b8;
|
||||
--code: #a5b4fc;
|
||||
--ok: #4ade80;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
html { scroll-behavior: smooth; }
|
||||
body {
|
||||
margin: 0; color: var(--text); background:
|
||||
radial-gradient(900px 520px at 8% -8%, rgba(99, 102, 241, .18), transparent 60%),
|
||||
radial-gradient(760px 460px at 100% 0%, rgba(217, 70, 239, .12), transparent 55%),
|
||||
var(--bg);
|
||||
font-family: system-ui, -apple-system, 'Segoe UI', sans-serif;
|
||||
line-height: 1.62;
|
||||
}
|
||||
a { color: #c7d2fe; text-decoration: none; }
|
||||
a:hover { color: #fff; text-decoration: underline; text-underline-offset: 3px; }
|
||||
.topbar {
|
||||
position: sticky; top: 0; z-index: 20; display: flex; align-items: center; gap: 14px;
|
||||
padding: 12px 22px; background: rgba(7, 10, 21, .82); border-bottom: 1px solid var(--border);
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
.brand { font-weight: 800; font-size: 15px; letter-spacing: -.2px; }
|
||||
.brand span { background: linear-gradient(90deg, #818cf8, #e879f9); -webkit-background-clip: text; background-clip: text; color: transparent; }
|
||||
.topbar .spacer { flex: 1; }
|
||||
.topbar a.pill { font-size: 12px; border: 1px solid var(--border); border-radius: 999px; padding: 6px 12px; background: var(--panel); }
|
||||
.wrap { display: grid; grid-template-columns: 236px minmax(0, 1fr); gap: 34px; max-width: 1180px; margin: 0 auto; padding: 30px 22px 90px; }
|
||||
.toc { position: sticky; top: 78px; align-self: start; display: flex; flex-direction: column; gap: 3px; font-size: 13px; }
|
||||
.toc .toc-title { font-size: 10.5px; text-transform: uppercase; letter-spacing: 1.2px; color: var(--accent); font-weight: 800; margin-bottom: 6px; }
|
||||
.toc a { color: var(--muted); padding: 5px 9px; border-radius: 8px; border: 1px solid transparent; }
|
||||
.toc a:hover { color: #fff; background: var(--panel-2); border-color: var(--border); text-decoration: none; }
|
||||
main { min-width: 0; }
|
||||
.hero { padding: 10px 0 26px; border-bottom: 1px solid var(--border); margin-bottom: 26px; }
|
||||
.hero h1 { margin: 0 0 8px; font-size: clamp(28px, 4vw, 42px); letter-spacing: -1px; line-height: 1.1; }
|
||||
.hero h1 span { background: linear-gradient(90deg, #818cf8, #e879f9); -webkit-background-clip: text; background-clip: text; color: transparent; }
|
||||
.hero p { margin: 0; color: var(--muted); font-size: 15px; max-width: 720px; }
|
||||
.badges { display: flex; flex-wrap: wrap; gap: 7px; margin-top: 14px; }
|
||||
.badge { font-size: 11px; color: #c7d2fe; background: rgba(99,102,241,.14); border: 1px solid rgba(129,140,248,.3); border-radius: 999px; padding: 3px 10px; }
|
||||
section { margin-bottom: 38px; scroll-margin-top: 84px; }
|
||||
h2 { font-size: 21px; margin: 0 0 12px; letter-spacing: -.3px; display: flex; align-items: center; gap: 9px; }
|
||||
h2::before { content: ''; width: 4px; height: 20px; border-radius: 99px; background: linear-gradient(180deg, #818cf8, #e879f9); }
|
||||
h3 { font-size: 14.5px; margin: 20px 0 8px; color: #c7d2fe; }
|
||||
p { margin: 8px 0 12px; color: #cbd5e1; }
|
||||
ul, ol { margin: 8px 0 14px; padding-left: 22px; color: #cbd5e1; }
|
||||
li { margin: 5px 0; }
|
||||
code { font-family: ui-monospace, 'SFMono-Regular', Consolas, monospace; font-size: .9em; color: var(--code); background: rgba(99,102,241,.13); border: 1px solid rgba(129,140,248,.16); border-radius: 5px; padding: 1px 5px; }
|
||||
pre {
|
||||
margin: 10px 0 16px; padding: 14px 16px; overflow-x: auto; border-radius: 12px;
|
||||
background: rgba(2, 4, 10, .72); border: 1px solid var(--border);
|
||||
font-family: ui-monospace, 'SFMono-Regular', Consolas, monospace; font-size: 12.5px; line-height: 1.55;
|
||||
color: #dbe4f7; tab-size: 2;
|
||||
}
|
||||
pre code { background: none; border: none; padding: 0; color: inherit; font-size: inherit; }
|
||||
.card { background: var(--panel); border: 1px solid var(--border); border-radius: 14px; padding: 16px 18px; margin: 12px 0; }
|
||||
.card.note { border-color: rgba(129,140,248,.3); background: linear-gradient(160deg, rgba(99,102,241,.1), rgba(12,17,33,.5) 60%); }
|
||||
.card.warn { border-color: rgba(251,191,36,.3); background: linear-gradient(160deg, rgba(251,191,36,.08), rgba(12,17,33,.5) 60%); }
|
||||
.card strong { color: #e2e8f0; }
|
||||
.card p:last-child { margin-bottom: 0; }
|
||||
table { width: 100%; border-collapse: collapse; margin: 10px 0 18px; font-size: 13px; }
|
||||
th, td { text-align: left; padding: 9px 11px; border-bottom: 1px solid var(--border); vertical-align: top; }
|
||||
th { font-size: 10.5px; text-transform: uppercase; letter-spacing: .9px; color: var(--accent); }
|
||||
td:first-child { white-space: nowrap; }
|
||||
tr:hover td { background: rgba(255,255,255,.025); }
|
||||
.api { color: #a5b4fc; font-family: ui-monospace, Consolas, monospace; font-size: 12px; }
|
||||
.table-wrap { overflow-x: auto; }
|
||||
.muted { color: var(--muted); }
|
||||
.footer { margin-top: 48px; padding-top: 18px; border-top: 1px solid var(--border); color: #64748b; font-size: 12px; display: flex; flex-wrap: wrap; gap: 12px; justify-content: space-between; }
|
||||
@media (max-width: 860px) {
|
||||
.wrap { grid-template-columns: 1fr; gap: 18px; padding: 20px 14px 70px; }
|
||||
.toc { position: static; display: grid; grid-template-columns: 1fr 1fr; }
|
||||
.toc .toc-title { grid-column: 1 / -1; }
|
||||
.hero h1 { font-size: 30px; }
|
||||
}
|
||||
@media (max-width: 520px) {
|
||||
.topbar { padding: 10px 14px; }
|
||||
.topbar .pill { padding: 5px 9px; font-size: 11px; }
|
||||
.toc { grid-template-columns: 1fr; }
|
||||
table { font-size: 12px; }
|
||||
th, td { padding: 7px 8px; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="topbar">
|
||||
<div class="brand">🎤 Prompt<span>ly</span> · Lua API</div>
|
||||
<span class="spacer"></span>
|
||||
<a class="pill" href="index.html">Дашборд</a>
|
||||
<a class="pill" href="editor.html">Редактор</a>
|
||||
</header>
|
||||
|
||||
<div class="wrap">
|
||||
<nav class="toc">
|
||||
<div class="toc-title">Содержание</div>
|
||||
<a href="#start">Быстрый старт</a>
|
||||
<a href="#where">Где выполняется код</a>
|
||||
<a href="#vars">Переменные</a>
|
||||
<a href="#nav">Навигация</a>
|
||||
<a href="#audio">Аудио</a>
|
||||
<a href="#video">Видео</a>
|
||||
<a href="#log">Логи и ошибки</a>
|
||||
<a href="#graph">Нодовый граф</a>
|
||||
<a href="#lifecycle">Жизненный цикл</a>
|
||||
<a href="#commands">Команды докладчика</a>
|
||||
<a href="#examples">Примеры</a>
|
||||
<a href="#window">Окно Chrome</a>
|
||||
<a href="#faq">Ограничения</a>
|
||||
</nav>
|
||||
|
||||
<main>
|
||||
<div class="hero">
|
||||
<h1>Lua в <span>Promptly</span></h1>
|
||||
<p>Полный справочник по скриптам презентации: глобальные переменные, переключение слайдов, звук, видео и консоль докладчика. Синтаксис — обычный Lua 5.3, который исполняется в браузере докладчика.</p>
|
||||
<div class="badges">
|
||||
<span class="badge">app.* API</span>
|
||||
<span class="badge">vars.*</span>
|
||||
<span class="badge">1-based слайды</span>
|
||||
<span class="badge">синхронизация переменных</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<section id="start">
|
||||
<h2>Быстрый старт</h2>
|
||||
<p>Откройте <a href="editor.html">редактор</a>, нажмите «Настройки» и впишите код в «Глобальный Lua». Он выполнится один раз при старте показа. Для локальной логики используйте Lua слайда или Lua-кнопку.</p>
|
||||
<pre><code>vars.score = 0
|
||||
vars.speaker = "Иван"
|
||||
app.log("Презентация готова")</code></pre>
|
||||
<div class="card note">
|
||||
<p><strong>Три места для кода.</strong> Глобальный скрипт — при запуске показа. Скрипт слайда — при входе на слайд. Скрипт кнопки — по нажатию. У всех общее пространство <code>vars</code> и один Lua-виртуальный автомат.</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section id="where">
|
||||
<h2>Где выполняется код</h2>
|
||||
<p>Lua выполняется <strong>только в окне докладчика</strong>. Зрители не исполняют скрипты и не могут менять переменные: они получают готовые значения <code>vars</code> по WebSocket, поэтому все экраны показывают одинаковые данные.</p>
|
||||
<ul>
|
||||
<li>Код не имеет доступа к сети, файлам, DOM и системным командам.</li>
|
||||
<li>Можно использовать стандартную библиотеку Lua: <code>string</code>, <code>table</code>, <code>math</code>, <code>os.time</code> и т. д.</li>
|
||||
<li>Переменные должны быть простыми: строка, число или boolean.</li>
|
||||
<li>Зрители видят результат через <code>{{key}}</code> в текстах и подписях кнопок.</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section id="vars">
|
||||
<h2>Переменные</h2>
|
||||
<p>Глобальная таблица <code>vars</code> синхронизируется между докладчиком и зрителями. Значения из настроек презентации попадают в неё автоматически.</p>
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead><tr><th>Выражение</th><th>Что делает</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td class="api">vars.name</td><td>Чтение или запись переменной. Если переменной нет, вернётся <code>nil</code>.</td></tr>
|
||||
<tr><td class="api">vars.score = 0</td><td>Создаёт переменную. Изменения отправляются зрителям при следующей синхронизации.</td></tr>
|
||||
<tr><td class="api">app.setVar("score", 10)</td><td>То же самое, но удобно, когда имя приходит строкой.</td></tr>
|
||||
<tr><td class="api">app.getVar("score")</td><td>Безопасное чтение по строковому имени.</td></tr>
|
||||
<tr><td class="api">{{score}}</td><td>Подстановка в текст слайда, подпись кнопки или аудио.</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<pre><code>-- Счётчик кликов
|
||||
vars.clicks = (vars.clicks or 0) + 1
|
||||
app.log("Кликов: " .. vars.clicks)
|
||||
|
||||
-- В тексте слайда напишите: Нажатий: {{clicks}}</code></pre>
|
||||
<div class="card warn">
|
||||
<p><strong>Не храните таблицы.</strong> Вложенные таблицы не переживут синхронизацию. Храните плоские значения, а сложные структуры собирайте из ключей: <code>vars.user_name</code>, <code>vars.user_role</code>.</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section id="nav">
|
||||
<h2>Навигация по слайдам</h2>
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead><tr><th>Функция</th><th>Описание</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td class="api">app.go(n)</td><td>Перейти на слайд <code>n</code>. Нумерация с единицы: <code>app.go(1)</code> — первый слайд.</td></tr>
|
||||
<tr><td class="api">app.next()</td><td>Следующий слайд. На последнем слайде ничего не происходит.</td></tr>
|
||||
<tr><td class="api">app.prev()</td><td>Предыдущий слайд. На первом слайде ничего не происходит.</td></tr>
|
||||
<tr><td class="api">app.slide()</td><td>Возвращает номер текущего слайда, начиная с 1.</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<pre><code>-- Перейти к финалу
|
||||
app.go(12)
|
||||
|
||||
-- Условный переход
|
||||
if (vars.score or 0) >= 10 then
|
||||
app.go(8)
|
||||
else
|
||||
app.next()
|
||||
end</code></pre>
|
||||
<p>Докладчик может нажимать стрелки, <code>Space</code>, <code>PageUp</code>/<code>PageDown</code>, <code>Home</code>/<code>End</code> и кнопки навигации внизу. Переходы синхронизируются со зрителями.</p>
|
||||
</section>
|
||||
|
||||
<section id="audio">
|
||||
<h2>Аудио</h2>
|
||||
<p>Аудиоэлементы имеют <code>id</code>. Найти его можно в редакторе: выберите аудио и посмотрите панель справа, либо используйте кнопку «Прослушать». Фоновая музыка задаётся отдельно в настройках презентации.</p>
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead><tr><th>Функция</th><th>Описание</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td class="api">app.play(id)</td><td>Запустить аудиоэлемент по id. Если он уже играет — перезапускает.</td></tr>
|
||||
<tr><td class="api">app.stop(id)</td><td>Остановить конкретное аудио. <code>app.stop("*")</code> останавливает все эффекты.</td></tr>
|
||||
<tr><td class="api">app.volume(id, v)</td><td>Громкость эффекта от <code>0</code> до <code>1</code>.</td></tr>
|
||||
<tr><td class="api">app.music(url)</td><td>Включить фоновую музыку по ссылке или локальному пути.</td></tr>
|
||||
<tr><td class="api">app.musicPlay()</td><td>Продолжить фоновую музыку с текущего источника.</td></tr>
|
||||
<tr><td class="api">app.musicStop()</td><td>Остановить фоновую музыку.</td></tr>
|
||||
<tr><td class="api">app.musicVolume(v)</td><td>Громкость фона от <code>0</code> до <code>1</code>. Зрители слышат тот же уровень.</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<pre><code>-- Торжественный момент
|
||||
app.musicStop()
|
||||
app.play("el_6f2c1a")
|
||||
app.volume("el_6f2c1a", 0.9)
|
||||
|
||||
-- Приглушить фон под голос
|
||||
app.musicVolume(0.25)</code></pre>
|
||||
<div class="card note">
|
||||
<p>Звук управляется с окна докладчика. Команды ретранслируются сервером всем зрителям, поэтому громкость и пауза совпадают. Браузер может заблокировать автозапуск — используйте кнопку «Включить звук» в углу.</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section id="video">
|
||||
<h2>Видео</h2>
|
||||
<p>Видеоэлемент ведёт себя как обычный плеер, но команды докладчика синхронизируются. Id видео также виден в инспекторе редактора.</p>
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead><tr><th>Функция</th><th>Описание</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td class="api">app.videoPlay(id)</td><td>Запустить видео.</td></tr>
|
||||
<tr><td class="api">app.videoPause(id)</td><td>Поставить на паузу.</td></tr>
|
||||
<tr><td class="api">app.videoRestart(id)</td><td>Перемотать в начало и запустить.</td></tr>
|
||||
<tr><td class="api">app.videoSeek(id, seconds)</td><td>Перейти к секунде <code>seconds</code> (дробное число допустимо).</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<pre><code>-- Показать ролик с 12-й секунды
|
||||
app.videoSeek("el_video_intro", 12)
|
||||
app.videoPlay("el_video_intro")
|
||||
|
||||
-- Пауза после обсуждения
|
||||
app.videoPause("el_video_intro")</code></pre>
|
||||
<p>Видео можно добавить ссылкой или загрузить файл: редактор → «Видео» → «Загрузить файл». Файл сохраняется на сервере в <code>public/uploads</code> и доступен по локальному URL.</p>
|
||||
</section>
|
||||
|
||||
<section id="log">
|
||||
<h2>Логи и ошибки</h2>
|
||||
<p><code>app.log()</code> пишет строку в консоль браузера и в лог консоли команд докладчика. Ошибки Lua также появляются в логе и всплывающим уведомлением.</p>
|
||||
<pre><code>app.log("Старт: слайд " .. app.slide())
|
||||
app.log("Значение score = " .. tostring(vars.score))</code></pre>
|
||||
<div class="card warn">
|
||||
<p><strong>Ошибка не останавливает показ.</strong> Скрипт с ошибкой прекращает выполнение, но презентация продолжает работать. Проверяйте лог в консоли команд и консоль браузера (F12).</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section id="graph">
|
||||
<h2>Нодовый граф</h2>
|
||||
<p>Переключите редактор в режим «Граф». Каждый слайд — нода с входом, отдельными выходами «Дальше» и «Назад», выходами кнопок и входами переменных. Соединяйте порты вручную: потяните от выхода к входу. Линия и стрелка показывают направление связи.</p>
|
||||
<ul>
|
||||
<li><strong>Слайд</strong> — вход <code>вход</code>, выходы <code>Дальше</code>, <code>Назад</code>, выходы кнопок и входы <code>⌘ имя</code> для переменных.</li>
|
||||
<li><strong>Код</strong> — вход запуска. Соедините выход кнопки с входом ноды кода, и кнопка начнёт выполнять этот Lua.</li>
|
||||
<li><strong>Аудио</strong> — отдельная нода с входом запуска или остановки. В инспекторе выберите аудиоэлемент и команду.</li>
|
||||
<li><strong>Переменная</strong> — отдельная нода с выходом <code>value</code>. Соедините её с портом <code>⌘ имя</code> слайда.</li>
|
||||
</ul>
|
||||
<p>Если в тексте слайда есть <code>{{score}}</code>, у ноды слайда появляется порт <code>⌘ score</code>. Подключите к нему другую переменную, например <code>rank</code>, — текст автоматически станет <code>{{rank}}</code>, а инспектор текста покажет новую привязку. Переименование переменной в инспекторе также обновляет все подключённые вставки.</p>
|
||||
<p>Связи «Дальше» и «Назад» задают навигацию для кнопок, клавиатуры и стрелок в окне показа. Если связи нет, используется обычный порядок слайдов. Связи кнопок заменяют ручной выбор действия в инспекторе: действие кнопки всегда совпадает с тем, куда ведёт её выход.</p>
|
||||
<div class="card note">
|
||||
<p><strong>Удаление связи.</strong> Кликните по линии и нажмите <code>Delete</code>. Для кнопки действие сбросится в «без действия», а переход «Дальше»/«Назад» вернётся к обычному порядку слайдов. Ноду можно удалить клавишей <code>Delete</code> после выбора.</p>
|
||||
</div>
|
||||
<pre><code>Слайд 1 ──[Дальше]──▶ Слайд 3
|
||||
Слайд 1 ──[Кнопка «Аплодисменты»]──▶ Аудио (play)
|
||||
Переменная rank ──[value]──▶ Слайд 1 ⌘ score</code></pre>
|
||||
<p>Двойной клик по ноде слайда открывает его холст. Кнопки на панели графа добавляют ноды кода, аудио и переменных. Все связи сохраняются вместе с презентацией и переживают перезагрузку.</p>
|
||||
</section>
|
||||
|
||||
<section id="lifecycle">
|
||||
<h2>Жизненный цикл</h2>
|
||||
<ol>
|
||||
<li><strong>Старт показа.</strong> Загружается глобальный Lua из настроек, затем переменные из презентации.</li>
|
||||
<li><strong>Вход на слайд.</strong> Выполняется Lua этого слайда. Это происходит при каждом переходе, включая возврат назад.</li>
|
||||
<li><strong>Нажатие кнопки.</strong> Выполняется действие кнопки: переход, аудио или Lua-код.</li>
|
||||
<li><strong>Команда из консоли.</strong> Докладчик запускает заранее заготовленный Lua из списка команд.</li>
|
||||
</ol>
|
||||
<p>Переменные синхронизируются после каждого запуска кода. Слайд-скрипт не должен зависеть от того, что он выполнится ровно один раз: используйте проверки и счётчики.</p>
|
||||
<pre><code>-- Безопасный вход на слайд
|
||||
vars.visited_final = (vars.visited_final or 0) + 1
|
||||
if vars.visited_final == 1 then
|
||||
app.log("Первый вход в финал")
|
||||
app.play("el_applause")
|
||||
end</code></pre>
|
||||
</section>
|
||||
|
||||
<section id="commands">
|
||||
<h2>Команды докладчика</h2>
|
||||
<p>В редакторе откройте «Команды» и добавьте заранее подготовленные сценарии. В окне показа они появятся в консоли под пометками: докладчик листает список стрелками <code>↑</code>/<code>↓</code> и запускает <code>Enter</code>. Можно и просто кликнуть по команде.</p>
|
||||
<pre><code>-- Пример команды «Показать ответ»
|
||||
vars.show_answer = true
|
||||
app.log("Ответ показан")</code></pre>
|
||||
<p>Команды выполняются только у докладчика. Их код — обычный Lua с доступом к <code>app</code> и <code>vars</code>.</p>
|
||||
</section>
|
||||
|
||||
<section id="examples">
|
||||
<h2>Примеры</h2>
|
||||
<h3>Голосование зала</h3>
|
||||
<pre><code>-- Команда «Голос +1»
|
||||
vars.votes = (vars.votes or 0) + 1
|
||||
app.log("Голосов: " .. vars.votes)</code></pre>
|
||||
|
||||
<h3>Таймер обратного отсчёта</h3>
|
||||
<p>Lua не имеет таймеров, но можно обновлять значение по команде докладчика:</p>
|
||||
<pre><code>-- Команда «Минус минута»
|
||||
vars.minutes_left = math.max(0, (vars.minutes_left or 5) - 1)
|
||||
if vars.minutes_left == 0 then
|
||||
app.play("el_time_up")
|
||||
end
|
||||
app.log("Осталось минут: " .. vars.minutes_left)</code></pre>
|
||||
|
||||
<h3>Ветвление сценария</h3>
|
||||
<pre><code>-- Кнопка «Дальше» с выбором пути
|
||||
if vars.audience == "expert" then
|
||||
app.go(9)
|
||||
else
|
||||
app.go(5)
|
||||
end</code></pre>
|
||||
|
||||
<h3>Финальный слайд</h3>
|
||||
<pre><code>app.musicStop()
|
||||
app.play("el_final_chord")
|
||||
vars.finished = true
|
||||
app.log("Финал")</code></pre>
|
||||
</section>
|
||||
|
||||
<section id="window">
|
||||
<h2>Трансляция окна Chrome</h2>
|
||||
<p>Элемент «Окно» в редакторе показывает живой экран другого окна Chrome и позволяет нажимать в нём кнопки прямо из презентации. Это работает через Chrome DevTools Protocol.</p>
|
||||
<ol>
|
||||
<li>Запустите отдельный Chrome с отладочным портом:</li>
|
||||
</ol>
|
||||
<pre><code>google-chrome --remote-debugging-port=9222 \
|
||||
--user-data-dir=/tmp/promptly-chrome</code></pre>
|
||||
<ol start="2">
|
||||
<li>Откройте в этом Chrome нужную страницу или приложение.</li>
|
||||
<li>В редакторе выберите «Окно» → «Обновить список окон» и укажите цель.</li>
|
||||
<li>В окне докладчика нажмите «Транслировать». Клик по картинке передаёт клик в Chrome, «Пульт» добавляет клавиши и ввод текста.</li>
|
||||
</ol>
|
||||
<div class="card warn">
|
||||
<p><strong>Важно.</strong> Браузер не может перехватывать произвольные нативные приложения. Трансляция и клики работают только для Chrome/Chromium/Electron с включённым remote debugging. Для остальных приложений используйте обычную демонстрацию экрана.</p>
|
||||
</div>
|
||||
<p>Переменная окружения <code>CHROME_DEBUG_URL</code> позволяет указать другой адрес, например <code>http://127.0.0.1:9223</code>.</p>
|
||||
</section>
|
||||
|
||||
<section id="faq">
|
||||
<h2>Ограничения и советы</h2>
|
||||
<ul>
|
||||
<li>Lua выполняется у докладчика. Если окно докладчика закрыто, скрипты не работают.</li>
|
||||
<li>Переменные синхронизируются целиком; не храните в них большие строки и файлы.</li>
|
||||
<li>Слайды нумеруются с 1, даже если в интерфейсе это «Слайд 0» в массиве.</li>
|
||||
<li><code>app.stop(id)</code> с пустым id останавливает все эффекты. <code>*</code> делает то же явно.</li>
|
||||
<li>Кнопка с Lua хранит код в отдельной ноде графа; редактирование кода в ноде и в инспекторе кнопки — одно и то же. Связь «выход кнопки → вход ноды» определяет, что кнопка делает.</li>
|
||||
<li>Переменные в графе — отдельные ноды. Переподключение ноды к порту <code>⌘ имя</code> меняет вставку <code>{{...}}</code> в тексте слайда.</li>
|
||||
<li>Для отладки используйте <code>app.log()</code>: консоль команд докладчика показывает последние строки.</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<div class="footer">
|
||||
<span>Promptly · личная студия презентаций</span>
|
||||
<span><a href="editor.html">Редактор</a> · <a href="index.html">Дашборд</a></span>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
+3171
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,373 @@
|
||||
<!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: #070a15;
|
||||
--panel: rgba(255, 255, 255, .045);
|
||||
--border: rgba(255, 255, 255, .09);
|
||||
--accent: #818cf8;
|
||||
--text: #e8ecf6;
|
||||
--muted: #94a3b8;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0; min-height: 100vh; color: var(--text);
|
||||
font-family: system-ui, -apple-system, 'Segoe UI', sans-serif;
|
||||
background:
|
||||
radial-gradient(1200px 620px at 12% -10%, rgba(99, 102, 241, .27), transparent 60%),
|
||||
radial-gradient(900px 520px at 108% 2%, rgba(217, 70, 239, .16), transparent 56%),
|
||||
radial-gradient(900px 600px at 50% 120%, rgba(14, 165, 233, .08), transparent 60%),
|
||||
var(--bg);
|
||||
}
|
||||
button { border: none; border-radius: 10px; padding: 9px 14px; font: inherit; font-size: 13px; cursor: pointer; transition: .16s; background: rgba(255,255,255,.08); color: var(--text); }
|
||||
button:hover:not(:disabled) { background: rgba(255,255,255,.15); }
|
||||
button:disabled { opacity: .35; cursor: default; }
|
||||
input { font: inherit; }
|
||||
|
||||
.shell { max-width: 1220px; margin: 0 auto; padding: 0 36px 80px; }
|
||||
header { display: flex; align-items: center; justify-content: space-between; gap: 18px; padding: 26px 0 10px; }
|
||||
.logo { font-size: 23px; font-weight: 800; letter-spacing: -.6px; display: flex; align-items: center; gap: 9px; }
|
||||
.logo span { background: linear-gradient(90deg, #818cf8, #e879f9); -webkit-background-clip: text; background-clip: text; color: transparent; }
|
||||
.logo small { font-size: 10px; letter-spacing: 1.6px; text-transform: uppercase; color: var(--muted); font-weight: 700; background: rgba(255,255,255,.05); border: 1px solid var(--border); padding: 3px 7px; border-radius: 999px; }
|
||||
.status { display: flex; align-items: center; gap: 8px; font-size: 12.5px; color: var(--muted); }
|
||||
.dot { width: 8px; height: 8px; border-radius: 50%; background: #22c55e; box-shadow: 0 0 10px #22c55e; }
|
||||
.dot.off { background: #ef4444; box-shadow: 0 0 10px #ef4444; }
|
||||
|
||||
.dash-head { display: flex; align-items: center; justify-content: space-between; gap: 16px; flex-wrap: wrap; padding: 30px 0 18px; border-bottom: 1px solid rgba(255,255,255,.06); margin-bottom: 20px; }
|
||||
.dash-title { display: flex; flex-direction: column; gap: 4px; }
|
||||
.dash-title h1 { font-size: 24px; letter-spacing: -.7px; margin: 0; font-weight: 750; }
|
||||
.dash-title p { margin: 0; color: var(--muted); font-size: 13px; }
|
||||
.dash-actions { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||
.dash-actions .link { font-size: 12.5px; color: #c7d2fe; text-decoration: none; padding: 9px 13px; border-radius: 10px; background: rgba(255,255,255,.05); border: 1px solid var(--border); transition: .15s; }
|
||||
.dash-actions .link:hover { background: rgba(255,255,255,.1); color: #fff; }
|
||||
.create-btn { font-size: 13.5px; padding: 10px 18px; border-radius: 11px; font-weight: 650; background: linear-gradient(90deg, #6366f1, #a855f7); color: #fff; }
|
||||
.create-btn:hover { filter: brightness(1.1); background: linear-gradient(90deg, #6366f1, #a855f7); }
|
||||
.stats-line { display: flex; align-items: center; gap: 18px; font-size: 12.5px; color: var(--muted); padding: 0 0 16px; flex-wrap: wrap; }
|
||||
.stats-line b { color: #e8ecf6; font-size: 14px; font-variant-numeric: tabular-nums; }
|
||||
|
||||
.tabs { display: flex; gap: 7px; margin-bottom: 16px; flex-wrap: wrap; align-items: center; }
|
||||
.tab { padding: 9px 16px; border-radius: 999px; border: 1px solid var(--border); background: rgba(255,255,255,.04); color: #cbd5e1; cursor: pointer; font: inherit; font-size: 13px; transition: .18s; display: flex; align-items: center; gap: 8px; }
|
||||
.tab:hover { background: rgba(255,255,255,.09); }
|
||||
.tab.active { background: linear-gradient(90deg, rgba(99, 102, 241, .38), rgba(217, 70, 239, .26)); border-color: rgba(129, 140, 248, .6); color: #fff; font-weight: 600; }
|
||||
.badge { background: rgba(255, 255, 255, .14); border-radius: 999px; padding: 1px 8px; font-size: 11px; min-width: 21px; text-align: center; }
|
||||
|
||||
.toolbar { display: flex; align-items: center; gap: 12px; margin-bottom: 18px; flex-wrap: wrap; }
|
||||
.search-wrap { position: relative; flex: 1; max-width: 380px; }
|
||||
.search-wrap::before { content: '⌕'; position: absolute; left: 13px; top: 50%; transform: translateY(-50%); color: #64748b; font-size: 16px; }
|
||||
.search { width: 100%; padding: 11px 14px 11px 36px; border-radius: 11px; font-size: 13.5px; background: rgba(255, 255, 255, .045); border: 1px solid var(--border); color: var(--text); }
|
||||
.search::placeholder { color: #64748b; }
|
||||
.search:focus { outline: 2px solid rgba(129, 140, 248, .6); border-color: transparent; }
|
||||
.toolbar .muted { margin-left: auto; }
|
||||
|
||||
.panel { display: none; } .panel.active { display: block; animation: fade .25s ease; }
|
||||
@keyframes fade { from { opacity: 0; transform: translateY(5px); } to { opacity: 1; transform: none; } }
|
||||
|
||||
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 18px; }
|
||||
.card { background: rgba(255,255,255,.04); border: 1px solid var(--border); border-radius: 18px; overflow: hidden; display: flex; flex-direction: column; backdrop-filter: blur(10px); transition: .2s; }
|
||||
.card:hover { border-color: rgba(129, 140, 248, .45); transform: translateY(-3px); box-shadow: 0 20px 46px rgba(0, 0, 0, .38); }
|
||||
.thumb { position: relative; aspect-ratio: 16 / 9; overflow: hidden; background: #0b1020; border-bottom: 1px solid rgba(255,255,255,.06); }
|
||||
.thumb-canvas { position: absolute; inset: 0; }
|
||||
.thumb-chips { position: absolute; top: 9px; left: 9px; right: 9px; display: flex; align-items: center; gap: 6px; pointer-events: none; }
|
||||
.chip { font-size: 10.5px; color: #e2e8f0; background: rgba(5, 8, 18, .68); border: 1px solid rgba(255,255,255,.14); padding: 3px 8px; border-radius: 999px; backdrop-filter: blur(8px); }
|
||||
.chip.live { margin-left: auto; color: #fdf4ff; background: rgba(217, 70, 239, .4); border-color: rgba(232, 121, 249, .55); font-weight: 700; display: inline-flex; align-items: center; gap: 5px; }
|
||||
.chip.live .dot { width: 6px; height: 6px; background: #f0abfc; box-shadow: 0 0 8px #f0abfc; animation: pulse 1.2s infinite; }
|
||||
@keyframes pulse { 50% { opacity: .25; } }
|
||||
|
||||
.card-body { padding: 14px 16px 16px; display: flex; flex-direction: column; gap: 11px; flex: 1; }
|
||||
.card-body h3 { margin: 0; font-size: 16.5px; line-height: 1.3; letter-spacing: -.2px; }
|
||||
.muted { color: var(--muted); font-size: 12px; }
|
||||
.actions { display: flex; gap: 7px; flex-wrap: wrap; }
|
||||
.actions .grow { flex: 1; }
|
||||
.primary { background: linear-gradient(90deg, #6366f1, #a855f7); color: #fff; font-weight: 600; }
|
||||
.primary:hover:not(:disabled) { filter: brightness(1.12); background: linear-gradient(90deg, #6366f1, #a855f7); }
|
||||
.ghost { background: rgba(255,255,255,.07); }
|
||||
.danger { background: rgba(239, 68, 68, .13); color: #fca5a5; border: 1px solid rgba(239, 68, 68, .32); }
|
||||
.danger:hover:not(:disabled) { background: rgba(239, 68, 68, .25); }
|
||||
.icon-btn { padding: 9px 11px; }
|
||||
|
||||
.live { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; color: #f0abfc; }
|
||||
.live .dot { width: 7px; height: 7px; background: #e879f9; box-shadow: 0 0 8px #e879f9; animation: pulse 1.2s infinite; }
|
||||
.empty { color: #64748b; padding: 52px 20px; text-align: center; border: 1px dashed rgba(255, 255, 255, .12); border-radius: 18px; font-size: 13.5px; line-height: 1.6; }
|
||||
.empty b { color: #c7d2fe; }
|
||||
|
||||
.session-card { padding: 18px; display: flex; flex-direction: column; gap: 13px; }
|
||||
.session-top { display: flex; justify-content: space-between; gap: 14px; align-items: flex-start; }
|
||||
.session-top h3 { margin: 0 0 6px; font-size: 16.5px; }
|
||||
.progress { height: 6px; border-radius: 999px; background: rgba(255, 255, 255, .08); overflow: hidden; }
|
||||
.progress > div { height: 100%; border-radius: 999px; background: linear-gradient(90deg, #6366f1, #e879f9); transition: width .3s; }
|
||||
.session-meta { display: flex; gap: 12px; flex-wrap: wrap; font-size: 12.5px; color: var(--muted); align-items: center; }
|
||||
.viewers { display: inline-flex; align-items: center; gap: 5px; font-weight: 700; color: #f0abfc; font-size: 13px; }
|
||||
.session-actions { display: flex; gap: 7px; flex-wrap: wrap; }
|
||||
.session-actions button { flex: 1; min-width: 120px; }
|
||||
|
||||
.foot { margin-top: 44px; color: #475569; font-size: 11.5px; display: flex; justify-content: space-between; flex-wrap: wrap; gap: 10px; border-top: 1px solid rgba(255,255,255,.06); padding-top: 16px; }
|
||||
|
||||
::-webkit-scrollbar { width: 10px; height: 10px; }
|
||||
::-webkit-scrollbar-thumb { background: rgba(255,255,255,.12); border-radius: 999px; }
|
||||
::-webkit-scrollbar-track { background: transparent; }
|
||||
|
||||
@media (max-width: 760px) {
|
||||
.shell { padding: 0 20px 60px; }
|
||||
.dash-head { padding-top: 20px; }
|
||||
.dash-actions { width: 100%; }
|
||||
.dash-actions .create-btn { flex: 1; }
|
||||
header { flex-wrap: wrap; }
|
||||
.grid { grid-template-columns: 1fr; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="shell">
|
||||
<header>
|
||||
<div class="logo">🎤 Prompt<span>ly</span> <small>studio</small></div>
|
||||
<div class="status"><span class="dot" id="conn-dot"></span><span id="conn-text">Подключение…</span></div>
|
||||
</header>
|
||||
|
||||
<section class="dash-head">
|
||||
<div class="dash-title">
|
||||
<h1>Студия</h1>
|
||||
<p>Презентации, прямые эфиры и материалы</p>
|
||||
</div>
|
||||
<div class="dash-actions">
|
||||
<a class="link" href="docs.html" target="_blank" rel="noopener">📖 Lua API</a>
|
||||
<button class="create-btn" id="create-btn">+ Новая презентация</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div class="stats-line">
|
||||
<span><b id="stat-presentations">0</b> презентаций</span>
|
||||
<span><b id="stat-sessions">0</b> в эфире</span>
|
||||
</div>
|
||||
|
||||
<div class="tabs">
|
||||
<button class="tab active" data-tab="presentations">Мои презентации <span class="badge" id="count-presentations">0</span></button>
|
||||
<button class="tab" data-tab="sessions">Прямые эфиры <span class="badge" id="count-sessions">0</span></button>
|
||||
</div>
|
||||
|
||||
<div class="panel active" id="panel-presentations">
|
||||
<div class="toolbar">
|
||||
<div class="search-wrap">
|
||||
<input class="search" id="search" placeholder="Поиск по названию…">
|
||||
</div>
|
||||
<span class="muted" id="result-count"></span>
|
||||
</div>
|
||||
<div class="grid" id="presentations"></div>
|
||||
</div>
|
||||
|
||||
<div class="panel" id="panel-sessions">
|
||||
<div class="grid" id="sessions"></div>
|
||||
</div>
|
||||
|
||||
<div class="foot">
|
||||
<span>Promptly Studio · презентации в реальном времени</span>
|
||||
<span>Докладчик управляет слайдами, кнопками и звуком · зрители видят только слайд</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="js/slide-view.js"></script>
|
||||
<script>
|
||||
const state = { presentations: [], sessions: [], search: '' };
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
const presentationsEl = $('presentations');
|
||||
const sessionsEl = $('sessions');
|
||||
const connDot = $('conn-dot');
|
||||
const connText = $('conn-text');
|
||||
|
||||
const esc = (s) =>
|
||||
String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
|
||||
function timeAgo(ts) {
|
||||
const diff = Math.max(0, Date.now() - ts);
|
||||
const min = Math.floor(diff / 60000);
|
||||
if (min < 1) return 'только что';
|
||||
if (min < 60) return `${min} мин назад`;
|
||||
const hours = Math.floor(min / 60);
|
||||
if (hours < 24) return `${hours} ч назад`;
|
||||
return new Date(ts).toLocaleDateString('ru-RU');
|
||||
}
|
||||
|
||||
function plural(n, one, few, many) {
|
||||
const mod10 = n % 10;
|
||||
const mod100 = n % 100;
|
||||
if (mod10 === 1 && mod100 !== 11) return one;
|
||||
if (mod10 >= 2 && mod10 <= 4 && (mod100 < 10 || mod100 >= 20)) return few;
|
||||
return many;
|
||||
}
|
||||
|
||||
function isLive(id) {
|
||||
return state.sessions.some((session) => session.presentationId === id);
|
||||
}
|
||||
|
||||
function renderPresentations() {
|
||||
const total = state.presentations.length;
|
||||
$('count-presentations').textContent = total;
|
||||
$('stat-presentations').textContent = total;
|
||||
|
||||
const query = state.search.trim().toLowerCase();
|
||||
const list = query
|
||||
? state.presentations.filter((p) => p.title.toLowerCase().includes(query))
|
||||
: state.presentations;
|
||||
$('result-count').textContent = query ? `Найдено: ${list.length}` : '';
|
||||
|
||||
if (!list.length) {
|
||||
presentationsEl.innerHTML = `<div class="empty" style="grid-column:1/-1">${
|
||||
query ? 'Ничего не найдено по запросу.' : 'Пока нет презентаций — <b>создайте первую!</b>'
|
||||
}</div>`;
|
||||
return;
|
||||
}
|
||||
|
||||
presentationsEl.innerHTML = list.map((p) => {
|
||||
const slides = (p.slides || []).length;
|
||||
const live = isLive(p.id);
|
||||
return `
|
||||
<div class="card">
|
||||
<div class="thumb">
|
||||
<div class="thumb-canvas" data-pres="${esc(p.id)}"></div>
|
||||
<div class="thumb-chips">
|
||||
<span class="chip">${slides} ${plural(slides, 'слайд', 'слайда', 'слайдов')}</span>
|
||||
${live ? '<span class="chip live"><span class="dot"></span> LIVE</span>' : ''}
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<h3>${esc(p.title)}</h3>
|
||||
<div class="muted">Обновлено ${timeAgo(p.updatedAt)}</div>
|
||||
<div class="actions">
|
||||
<button class="primary grow" onclick="startDemo('${esc(p.id)}')">▶ Демонстрировать</button>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<button class="ghost grow" onclick="editPresentation('${esc(p.id)}')">✎ Изменить</button>
|
||||
${live ? `<button class="ghost" onclick="watchSession('${esc(p.id)}')" title="Смотреть как зритель">👁</button>` : ''}
|
||||
<button class="ghost icon-btn" onclick="duplicatePresentation('${esc(p.id)}')" title="Дублировать">⧉</button>
|
||||
<button class="danger icon-btn" onclick="removePresentation('${esc(p.id)}')" title="Удалить">🗑</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>`;
|
||||
}).join('');
|
||||
|
||||
mountThumbs();
|
||||
}
|
||||
|
||||
function mountThumbs() {
|
||||
presentationsEl.querySelectorAll('.thumb-canvas').forEach((container) => {
|
||||
const presentation = state.presentations.find((item) => item.id === container.dataset.pres);
|
||||
if (!presentation) return;
|
||||
const slide = (presentation.slides || [])[0] || { elements: [] };
|
||||
SlideView.render(container, slide, { variables: presentation.variables || {} });
|
||||
});
|
||||
}
|
||||
|
||||
function renderSessions() {
|
||||
const total = state.sessions.length;
|
||||
$('count-sessions').textContent = total;
|
||||
$('stat-sessions').textContent = total;
|
||||
|
||||
if (!total) {
|
||||
sessionsEl.innerHTML = '<div class="empty" style="grid-column:1/-1">Сейчас нет активных демонстраций.<br>Нажмите «Демонстрировать» на любой презентации.</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
sessionsEl.innerHTML = state.sessions.map((session) => {
|
||||
const progress = session.slidesCount ? Math.round(((session.currentSlide + 1) / session.slidesCount) * 100) : 0;
|
||||
return `
|
||||
<div class="card session-card">
|
||||
<div class="session-top">
|
||||
<div>
|
||||
<h3>${esc(session.title)}</h3>
|
||||
<div class="live"><span class="dot"></span> идёт ${timeAgo(session.startedAt)}</div>
|
||||
</div>
|
||||
<span class="viewers">👁 ${session.viewers}</span>
|
||||
</div>
|
||||
<div class="progress"><div style="width:${progress}%"></div></div>
|
||||
<div class="session-meta">
|
||||
<span>Слайд ${session.currentSlide + 1} из ${session.slidesCount}</span>
|
||||
${session.presenters ? '<span>🎤 докладчик на связи</span>' : '<span>🎤 докладчик не подключён</span>'}
|
||||
</div>
|
||||
<div class="session-actions">
|
||||
<button class="ghost" onclick="watchSession('${esc(session.presentationId)}')">👁 Смотреть</button>
|
||||
<button class="danger" onclick="stopSession('${esc(session.presentationId)}')">■ Остановить</button>
|
||||
</div>
|
||||
</div>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function renderAll() {
|
||||
renderPresentations();
|
||||
renderSessions();
|
||||
}
|
||||
|
||||
$('search').addEventListener('input', (event) => {
|
||||
state.search = event.target.value;
|
||||
renderPresentations();
|
||||
});
|
||||
|
||||
$('create-btn').addEventListener('click', () => (location.href = 'editor.html'));
|
||||
|
||||
window.startDemo = (id) => window.open(`viewer.html?id=${encodeURIComponent(id)}&mode=speaker`, '_blank');
|
||||
window.watchSession = (id) => window.open(`viewer.html?id=${encodeURIComponent(id)}&mode=audience`, '_blank');
|
||||
window.editPresentation = (id) => (location.href = `editor.html?id=${encodeURIComponent(id)}`);
|
||||
|
||||
window.duplicatePresentation = async (id) => {
|
||||
await fetch(`/api/presentations/${encodeURIComponent(id)}/duplicate`, { method: 'POST' });
|
||||
};
|
||||
|
||||
window.removePresentation = async (id) => {
|
||||
if (!confirm('Удалить презентацию? Это действие необратимо.')) return;
|
||||
await fetch(`/api/presentations/${encodeURIComponent(id)}`, { method: 'DELETE' });
|
||||
};
|
||||
|
||||
window.stopSession = async (presentationId) => {
|
||||
if (!confirm('Остановить демонстрацию для всех зрителей?')) return;
|
||||
await fetch(`/api/sessions/${encodeURIComponent(presentationId)}`, { method: 'DELETE' });
|
||||
};
|
||||
|
||||
document.querySelectorAll('.tab').forEach((tab) => {
|
||||
tab.addEventListener('click', () => {
|
||||
document.querySelectorAll('.tab').forEach((item) => item.classList.remove('active'));
|
||||
document.querySelectorAll('.panel').forEach((panel) => panel.classList.remove('active'));
|
||||
tab.classList.add('active');
|
||||
$('panel-' + tab.dataset.tab).classList.add('active');
|
||||
});
|
||||
});
|
||||
|
||||
let ws;
|
||||
function connect() {
|
||||
connText.textContent = 'Подключение…';
|
||||
ws = new WebSocket(`ws://${location.host}/`);
|
||||
|
||||
ws.onopen = () => {
|
||||
connDot.classList.remove('off');
|
||||
connText.textContent = 'Онлайн';
|
||||
};
|
||||
|
||||
ws.onmessage = (event) => {
|
||||
let message;
|
||||
try { message = JSON.parse(event.data); } catch (error) { return; }
|
||||
if (message.type === 'presentations') {
|
||||
state.presentations = message.presentations;
|
||||
renderAll();
|
||||
}
|
||||
if (message.type === 'sessions') {
|
||||
state.sessions = message.sessions;
|
||||
renderAll();
|
||||
}
|
||||
};
|
||||
|
||||
ws.onclose = () => {
|
||||
connDot.classList.add('off');
|
||||
connText.textContent = 'Нет соединения — переподключение…';
|
||||
setTimeout(connect, 1500);
|
||||
};
|
||||
|
||||
ws.onerror = () => ws.close();
|
||||
}
|
||||
|
||||
connect();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,301 @@
|
||||
// Аудио-движок презентации: фоновая музыка, эффекты, ducking и раздельные громкости.
|
||||
// Работает на клиенте; команды синхронизируются докладчиком через WebSocket.
|
||||
(function () {
|
||||
const DUCK = 0.22; // насколько приглушается фон, пока играет эффект
|
||||
const FADE_IN = 500;
|
||||
const FADE_OUT = 380;
|
||||
|
||||
function clamp(value, fallback = 0) {
|
||||
const n = Number(value);
|
||||
if (!Number.isFinite(n)) return fallback;
|
||||
return Math.max(0, Math.min(1, n));
|
||||
}
|
||||
|
||||
function fadeTo(audio, target, ms) {
|
||||
if (!audio) return;
|
||||
const to = clamp(target, 0);
|
||||
if (audio._fadeTimer) clearInterval(audio._fadeTimer);
|
||||
const from = audio.volume;
|
||||
const start = performance.now();
|
||||
const duration = Math.max(1, ms || 1);
|
||||
if (Math.abs(from - to) < 0.005) {
|
||||
audio.volume = to;
|
||||
return;
|
||||
}
|
||||
audio._fadeTimer = setInterval(() => {
|
||||
const t = Math.min(1, (performance.now() - start) / duration);
|
||||
const eased = t * t * (3 - 2 * t);
|
||||
audio.volume = clamp(from + (to - from) * eased, 0);
|
||||
if (t >= 1) {
|
||||
clearInterval(audio._fadeTimer);
|
||||
audio._fadeTimer = null;
|
||||
}
|
||||
}, 28);
|
||||
}
|
||||
|
||||
function createAudioController(options = {}) {
|
||||
const onBlocked = typeof options.onBlocked === 'function' ? options.onBlocked : () => {};
|
||||
const onState = typeof options.onState === 'function' ? options.onState : () => {};
|
||||
const onEnded = typeof options.onEnded === 'function' ? options.onEnded : () => {};
|
||||
|
||||
const bgm = new Audio();
|
||||
bgm.preload = 'auto';
|
||||
bgm.loop = true;
|
||||
|
||||
const effects = new Map(); // id -> { audio, volume, loop }
|
||||
let musicSrc = '';
|
||||
let musicPlaying = false;
|
||||
let bgmLevel = 0.5;
|
||||
let sfxLevel = 0.8;
|
||||
let unlocked = false;
|
||||
let blockedNotified = false;
|
||||
let pending = []; // команды, которые не удалось запустить до разблокировки звука
|
||||
|
||||
function activeEffects() {
|
||||
let count = 0;
|
||||
effects.forEach((entry) => {
|
||||
if (!entry.audio.paused && !entry.audio.ended) count += 1;
|
||||
});
|
||||
return count;
|
||||
}
|
||||
|
||||
function bgmTarget() {
|
||||
if (!musicPlaying) return 0;
|
||||
return clamp(bgmLevel * (activeEffects() > 0 ? DUCK : 1), 0);
|
||||
}
|
||||
|
||||
function updateDucking() {
|
||||
fadeTo(bgm, bgmTarget(), 420);
|
||||
}
|
||||
|
||||
function state() {
|
||||
return { musicSrc, musicPlaying, bgm: bgmLevel, sfx: sfxLevel };
|
||||
}
|
||||
|
||||
function emitState() {
|
||||
onState(state());
|
||||
}
|
||||
|
||||
function notifyBlocked() {
|
||||
if (blockedNotified) return;
|
||||
blockedNotified = true;
|
||||
onBlocked();
|
||||
}
|
||||
|
||||
function clearBlocked() {
|
||||
blockedNotified = false;
|
||||
}
|
||||
|
||||
function safePlay(audio, onFail) {
|
||||
const promise = audio.play();
|
||||
if (promise && typeof promise.catch === 'function') {
|
||||
promise.catch((err) => {
|
||||
// Autoplay policy: ждём клика пользователя
|
||||
if (err && (err.name === 'NotAllowedError' || err.name === 'NotSupportedError' || err.name === 'AbortError')) {
|
||||
notifyBlocked();
|
||||
if (typeof onFail === 'function') onFail(err);
|
||||
}
|
||||
});
|
||||
}
|
||||
return promise;
|
||||
}
|
||||
|
||||
function setMusicSource(src) {
|
||||
const next = String(src || '');
|
||||
if (next === musicSrc && bgm.src) return;
|
||||
musicSrc = next;
|
||||
if (next) {
|
||||
bgm.src = next;
|
||||
bgm.load();
|
||||
} else {
|
||||
bgm.pause();
|
||||
bgm.removeAttribute('src');
|
||||
bgm.load();
|
||||
}
|
||||
}
|
||||
|
||||
function playMusic(src) {
|
||||
if (src) setMusicSource(src);
|
||||
if (!musicSrc) return;
|
||||
musicPlaying = true;
|
||||
bgm.loop = true;
|
||||
if (bgm.volume === 0) bgm.volume = 0;
|
||||
safePlay(bgm, () => {
|
||||
// Попробуем ещё раз, когда пользователь разблокирует звук
|
||||
pending.push({ action: 'music', src: musicSrc, play: true });
|
||||
});
|
||||
setTimeout(updateDucking, 60);
|
||||
emitState();
|
||||
}
|
||||
|
||||
function stopMusic() {
|
||||
musicPlaying = false;
|
||||
fadeTo(bgm, 0, FADE_OUT);
|
||||
setTimeout(() => {
|
||||
if (!musicPlaying) bgm.pause();
|
||||
}, FADE_OUT + 30);
|
||||
emitState();
|
||||
}
|
||||
|
||||
function playEffect(command) {
|
||||
const id = String(command.id || command.audioId || '');
|
||||
if (!id) return;
|
||||
const existing = effects.get(id);
|
||||
if (existing) {
|
||||
try {
|
||||
existing.audio.pause();
|
||||
} catch (e) {
|
||||
/* noop */
|
||||
}
|
||||
effects.delete(id);
|
||||
}
|
||||
if (!command.src) return;
|
||||
|
||||
const audio = new Audio();
|
||||
audio.preload = 'auto';
|
||||
audio.src = command.src;
|
||||
audio.loop = !!command.loop;
|
||||
audio.volume = 0;
|
||||
const volume = clamp(command.volume, 0.8);
|
||||
const entry = { audio, volume, loop: !!command.loop };
|
||||
effects.set(id, entry);
|
||||
|
||||
audio.addEventListener('ended', () => {
|
||||
if (effects.get(id) === entry) effects.delete(id);
|
||||
updateDucking();
|
||||
emitState();
|
||||
onEnded(id);
|
||||
});
|
||||
|
||||
safePlay(audio, () => {
|
||||
pending.push({ action: 'play', id, src: command.src, loop: !!command.loop, volume });
|
||||
});
|
||||
fadeTo(audio, clamp(volume * sfxLevel, 0), FADE_IN);
|
||||
updateDucking();
|
||||
emitState();
|
||||
}
|
||||
|
||||
function stopEffect(id) {
|
||||
const key = String(id || '');
|
||||
if (!key) return;
|
||||
const entry = effects.get(key);
|
||||
if (!entry) return;
|
||||
effects.delete(key);
|
||||
const audio = entry.audio;
|
||||
fadeTo(audio, 0, FADE_OUT);
|
||||
setTimeout(() => {
|
||||
try {
|
||||
audio.pause();
|
||||
} catch (e) {
|
||||
/* noop */
|
||||
}
|
||||
}, FADE_OUT + 30);
|
||||
updateDucking();
|
||||
emitState();
|
||||
}
|
||||
|
||||
function stopAllEffects() {
|
||||
effects.forEach((entry) => {
|
||||
const audio = entry.audio;
|
||||
fadeTo(audio, 0, FADE_OUT);
|
||||
setTimeout(() => {
|
||||
try {
|
||||
audio.pause();
|
||||
} catch (e) {
|
||||
/* noop */
|
||||
}
|
||||
}, FADE_OUT + 30);
|
||||
});
|
||||
effects.clear();
|
||||
updateDucking();
|
||||
emitState();
|
||||
}
|
||||
|
||||
function applyVolumes(bgmValue, sfxValue) {
|
||||
bgmLevel = clamp(bgmValue, bgmLevel);
|
||||
sfxLevel = clamp(sfxValue, sfxLevel);
|
||||
updateDucking();
|
||||
effects.forEach((entry) => {
|
||||
fadeTo(entry.audio, clamp(entry.volume * sfxLevel, 0), 220);
|
||||
});
|
||||
emitState();
|
||||
}
|
||||
|
||||
function applyCommand(command) {
|
||||
if (!command || typeof command !== 'object') return;
|
||||
switch (command.action) {
|
||||
case 'music':
|
||||
if (typeof command.src === 'string' && command.src) setMusicSource(command.src);
|
||||
if (command.play === false) stopMusic();
|
||||
else playMusic();
|
||||
break;
|
||||
case 'musicStop':
|
||||
stopMusic();
|
||||
break;
|
||||
case 'play':
|
||||
playEffect(command);
|
||||
break;
|
||||
case 'stop':
|
||||
if (command.id === '*' || command.all) stopAllEffects();
|
||||
else stopEffect(command.id);
|
||||
break;
|
||||
case 'effectVolume': {
|
||||
const entry = effects.get(String(command.id || ''));
|
||||
if (entry) {
|
||||
entry.volume = clamp(command.volume, entry.volume);
|
||||
fadeTo(entry.audio, clamp(entry.volume * sfxLevel, 0), 220);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'volumes':
|
||||
applyVolumes(command.bgm, command.sfx);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
emitState();
|
||||
}
|
||||
|
||||
// Разблокировка звука по клику пользователя (autoplay policy браузеров)
|
||||
function unlock() {
|
||||
unlocked = true;
|
||||
clearBlocked();
|
||||
const silent = new Audio(
|
||||
'data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAgD4AAAB9AAACABAAZGF0YQAAAAA='
|
||||
);
|
||||
silent.volume = 0.001;
|
||||
silent.play().catch(() => {});
|
||||
if (musicPlaying && musicSrc) safePlay(bgm);
|
||||
const queue = pending.splice(0);
|
||||
queue.forEach((command) => applyCommand(command));
|
||||
emitState();
|
||||
return true;
|
||||
}
|
||||
|
||||
function getPlayingEffectIds() {
|
||||
const ids = [];
|
||||
effects.forEach((entry, id) => {
|
||||
if (!entry.audio.paused) ids.push(id);
|
||||
});
|
||||
return ids;
|
||||
}
|
||||
|
||||
return {
|
||||
applyCommand,
|
||||
applyVolumes,
|
||||
playMusic,
|
||||
stopMusic,
|
||||
playEffect,
|
||||
stopEffect,
|
||||
stopAllEffects,
|
||||
setBgmLevel: (value) => applyVolumes(value, sfxLevel),
|
||||
setSfxLevel: (value) => applyVolumes(bgmLevel, value),
|
||||
getState: state,
|
||||
getPlayingEffectIds,
|
||||
isUnlocked: () => unlocked,
|
||||
unlock,
|
||||
};
|
||||
}
|
||||
|
||||
window.createAudioController = createAudioController;
|
||||
})();
|
||||
@@ -0,0 +1,156 @@
|
||||
// Мост Lua ↔ JS для интерактивных презентаций.
|
||||
// Использует глобальный fengari (vendor/fengari-web.js).
|
||||
(function () {
|
||||
const { lua, lauxlib, lualib, to_luastring, to_jsstring } = window.fengari;
|
||||
const T = lua;
|
||||
|
||||
function readValue(L, idx) {
|
||||
const type = T.lua_type(L, idx);
|
||||
if (type === T.LUA_TBOOLEAN) return !!T.lua_toboolean(L, idx);
|
||||
if (type === T.LUA_TNUMBER) return T.lua_tonumber(L, idx);
|
||||
if (type === T.LUA_TSTRING) {
|
||||
const s = T.lua_tostring(L, idx);
|
||||
return s ? to_jsstring(s) : '';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function pushValue(L, value) {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) T.lua_pushnumber(L, value);
|
||||
else if (typeof value === 'boolean') T.lua_pushboolean(L, value);
|
||||
else if (typeof value === 'string') T.lua_pushstring(L, to_luastring(value));
|
||||
else T.lua_pushnil(L);
|
||||
}
|
||||
|
||||
function jsString(L, idx) {
|
||||
const s = T.lua_tostring(L, idx);
|
||||
return s ? to_jsstring(s) : '';
|
||||
}
|
||||
|
||||
function createRuntime(hooks = {}) {
|
||||
const L = lauxlib.luaL_newstate();
|
||||
lualib.luaL_openlibs(L);
|
||||
|
||||
const noop = () => {};
|
||||
const h = {
|
||||
go: hooks.go || noop,
|
||||
next: hooks.next || noop,
|
||||
prev: hooks.prev || noop,
|
||||
play: hooks.play || noop,
|
||||
stop: hooks.stop || noop,
|
||||
volume: hooks.volume || noop,
|
||||
music: hooks.music || noop,
|
||||
musicPlay: hooks.musicPlay || noop,
|
||||
musicStop: hooks.musicStop || noop,
|
||||
musicVolume: hooks.musicVolume || noop,
|
||||
videoPlay: hooks.videoPlay || noop,
|
||||
videoPause: hooks.videoPause || noop,
|
||||
videoRestart: hooks.videoRestart || noop,
|
||||
videoSeek: hooks.videoSeek || noop,
|
||||
currentSlide: hooks.currentSlide || (() => 1),
|
||||
log: hooks.log || ((msg) => console.log('[lua]', msg)),
|
||||
error: hooks.error || ((msg) => console.error('[lua]', msg)),
|
||||
};
|
||||
|
||||
const setFn = (name, fn) => {
|
||||
T.lua_pushcfunction(L, (state) => {
|
||||
try {
|
||||
return fn(state) || 0;
|
||||
} catch (err) {
|
||||
h.error(String(err && err.message ? err.message : err));
|
||||
return 0;
|
||||
}
|
||||
});
|
||||
T.lua_setfield(L, -2, to_luastring(name));
|
||||
};
|
||||
|
||||
// app.*
|
||||
T.lua_newtable(L);
|
||||
setFn('go', (Ls) => {
|
||||
h.go(Math.max(0, Math.floor(readValue(Ls, 1) || 1) - 1));
|
||||
return 0;
|
||||
});
|
||||
setFn('next', () => (h.next(), 0));
|
||||
setFn('prev', () => (h.prev(), 0));
|
||||
setFn('play', (Ls) => (h.play(jsString(Ls, 1)), 0));
|
||||
setFn('stop', (Ls) => (h.stop(jsString(Ls, 1)), 0));
|
||||
setFn('volume', (Ls) => (h.volume(jsString(Ls, 1), readValue(Ls, 2)), 0));
|
||||
setFn('music', (Ls) => (h.music(jsString(Ls, 1)), 0));
|
||||
setFn('musicPlay', () => (h.musicPlay(), 0));
|
||||
setFn('musicStop', () => (h.musicStop(), 0));
|
||||
setFn('musicVolume', (Ls) => (h.musicVolume(readValue(Ls, 1)), 0));
|
||||
setFn('videoPlay', (Ls) => (h.videoPlay(jsString(Ls, 1)), 0));
|
||||
setFn('videoPause', (Ls) => (h.videoPause(jsString(Ls, 1)), 0));
|
||||
setFn('videoRestart', (Ls) => (h.videoRestart(jsString(Ls, 1)), 0));
|
||||
setFn('videoSeek', (Ls) => (h.videoSeek(jsString(Ls, 1), readValue(Ls, 2)), 0));
|
||||
setFn('slide', (Ls) => (T.lua_pushnumber(Ls, h.currentSlide()), 1));
|
||||
setFn('log', (Ls) => (h.log(jsString(Ls, 1)), 0));
|
||||
T.lua_setglobal(L, to_luastring('app'));
|
||||
|
||||
// vars
|
||||
T.lua_newtable(L);
|
||||
T.lua_setglobal(L, to_luastring('vars'));
|
||||
|
||||
function setVars(obj = {}) {
|
||||
T.lua_getglobal(L, to_luastring('vars'));
|
||||
for (const key of Object.keys(obj)) {
|
||||
pushValue(L, obj[key]);
|
||||
T.lua_setfield(L, -2, to_luastring(key));
|
||||
}
|
||||
T.lua_pop(L, 1);
|
||||
}
|
||||
|
||||
function getVars() {
|
||||
const result = {};
|
||||
T.lua_getglobal(L, to_luastring('vars'));
|
||||
const tableIndex = T.lua_gettop(L);
|
||||
T.lua_pushnil(L);
|
||||
while (T.lua_next(L, tableIndex) !== 0) {
|
||||
const key = T.lua_tostring(L, -2);
|
||||
if (key) result[to_jsstring(key)] = readValue(L, -1);
|
||||
T.lua_pop(L, 1);
|
||||
}
|
||||
T.lua_pop(L, 1);
|
||||
return result;
|
||||
}
|
||||
|
||||
T.lua_getglobal(L, to_luastring('app'));
|
||||
setFn('setVar', (Ls) => {
|
||||
T.lua_getglobal(L, to_luastring('vars'));
|
||||
pushValue(Ls, readValue(Ls, 2));
|
||||
T.lua_setfield(Ls, -2, T.lua_tostring(Ls, 1));
|
||||
T.lua_pop(Ls, 1);
|
||||
return 0;
|
||||
});
|
||||
setFn('getVar', (Ls) => {
|
||||
T.lua_getglobal(Ls, to_luastring('vars'));
|
||||
T.lua_getfield(Ls, -1, T.lua_tostring(Ls, 1));
|
||||
T.lua_remove(Ls, -2);
|
||||
return 1;
|
||||
});
|
||||
T.lua_pop(L, 1);
|
||||
|
||||
function run(code, label = 'script') {
|
||||
if (!code || !String(code).trim()) return getVars();
|
||||
const status = lauxlib.luaL_dostring(L, to_luastring(String(code)));
|
||||
if (status !== T.LUA_OK) {
|
||||
const err = T.lua_tostring(L, -1);
|
||||
h.error(`Lua (${label}): ${err ? to_jsstring(err) : 'unknown error'}`);
|
||||
T.lua_pop(L, 1);
|
||||
}
|
||||
return getVars();
|
||||
}
|
||||
|
||||
function reset(obj = {}) {
|
||||
T.lua_newtable(L);
|
||||
T.lua_setglobal(L, to_luastring('vars'));
|
||||
setVars(obj);
|
||||
}
|
||||
|
||||
reset(hooks.vars || {});
|
||||
|
||||
return { run, getVars, setVars, reset };
|
||||
}
|
||||
|
||||
window.createLuaRuntime = createRuntime;
|
||||
})();
|
||||
@@ -0,0 +1,448 @@
|
||||
// Общий рендерер слайдов: используется в редакторе, демонстрации и превью на главной.
|
||||
// Элементы позиционируются в процентах, размеры шрифтов — в cqw (1% ширины слайда).
|
||||
(function () {
|
||||
const DEFAULT_GRADIENT = 'linear-gradient(135deg, #0f172a 0%, #1e1b4b 55%, #312e81 100%)';
|
||||
|
||||
if (!document.getElementById('slide-view-styles')) {
|
||||
const style = document.createElement('style');
|
||||
style.id = 'slide-view-styles';
|
||||
style.textContent = `
|
||||
.sv-root {
|
||||
position: absolute; inset: 0; overflow: hidden;
|
||||
container-type: inline-size;
|
||||
font-family: system-ui, -apple-system, 'Segoe UI', sans-serif;
|
||||
color: #f8fafc; user-select: none;
|
||||
}
|
||||
.sv-el { position: absolute; box-sizing: border-box; }
|
||||
.sv-root.editable .sv-el { cursor: move; }
|
||||
.sv-root.editable .sv-el:hover { outline: 1px dashed rgba(129, 140, 248, .7); outline-offset: 1px; }
|
||||
.sv-root.editable .sv-el.sv-selected { outline: 2px solid #818cf8; outline-offset: 1px; }
|
||||
.sv-text {
|
||||
display: flex; white-space: pre-wrap; line-height: 1.16; word-break: break-word;
|
||||
overflow: hidden; box-sizing: border-box; font-weight: 700;
|
||||
}
|
||||
.sv-image { width: 100%; height: 100%; display: block; object-fit: cover; }
|
||||
.sv-image-missing {
|
||||
width: 100%; height: 100%; display: flex; flex-direction: column; gap: 1cqw;
|
||||
align-items: center; justify-content: center; border: 1px dashed rgba(148, 163, 184, .5);
|
||||
border-radius: 10px; color: #94a3b8; font-size: 1.6cqw; background: rgba(15, 23, 42, .35);
|
||||
}
|
||||
.sv-image-missing b { font-size: 3cqw; line-height: 1; }
|
||||
.sv-video {
|
||||
position: relative; width: 100%; height: 100%; overflow: hidden; background: #02040a;
|
||||
}
|
||||
.sv-video video {
|
||||
width: 100%; height: 100%; display: block; background: #02040a;
|
||||
}
|
||||
.sv-video .sv-media-missing {
|
||||
position: absolute; inset: 0; display: flex; flex-direction: column; gap: 1cqw;
|
||||
align-items: center; justify-content: center; border: 1px dashed rgba(148, 163, 184, .5);
|
||||
color: #94a3b8; font-size: 1.6cqw; background: rgba(15, 23, 42, .35); text-align: center;
|
||||
box-sizing: border-box; padding: 1cqw;
|
||||
}
|
||||
.sv-video .sv-media-missing b { font-size: 3cqw; line-height: 1; }
|
||||
.sv-root.editable .sv-video { pointer-events: none; }
|
||||
.sv-window {
|
||||
position: relative; width: 100%; height: 100%; overflow: hidden; background: #02040a;
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
}
|
||||
.sv-window img {
|
||||
width: 100%; height: 100%; display: block; object-fit: fill;
|
||||
}
|
||||
.sv-window .sv-window-placeholder {
|
||||
position: absolute; inset: 0; display: flex; flex-direction: column; gap: .6cqw;
|
||||
align-items: center; justify-content: center; text-align: center; padding: 2cqw;
|
||||
color: #94a3b8; font-size: 1.5cqw; border: 1px dashed rgba(148, 163, 184, .45);
|
||||
background: radial-gradient(circle at 50% 40%, rgba(99, 102, 241, .16), rgba(2, 4, 10, .9));
|
||||
}
|
||||
.sv-window .sv-window-placeholder b { font-size: 2.6cqw; }
|
||||
.sv-window .sv-window-live {
|
||||
position: absolute; top: .7cqw; right: .7cqw; display: flex; align-items: center; gap: .5cqw;
|
||||
padding: .35cqw .8cqw; border-radius: 999px; background: rgba(5, 8, 18, .7);
|
||||
color: #f0abfc; font-size: 1.1cqw; font-weight: 700; letter-spacing: .5px;
|
||||
border: 1px solid rgba(232, 121, 249, .35); pointer-events: none;
|
||||
}
|
||||
.sv-window .sv-window-live i { width: .55cqw; height: .55cqw; border-radius: 50%; background: #e879f9; }
|
||||
.sv-root:not(.editable) .sv-window[data-live="1"] { cursor: crosshair; }
|
||||
.sv-root:not(.editable) .sv-window[data-live="1"]:hover { box-shadow: inset 0 0 0 2px rgba(129, 140, 248, .55); }
|
||||
.sv-button {
|
||||
width: 100%; height: 100%; display: flex; align-items: center; justify-content: center;
|
||||
border: none; font-family: inherit; font-weight: 700; line-height: 1.15; padding: 0 4%;
|
||||
box-sizing: border-box; cursor: pointer; text-align: center;
|
||||
transition: transform .12s ease, filter .12s ease, box-shadow .12s ease;
|
||||
box-shadow: 0 8px 26px rgba(0, 0, 0, .28);
|
||||
}
|
||||
.sv-button:hover { filter: brightness(1.1); }
|
||||
.sv-button:active { transform: scale(.98); }
|
||||
.sv-root.editable .sv-button { pointer-events: none; }
|
||||
.sv-audio {
|
||||
width: 100%; height: 100%; display: flex; align-items: center; gap: .8em;
|
||||
padding: 0 1.2em; box-sizing: border-box; border-radius: 999px;
|
||||
background: rgba(15, 23, 42, .62); border: 1px solid rgba(255, 255, 255, .18);
|
||||
color: #e2e8f0; font-size: clamp(8px, 1.7cqw, 30px); font-weight: 600;
|
||||
backdrop-filter: blur(10px); overflow: hidden; white-space: nowrap;
|
||||
box-shadow: 0 10px 30px rgba(0, 0, 0, .3);
|
||||
}
|
||||
.sv-audio.playing { border-color: rgba(129, 140, 248, .75); box-shadow: 0 0 0 1px rgba(129, 140, 248, .25), 0 10px 30px rgba(0, 0, 0, .3); }
|
||||
.sv-root:not(.editable) .sv-audio[data-clickable="1"] { cursor: pointer; }
|
||||
.sv-root:not(.editable) .sv-audio[data-clickable="1"]:hover { background: rgba(30, 41, 59, .8); }
|
||||
.sv-audio-icon {
|
||||
width: 2.1em; height: 2.1em; flex-shrink: 0; border-radius: 50%;
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
background: linear-gradient(135deg, #6366f1, #a855f7); color: #fff; font-size: .95em;
|
||||
}
|
||||
.sv-audio-label { overflow: hidden; text-overflow: ellipsis; }
|
||||
.sv-bars { display: flex; align-items: flex-end; gap: .16em; height: 1.1em; margin-left: auto; }
|
||||
.sv-bars i { width: .2em; background: #a5b4fc; border-radius: 999px; animation: svBar .9s ease-in-out infinite; }
|
||||
.sv-bars i:nth-child(2) { animation-delay: .15s; }
|
||||
.sv-bars i:nth-child(3) { animation-delay: .3s; }
|
||||
.sv-bars i:nth-child(4) { animation-delay: .45s; }
|
||||
@keyframes svBar { 0%, 100% { height: 25%; } 50% { height: 100%; } }
|
||||
.sv-empty {
|
||||
position: absolute; inset: 0; display: flex; align-items: center; justify-content: center;
|
||||
color: rgba(148, 163, 184, .6); font-size: clamp(11px, 2.4cqw, 30px); font-weight: 600;
|
||||
text-align: center; padding: 8%;
|
||||
}
|
||||
/* Переходы между слайдами */
|
||||
.sv-anim-fade { animation: svFade .45s cubic-bezier(.2, .7, .3, 1) both; }
|
||||
.sv-anim-slide { animation: svSlide .5s cubic-bezier(.2, .7, .3, 1) both; }
|
||||
.sv-anim-zoom { animation: svZoom .45s cubic-bezier(.2, .7, .3, 1) both; }
|
||||
@keyframes svFade { from { opacity: 0; } to { opacity: 1; } }
|
||||
@keyframes svSlide { from { opacity: 0; transform: translateX(5%); } to { opacity: 1; transform: none; } }
|
||||
@keyframes svZoom { from { opacity: 0; transform: scale(.94); } to { opacity: 1; transform: none; } }
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
|
||||
function esc(value) {
|
||||
return String(value ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
}
|
||||
|
||||
function interpolate(text, vars) {
|
||||
if (!text) return '';
|
||||
if (!vars) return String(text);
|
||||
return String(text).replace(/\{\{\s*([\w.-]+)\s*\}\}/g, (match, key) => {
|
||||
if (Object.prototype.hasOwnProperty.call(vars, key)) {
|
||||
const value = vars[key];
|
||||
if (value === null || value === undefined) return '';
|
||||
return String(value);
|
||||
}
|
||||
return match;
|
||||
});
|
||||
}
|
||||
|
||||
function backgroundStyle(background) {
|
||||
const bg = background || {};
|
||||
const type = bg.type || (bg.image ? 'image' : bg.gradient ? 'gradient' : 'color');
|
||||
if (type === 'image' && bg.image) {
|
||||
return {
|
||||
backgroundImage: `url("${String(bg.image).replace(/"/g, '%22')}")`,
|
||||
backgroundSize: 'cover',
|
||||
backgroundPosition: 'center',
|
||||
backgroundColor: '#0f172a',
|
||||
};
|
||||
}
|
||||
if (type === 'gradient') {
|
||||
return { background: bg.gradient || DEFAULT_GRADIENT };
|
||||
}
|
||||
return { background: bg.color || '#0f172a' };
|
||||
}
|
||||
|
||||
function styleObjectToString(styles) {
|
||||
return Object.keys(styles)
|
||||
.map((key) => `${key.replace(/[A-Z]/g, (m) => '-' + m.toLowerCase())}:${styles[key]}`)
|
||||
.join(';');
|
||||
}
|
||||
|
||||
function radius(px) {
|
||||
const value = Number(px);
|
||||
if (!Number.isFinite(value) || value <= 0) return '';
|
||||
return `min(${value}px, 2cqw)`;
|
||||
}
|
||||
|
||||
function createTextElement(element, vars) {
|
||||
const node = document.createElement('div');
|
||||
node.className = 'sv-text';
|
||||
const justify = element.align === 'left' ? 'flex-start' : element.align === 'right' ? 'flex-end' : 'center';
|
||||
node.style.justifyContent = justify;
|
||||
node.style.textAlign = element.align || 'center';
|
||||
node.style.fontSize = `${Number(element.fontSize) || 5}cqw`;
|
||||
node.style.fontWeight = String(element.weight || 700);
|
||||
node.style.color = element.color || '#f8fafc';
|
||||
if (element.bg) {
|
||||
node.style.background = element.bg;
|
||||
node.style.borderRadius = 'min(18px, 2cqw)';
|
||||
node.style.padding = '1.4cqw 2cqw';
|
||||
}
|
||||
node.textContent = interpolate(element.text || '', vars);
|
||||
return node;
|
||||
}
|
||||
|
||||
function createImageElement(element, editable) {
|
||||
if (!element.src) {
|
||||
const placeholder = document.createElement('div');
|
||||
placeholder.className = 'sv-image-missing';
|
||||
placeholder.innerHTML = '<b>🖼</b><span>Укажите URL изображения</span>';
|
||||
return placeholder;
|
||||
}
|
||||
const img = document.createElement('img');
|
||||
img.className = 'sv-image';
|
||||
img.src = element.src;
|
||||
img.alt = '';
|
||||
img.draggable = false;
|
||||
img.loading = 'lazy';
|
||||
img.style.objectFit = element.fit === 'contain' ? 'contain' : 'cover';
|
||||
img.style.borderRadius = radius(element.radius);
|
||||
if (editable) img.style.pointerEvents = 'none';
|
||||
return img;
|
||||
}
|
||||
|
||||
function createVideoElement(element, opts) {
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = 'sv-video';
|
||||
wrap.dataset.mediaId = element.id || '';
|
||||
wrap.style.borderRadius = radius(element.radius);
|
||||
|
||||
if (!element.src) {
|
||||
wrap.innerHTML = '<div class="sv-media-missing"><b>🎬</b><span>Добавьте видеофайл или ссылку</span></div>';
|
||||
return wrap;
|
||||
}
|
||||
|
||||
const video = document.createElement('video');
|
||||
video.src = element.src;
|
||||
video.poster = element.poster || '';
|
||||
video.muted = element.muted !== false;
|
||||
video.loop = !!element.loop;
|
||||
const frozen = opts.editable || opts.staticPreview;
|
||||
video.controls = !frozen && element.controls !== false;
|
||||
video.playsInline = true;
|
||||
video.preload = 'metadata';
|
||||
video.dataset.mediaId = element.id || '';
|
||||
video.style.objectFit = element.fit === 'contain' ? 'contain' : 'cover';
|
||||
video.style.borderRadius = radius(element.radius);
|
||||
if (frozen) {
|
||||
video.autoplay = false;
|
||||
video.controls = false;
|
||||
video.style.pointerEvents = 'none';
|
||||
} else {
|
||||
video.autoplay = !!element.autoplay;
|
||||
if (typeof opts.onVideoEvent === 'function') {
|
||||
const fire = (type) => {
|
||||
if (video._applyingRemote) return;
|
||||
opts.onVideoEvent(element, type, video);
|
||||
};
|
||||
video.addEventListener('play', () => fire('play'));
|
||||
video.addEventListener('pause', () => fire('pause'));
|
||||
video.addEventListener('seeked', () => fire('seek'));
|
||||
video.addEventListener('ended', () => fire('ended'));
|
||||
}
|
||||
}
|
||||
wrap.appendChild(video);
|
||||
return wrap;
|
||||
}
|
||||
|
||||
function windowDataUrl(data) {
|
||||
if (!data) return '';
|
||||
if (/^data:/.test(data)) return data;
|
||||
return `data:image/jpeg;base64,${data}`;
|
||||
}
|
||||
|
||||
function createWindowElement(element, opts) {
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = 'sv-window';
|
||||
wrap.dataset.windowId = element.id || '';
|
||||
wrap.style.borderRadius = radius(element.radius);
|
||||
|
||||
const live = !opts.editable && typeof opts.onWindowInput === 'function';
|
||||
const frameData = opts.windowFrames && opts.windowFrames[element.id];
|
||||
const img = document.createElement('img');
|
||||
img.className = 'sv-window-frame';
|
||||
img.alt = '';
|
||||
img.draggable = false;
|
||||
if (frameData) {
|
||||
img.src = windowDataUrl(frameData);
|
||||
if (live) {
|
||||
wrap.dataset.live = '1';
|
||||
const badge = document.createElement('span');
|
||||
badge.className = 'sv-window-live';
|
||||
badge.innerHTML = '<i></i>LIVE';
|
||||
wrap.appendChild(badge);
|
||||
}
|
||||
} else {
|
||||
const placeholder = document.createElement('div');
|
||||
placeholder.className = 'sv-window-placeholder';
|
||||
placeholder.innerHTML = `<b>🖥</b><span></span>`;
|
||||
placeholder.querySelector('span').textContent = opts.editable
|
||||
? (element.targetTitle || 'Окно Chrome — выберите цель в инспекторе')
|
||||
: 'Трансляция не запущена';
|
||||
wrap.appendChild(placeholder);
|
||||
}
|
||||
wrap.insertBefore(img, wrap.firstChild);
|
||||
|
||||
if (live) {
|
||||
const normalize = (event) => {
|
||||
const rect = wrap.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)),
|
||||
};
|
||||
};
|
||||
let lastMove = 0;
|
||||
wrap.addEventListener('click', (event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const point = normalize(event);
|
||||
if (point) opts.onWindowInput(element, { kind: 'click', ...point });
|
||||
});
|
||||
wrap.addEventListener('pointermove', (event) => {
|
||||
const now = Date.now();
|
||||
if (now - lastMove < 120) return;
|
||||
lastMove = now;
|
||||
const point = normalize(event);
|
||||
if (point) opts.onWindowInput(element, { kind: 'move', ...point });
|
||||
});
|
||||
wrap.addEventListener(
|
||||
'wheel',
|
||||
(event) => {
|
||||
event.preventDefault();
|
||||
const point = normalize(event);
|
||||
if (point) {
|
||||
opts.onWindowInput(element, {
|
||||
kind: 'wheel',
|
||||
...point,
|
||||
deltaX: event.deltaX,
|
||||
deltaY: event.deltaY,
|
||||
});
|
||||
}
|
||||
},
|
||||
{ passive: false }
|
||||
);
|
||||
}
|
||||
return wrap;
|
||||
}
|
||||
|
||||
function createButtonElement(element, vars, opts) {
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'sv-button';
|
||||
button.style.background = element.bg || '#6366f1';
|
||||
button.style.color = element.color || '#ffffff';
|
||||
button.style.fontSize = `${Number(element.fontSize) || 2.2}cqw`;
|
||||
button.style.borderRadius = radius(element.radius);
|
||||
button.textContent = interpolate(element.label || '', vars);
|
||||
if (!opts.editable) {
|
||||
button.addEventListener('click', (event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (typeof opts.onAction === 'function' && element.action) opts.onAction(element.action, element);
|
||||
});
|
||||
}
|
||||
return button;
|
||||
}
|
||||
|
||||
function createAudioElement(element, opts) {
|
||||
const playing = typeof opts.isAudioPlaying === 'function' ? !!opts.isAudioPlaying(element.id) : false;
|
||||
const node = document.createElement('div');
|
||||
node.className = 'sv-audio' + (playing ? ' playing' : '');
|
||||
const canClick = !opts.editable && typeof opts.onAction === 'function';
|
||||
if (canClick) {
|
||||
node.dataset.clickable = '1';
|
||||
node.addEventListener('click', (event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
opts.onAction(playing ? { type: 'stop', audioId: element.id } : { type: 'play', audioId: element.id }, element);
|
||||
});
|
||||
}
|
||||
|
||||
const icon = document.createElement('span');
|
||||
icon.className = 'sv-audio-icon';
|
||||
icon.textContent = playing ? '⏸' : '▶';
|
||||
const label = document.createElement('span');
|
||||
label.className = 'sv-audio-label';
|
||||
label.textContent = interpolate(element.label || 'Аудио', opts.variables);
|
||||
node.appendChild(icon);
|
||||
node.appendChild(label);
|
||||
|
||||
if (playing) {
|
||||
const bars = document.createElement('span');
|
||||
bars.className = 'sv-bars';
|
||||
for (let i = 0; i < 4; i += 1) bars.appendChild(document.createElement('i'));
|
||||
node.appendChild(bars);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
function applyPosition(node, element) {
|
||||
node.style.left = `${Number(element.x) || 0}%`;
|
||||
node.style.top = `${Number(element.y) || 0}%`;
|
||||
node.style.width = `${Number(element.w) || 10}%`;
|
||||
node.style.height = `${Number(element.h) || 10}%`;
|
||||
node.style.zIndex = String(Number(element.z) || 1);
|
||||
}
|
||||
|
||||
function render(container, slide, options = {}) {
|
||||
if (!container) return { nodes: new Map() };
|
||||
const opts = Object.assign({ variables: {}, editable: false }, options);
|
||||
const root = document.createElement('div');
|
||||
root.className = 'sv-root' + (opts.editable ? ' editable' : '');
|
||||
const bgStyle = backgroundStyle(slide && slide.background);
|
||||
root.setAttribute('style', styleObjectToString(bgStyle));
|
||||
|
||||
if (container._svRoot && container._svRoot.parentNode === container) {
|
||||
container.removeChild(container._svRoot);
|
||||
}
|
||||
if (container._svRoot) container._svRoot.remove();
|
||||
container._svRoot = root;
|
||||
container.appendChild(root);
|
||||
|
||||
const elements = slide && Array.isArray(slide.elements) ? slide.elements : [];
|
||||
const nodes = new Map();
|
||||
const sorted = [...elements].sort((a, b) => (Number(a.z) || 0) - (Number(b.z) || 0));
|
||||
|
||||
sorted.forEach((element) => {
|
||||
if (!element || !element.type) return;
|
||||
if (element.type === 'audio' && !element.visible) return;
|
||||
|
||||
const node = document.createElement('div');
|
||||
node.className = 'sv-el';
|
||||
node.dataset.el = element.id || '';
|
||||
node.dataset.type = element.type;
|
||||
applyPosition(node, element);
|
||||
if (opts.selectedId && opts.selectedId === element.id) node.classList.add('sv-selected');
|
||||
|
||||
let inner;
|
||||
if (element.type === 'text') inner = createTextElement(element, opts.variables);
|
||||
else if (element.type === 'image') inner = createImageElement(element, opts.editable);
|
||||
else if (element.type === 'button') inner = createButtonElement(element, opts.variables, opts);
|
||||
else if (element.type === 'audio') inner = createAudioElement(element, opts);
|
||||
else if (element.type === 'video') inner = createVideoElement(element, opts);
|
||||
else if (element.type === 'window') inner = createWindowElement(element, opts);
|
||||
else inner = document.createElement('div');
|
||||
|
||||
node.appendChild(inner);
|
||||
nodes.set(element.id, node);
|
||||
root.appendChild(node);
|
||||
});
|
||||
|
||||
if (!elements.length && opts.placeholder) {
|
||||
const hint = document.createElement('div');
|
||||
hint.className = 'sv-empty';
|
||||
hint.textContent = opts.placeholder;
|
||||
root.appendChild(hint);
|
||||
}
|
||||
|
||||
if (opts.animate && slide && slide.transition && slide.transition !== 'none') {
|
||||
root.classList.add(`sv-anim-${slide.transition}`);
|
||||
}
|
||||
|
||||
return { root, nodes };
|
||||
}
|
||||
|
||||
window.SlideView = {
|
||||
render,
|
||||
interpolate,
|
||||
backgroundStyle,
|
||||
DEFAULT_GRADIENT,
|
||||
};
|
||||
})();
|
||||
Binary file not shown.
Vendored
+8
@@ -0,0 +1,8 @@
|
||||
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.fengari=e():t.fengari=e()}(window,function(){return function(t){var e={};function r(n){if(e[n])return e[n].exports;var a=e[n]={i:n,l:!1,exports:{}};return t[n].call(a.exports,a,a.exports,r),a.l=!0,a.exports}return r.m=t,r.c=e,r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var a in t)r.d(n,a,function(e){return t[e]}.bind(null,a));return n},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=34)}([function(t,e,r){"use strict";
|
||||
/**
|
||||
@license MIT
|
||||
|
||||
Copyright © 2017-2018 Benoit Giannangeli
|
||||
Copyright © 2017-2018 Daurnimator
|
||||
Copyright © 1994–2017 Lua.org, PUC-Rio.
|
||||
*/var n=r(5);t.exports.FENGARI_AUTHORS=n.FENGARI_AUTHORS,t.exports.FENGARI_COPYRIGHT=n.FENGARI_COPYRIGHT,t.exports.FENGARI_RELEASE=n.FENGARI_RELEASE,t.exports.FENGARI_VERSION=n.FENGARI_VERSION,t.exports.FENGARI_VERSION_MAJOR=n.FENGARI_VERSION_MAJOR,t.exports.FENGARI_VERSION_MINOR=n.FENGARI_VERSION_MINOR,t.exports.FENGARI_VERSION_NUM=n.FENGARI_VERSION_NUM,t.exports.FENGARI_VERSION_RELEASE=n.FENGARI_VERSION_RELEASE,t.exports.luastring_eq=n.luastring_eq,t.exports.luastring_indexOf=n.luastring_indexOf,t.exports.luastring_of=n.luastring_of,t.exports.to_jsstring=n.to_jsstring,t.exports.to_luastring=n.to_luastring,t.exports.to_uristring=n.to_uristring;var a=r(3),u=r(2),s=r(7),o=r(17);t.exports.luaconf=a,t.exports.lua=u,t.exports.lauxlib=s,t.exports.lualib=o},function(t,e,r){"use strict";var n,a,u;if(n="function"==typeof Uint8Array.from?Uint8Array.from.bind(Uint8Array):function(t){for(var e=0,r=t.length,n=new Uint8Array(r);r>e;)n[e]=t[e++];return n},"function"==typeof(new Uint8Array).indexOf)a=function(t,e,r){return t.indexOf(e,r)};else{var s=[].indexOf;if(0!==s.call(new Uint8Array(1),0))throw Error("missing .indexOf");a=function(t,e,r){return s.call(t,e,r)}}u="function"==typeof Uint8Array.of?Uint8Array.of.bind(Uint8Array):function(){return n(arguments)};var o=function(t){return t instanceof Uint8Array},l="cannot convert invalid utf8 to javascript string",i=";,/?:@&=+$abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,-_.!~*'()#".split("").reduce(function(t,e){return t[e.charCodeAt(0)]=!0,t},{}),c={},f=function(t,e){if("string"!=typeof t)throw new TypeError("to_luastring expects a javascript string");if(e){var r=c[t];if(o(r))return r}for(var a=t.length,u=Array(a),s=0,l=0;l<a;++l){var i=t.charCodeAt(l);if(i<=127)u[s++]=i;else if(i<=2047)u[s++]=192|i>>6,u[s++]=128|63&i;else{if(i>=55296&&i<=56319&&l+1<a){var f=t.charCodeAt(l+1);f>=56320&&f<=57343&&(l++,i=1024*(i-55296)+f+9216)}i<=65535?(u[s++]=224|i>>12,u[s++]=128|i>>6&63,u[s++]=128|63&i):(u[s++]=240|i>>18,u[s++]=128|i>>12&63,u[s++]=128|i>>6&63,u[s++]=128|63&i)}}return u=n(u),e&&(c[t]=u),u};t.exports.luastring_from=n,t.exports.luastring_indexOf=a,t.exports.luastring_of=u,t.exports.is_luastring=o,t.exports.luastring_eq=function(t,e){if(t!==e){var r=t.length;if(r!==e.length)return!1;for(var n=0;n<r;n++)if(t[n]!==e[n])return!1}return!0},t.exports.to_jsstring=function(t,e,r,n){if(!o(t))throw new TypeError("to_jsstring expects a Uint8Array");r=void 0===r?t.length:Math.min(t.length,r);for(var a="",u=void 0!==e?e:0;u<r;){var s=t[u++];if(s<128)a+=String.fromCharCode(s);else if(s<194||s>244){if(!n)throw RangeError(l);a+="�"}else if(s<=223){if(u>=r){if(!n)throw RangeError(l);a+="�";continue}var i=t[u++];if(128!=(192&i)){if(!n)throw RangeError(l);a+="�";continue}a+=String.fromCharCode(((31&s)<<6)+(63&i))}else if(s<=239){if(u+1>=r){if(!n)throw RangeError(l);a+="�";continue}var c=t[u++];if(128!=(192&c)){if(!n)throw RangeError(l);a+="�";continue}var f=t[u++];if(128!=(192&f)){if(!n)throw RangeError(l);a+="�";continue}var _=((15&s)<<12)+((63&c)<<6)+(63&f);if(_<=65535)a+=String.fromCharCode(_);else{var p=55296+((_-=65536)>>10),v=_%1024+56320;a+=String.fromCharCode(p,v)}}else{if(u+2>=r){if(!n)throw RangeError(l);a+="�";continue}var h=t[u++];if(128!=(192&h)){if(!n)throw RangeError(l);a+="�";continue}var L=t[u++];if(128!=(192&L)){if(!n)throw RangeError(l);a+="�";continue}var d=t[u++];if(128!=(192&d)){if(!n)throw RangeError(l);a+="�";continue}var A=((7&s)<<18)+((63&h)<<12)+((63&L)<<6)+(63&d),g=55296+((A-=65536)>>10),T=A%1024+56320;a+=String.fromCharCode(g,T)}}return a},t.exports.to_uristring=function(t){if(!o(t))throw new TypeError("to_uristring expects a Uint8Array");for(var e="",r=0;r<t.length;r++){var n=t[r];i[n]?e+=String.fromCharCode(n):e+="%"+(n<16?"0":"")+n.toString(16)}return e},t.exports.to_luastring=f,t.exports.from_userstring=function(t){if(!o(t)){if("string"!=typeof t)throw new TypeError("expects an array of bytes or javascript string");t=f(t)}return t};var _=f("Lua");t.exports.LUA_SIGNATURE=_,t.exports.LUA_VERSION_MAJOR="5",t.exports.LUA_VERSION_MINOR="3",t.exports.LUA_VERSION_NUM=503,t.exports.LUA_VERSION_RELEASE="4",t.exports.LUA_VERSION="Lua 5.3",t.exports.LUA_RELEASE="Lua 5.3.4",t.exports.LUA_COPYRIGHT="Lua 5.3.4 Copyright (C) 1994-2017 Lua.org, PUC-Rio",t.exports.LUA_AUTHORS="R. Ierusalimschy, L. H. de Figueiredo, W. Celes";var p={LUA_TNONE:-1,LUA_TNIL:0,LUA_TBOOLEAN:1,LUA_TLIGHTUSERDATA:2,LUA_TNUMBER:3,LUA_TSTRING:4,LUA_TTABLE:5,LUA_TFUNCTION:6,LUA_TUSERDATA:7,LUA_TTHREAD:8,LUA_NUMTAGS:9};p.LUA_TSHRSTR=0|p.LUA_TSTRING,p.LUA_TLNGSTR=16|p.LUA_TSTRING,p.LUA_TNUMFLT=0|p.LUA_TNUMBER,p.LUA_TNUMINT=16|p.LUA_TNUMBER,p.LUA_TLCL=0|p.LUA_TFUNCTION,p.LUA_TLCF=16|p.LUA_TFUNCTION,p.LUA_TCCL=32|p.LUA_TFUNCTION;var v=-r(3).LUAI_MAXSTACK-1e3;t.exports.LUA_HOOKCALL=0,t.exports.LUA_HOOKCOUNT=3,t.exports.LUA_HOOKLINE=2,t.exports.LUA_HOOKRET=1,t.exports.LUA_HOOKTAILCALL=4,t.exports.LUA_MASKCALL=1,t.exports.LUA_MASKCOUNT=8,t.exports.LUA_MASKLINE=4,t.exportsLine truncated
|
||||
+1518
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,19 @@
|
||||
const express = require('express');
|
||||
const http = require('http');
|
||||
const { setupWebSocket } = require('./server/ws');
|
||||
const apiRouter = require('./server/routes');
|
||||
|
||||
const app = express();
|
||||
app.use(express.json({ limit: '10mb' }));
|
||||
app.use('/api', apiRouter);
|
||||
|
||||
app.use(express.static(require('path').join(__dirname, 'public')));
|
||||
|
||||
const server = http.createServer(app);
|
||||
setupWebSocket(server);
|
||||
|
||||
const PORT = process.env.PORT || 3045;
|
||||
|
||||
server.listen(PORT, () => {
|
||||
console.log(`Server listening on http://localhost:${PORT}`);
|
||||
});
|
||||
+302
@@ -0,0 +1,302 @@
|
||||
// Трансляция и управление окном Chrome/Chromium/Electron через DevTools Protocol.
|
||||
// Браузер не может кликать по произвольным окнам ОС, но Chrome с --remote-debugging-port
|
||||
// отдаёт скринкаст страницы и принимает синтетические клики/клавиши.
|
||||
const WebSocket = require('ws');
|
||||
|
||||
const ENDPOINT = (process.env.CHROME_DEBUG_URL || 'http://127.0.0.1:9222').replace(/\/+$/, '');
|
||||
const sessions = new Map(); // key `${presentationId}::${elementId}` -> session
|
||||
|
||||
let targetsCache = { at: 0, targets: [] };
|
||||
|
||||
const clamp01 = (value, fallback = 0) => {
|
||||
const n = Number(value);
|
||||
if (!Number.isFinite(n)) return fallback;
|
||||
return Math.max(0, Math.min(1, n));
|
||||
};
|
||||
|
||||
async function listTargets(force = false) {
|
||||
if (!force && Date.now() - targetsCache.at < 1200) return targetsCache.targets;
|
||||
try {
|
||||
const response = await fetch(`${ENDPOINT}/json/list`, { signal: AbortSignal.timeout(2500) });
|
||||
if (!response.ok) throw new Error(`CDP HTTP ${response.status}`);
|
||||
const list = await response.json();
|
||||
const targets = list
|
||||
.filter((item) => item.type === 'page' && item.webSocketDebuggerUrl)
|
||||
.map((item) => ({
|
||||
id: item.id,
|
||||
title: item.title || 'Без названия',
|
||||
url: item.url || '',
|
||||
webSocketDebuggerUrl: item.webSocketDebuggerUrl,
|
||||
}));
|
||||
targetsCache = { at: Date.now(), targets };
|
||||
return targets;
|
||||
} catch (error) {
|
||||
targetsCache = { at: Date.now(), targets: [] };
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async function findTarget(targetId) {
|
||||
const targets = await listTargets(true);
|
||||
if (!targets.length) return null;
|
||||
return targets.find((item) => item.id === targetId) || targets[0];
|
||||
}
|
||||
|
||||
function createSession(key, presentationId, elementId, target, handlers) {
|
||||
const socket = new WebSocket(target.webSocketDebuggerUrl);
|
||||
let seq = 0;
|
||||
let closed = false;
|
||||
let viewport = { width: 1280, height: 720 };
|
||||
const pending = new Map();
|
||||
|
||||
const session = {
|
||||
key,
|
||||
presentationId,
|
||||
elementId,
|
||||
target,
|
||||
socket,
|
||||
get viewport() {
|
||||
return viewport;
|
||||
},
|
||||
async send(method, params = {}) {
|
||||
if (closed || socket.readyState !== WebSocket.OPEN) {
|
||||
throw new Error('Окно не подключено');
|
||||
}
|
||||
seq += 1;
|
||||
const id = seq;
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
pending.delete(id);
|
||||
reject(new Error(`CDP timeout: ${method}`));
|
||||
}, 8000);
|
||||
pending.set(id, { resolve, reject, timer });
|
||||
socket.send(JSON.stringify({ id, method, params }));
|
||||
});
|
||||
},
|
||||
async refreshMetrics() {
|
||||
try {
|
||||
const metrics = await session.send('Page.getLayoutMetrics');
|
||||
const view = metrics.cssLayoutViewport || metrics.layoutViewport || {};
|
||||
if (view.clientWidth && view.clientHeight) {
|
||||
viewport = { width: view.clientWidth, height: view.clientHeight };
|
||||
}
|
||||
} catch (error) {
|
||||
/* оставляем прошлые размеры */
|
||||
}
|
||||
},
|
||||
async input(event) {
|
||||
if (!event || typeof event !== 'object') return;
|
||||
const x = clamp01(event.x, 0.5) * viewport.width;
|
||||
const y = clamp01(event.y, 0.5) * viewport.height;
|
||||
const kind = event.kind;
|
||||
|
||||
if (kind === 'move') {
|
||||
await session.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x, y, button: 'none' });
|
||||
return;
|
||||
}
|
||||
if (kind === 'click') {
|
||||
await session.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x, y, button: 'none' });
|
||||
await session.send('Input.dispatchMouseEvent', {
|
||||
type: 'mousePressed', x, y, button: 'left', buttons: 1, clickCount: 1,
|
||||
});
|
||||
await session.send('Input.dispatchMouseEvent', {
|
||||
type: 'mouseReleased', x, y, button: 'left', buttons: 0, clickCount: 1,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (kind === 'wheel') {
|
||||
await session.send('Input.dispatchMouseEvent', {
|
||||
type: 'mouseWheel', x, y, deltaX: Number(event.deltaX) || 0, deltaY: Number(event.deltaY) || 0,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (kind === 'text') {
|
||||
const text = String(event.text || '');
|
||||
if (text) await session.send('Input.insertText', { text });
|
||||
return;
|
||||
}
|
||||
if (kind === 'key') {
|
||||
const key = String(event.key || '');
|
||||
const map = {
|
||||
Enter: { code: 'Enter', keyCode: 13, text: '\r' },
|
||||
Backspace: { code: 'Backspace', keyCode: 8 },
|
||||
Tab: { code: 'Tab', keyCode: 9 },
|
||||
Escape: { code: 'Escape', keyCode: 27 },
|
||||
Delete: { code: 'Delete', keyCode: 46 },
|
||||
ArrowLeft: { code: 'ArrowLeft', keyCode: 37 },
|
||||
ArrowUp: { code: 'ArrowUp', keyCode: 38 },
|
||||
ArrowRight: { code: 'ArrowRight', keyCode: 39 },
|
||||
ArrowDown: { code: 'ArrowDown', keyCode: 40 },
|
||||
Home: { code: 'Home', keyCode: 36 },
|
||||
End: { code: 'End', keyCode: 35 },
|
||||
PageUp: { code: 'PageUp', keyCode: 33 },
|
||||
PageDown: { code: 'PageDown', keyCode: 34 },
|
||||
' ': { code: 'Space', keyCode: 32, text: ' ' },
|
||||
};
|
||||
const info = map[key];
|
||||
if (info) {
|
||||
await session.send('Input.dispatchKeyEvent', {
|
||||
type: 'keyDown',
|
||||
key,
|
||||
code: info.code,
|
||||
windowsVirtualKeyCode: info.keyCode,
|
||||
nativeVirtualKeyCode: info.keyCode,
|
||||
text: info.text,
|
||||
});
|
||||
await session.send('Input.dispatchKeyEvent', {
|
||||
type: 'keyUp',
|
||||
key,
|
||||
code: info.code,
|
||||
windowsVirtualKeyCode: info.keyCode,
|
||||
nativeVirtualKeyCode: info.keyCode,
|
||||
});
|
||||
} else if (key.length === 1) {
|
||||
await session.send('Input.insertText', { text: key });
|
||||
}
|
||||
}
|
||||
},
|
||||
close() {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
pending.forEach(({ reject, timer }) => {
|
||||
clearTimeout(timer);
|
||||
reject(new Error('Окно отключено'));
|
||||
});
|
||||
pending.clear();
|
||||
try {
|
||||
socket.close();
|
||||
} catch (error) {
|
||||
/* noop */
|
||||
}
|
||||
handlers.onClose && handlers.onClose();
|
||||
},
|
||||
};
|
||||
|
||||
socket.on('message', (raw) => {
|
||||
let message;
|
||||
try {
|
||||
message = JSON.parse(raw.toString());
|
||||
} catch (error) {
|
||||
return;
|
||||
}
|
||||
if (message.id && pending.has(message.id)) {
|
||||
const entry = pending.get(message.id);
|
||||
pending.delete(message.id);
|
||||
clearTimeout(entry.timer);
|
||||
if (message.error) entry.reject(new Error(message.error.message || 'CDP error'));
|
||||
else entry.resolve(message.result);
|
||||
return;
|
||||
}
|
||||
if (message.method === 'Page.screencastFrame') {
|
||||
const { data, metadata, sessionId } = message.params || {};
|
||||
if (sessionId !== undefined) {
|
||||
session.send('Page.screencastFrameAck', { sessionId }).catch(() => {});
|
||||
}
|
||||
if (data) handlers.onFrame && handlers.onFrame({ data, metadata: metadata || {} });
|
||||
return;
|
||||
}
|
||||
if (message.method === 'Page.frameNavigated') {
|
||||
session.refreshMetrics();
|
||||
}
|
||||
});
|
||||
|
||||
socket.on('error', (error) => {
|
||||
if (handlers.onError) handlers.onError(error);
|
||||
});
|
||||
|
||||
socket.on('close', () => {
|
||||
session.close();
|
||||
});
|
||||
|
||||
const ready = new Promise((resolve, reject) => {
|
||||
socket.on('open', resolve);
|
||||
socket.on('error', reject);
|
||||
});
|
||||
|
||||
ready
|
||||
.then(async () => {
|
||||
await session.send('Page.enable');
|
||||
try {
|
||||
await session.send('Page.bringToFront');
|
||||
} catch (error) {
|
||||
/* фоновая вкладка может не поддерживать bringToFront */
|
||||
}
|
||||
await session.refreshMetrics();
|
||||
await session.send('Page.startScreencast', {
|
||||
format: 'jpeg',
|
||||
quality: 58,
|
||||
maxWidth: 1280,
|
||||
maxHeight: 720,
|
||||
everyNthFrame: 2,
|
||||
});
|
||||
handlers.onStart && handlers.onStart({ target, viewport });
|
||||
// Скринкаст присылает кадр только при перерисовке. Делаем стартовый
|
||||
// снимок, чтобы зрители сразу увидели окно, даже если страница статична.
|
||||
try {
|
||||
const shot = await session.send('Page.captureScreenshot', {
|
||||
format: 'jpeg',
|
||||
quality: 58,
|
||||
fromSurface: true,
|
||||
});
|
||||
if (shot && shot.data) {
|
||||
handlers.onFrame && handlers.onFrame({ data: shot.data, metadata: { initial: true } });
|
||||
}
|
||||
} catch (error) {
|
||||
/* снимок не критичен */
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
if (handlers.onError) handlers.onError(error);
|
||||
session.close();
|
||||
});
|
||||
|
||||
return session;
|
||||
}
|
||||
|
||||
async function start(key, presentationId, elementId, targetId, handlers = {}) {
|
||||
stop(key);
|
||||
const target = await findTarget(targetId);
|
||||
if (!target) {
|
||||
throw new Error(
|
||||
`Chrome не найден на ${ENDPOINT}. Запустите окно с --remote-debugging-port=9222`
|
||||
);
|
||||
}
|
||||
const session = createSession(key, presentationId, elementId, target, handlers);
|
||||
sessions.set(key, session);
|
||||
return session;
|
||||
}
|
||||
|
||||
function stop(key) {
|
||||
const session = sessions.get(key);
|
||||
if (!session) return false;
|
||||
sessions.delete(key);
|
||||
session.close();
|
||||
return true;
|
||||
}
|
||||
|
||||
function stopPresentation(presentationId) {
|
||||
const prefix = `${presentationId}::`;
|
||||
for (const key of [...sessions.keys()]) {
|
||||
if (key.startsWith(prefix)) stop(key);
|
||||
}
|
||||
}
|
||||
|
||||
function get(key) {
|
||||
return sessions.get(key) || null;
|
||||
}
|
||||
|
||||
async function input(key, event) {
|
||||
const session = sessions.get(key);
|
||||
if (!session) throw new Error('Трансляция окна не запущена');
|
||||
return session.input(event);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
ENDPOINT,
|
||||
listTargets,
|
||||
start,
|
||||
stop,
|
||||
stopPresentation,
|
||||
get,
|
||||
input,
|
||||
};
|
||||
+266
@@ -0,0 +1,266 @@
|
||||
// Хаб реального времени: глобальные клиенты, комнаты, сессии, переменные и аудио-состояние
|
||||
const store = require('./store');
|
||||
const cdp = require('./cdp');
|
||||
|
||||
const clients = new Set();
|
||||
const rooms = new Map(); // presentationId -> Set<ws>
|
||||
const clientRooms = new WeakMap();
|
||||
const clientRoles = new WeakMap();
|
||||
const startedAt = new Map();
|
||||
const roomVars = new Map(); // presentationId -> переменные сессии
|
||||
const audioState = new Map(); // presentationId -> музыка/громкости
|
||||
const mediaState = new Map(); // presentationId -> Map<elementId, media command>
|
||||
const windowState = new Map(); // presentationId -> Map<elementId, состояние окна>
|
||||
const windowFrames = new Map(); // presentationId -> Map<elementId, последний кадр>
|
||||
|
||||
const clamp01 = (v, d = 0) => Math.max(0, Math.min(1, Number.isFinite(Number(v)) ? Number(v) : d));
|
||||
|
||||
function send(ws, payload) {
|
||||
if (ws.readyState === 1) ws.send(JSON.stringify(payload));
|
||||
}
|
||||
|
||||
function broadcastAll(payload) {
|
||||
const data = JSON.stringify(payload);
|
||||
clients.forEach((ws) => {
|
||||
if (ws.readyState === 1) ws.send(data);
|
||||
});
|
||||
}
|
||||
|
||||
function presentationsSnapshot() {
|
||||
return { type: 'presentations', presentations: store.listPresentations() };
|
||||
}
|
||||
|
||||
function sessionsSnapshot() {
|
||||
const sessions = [];
|
||||
for (const [presentationId, room] of rooms) {
|
||||
if (room.size === 0) continue;
|
||||
const p = store.getPresentation(presentationId);
|
||||
let viewers = 0;
|
||||
let presenters = 0;
|
||||
room.forEach((client) => {
|
||||
if (clientRoles.get(client) === 'speaker') presenters += 1;
|
||||
else viewers += 1;
|
||||
});
|
||||
sessions.push({
|
||||
presentationId,
|
||||
title: p ? p.title : 'Без названия',
|
||||
currentSlide: p ? p.currentSlide : 0,
|
||||
slidesCount: p ? p.slides.length : 0,
|
||||
viewers,
|
||||
presenters,
|
||||
startedAt: startedAt.get(presentationId) || Date.now(),
|
||||
});
|
||||
}
|
||||
return { type: 'sessions', sessions };
|
||||
}
|
||||
|
||||
function broadcastPresentations() {
|
||||
broadcastAll(presentationsSnapshot());
|
||||
}
|
||||
|
||||
function broadcastSessions() {
|
||||
broadcastAll(sessionsSnapshot());
|
||||
}
|
||||
|
||||
function registerClient(ws) {
|
||||
clients.add(ws);
|
||||
send(ws, presentationsSnapshot());
|
||||
send(ws, sessionsSnapshot());
|
||||
}
|
||||
|
||||
function cleanupRoom(presentationId) {
|
||||
rooms.delete(presentationId);
|
||||
startedAt.delete(presentationId);
|
||||
roomVars.delete(presentationId);
|
||||
audioState.delete(presentationId);
|
||||
mediaState.delete(presentationId);
|
||||
windowState.delete(presentationId);
|
||||
windowFrames.delete(presentationId);
|
||||
cdp.stopPresentation(presentationId);
|
||||
}
|
||||
|
||||
function unregisterClient(ws) {
|
||||
clients.delete(ws);
|
||||
const presentationId = clientRooms.get(ws);
|
||||
if (!presentationId) return;
|
||||
clientRooms.delete(ws);
|
||||
clientRoles.delete(ws);
|
||||
|
||||
const room = rooms.get(presentationId);
|
||||
if (!room) return;
|
||||
room.delete(ws);
|
||||
if (room.size === 0) cleanupRoom(presentationId);
|
||||
broadcastSessions();
|
||||
}
|
||||
|
||||
function joinRoom(presentationId, ws, role = 'audience') {
|
||||
if (!rooms.has(presentationId)) {
|
||||
rooms.set(presentationId, new Set());
|
||||
startedAt.set(presentationId, Date.now());
|
||||
}
|
||||
rooms.get(presentationId).add(ws);
|
||||
clientRooms.set(ws, presentationId);
|
||||
clientRoles.set(ws, role === 'speaker' ? 'speaker' : 'audience');
|
||||
broadcastSessions();
|
||||
}
|
||||
|
||||
function broadcastRoom(presentationId, payload, exclude = null) {
|
||||
const room = rooms.get(presentationId);
|
||||
if (!room) return;
|
||||
const data = JSON.stringify(payload);
|
||||
room.forEach((ws) => {
|
||||
if (ws !== exclude && ws.readyState === 1) ws.send(data);
|
||||
});
|
||||
}
|
||||
|
||||
function endSession(presentationId, reason = 'stopped') {
|
||||
const room = rooms.get(presentationId);
|
||||
if (!room) return false;
|
||||
const payload = JSON.stringify({ type: 'session-ended', reason });
|
||||
room.forEach((ws) => {
|
||||
if (ws.readyState === 1) ws.send(payload);
|
||||
clientRooms.delete(ws);
|
||||
clientRoles.delete(ws);
|
||||
});
|
||||
cleanupRoom(presentationId);
|
||||
broadcastSessions();
|
||||
return true;
|
||||
}
|
||||
|
||||
function listSessions() {
|
||||
return sessionsSnapshot().sessions;
|
||||
}
|
||||
|
||||
// ---- Переменные сессии ----
|
||||
|
||||
function setRoomVars(presentationId, vars) {
|
||||
if (vars && typeof vars === 'object') roomVars.set(presentationId, vars);
|
||||
}
|
||||
|
||||
function getRoomVars(presentationId) {
|
||||
return roomVars.get(presentationId) || null;
|
||||
}
|
||||
|
||||
// ---- Аудио-состояние сессии ----
|
||||
|
||||
const DEFAULT_AUDIO = { musicSrc: '', musicPlaying: false, bgm: 0.5, sfx: 0.8 };
|
||||
|
||||
function getAudioState(presentationId) {
|
||||
return audioState.get(presentationId) || { ...DEFAULT_AUDIO };
|
||||
}
|
||||
|
||||
function hasAudioState(presentationId) {
|
||||
return audioState.has(presentationId);
|
||||
}
|
||||
|
||||
// ---- Медиа (видео на слайде) ----
|
||||
|
||||
function applyMediaCommand(presentationId, command) {
|
||||
if (!command || typeof command !== 'object' || !command.elementId) return;
|
||||
const map = mediaState.get(presentationId) || new Map();
|
||||
map.set(command.elementId, { ...command, at: Date.now() });
|
||||
mediaState.set(presentationId, map);
|
||||
}
|
||||
|
||||
function getMediaStates(presentationId) {
|
||||
const map = mediaState.get(presentationId);
|
||||
return map ? [...map.values()] : [];
|
||||
}
|
||||
|
||||
// ---- Трансляция окна Chrome ----
|
||||
|
||||
function setWindowState(presentationId, elementId, patch = {}) {
|
||||
const map = windowState.get(presentationId) || new Map();
|
||||
const current = map.get(elementId) || {
|
||||
elementId,
|
||||
active: false,
|
||||
targetId: '',
|
||||
targetTitle: '',
|
||||
error: '',
|
||||
};
|
||||
const next = { ...current, ...patch, elementId };
|
||||
map.set(elementId, next);
|
||||
windowState.set(presentationId, map);
|
||||
return next;
|
||||
}
|
||||
|
||||
function getWindowStates(presentationId) {
|
||||
const map = windowState.get(presentationId);
|
||||
return map ? [...map.values()] : [];
|
||||
}
|
||||
|
||||
function clearWindowState(presentationId, elementId) {
|
||||
const map = windowState.get(presentationId);
|
||||
if (map) {
|
||||
if (elementId) map.delete(elementId);
|
||||
else map.clear();
|
||||
if (!map.size) windowState.delete(presentationId);
|
||||
}
|
||||
const frames = windowFrames.get(presentationId);
|
||||
if (frames) {
|
||||
if (elementId) frames.delete(elementId);
|
||||
else frames.clear();
|
||||
if (!frames.size) windowFrames.delete(presentationId);
|
||||
}
|
||||
}
|
||||
|
||||
// Последний кадр трансляции: нужен зрителям, которые подключились позже,
|
||||
// потому что CDP присылает новый кадр только при изменении страницы.
|
||||
function setWindowFrame(presentationId, elementId, data) {
|
||||
if (!data || typeof data !== 'string') return;
|
||||
const map = windowFrames.get(presentationId) || new Map();
|
||||
map.set(elementId, { data, at: Date.now() });
|
||||
windowFrames.set(presentationId, map);
|
||||
}
|
||||
|
||||
function getWindowFrames(presentationId) {
|
||||
const map = windowFrames.get(presentationId);
|
||||
if (!map) return [];
|
||||
return [...map.entries()].map(([elementId, item]) => ({ elementId, data: item.data, at: item.at }));
|
||||
}
|
||||
|
||||
function applyAudioCommand(presentationId, command) {
|
||||
if (!command || typeof command !== 'object') return;
|
||||
let state = audioState.get(presentationId);
|
||||
if (!state) {
|
||||
const presentation = store.getPresentation(presentationId);
|
||||
const initialVolume = presentation && presentation.music ? presentation.music.volume : DEFAULT_AUDIO.bgm;
|
||||
state = { ...DEFAULT_AUDIO, bgm: clamp01(initialVolume, DEFAULT_AUDIO.bgm) };
|
||||
} else {
|
||||
state = { ...state };
|
||||
}
|
||||
if (command.action === 'music') {
|
||||
if (typeof command.src === 'string') state.musicSrc = command.src;
|
||||
state.musicPlaying = command.play !== false;
|
||||
}
|
||||
if (command.action === 'musicStop') state.musicPlaying = false;
|
||||
if (command.action === 'volumes') {
|
||||
state.bgm = clamp01(command.bgm, state.bgm);
|
||||
state.sfx = clamp01(command.sfx, state.sfx);
|
||||
}
|
||||
audioState.set(presentationId, state);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
registerClient,
|
||||
unregisterClient,
|
||||
joinRoom,
|
||||
broadcastRoom,
|
||||
broadcastAll,
|
||||
broadcastPresentations,
|
||||
broadcastSessions,
|
||||
endSession,
|
||||
listSessions,
|
||||
setRoomVars,
|
||||
getRoomVars,
|
||||
getAudioState,
|
||||
hasAudioState,
|
||||
applyAudioCommand,
|
||||
applyMediaCommand,
|
||||
getMediaStates,
|
||||
setWindowState,
|
||||
getWindowStates,
|
||||
setWindowFrame,
|
||||
getWindowFrames,
|
||||
clearWindowState,
|
||||
};
|
||||
@@ -0,0 +1,152 @@
|
||||
const express = require('express');
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const store = require('./store');
|
||||
const hub = require('./hub');
|
||||
const cdp = require('./cdp');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
const UPLOAD_DIR = path.join(__dirname, '..', 'public', 'uploads');
|
||||
fs.mkdirSync(UPLOAD_DIR, { recursive: true });
|
||||
|
||||
function safeFileName(raw, fallbackExt = '') {
|
||||
const base = String(raw || 'file')
|
||||
.replace(/\\/g, '/')
|
||||
.split('/')
|
||||
.pop();
|
||||
const extMatch = base.match(/\.([a-zA-Z0-9]{1,12})$/);
|
||||
const ext = extMatch ? `.${extMatch[1].toLowerCase()}` : fallbackExt;
|
||||
const stem = base
|
||||
.slice(0, extMatch ? -extMatch[0].length : undefined)
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9._-]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '')
|
||||
.slice(0, 48) || 'file';
|
||||
const suffix = crypto.randomBytes(4).toString('hex');
|
||||
return `${stem}-${Date.now().toString(36)}-${suffix}${ext}`;
|
||||
}
|
||||
|
||||
// ---- Презентации ----
|
||||
|
||||
router.get('/presentations', (req, res) => {
|
||||
res.json({ presentations: store.listPresentations() });
|
||||
});
|
||||
|
||||
router.post('/presentations', (req, res) => {
|
||||
const presentation = store.createPresentation(req.body || {});
|
||||
hub.broadcastPresentations();
|
||||
res.status(201).json(presentation);
|
||||
});
|
||||
|
||||
router.get('/presentations/:id', (req, res) => {
|
||||
const presentation = store.getPresentation(req.params.id);
|
||||
if (!presentation) {
|
||||
return res.status(404).json({ error: 'not_found' });
|
||||
}
|
||||
res.json(presentation);
|
||||
});
|
||||
|
||||
// Дублировать презентацию
|
||||
router.post('/presentations/:id/duplicate', (req, res) => {
|
||||
const source = store.getPresentation(req.params.id);
|
||||
if (!source) {
|
||||
return res.status(404).json({ error: 'not_found' });
|
||||
}
|
||||
const copy = store.createPresentation({
|
||||
title: `${source.title} (копия)`,
|
||||
slides: source.slides,
|
||||
variables: source.variables,
|
||||
music: source.music,
|
||||
lua: source.lua,
|
||||
commands: source.commands,
|
||||
graph: source.graph,
|
||||
});
|
||||
hub.broadcastPresentations();
|
||||
res.status(201).json(copy);
|
||||
});
|
||||
|
||||
router.put('/presentations/:id', (req, res) => {
|
||||
const presentation = store.getPresentation(req.params.id);
|
||||
if (!presentation) {
|
||||
return res.status(404).json({ error: 'not_found' });
|
||||
}
|
||||
const body = req.body || {};
|
||||
if (body.slides !== undefined && !Array.isArray(body.slides)) {
|
||||
return res.status(400).json({ error: 'bad_slides' });
|
||||
}
|
||||
|
||||
const updated = store.updatePresentation(req.params.id, body);
|
||||
|
||||
// Обновляем открытые демонстрации «на лету»
|
||||
hub.broadcastRoom(updated.id, {
|
||||
type: 'sync',
|
||||
presentationId: updated.id,
|
||||
title: updated.title,
|
||||
slides: updated.slides,
|
||||
slideIndex: updated.currentSlide,
|
||||
variables: updated.variables,
|
||||
music: updated.music,
|
||||
lua: updated.lua,
|
||||
commands: updated.commands,
|
||||
graph: updated.graph,
|
||||
});
|
||||
hub.broadcastPresentations();
|
||||
hub.broadcastSessions();
|
||||
res.json(updated);
|
||||
});
|
||||
|
||||
router.delete('/presentations/:id', (req, res) => {
|
||||
hub.endSession(req.params.id, 'deleted');
|
||||
store.deletePresentation(req.params.id);
|
||||
hub.broadcastPresentations();
|
||||
hub.broadcastSessions();
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
// ---- Загрузка медиа ----
|
||||
|
||||
// Файл передаётся сырым телом запроса, чтобы не тянуть multipart-зависимость.
|
||||
router.post(
|
||||
'/uploads',
|
||||
express.raw({ type: () => true, limit: '512mb' }),
|
||||
(req, res) => {
|
||||
if (!req.body || !Buffer.isBuffer(req.body) || !req.body.length) {
|
||||
return res.status(400).json({ error: 'empty_file' });
|
||||
}
|
||||
const original = req.query.name || req.get('x-file-name') || 'file';
|
||||
const fallbackExt = String(req.get('content-type') || '').includes('video') ? '.mp4' : '';
|
||||
const fileName = safeFileName(original, fallbackExt);
|
||||
try {
|
||||
fs.writeFileSync(path.join(UPLOAD_DIR, fileName), req.body);
|
||||
} catch (error) {
|
||||
return res.status(500).json({ error: 'write_failed', message: String(error.message || error) });
|
||||
}
|
||||
const url = `/uploads/${fileName}`;
|
||||
res.status(201).json({ url, name: original, size: req.body.length });
|
||||
}
|
||||
);
|
||||
|
||||
// ---- Окна Chrome для трансляции ----
|
||||
|
||||
router.get('/windows', async (req, res) => {
|
||||
const targets = await cdp.listTargets(true);
|
||||
res.json({
|
||||
endpoint: cdp.ENDPOINT,
|
||||
targets: targets.map(({ id, title, url }) => ({ id, title, url })),
|
||||
});
|
||||
});
|
||||
|
||||
// ---- Сессии демонстраций ----
|
||||
|
||||
router.get('/sessions', (req, res) => {
|
||||
res.json({ sessions: hub.listSessions() });
|
||||
});
|
||||
|
||||
router.delete('/sessions/:presentationId', (req, res) => {
|
||||
const stopped = hub.endSession(req.params.presentationId, 'stopped');
|
||||
res.json({ ok: stopped });
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
+383
@@ -0,0 +1,383 @@
|
||||
// In-memory хранилище презентаций с нормализацией новых интерактивных слайдов
|
||||
const crypto = require('crypto');
|
||||
|
||||
const presentations = new Map();
|
||||
|
||||
const uid = (prefix) => `${prefix}_${crypto.randomUUID()}`;
|
||||
const num = (value, fallback) => (Number.isFinite(Number(value)) ? Number(value) : fallback);
|
||||
const clamp01 = (value, fallback = 0) => Math.max(0, Math.min(1, num(value, fallback)));
|
||||
const str = (value, fallback = '') => (typeof value === 'string' ? value : fallback);
|
||||
const plainObject = (value) => (value && typeof value === 'object' && !Array.isArray(value) ? value : {});
|
||||
|
||||
const DEFAULT_GRADIENT = 'linear-gradient(135deg, #0f172a 0%, #1e1b4b 55%, #312e81 100%)';
|
||||
|
||||
function normalizeBackground(background) {
|
||||
const bg = plainObject(background);
|
||||
const type = ['color', 'gradient', 'image'].includes(bg.type)
|
||||
? bg.type
|
||||
: bg.image
|
||||
? 'image'
|
||||
: bg.gradient
|
||||
? 'gradient'
|
||||
: 'color';
|
||||
return {
|
||||
type,
|
||||
color: str(bg.color, '#0f172a') || '#0f172a',
|
||||
gradient: str(bg.gradient, DEFAULT_GRADIENT) || DEFAULT_GRADIENT,
|
||||
image: str(bg.image, ''),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeAction(action) {
|
||||
const a = plainObject(action);
|
||||
const type = ['none', 'go', 'next', 'prev', 'play', 'stop', 'lua'].includes(a.type) ? a.type : 'next';
|
||||
return {
|
||||
type,
|
||||
slideIndex: Math.max(0, Math.floor(num(a.slideIndex, 0))),
|
||||
audioId: str(a.audioId, ''),
|
||||
code: str(a.code, ''),
|
||||
scriptNodeId: str(a.scriptNodeId, ''),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeElement(element, index) {
|
||||
const el = plainObject(element);
|
||||
const type = ['text', 'image', 'button', 'audio', 'video', 'window'].includes(el.type) ? el.type : 'text';
|
||||
const base = {
|
||||
id: str(el.id, '') || uid('el'),
|
||||
type,
|
||||
x: num(el.x, 10),
|
||||
y: num(el.y, 10),
|
||||
w: num(el.w, 40),
|
||||
h: num(el.h, 15),
|
||||
z: Math.floor(num(el.z, index + 1)),
|
||||
};
|
||||
|
||||
if (type === 'text') {
|
||||
return {
|
||||
...base,
|
||||
text: str(el.text, ''),
|
||||
fontSize: num(el.fontSize, 5),
|
||||
color: str(el.color, '#f8fafc'),
|
||||
weight: Math.floor(num(el.weight, 700)),
|
||||
align: ['left', 'center', 'right'].includes(el.align) ? el.align : 'center',
|
||||
bg: str(el.bg, ''),
|
||||
};
|
||||
}
|
||||
if (type === 'image') {
|
||||
return {
|
||||
...base,
|
||||
src: str(el.src, ''),
|
||||
fit: el.fit === 'contain' ? 'contain' : 'cover',
|
||||
radius: num(el.radius, 14),
|
||||
};
|
||||
}
|
||||
if (type === 'button') {
|
||||
return {
|
||||
...base,
|
||||
label: str(el.label, 'Кнопка'),
|
||||
bg: str(el.bg, '#6366f1'),
|
||||
color: str(el.color, '#ffffff'),
|
||||
fontSize: num(el.fontSize, 2.2),
|
||||
radius: num(el.radius, 12),
|
||||
action: normalizeAction(el.action),
|
||||
};
|
||||
}
|
||||
if (type === 'audio') {
|
||||
return {
|
||||
...base,
|
||||
src: str(el.src, ''),
|
||||
loop: !!el.loop,
|
||||
visible: el.visible !== false,
|
||||
volume: clamp01(el.volume, 0.8),
|
||||
label: str(el.label, 'Аудио'),
|
||||
};
|
||||
}
|
||||
if (type === 'video') {
|
||||
return {
|
||||
...base,
|
||||
src: str(el.src, ''),
|
||||
poster: str(el.poster, ''),
|
||||
fit: el.fit === 'contain' ? 'contain' : 'cover',
|
||||
radius: num(el.radius, 12),
|
||||
autoplay: el.autoplay !== false,
|
||||
loop: !!el.loop,
|
||||
muted: el.muted !== false,
|
||||
controls: el.controls !== false,
|
||||
label: str(el.label, 'Видео'),
|
||||
};
|
||||
}
|
||||
if (type === 'window') {
|
||||
return {
|
||||
...base,
|
||||
targetId: str(el.targetId, ''),
|
||||
targetTitle: str(el.targetTitle, ''),
|
||||
targetUrl: str(el.targetUrl, ''),
|
||||
fit: el.fit === 'contain' ? 'contain' : 'contain',
|
||||
radius: num(el.radius, 12),
|
||||
autoStart: el.autoStart !== false,
|
||||
label: str(el.label, 'Окно Chrome'),
|
||||
};
|
||||
}
|
||||
return {
|
||||
...base,
|
||||
src: str(el.src, ''),
|
||||
loop: !!el.loop,
|
||||
visible: el.visible !== false,
|
||||
volume: clamp01(el.volume, 0.8),
|
||||
label: str(el.label, 'Аудио'),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeSlide(slide, index = 0) {
|
||||
const s = plainObject(slide);
|
||||
let elements = Array.isArray(s.elements) ? s.elements.map(normalizeElement) : [];
|
||||
|
||||
// Совместимость со старым форматом: text + image
|
||||
if (!elements.length) {
|
||||
if (str(s.text).trim()) {
|
||||
elements.push(
|
||||
normalizeElement(
|
||||
{ type: 'text', text: s.text, x: 8, y: 34, w: 84, h: 32, fontSize: 6, align: 'center', color: '#f8fafc' },
|
||||
0
|
||||
)
|
||||
);
|
||||
}
|
||||
if (str(s.image).trim()) {
|
||||
elements.push(
|
||||
normalizeElement({ type: 'image', src: s.image, x: 22, y: 18, w: 56, h: 48, fit: 'contain', z: 0 }, 1)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id: str(s.id, '') || uid('slide'),
|
||||
notes: str(s.notes, ''),
|
||||
transition: ['none', 'fade', 'slide', 'zoom'].includes(s.transition) ? s.transition : 'fade',
|
||||
background: normalizeBackground(s.background),
|
||||
lua: str(s.lua, ''),
|
||||
elements,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeVariables(variables) {
|
||||
const result = {};
|
||||
for (const [key, value] of Object.entries(plainObject(variables))) {
|
||||
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
|
||||
result[key] = value;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function defaultNodePosition(index) {
|
||||
return { x: 340 + (index % 4) * 320, y: 60 + Math.floor(index / 4) * 300 };
|
||||
}
|
||||
|
||||
function normalizeGraph(graph, slides) {
|
||||
const g = plainObject(graph);
|
||||
const sourcePositions = plainObject(g.positions);
|
||||
const positions = {};
|
||||
slides.forEach((slide, index) => {
|
||||
const p = plainObject(sourcePositions[slide.id]);
|
||||
const fallback = defaultNodePosition(index);
|
||||
positions[slide.id] = { x: num(p.x, fallback.x), y: num(p.y, fallback.y) };
|
||||
});
|
||||
const scripts = (Array.isArray(g.scripts) ? g.scripts : []).map((node, index) => {
|
||||
const n = plainObject(node);
|
||||
return {
|
||||
id: str(n.id, '') || uid('script'),
|
||||
name: str(n.name, 'Скрипт') || 'Скрипт',
|
||||
code: str(n.code, ''),
|
||||
x: num(n.x, 60 + (index % 3) * 320),
|
||||
y: num(n.y, 520 + Math.floor(index / 3) * 220),
|
||||
slideId: str(n.slideId, ''),
|
||||
elementId: str(n.elementId, ''),
|
||||
};
|
||||
});
|
||||
const audios = (Array.isArray(g.audios) ? g.audios : []).map((node, index) => {
|
||||
const n = plainObject(node);
|
||||
return {
|
||||
id: str(n.id, '') || uid('audio'),
|
||||
name: str(n.name, 'Аудио') || 'Аудио',
|
||||
elementId: str(n.elementId, ''),
|
||||
mode: n.mode === 'stop' ? 'stop' : 'play',
|
||||
x: num(n.x, 60 + (index % 3) * 320),
|
||||
y: num(n.y, 840 + Math.floor(index / 3) * 110),
|
||||
};
|
||||
});
|
||||
const variables = (Array.isArray(g.variables) ? g.variables : []).map((node, index) => {
|
||||
const n = plainObject(node);
|
||||
return {
|
||||
id: str(n.id, '') || uid('var'),
|
||||
name: str(n.name, '') || `var${index + 1}`,
|
||||
x: num(n.x, 40),
|
||||
y: num(n.y, 520 + index * 96),
|
||||
};
|
||||
});
|
||||
|
||||
const slideIds = new Set(slides.map((slide) => slide.id));
|
||||
const idsByKind = {
|
||||
slide: slideIds,
|
||||
script: new Set(scripts.map((node) => node.id)),
|
||||
audio: new Set(audios.map((node) => node.id)),
|
||||
variable: new Set(variables.map((node) => node.id)),
|
||||
};
|
||||
const links = (Array.isArray(g.links) ? g.links : []).map((link) => {
|
||||
const l = plainObject(link);
|
||||
const from = plainObject(l.from);
|
||||
const to = plainObject(l.to);
|
||||
if (!from.kind || !to.kind || !Object.prototype.hasOwnProperty.call(idsByKind, from.kind) || !Object.prototype.hasOwnProperty.call(idsByKind, to.kind)) return null;
|
||||
if (!idsByKind[from.kind].has(String(from.id)) || !idsByKind[to.kind].has(String(to.id))) return null;
|
||||
if (!str(from.port, '') || !str(to.port, '')) return null;
|
||||
return {
|
||||
id: str(l.id, '') || uid('link'),
|
||||
from: { kind: from.kind, id: String(from.id), port: String(from.port) },
|
||||
to: { kind: to.kind, id: String(to.id), port: String(to.port) },
|
||||
};
|
||||
}).filter(Boolean);
|
||||
|
||||
// Переходы «дальше/назад» выводятся из связей — это источник истины.
|
||||
const jumps = {};
|
||||
links.forEach((link) => {
|
||||
if (link.from.kind !== 'slide' || !['next', 'prev'].includes(link.from.port)) return;
|
||||
if (link.to.kind !== 'slide' || link.to.port !== 'in') return;
|
||||
jumps[link.from.id] = jumps[link.from.id] || {};
|
||||
jumps[link.from.id][link.from.port] = link.to.id;
|
||||
});
|
||||
|
||||
return { positions, scripts, audios, variables, links, jumps };
|
||||
}
|
||||
|
||||
// Кнопки с Lua из старых версий получают отдельную ноду в графе.
|
||||
function migrateLuaScripts(slides, graph) {
|
||||
slides.forEach((slide) => {
|
||||
(slide.elements || []).forEach((element) => {
|
||||
if (element.type !== 'button' || !element.action || element.action.type !== 'lua') return;
|
||||
const action = element.action;
|
||||
let node = graph.scripts.find(
|
||||
(item) => item.id === action.scriptNodeId || (item.elementId === element.id && item.slideId === slide.id)
|
||||
);
|
||||
if (!node) {
|
||||
const base = graph.positions[slide.id] || { x: 60, y: 60 };
|
||||
node = {
|
||||
id: uid('script'),
|
||||
name: `Lua · ${element.label || 'Кнопка'}`,
|
||||
code: action.code || '',
|
||||
x: base.x + 330,
|
||||
y: base.y + 20,
|
||||
slideId: slide.id,
|
||||
elementId: element.id,
|
||||
};
|
||||
graph.scripts.push(node);
|
||||
} else if (!node.code && action.code) {
|
||||
node.code = action.code;
|
||||
}
|
||||
if (!node.elementId) {
|
||||
node.elementId = element.id;
|
||||
node.slideId = slide.id;
|
||||
}
|
||||
action.scriptNodeId = node.id;
|
||||
if (node.code) action.code = node.code;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeCommands(commands) {
|
||||
return (Array.isArray(commands) ? commands : []).map((item) => {
|
||||
const command = plainObject(item);
|
||||
return {
|
||||
id: str(command.id, '') || uid('cmd'),
|
||||
label: str(command.label, 'Команда') || 'Команда',
|
||||
description: str(command.description, ''),
|
||||
code: str(command.code, ''),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function normalizePresentation(input = {}) {
|
||||
const data = plainObject(input);
|
||||
const slides = Array.isArray(data.slides) ? data.slides.map(normalizeSlide) : [];
|
||||
const finalSlides = slides.length ? slides : [normalizeSlide({})];
|
||||
const graph = normalizeGraph(data.graph, finalSlides);
|
||||
migrateLuaScripts(finalSlides, graph);
|
||||
return {
|
||||
title: str(data.title, '').trim() || 'Без названия',
|
||||
variables: normalizeVariables(data.variables),
|
||||
music: {
|
||||
src: str(data.music && data.music.src, ''),
|
||||
volume: clamp01(data.music && data.music.volume, 0.5),
|
||||
},
|
||||
lua: str(data.lua, ''),
|
||||
commands: normalizeCommands(data.commands),
|
||||
graph,
|
||||
slides: finalSlides,
|
||||
};
|
||||
}
|
||||
|
||||
function createPresentation(input = {}) {
|
||||
const id = uid('pres');
|
||||
const presentation = {
|
||||
id,
|
||||
...normalizePresentation(input),
|
||||
currentSlide: 0,
|
||||
createdAt: Date.now(),
|
||||
updatedAt: Date.now(),
|
||||
};
|
||||
presentations.set(id, presentation);
|
||||
return presentation;
|
||||
}
|
||||
|
||||
function getPresentation(id) {
|
||||
return presentations.get(id);
|
||||
}
|
||||
|
||||
function updatePresentation(id, input = {}) {
|
||||
const presentation = presentations.get(id);
|
||||
if (!presentation) return null;
|
||||
const normalized = normalizePresentation({
|
||||
title: input.title ?? presentation.title,
|
||||
variables: input.variables ?? presentation.variables,
|
||||
music: input.music ?? presentation.music,
|
||||
lua: input.lua ?? presentation.lua,
|
||||
commands: input.commands ?? presentation.commands,
|
||||
graph: input.graph ?? presentation.graph,
|
||||
slides: input.slides ?? presentation.slides,
|
||||
});
|
||||
Object.assign(presentation, normalized, { updatedAt: Date.now() });
|
||||
return presentation;
|
||||
}
|
||||
|
||||
function savePresentation(presentation) {
|
||||
presentations.set(presentation.id, presentation);
|
||||
return presentation;
|
||||
}
|
||||
|
||||
function deletePresentation(id) {
|
||||
return presentations.delete(id);
|
||||
}
|
||||
|
||||
function listPresentations() {
|
||||
return [...presentations.values()].map((p) => ({
|
||||
id: p.id,
|
||||
title: p.title,
|
||||
slides: p.slides,
|
||||
variables: p.variables,
|
||||
music: p.music,
|
||||
lua: p.lua,
|
||||
commands: p.commands,
|
||||
graph: p.graph,
|
||||
currentSlide: p.currentSlide,
|
||||
createdAt: p.createdAt,
|
||||
updatedAt: p.updatedAt,
|
||||
}));
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
createPresentation,
|
||||
getPresentation,
|
||||
updatePresentation,
|
||||
savePresentation,
|
||||
deletePresentation,
|
||||
listPresentations,
|
||||
};
|
||||
+229
@@ -0,0 +1,229 @@
|
||||
const { WebSocketServer } = require('ws');
|
||||
const hub = require('./hub');
|
||||
const store = require('./store');
|
||||
const cdp = require('./cdp');
|
||||
|
||||
function setupWebSocket(server) {
|
||||
const wss = new WebSocketServer({ server });
|
||||
|
||||
wss.on('connection', (ws, req) => {
|
||||
const { searchParams } = new URL(req.url, 'http://localhost');
|
||||
const presentationId = searchParams.get('id');
|
||||
const role = searchParams.get('role') === 'speaker' ? 'speaker' : 'audience';
|
||||
|
||||
hub.registerClient(ws);
|
||||
|
||||
// Глобальный клиент (дашборд/редактор)
|
||||
if (!presentationId) {
|
||||
ws.on('close', () => hub.unregisterClient(ws));
|
||||
return;
|
||||
}
|
||||
|
||||
const presentation = store.getPresentation(presentationId);
|
||||
if (!presentation) {
|
||||
ws.send(JSON.stringify({ type: 'error', error: 'not_found' }));
|
||||
ws.close(4004, 'presentation not found');
|
||||
return;
|
||||
}
|
||||
|
||||
hub.joinRoom(presentationId, ws, role);
|
||||
ws._presentationId = presentationId;
|
||||
|
||||
const syncPayload = () => ({
|
||||
type: 'sync',
|
||||
presentationId,
|
||||
title: presentation.title,
|
||||
slides: presentation.slides,
|
||||
slideIndex: presentation.currentSlide,
|
||||
variables: presentation.variables,
|
||||
music: presentation.music,
|
||||
lua: presentation.lua,
|
||||
commands: presentation.commands,
|
||||
graph: presentation.graph,
|
||||
});
|
||||
|
||||
ws.send(JSON.stringify(syncPayload()));
|
||||
|
||||
const roomVars = hub.getRoomVars(presentationId);
|
||||
if (roomVars) ws.send(JSON.stringify({ type: 'vars', vars: roomVars }));
|
||||
|
||||
const audioState = hub.getAudioState(presentationId);
|
||||
if (hub.hasAudioState(presentationId)) {
|
||||
ws.send(JSON.stringify({ type: 'audio-state', state: audioState }));
|
||||
}
|
||||
|
||||
const mediaStates = hub.getMediaStates(presentationId);
|
||||
if (mediaStates.length) ws.send(JSON.stringify({ type: 'media-state', states: mediaStates }));
|
||||
|
||||
hub.getWindowStates(presentationId).forEach((state) => {
|
||||
ws.send(JSON.stringify({ type: 'window-state', state }));
|
||||
});
|
||||
hub.getWindowFrames(presentationId).forEach((frame) => {
|
||||
ws.send(JSON.stringify({ type: 'window-frame', elementId: frame.elementId, data: frame.data, cached: true }));
|
||||
});
|
||||
|
||||
function sendWindowError(elementId, message) {
|
||||
if (ws.readyState === 1) {
|
||||
ws.send(JSON.stringify({ type: 'window-error', elementId, message }));
|
||||
}
|
||||
}
|
||||
|
||||
function findWindowElement(elementId) {
|
||||
const fresh = store.getPresentation(presentationId) || presentation;
|
||||
for (const slide of fresh.slides) {
|
||||
const found = (slide.elements || []).find((element) => element.id === elementId && element.type === 'window');
|
||||
if (found) return found;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function startWindow(elementId, targetId) {
|
||||
const element = findWindowElement(elementId);
|
||||
if (!element) {
|
||||
sendWindowError(elementId, 'Элемент окна не найден на слайдах');
|
||||
return;
|
||||
}
|
||||
const wanted = String(targetId || element.targetId || '');
|
||||
let lastFrameAt = 0;
|
||||
hub.setWindowState(presentationId, elementId, {
|
||||
active: true,
|
||||
targetId: wanted,
|
||||
targetTitle: element.targetTitle || '',
|
||||
error: '',
|
||||
});
|
||||
ws.send(JSON.stringify({ type: 'window-starting', elementId, targetId: wanted }));
|
||||
hub.broadcastRoom(presentationId, {
|
||||
type: 'window-state',
|
||||
state: hub.getWindowStates(presentationId).find((item) => item.elementId === elementId) || { elementId, active: true, targetId: wanted },
|
||||
});
|
||||
try {
|
||||
await cdp.start(`${presentationId}::${elementId}`, presentationId, elementId, wanted, {
|
||||
onStart({ target, viewport }) {
|
||||
const state = hub.setWindowState(presentationId, elementId, {
|
||||
active: true,
|
||||
targetId: target.id,
|
||||
targetTitle: target.title,
|
||||
error: '',
|
||||
width: viewport.width,
|
||||
height: viewport.height,
|
||||
});
|
||||
hub.broadcastRoom(presentationId, { type: 'window-state', state });
|
||||
},
|
||||
onFrame({ data }) {
|
||||
hub.setWindowFrame(presentationId, elementId, data);
|
||||
const now = Date.now();
|
||||
if (now - lastFrameAt < 55) return;
|
||||
lastFrameAt = now;
|
||||
hub.broadcastRoom(presentationId, { type: 'window-frame', elementId, data });
|
||||
},
|
||||
onError(error) {
|
||||
const message = String(error && error.message ? error.message : error);
|
||||
hub.setWindowState(presentationId, elementId, { active: false, error: message });
|
||||
hub.broadcastRoom(presentationId, { type: 'window-error', elementId, message });
|
||||
},
|
||||
onClose() {
|
||||
const states = hub.getWindowStates(presentationId);
|
||||
const current = states.find((item) => item.elementId === elementId);
|
||||
if (current && current.active) {
|
||||
hub.setWindowState(presentationId, elementId, { active: false });
|
||||
hub.broadcastRoom(presentationId, { type: 'window-stop', elementId });
|
||||
}
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
const message = String(error && error.message ? error.message : error);
|
||||
hub.setWindowState(presentationId, elementId, { active: false, error: message });
|
||||
sendWindowError(elementId, message);
|
||||
}
|
||||
}
|
||||
|
||||
ws.on('message', (raw) => {
|
||||
let msg;
|
||||
try {
|
||||
msg = JSON.parse(raw);
|
||||
} catch (e) {
|
||||
return;
|
||||
}
|
||||
|
||||
const current = store.getPresentation(presentationId);
|
||||
if (!current) return;
|
||||
|
||||
if (msg.type === 'navigate') {
|
||||
const slideIndex = Math.max(
|
||||
0,
|
||||
Math.min(Number(msg.slideIndex) || 0, Math.max(current.slides.length - 1, 0))
|
||||
);
|
||||
current.currentSlide = slideIndex;
|
||||
store.savePresentation(current);
|
||||
hub.broadcastRoom(presentationId, {
|
||||
type: 'sync',
|
||||
presentationId,
|
||||
title: current.title,
|
||||
slides: current.slides,
|
||||
slideIndex,
|
||||
variables: current.variables,
|
||||
music: current.music,
|
||||
lua: current.lua,
|
||||
commands: current.commands,
|
||||
graph: current.graph,
|
||||
});
|
||||
hub.broadcastSessions();
|
||||
}
|
||||
|
||||
if (msg.type === 'audio' && msg.command) {
|
||||
if (role !== 'speaker') return;
|
||||
hub.applyAudioCommand(presentationId, msg.command);
|
||||
hub.broadcastRoom(presentationId, { type: 'audio', command: msg.command }, ws);
|
||||
}
|
||||
|
||||
if (msg.type === 'vars' && msg.vars && typeof msg.vars === 'object') {
|
||||
if (role !== 'speaker') return;
|
||||
hub.setRoomVars(presentationId, msg.vars);
|
||||
hub.broadcastRoom(presentationId, { type: 'vars', vars: msg.vars }, ws);
|
||||
}
|
||||
|
||||
if (msg.type === 'media' && msg.command) {
|
||||
if (role !== 'speaker') return;
|
||||
hub.applyMediaCommand(presentationId, msg.command);
|
||||
hub.broadcastRoom(presentationId, { type: 'media', command: msg.command }, ws);
|
||||
}
|
||||
|
||||
if (msg.type === 'window-start') {
|
||||
if (role !== 'speaker' || !msg.elementId) return;
|
||||
startWindow(String(msg.elementId), msg.targetId);
|
||||
}
|
||||
|
||||
if (msg.type === 'window-stop') {
|
||||
if (role !== 'speaker' || !msg.elementId) return;
|
||||
cdp.stop(`${presentationId}::${msg.elementId}`);
|
||||
hub.clearWindowState(presentationId, String(msg.elementId));
|
||||
hub.broadcastRoom(presentationId, { type: 'window-stop', elementId: String(msg.elementId) });
|
||||
}
|
||||
|
||||
if (msg.type === 'window-input') {
|
||||
if (role !== 'speaker' || !msg.elementId) return;
|
||||
cdp
|
||||
.input(`${presentationId}::${msg.elementId}`, msg.input)
|
||||
.catch((error) => sendWindowError(String(msg.elementId), String(error.message || error)));
|
||||
}
|
||||
|
||||
if (msg.type === 'window-targets') {
|
||||
cdp.listTargets(true).then((targets) => {
|
||||
if (ws.readyState === 1) {
|
||||
ws.send(JSON.stringify({
|
||||
type: 'window-targets',
|
||||
targets: targets.map(({ id, title, url }) => ({ id, title, url })),
|
||||
endpoint: cdp.ENDPOINT,
|
||||
}));
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
ws.on('close', () => hub.unregisterClient(ws));
|
||||
});
|
||||
|
||||
return wss;
|
||||
}
|
||||
|
||||
module.exports = { setupWebSocket };
|
||||
Reference in new issue
Block a user