Compare commits
37 Commits
2ce1e02753
...
v1.0.13
| Author | SHA1 | Date | |
|---|---|---|---|
| 0eadfdce30 | |||
| 7e7827224d | |||
| 8fa8467db7 | |||
| af4c2616f2 | |||
| 3877a6f2a6 | |||
| 1c6f06b278 | |||
| 064592d4d4 | |||
| e923de350d | |||
| 07641be2d2 | |||
| 8bc2e5bd49 | |||
| 2037144a5c | |||
| 1840227be6 | |||
| a15adfc3b1 | |||
| 82baef2b04 | |||
| e4b989c60f | |||
| e165a41180 | |||
| cd1f6dcc7e | |||
| 06ffe9bb29 | |||
| 0ba4b8379e | |||
| d3cdc468b5 | |||
| 875f8cbb3b | |||
| 93dad8a80d | |||
| a583859f62 | |||
| e76386ddb9 | |||
| 7fc952cc39 | |||
| 600b8f8321 | |||
| 30b57d842a | |||
| f462e65581 | |||
| 36776f4c5d | |||
| c9cad4dafd | |||
| d94a11d466 | |||
| a24e87035a | |||
| 8f8eef53c9 | |||
| 1d051f8bf9 | |||
| f823a7c05f | |||
| ffce066842 | |||
| add699a320 |
@@ -1,35 +0,0 @@
|
|||||||
---
|
|
||||||
name: frontend-senior
|
|
||||||
description: Senior frontend engineer
|
|
||||||
model: auto
|
|
||||||
tools: all
|
|
||||||
---
|
|
||||||
|
|
||||||
Ты senior frontend engineer.
|
|
||||||
|
|
||||||
Задача:
|
|
||||||
- реализовать feature или fix
|
|
||||||
- писать production-quality React + TypeScript код
|
|
||||||
|
|
||||||
Правила:
|
|
||||||
|
|
||||||
- сначала изучи nearby components
|
|
||||||
- следуй существующим patterns
|
|
||||||
- не делай лишних изменений
|
|
||||||
- избегай overengineering
|
|
||||||
- используй composition
|
|
||||||
|
|
||||||
UI:
|
|
||||||
|
|
||||||
- учитывай loading / error / empty / disabled
|
|
||||||
- соблюдай accessibility
|
|
||||||
|
|
||||||
Не делай:
|
|
||||||
|
|
||||||
- large refactors без запроса
|
|
||||||
- новые dependencies без причины
|
|
||||||
|
|
||||||
Output:
|
|
||||||
|
|
||||||
- список изменённых файлов
|
|
||||||
- краткое описание изменений
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
---
|
|
||||||
name: reviewer
|
|
||||||
description: Strict code reviewer
|
|
||||||
model: auto
|
|
||||||
tools: all
|
|
||||||
---
|
|
||||||
|
|
||||||
Ты строгий reviewer.
|
|
||||||
|
|
||||||
Цель:
|
|
||||||
- найти проблемы в изменениях
|
|
||||||
|
|
||||||
Проверяй:
|
|
||||||
|
|
||||||
- correctness
|
|
||||||
- regressions
|
|
||||||
- type safety
|
|
||||||
- accessibility
|
|
||||||
- performance
|
|
||||||
- edge cases
|
|
||||||
- missing tests
|
|
||||||
|
|
||||||
Формат:
|
|
||||||
|
|
||||||
- Severity: high / medium / low
|
|
||||||
- Problem
|
|
||||||
- Why
|
|
||||||
- Fix
|
|
||||||
|
|
||||||
Правила:
|
|
||||||
|
|
||||||
- не переписывай код без причины
|
|
||||||
- предлагай minimal fixes
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
---
|
|
||||||
name: unit-tests
|
|
||||||
description: Unit test specialist
|
|
||||||
model: auto
|
|
||||||
tools: all
|
|
||||||
---
|
|
||||||
|
|
||||||
Ты unit-test specialist.
|
|
||||||
|
|
||||||
Задача:
|
|
||||||
|
|
||||||
- добавить/обновить tests
|
|
||||||
- добиться green status
|
|
||||||
|
|
||||||
Подход:
|
|
||||||
|
|
||||||
- test behavior, not implementation
|
|
||||||
- follow existing patterns
|
|
||||||
- избегай flaky tests
|
|
||||||
|
|
||||||
Покрытие:
|
|
||||||
|
|
||||||
- happy path
|
|
||||||
- edge case
|
|
||||||
- error case
|
|
||||||
|
|
||||||
Workflow:
|
|
||||||
|
|
||||||
- сначала run relevant tests:
|
|
||||||
`npm run test -- <file>`
|
|
||||||
- затем при необходимости весь suite
|
|
||||||
|
|
||||||
Output:
|
|
||||||
|
|
||||||
- какие тесты добавлены
|
|
||||||
- что они проверяют
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
{
|
|
||||||
"version": 1,
|
|
||||||
"hooks": {
|
|
||||||
"stop": [
|
|
||||||
{
|
|
||||||
"command": "node .cursor/hooks/final-verify.cjs"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
const fs = require("fs");
|
|
||||||
const path = require("path");
|
|
||||||
const { execSync } = require("child_process");
|
|
||||||
|
|
||||||
const statePath = path.join(process.cwd(), ".cursor", "pipeline-state.json");
|
|
||||||
|
|
||||||
function readState() {
|
|
||||||
if (!fs.existsSync(statePath)) {
|
|
||||||
return {
|
|
||||||
implementation: "pending",
|
|
||||||
review: "pending",
|
|
||||||
tests: "pending"
|
|
||||||
};
|
|
||||||
}
|
|
||||||
return JSON.parse(fs.readFileSync(statePath, "utf8"));
|
|
||||||
}
|
|
||||||
|
|
||||||
function fail(msg) {
|
|
||||||
process.stdout.write(JSON.stringify({ followup_message: msg }));
|
|
||||||
process.exit(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
const state = readState();
|
|
||||||
|
|
||||||
if (state.implementation !== "done") {
|
|
||||||
fail("Run frontend-senior stage");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (state.review !== "done") {
|
|
||||||
fail("Run reviewer stage");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (state.tests !== "done") {
|
|
||||||
fail("Run unit-tests stage");
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
execSync("npm run lint", { stdio: "pipe" });
|
|
||||||
} catch {
|
|
||||||
fail("Lint failed");
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
execSync("npm run typecheck", { stdio: "pipe" });
|
|
||||||
} catch {
|
|
||||||
fail("Typecheck failed");
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
execSync("npm run test", { stdio: "pipe" });
|
|
||||||
} catch {
|
|
||||||
fail("Tests failed");
|
|
||||||
}
|
|
||||||
|
|
||||||
process.exit(0);
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
{
|
|
||||||
"version": 1,
|
|
||||||
"hooks": {
|
|
||||||
"stop": [
|
|
||||||
{
|
|
||||||
"command": "node .cursor/hooks/final-verify.cjs"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
{
|
|
||||||
"implementation": "done",
|
|
||||||
"review": "done",
|
|
||||||
"tests": "done",
|
|
||||||
"verify": "done"
|
|
||||||
}
|
|
||||||
@@ -1,112 +0,0 @@
|
|||||||
# PR: UI — выравнивание под макеты (редактор + пульт)
|
|
||||||
|
|
||||||
Связь с **feature-pipeline** (`.cursor/skills/feature-pipeline/SKILL.md`): критерии ниже сгруппированы по стадиям; после merge обновляют `.cursor/pipeline-state.json` по мере прохождения стадий.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Мета PR
|
|
||||||
|
|
||||||
| Поле | Значение |
|
|
||||||
|------|----------|
|
|
||||||
| **Цель** | Визуальная и UX-полировка существующих экранов без новых продуктовых фич из макета |
|
|
||||||
| **Область** | `EditorApp`, `SceneGraph`, `ControlApp`, общие токены/мелкие UI-баги |
|
|
||||||
| **Вне скоупа** | Новые пункты меню, новые типы сцен, новые каналы микшера, если их нет в коде |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Stage 1 — Implementation (subagent: `frontend-senior`)
|
|
||||||
|
|
||||||
### Чеклист PR
|
|
||||||
|
|
||||||
- [ ] **P0-A** Карточка узла графа: статусы «Авто / Цикл / Аудио» отражают **реальные** поля сцены (`previewVideoAutostart`, `settings.loopVideo`, наличие `media.audios`), а не статичный текст.
|
|
||||||
- [ ] **P0-B** Пульт: для сцены с видео-превью явно подписано, что **кисть эффектов** недоступна (согласовано с `PresentationView`: эффекты только для image).
|
|
||||||
- [ ] **P1-A** Пульт: порядок секций **Предпросмотр → Варианты ветвления → Музыка сцены → Быстрый микшер** (вертикальный поток как в референсе).
|
|
||||||
- [ ] **P1-B** Сетка «Варианты ветвления» без «дыр»: `repeat(auto-fit, minmax(...))` **или** фиксированные слоты с disabled/placeholder **без новых сценариев** — только визуальная сетка.
|
|
||||||
- [ ] **P2-A** Редактор: меню «Файл» — цвет текста пункта на валидном токене (`--text0` / `--text1`), без несуществующего `--text`.
|
|
||||||
- [ ] **P2-B** Список сцен: убрать пустой статус-ряд у неактивных карточек (без лишнего вертикального зазора).
|
|
||||||
|
|
||||||
### Критерии приёмки (Stage 1)
|
|
||||||
|
|
||||||
1. На графе для сцены **без видео-превью** не отображаются вводящие в заблуждение чипы «Авто/Цикл» видео-превью; при наличии аудио — корректный индикатор аудио.
|
|
||||||
2. Для сцены с **видео-превью** чипы «Авто»/«Цикл» совпадают с `previewVideoAutostart` и `scene.settings.loopVideo`.
|
|
||||||
3. В пульте при `previewAssetType === 'video'` пользователь видит **одну строку-пояснение** (вторичный текст), почему нет панели эффектов.
|
|
||||||
4. Визуальный порядок блоков пульта соответствует чеклисту P1-A; отступы между `Surface` единообразны (`gap` 16).
|
|
||||||
5. Нет регрессий drag-and-drop сцен на граф и переключения веток.
|
|
||||||
|
|
||||||
**Definition of Done (Stage 1):** все пункты чеклиста Stage 1 отмечены; `npm run build` успешен.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Stage 2 — Review (subagent: `reviewer`)
|
|
||||||
|
|
||||||
### Чеклист PR
|
|
||||||
|
|
||||||
- [ ] Нет «мёртвых» веток UI и ложных состояний (чипы/подписи соответствуют данным).
|
|
||||||
- [ ] a11y: фокус/клавиатура на интерактивах не сломаны; `aria-*` не ухудшены.
|
|
||||||
- [ ] Нет лишнего diff вне файлов задачи.
|
|
||||||
|
|
||||||
### Критерии приёмки (Stage 2)
|
|
||||||
|
|
||||||
1. Reviewer фиксирует замечания с **Severity**; все **high** устранены или явно отклонены с причиной в PR.
|
|
||||||
2. После правок по review снова выполняется `npm run build`.
|
|
||||||
|
|
||||||
**Definition of Done (Stage 2):** review-замечания закрыты; state `review: done`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Stage 3 — Tests (subagent: `unit-tests`)
|
|
||||||
|
|
||||||
### Чеклист PR
|
|
||||||
|
|
||||||
- [ ] Добавлены или обновлены тесты на **чистую логику** (например, хелпер разметки чипов по `Scene`, если вынесен в `app/shared`).
|
|
||||||
- [ ] Либо задокументировано в PR, что изменения только презентационные и покрыты smoke-тестом пайплайна.
|
|
||||||
|
|
||||||
### Критерии приёмки (Stage 3)
|
|
||||||
|
|
||||||
1. `npm run test` завершается с кодом 0.
|
|
||||||
2. Новые тесты не flaky, не зависят от Electron UI.
|
|
||||||
|
|
||||||
**Definition of Done (Stage 3):** `tests: done` в `.cursor/pipeline-state.json`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Stage 4 — Verify (локально / hook `final-verify.cjs`)
|
|
||||||
|
|
||||||
Выполнить подряд:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npm run lint
|
|
||||||
npm run typecheck
|
|
||||||
npm run test
|
|
||||||
```
|
|
||||||
|
|
||||||
**Если `npm run lint` падает на массовых `Delete ␍` (CRLF/LF) в файлах вне PR** — до отдельного chore-PR с нормализацией строк для этого чеклиста достаточно:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npx eslint app/renderer/control/ControlApp.tsx app/renderer/editor/graph/SceneGraph.tsx app/renderer/shared/ui/sceneGraphChips.ts app/renderer/shared/ui/sceneGraphChips.test.ts --max-warnings 0
|
|
||||||
npm run typecheck
|
|
||||||
npm run test
|
|
||||||
npm run build
|
|
||||||
```
|
|
||||||
|
|
||||||
### Критерии приёмки (Stage 4)
|
|
||||||
|
|
||||||
1. `npm run typecheck`, `npm run test`, `npm run build` — **exit 0**.
|
|
||||||
2. Линт: либо полный `npm run lint` — **exit 0**, либо (при известном eol-долге репозитория) scoped-ESLint по файлам PR — **exit 0**, как в блоке выше.
|
|
||||||
3. `node .cursor/hooks/final-verify.cjs` — успешное завершение пайплайна только когда полный `npm run lint` зелёный (хук вызывает полный lint; при падении lint хук пишет `followup_message` в stdout).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Синхронизация с `.cursor/pipeline-state.json`
|
|
||||||
|
|
||||||
После каждой стадии обновлять файл:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"implementation": "done",
|
|
||||||
"review": "done",
|
|
||||||
"tests": "done"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
До начала работы — все `"pending"`.
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
# .cursor/rules/project.mdc
|
|
||||||
|
|
||||||
# Project
|
|
||||||
|
|
||||||
React + TypeScript frontend project.
|
|
||||||
|
|
||||||
# Commands
|
|
||||||
|
|
||||||
- install: `npm install`
|
|
||||||
- dev: `npm run dev`
|
|
||||||
- build: `npm run build`
|
|
||||||
- lint: `npm run lint`
|
|
||||||
- typecheck: `npm run typecheck`
|
|
||||||
- test: `npm run test`
|
|
||||||
- test single: `npm run test -- <file>`
|
|
||||||
|
|
||||||
# Global rules
|
|
||||||
|
|
||||||
- Всегда изучай existing code и nearby components перед изменениями
|
|
||||||
- Делай minimal, review-friendly diff
|
|
||||||
- Не добавляй new dependencies без явной причины
|
|
||||||
- Следуй существующим patterns
|
|
||||||
|
|
||||||
# Done criteria
|
|
||||||
|
|
||||||
Перед завершением:
|
|
||||||
|
|
||||||
- lint passes
|
|
||||||
- typecheck passes
|
|
||||||
- tests pass
|
|
||||||
- нет regressions
|
|
||||||
|
|
||||||
# UI checklist
|
|
||||||
|
|
||||||
- loading state
|
|
||||||
- error state
|
|
||||||
- empty state
|
|
||||||
- disabled state
|
|
||||||
- accessibility
|
|
||||||
@@ -1,80 +0,0 @@
|
|||||||
---
|
|
||||||
name: feature-pipeline
|
|
||||||
description: Implementation → Review → Tests → Verify
|
|
||||||
---
|
|
||||||
|
|
||||||
# Workflow
|
|
||||||
|
|
||||||
## Stage 1 — Implementation
|
|
||||||
|
|
||||||
Используй subagent: frontend-senior
|
|
||||||
|
|
||||||
- реализуй задачу
|
|
||||||
- сделай minimal diff
|
|
||||||
|
|
||||||
Обнови state:
|
|
||||||
|
|
||||||
{
|
|
||||||
"implementation": "done"
|
|
||||||
}
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Stage 2 — Review
|
|
||||||
|
|
||||||
Используй subagent: reviewer
|
|
||||||
|
|
||||||
- проверь изменения
|
|
||||||
- найди проблемы
|
|
||||||
- исправь минимально
|
|
||||||
|
|
||||||
Обнови state:
|
|
||||||
|
|
||||||
{
|
|
||||||
"implementation": "done",
|
|
||||||
"review": "done"
|
|
||||||
}
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Stage 3 — Tests
|
|
||||||
|
|
||||||
Используй subagent: unit-tests
|
|
||||||
|
|
||||||
- добавь/обнови tests
|
|
||||||
- добейся green status
|
|
||||||
|
|
||||||
Обнови state:
|
|
||||||
|
|
||||||
{
|
|
||||||
"implementation": "done",
|
|
||||||
"review": "done",
|
|
||||||
"tests": "done"
|
|
||||||
}
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Stage 4 — Verify
|
|
||||||
|
|
||||||
Выполни:
|
|
||||||
|
|
||||||
- `npm run lint`
|
|
||||||
- `npm run typecheck`
|
|
||||||
- `npm run test`
|
|
||||||
|
|
||||||
Если ошибка:
|
|
||||||
- исправь
|
|
||||||
- повтори
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Final Output
|
|
||||||
|
|
||||||
- implementation summary
|
|
||||||
- review summary
|
|
||||||
- test summary
|
|
||||||
- verification status
|
|
||||||
|
|
||||||
## PR-чеклисты (приёмка по задаче)
|
|
||||||
|
|
||||||
Готовые чеклисты с критериями по стадиям лежат в `.cursor/pr-checklists/`. Для UI-выравнивания под макеты: `ui-mock-alignment.md`.
|
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
# Сборка по тегу v* и выкладка в публичный репо (ветка updates).
|
||||||
|
#
|
||||||
|
# Метки runs-on = labels твоих act_runner (Админка Gitea → Действия → Раннеры).
|
||||||
|
# Не используем windows-latest/macos-latest — это только GitHub-hosted.
|
||||||
|
# По умолчанию: один job на ubuntu-22.04 — Win (Wine+NSIS), Linux AppImage (x64+arm64), sync в updates без затирания других ОС.
|
||||||
|
#
|
||||||
|
# Один job без actions/upload-artifact: официальный upload-artifact@v4 с GitHub на Gitea
|
||||||
|
# падает (GHESNotSupportedError). Сборка и sync-update-feed идут в одном окружении.
|
||||||
|
#
|
||||||
|
# Secrets: DND_UPDATE_FEED_URL, DND_UPDATES_SERVER, UPDATES_REPO, DND_UPDATES_PUSH_TOKEN — docs/GITEA_AUTO_UPDATE.md
|
||||||
|
|
||||||
|
name: Release
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- 'v*'
|
||||||
|
|
||||||
|
env:
|
||||||
|
CSC_IDENTITY_AUTO_DISCOVERY: 'false'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
release:
|
||||||
|
runs-on: ubuntu-22.04
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: '22'
|
||||||
|
cache: 'npm'
|
||||||
|
|
||||||
|
# Не включаем i386 / wine32: на Debian с репами только amd64 (nginx, sury, …)
|
||||||
|
# apt ломается на цепочке libgphoto2/libgd:i386. NSIS — нативный пакет `nsis`;
|
||||||
|
# electron-builder подхватывает makensis; wine64 — для win-утилит (rcedit и т.п.).
|
||||||
|
# Пакет `wine` (мета) тянет wine32 → снова i386. electron-builder ищет именно `wine` в PATH.
|
||||||
|
- name: Зависимости Win-сборки на Linux (amd64, без multiarch i386)
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
sudo apt-get update
|
||||||
|
sudo DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
|
||||||
|
ca-certificates \
|
||||||
|
nsis \
|
||||||
|
wine64
|
||||||
|
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
|
||||||
|
W64="$(command -v wine64 2>/dev/null || true)"
|
||||||
|
if [[ -z "$W64" || ! -x "$W64" ]]; then
|
||||||
|
for p in /usr/bin/wine64 /usr/lib/wine/wine64; do
|
||||||
|
if [[ -x "$p" ]]; then W64="$p"; break; fi
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
if [[ -z "${W64:-}" || ! -x "$W64" ]]; then
|
||||||
|
echo "wine64 binary not found after apt install wine64" >&2
|
||||||
|
dpkg -L wine64 2>/dev/null | head -80 >&2 || true
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
printf '%s\n' '#!/bin/sh' "exec $W64 \"\$@\"" | sudo tee /usr/local/bin/wine >/dev/null
|
||||||
|
sudo chmod +x /usr/local/bin/wine
|
||||||
|
wine --version
|
||||||
|
|
||||||
|
- name: Версия из тега
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
TAG="${GITHUB_REF_NAME:-${GITEA_REF_NAME:-}}"
|
||||||
|
VERSION="${TAG#v}"
|
||||||
|
npm version "$VERSION" --allow-same-version --no-git-tag-version
|
||||||
|
|
||||||
|
- run: npm ci
|
||||||
|
|
||||||
|
- run: npm run build
|
||||||
|
|
||||||
|
# Linux AppImage (x64 + arm64) до подмешивания win32-sharp в node_modules.
|
||||||
|
- name: Зависимости Linux AppImage и кросс-сборка arm64 на amd64
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
sudo apt-get update
|
||||||
|
sudo DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
|
||||||
|
qemu-user-static \
|
||||||
|
binfmt-support \
|
||||||
|
desktop-file-utils \
|
||||||
|
squashfs-tools
|
||||||
|
|
||||||
|
- name: electron-builder (linux AppImage x64, arm64)
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
DND_UPDATE_FEED_URL: ${{ secrets.DND_UPDATE_FEED_URL }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
if [[ -z "${DND_UPDATE_FEED_URL:-}" ]]; then
|
||||||
|
echo "Secret DND_UPDATE_FEED_URL is not set (URL со слэшем в конце)" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
npx electron-builder --linux AppImage --x64 --arm64 --publish never \
|
||||||
|
--config.publish.provider=generic \
|
||||||
|
--config.publish.url="${DND_UPDATE_FEED_URL}"
|
||||||
|
|
||||||
|
# Не используем `npm install`: на Linux npm падает с EBADPLATFORM для win32-пакета.
|
||||||
|
- name: sharp (@img/sharp-win32-x64) для Windows-артефакта при сборке на Linux
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
tmp="$(mktemp -d)"
|
||||||
|
npm pack @img/sharp-win32-x64@0.34.5 --pack-destination "$tmp"
|
||||||
|
mkdir -p node_modules/@img/sharp-win32-x64
|
||||||
|
tar -xzf "$tmp/img-sharp-win32-x64-0.34.5.tgz" -C "$tmp"
|
||||||
|
cp -a "$tmp/package/." node_modules/@img/sharp-win32-x64/
|
||||||
|
test -f node_modules/@img/sharp-win32-x64/lib/sharp-win32-x64.node
|
||||||
|
rm -rf "$tmp"
|
||||||
|
|
||||||
|
- name: electron-builder (win)
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
DND_UPDATE_FEED_URL: ${{ secrets.DND_UPDATE_FEED_URL }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
if [[ -z "${DND_UPDATE_FEED_URL:-}" ]]; then
|
||||||
|
echo "Secret DND_UPDATE_FEED_URL is not set (URL со слэшем в конце)" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
npx electron-builder --win --publish never \
|
||||||
|
--config.publish.provider=generic \
|
||||||
|
--config.publish.url="${DND_UPDATE_FEED_URL}"
|
||||||
|
|
||||||
|
# Артефакты читает sync напрямую из release/ (без дублирующих _win/_linux — меньше ENOSPC).
|
||||||
|
- name: Пустой каталог mac (пока нет сборки mac в CI)
|
||||||
|
run: mkdir -p _mac
|
||||||
|
|
||||||
|
- name: Push в публичный репозиторий updates
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
DND_UPDATES_SERVER: ${{ secrets.DND_UPDATES_SERVER }}
|
||||||
|
UPDATES_REPO: ${{ secrets.UPDATES_REPO }}
|
||||||
|
DND_UPDATES_PUSH_TOKEN: ${{ secrets.DND_UPDATES_PUSH_TOKEN }}
|
||||||
|
ARTIFACT_WIN: ${{ github.workspace }}/release
|
||||||
|
ARTIFACT_MAC: ${{ github.workspace }}/_mac
|
||||||
|
ARTIFACT_LINUX: ${{ github.workspace }}/release
|
||||||
|
DND_FEED_TMP_ROOT: ${{ github.workspace }}/.dnd-feed-tmp
|
||||||
|
DND_UPDATES_SQUASH_HISTORY: '1'
|
||||||
|
GIT_COMMIT_TAG: ${{ github.ref_name }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
mkdir -p "${{ github.workspace }}/.dnd-feed-tmp" "${{ github.workspace }}/_mac"
|
||||||
|
node scripts/sync-update-feed.mjs
|
||||||
|
|
||||||
|
# Когда появится macOS-раннер: отдельный job build-macos, копирование eb-mac в _mac перед sync
|
||||||
|
# или расширить шаг «Каталог артефактов»; сейчас всё в одном job `release`.
|
||||||
|
#
|
||||||
|
# build-macos:
|
||||||
|
# runs-on: macos-14
|
||||||
|
# steps: ...
|
||||||
@@ -1,3 +1,6 @@
|
|||||||
|
# Cursor: канонический `.cursor/` в репозитории cursorAi; локально — junction на ../cursorAi/.cursor
|
||||||
|
.cursor/
|
||||||
|
|
||||||
release/
|
release/
|
||||||
build/
|
build/
|
||||||
mcps/
|
mcps/
|
||||||
|
|||||||
+118
-3
@@ -7,6 +7,7 @@ import { installIpcRouter, registerHandler, setLicenseAssert } from './ipc/route
|
|||||||
import { LicenseService } from './license/licenseService';
|
import { LicenseService } from './license/licenseService';
|
||||||
import { ZipProjectStore } from './project/zipStore';
|
import { ZipProjectStore } from './project/zipStore';
|
||||||
import { registerDndAssetProtocol } from './protocol/dndAssetProtocol';
|
import { registerDndAssetProtocol } from './protocol/dndAssetProtocol';
|
||||||
|
import { installAutoUpdater } from './update/installAutoUpdater';
|
||||||
import { getAppSemanticVersion, getOptionalBuildNumber } from './versionInfo';
|
import { getAppSemanticVersion, getOptionalBuildNumber } from './versionInfo';
|
||||||
import { VideoPlaybackStore } from './video/videoPlaybackStore';
|
import { VideoPlaybackStore } from './video/videoPlaybackStore';
|
||||||
import {
|
import {
|
||||||
@@ -21,12 +22,27 @@ import {
|
|||||||
createEditorWindowDeferred,
|
createEditorWindowDeferred,
|
||||||
createWindows,
|
createWindows,
|
||||||
focusEditorWindow,
|
focusEditorWindow,
|
||||||
|
isMultiWindowOpen,
|
||||||
markAppQuitting,
|
markAppQuitting,
|
||||||
openMultiWindow,
|
openMultiWindow,
|
||||||
togglePresentationFullscreen,
|
togglePresentationFullscreen,
|
||||||
waitForEditorWindowReady,
|
waitForEditorWindowReady,
|
||||||
} from './windows/createWindows';
|
} from './windows/createWindows';
|
||||||
|
|
||||||
|
function emitZipProgress(evt: {
|
||||||
|
kind: 'import' | 'export';
|
||||||
|
stage: string;
|
||||||
|
percent: number;
|
||||||
|
detail?: string;
|
||||||
|
}): void {
|
||||||
|
for (const win of BrowserWindow.getAllWindows()) {
|
||||||
|
win.webContents.send(
|
||||||
|
evt.kind === 'import' ? ipcChannels.project.importZipProgress : ipcChannels.project.exportZipProgress,
|
||||||
|
evt,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Отключение GPU ломает скорость вторичных окон (презентация/пульт — WebGL). По умолчанию не трогаем.
|
* Отключение GPU ломает скорость вторичных окон (презентация/пульт — WebGL). По умолчанию не трогаем.
|
||||||
* При чёрном экране в упакованной сборке: `DND_DISABLE_GPU=1`.
|
* При чёрном экране в упакованной сборке: `DND_DISABLE_GPU=1`.
|
||||||
@@ -63,6 +79,35 @@ if (!gotTheLock) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const projectStore = new ZipProjectStore();
|
const projectStore = new ZipProjectStore();
|
||||||
|
|
||||||
|
/** Без меню Electron не вешает горячие клавиши DevTools (Ctrl+Shift+I / F12). */
|
||||||
|
function wantsDevToolsMenu(): boolean {
|
||||||
|
return (
|
||||||
|
process.env.NODE_ENV === 'development' ||
|
||||||
|
Boolean(process.env.VITE_DEV_SERVER_URL) ||
|
||||||
|
process.env.DND_OPEN_DEVTOOLS === '1'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function installAppMenuForSession(): void {
|
||||||
|
if (!wantsDevToolsMenu()) {
|
||||||
|
Menu.setApplicationMenu(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const template: Electron.MenuItemConstructorOptions[] = [];
|
||||||
|
if (process.platform === 'darwin') {
|
||||||
|
template.push({
|
||||||
|
label: app.name,
|
||||||
|
submenu: [{ role: 'about' }, { type: 'separator' }, { role: 'quit' }],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
template.push({
|
||||||
|
label: 'Вид',
|
||||||
|
submenu: [{ role: 'reload' }, { role: 'forceReload' }, { type: 'separator' }, { role: 'toggleDevTools' }],
|
||||||
|
});
|
||||||
|
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
|
||||||
|
}
|
||||||
|
|
||||||
const effectsStore = new EffectsStore();
|
const effectsStore = new EffectsStore();
|
||||||
const videoStore = new VideoPlaybackStore();
|
const videoStore = new VideoPlaybackStore();
|
||||||
|
|
||||||
@@ -172,11 +217,32 @@ async function runStartupAfterHandlers(licenseService: LicenseService): Promise<
|
|||||||
|
|
||||||
async function main() {
|
async function main() {
|
||||||
await app.whenReady();
|
await app.whenReady();
|
||||||
|
/**
|
||||||
|
* `ZipProjectStore` пишет `project.json` в кэш синхронно с мутациями, а упаковку `.dnd.zip`
|
||||||
|
* откладывает (`queueSave`, ~250 мс). Без финального `saveNow()` при выходе на диске
|
||||||
|
* остаётся старый zip — при следующем открытии кэш пересоздаётся из него и теряются
|
||||||
|
* недавние поля (в т.ч. `campaignAudios`).
|
||||||
|
*/
|
||||||
|
let appQuittingAfterPendingSave = false;
|
||||||
|
app.on('before-quit', (e) => {
|
||||||
|
if (appQuittingAfterPendingSave) return;
|
||||||
|
e.preventDefault();
|
||||||
|
appQuittingAfterPendingSave = true;
|
||||||
|
void projectStore
|
||||||
|
.saveNow()
|
||||||
|
.catch((err: unknown) => {
|
||||||
|
console.error('[before-quit] saveNow failed', err);
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
app.quit();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
const licenseService = new LicenseService(app.getPath('userData'));
|
const licenseService = new LicenseService(app.getPath('userData'));
|
||||||
setLicenseAssert(() => {
|
setLicenseAssert(() => {
|
||||||
licenseService.assertForIpc();
|
licenseService.assertForIpc();
|
||||||
});
|
});
|
||||||
Menu.setApplicationMenu(null);
|
installAppMenuForSession();
|
||||||
registerDndAssetProtocol(projectStore);
|
registerDndAssetProtocol(projectStore);
|
||||||
registerHandler(ipcChannels.app.quit, () => {
|
registerHandler(ipcChannels.app.quit, () => {
|
||||||
markAppQuitting();
|
markAppQuitting();
|
||||||
@@ -186,6 +252,7 @@ async function main() {
|
|||||||
registerHandler(ipcChannels.app.getVersion, () => ({
|
registerHandler(ipcChannels.app.getVersion, () => ({
|
||||||
version: getAppSemanticVersion(),
|
version: getAppSemanticVersion(),
|
||||||
buildNumber: getOptionalBuildNumber(),
|
buildNumber: getOptionalBuildNumber(),
|
||||||
|
packaged: app.isPackaged,
|
||||||
}));
|
}));
|
||||||
registerHandler(ipcChannels.license.getStatus, () => licenseService.getStatus());
|
registerHandler(ipcChannels.license.getStatus, () => licenseService.getStatus());
|
||||||
registerHandler(ipcChannels.license.setToken, async ({ token }) => licenseService.setToken(token));
|
registerHandler(ipcChannels.license.setToken, async ({ token }) => licenseService.setToken(token));
|
||||||
@@ -203,6 +270,9 @@ async function main() {
|
|||||||
const isFullScreen = togglePresentationFullscreen();
|
const isFullScreen = togglePresentationFullscreen();
|
||||||
return { ok: true, isFullScreen };
|
return { ok: true, isFullScreen };
|
||||||
});
|
});
|
||||||
|
registerHandler(ipcChannels.windows.getMultiWindowState, () => {
|
||||||
|
return { open: isMultiWindowOpen() };
|
||||||
|
});
|
||||||
|
|
||||||
registerHandler(ipcChannels.project.list, async () => {
|
registerHandler(ipcChannels.project.list, async () => {
|
||||||
const projects = await projectStore.listProjects();
|
const projects = await projectStore.listProjects();
|
||||||
@@ -286,6 +356,30 @@ async function main() {
|
|||||||
emitSessionState();
|
emitSessionState();
|
||||||
return result;
|
return result;
|
||||||
});
|
});
|
||||||
|
registerHandler(ipcChannels.project.importCampaignAudio, async () => {
|
||||||
|
const { canceled, filePaths } = await dialog.showOpenDialog({
|
||||||
|
properties: ['openFile', 'multiSelections'],
|
||||||
|
filters: [
|
||||||
|
{
|
||||||
|
name: 'Аудио',
|
||||||
|
extensions: ['mp3', 'wav', 'ogg', 'm4a', 'aac'],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
if (canceled || filePaths.length === 0) {
|
||||||
|
const project = projectStore.getOpenProject();
|
||||||
|
if (!project) throw new Error('No open project');
|
||||||
|
return { canceled: true as const, project, imported: [] };
|
||||||
|
}
|
||||||
|
const result = await projectStore.importCampaignAudioFiles(filePaths);
|
||||||
|
emitSessionState();
|
||||||
|
return { canceled: false as const, ...result };
|
||||||
|
});
|
||||||
|
registerHandler(ipcChannels.project.updateCampaignAudios, async ({ audios }) => {
|
||||||
|
const project = await projectStore.setCampaignAudios(audios);
|
||||||
|
emitSessionState();
|
||||||
|
return { project };
|
||||||
|
});
|
||||||
registerHandler(ipcChannels.project.importScenePreview, async ({ sceneId }) => {
|
registerHandler(ipcChannels.project.importScenePreview, async ({ sceneId }) => {
|
||||||
const { canceled, filePaths } = await dialog.showOpenDialog({
|
const { canceled, filePaths } = await dialog.showOpenDialog({
|
||||||
properties: ['openFile'],
|
properties: ['openFile'],
|
||||||
@@ -358,7 +452,18 @@ async function main() {
|
|||||||
if (canceled || !filePaths[0]) {
|
if (canceled || !filePaths[0]) {
|
||||||
return { canceled: true as const };
|
return { canceled: true as const };
|
||||||
}
|
}
|
||||||
const project = await projectStore.importProjectFromExternalZip(filePaths[0]);
|
const srcPath = filePaths[0];
|
||||||
|
emitZipProgress({ kind: 'import', stage: 'copy', percent: 0, detail: 'Копирование…' });
|
||||||
|
// Let store import; progress for unzip is emitted from unzipToDir wrapper in store.
|
||||||
|
const project = await projectStore.importProjectFromExternalZip(srcPath, (p) => {
|
||||||
|
emitZipProgress({
|
||||||
|
kind: 'import',
|
||||||
|
stage: p.stage,
|
||||||
|
percent: p.percent,
|
||||||
|
...(p.detail ? { detail: p.detail } : null),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
emitZipProgress({ kind: 'import', stage: 'done', percent: 100, detail: 'Готово' });
|
||||||
emitSessionState();
|
emitSessionState();
|
||||||
return { canceled: false as const, project };
|
return { canceled: false as const, project };
|
||||||
});
|
});
|
||||||
@@ -383,7 +488,16 @@ async function main() {
|
|||||||
if (!lower.endsWith('.dnd.zip')) {
|
if (!lower.endsWith('.dnd.zip')) {
|
||||||
dest = lower.endsWith('.zip') ? dest.replace(/\.zip$/iu, '.dnd.zip') : `${dest}.dnd.zip`;
|
dest = lower.endsWith('.zip') ? dest.replace(/\.zip$/iu, '.dnd.zip') : `${dest}.dnd.zip`;
|
||||||
}
|
}
|
||||||
await projectStore.exportProjectZipToPath(projectId, dest);
|
emitZipProgress({ kind: 'export', stage: 'copy', percent: 0, detail: 'Экспорт…' });
|
||||||
|
await projectStore.exportProjectZipToPath(projectId, dest, (p) => {
|
||||||
|
emitZipProgress({
|
||||||
|
kind: 'export',
|
||||||
|
stage: p.stage,
|
||||||
|
percent: p.percent,
|
||||||
|
...(p.detail ? { detail: p.detail } : null),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
emitZipProgress({ kind: 'export', stage: 'done', percent: 100, detail: 'Готово' });
|
||||||
return { canceled: false as const };
|
return { canceled: false as const };
|
||||||
});
|
});
|
||||||
registerHandler(ipcChannels.project.deleteProject, async ({ projectId }) => {
|
registerHandler(ipcChannels.project.deleteProject, async ({ projectId }) => {
|
||||||
@@ -413,6 +527,7 @@ async function main() {
|
|||||||
return { ok: true };
|
return { ok: true };
|
||||||
});
|
});
|
||||||
|
|
||||||
|
installAutoUpdater(licenseService, registerHandler);
|
||||||
installIpcRouter();
|
installIpcRouter();
|
||||||
applyDockIconIfNeeded();
|
applyDockIconIfNeeded();
|
||||||
await runStartupAfterHandlers(licenseService);
|
await runStartupAfterHandlers(licenseService);
|
||||||
|
|||||||
@@ -19,6 +19,8 @@ function channelRequiresLicense(channel: string): boolean {
|
|||||||
if (channel.startsWith('app.')) return false;
|
if (channel.startsWith('app.')) return false;
|
||||||
if (channel === ipcChannels.windows.closeMultiWindow) return false;
|
if (channel === ipcChannels.windows.closeMultiWindow) return false;
|
||||||
if (channel === ipcChannels.windows.togglePresentationFullscreen) return false;
|
if (channel === ipcChannels.windows.togglePresentationFullscreen) return false;
|
||||||
|
// Список файлов в %userData%/projects — только чтение; без лицензии список не должен «пропадать».
|
||||||
|
if (channel === ipcChannels.project.list) return false;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -34,6 +36,8 @@ export function registerHandler<K extends keyof IpcInvokeMap>(channel: K, handle
|
|||||||
handlers.set(channelStr, inner);
|
handlers.set(channelStr, inner);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type IpcRegisterHandler = typeof registerHandler;
|
||||||
|
|
||||||
export function installIpcRouter(): void {
|
export function installIpcRouter(): void {
|
||||||
for (const [channel, handler] of handlers.entries()) {
|
for (const [channel, handler] of handlers.entries()) {
|
||||||
ipcMain.handle(channel, async (_event, payload: unknown) => handler(payload));
|
ipcMain.handle(channel, async (_event, payload: unknown) => handler(payload));
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import crypto from 'node:crypto';
|
||||||
import fs from 'node:fs';
|
import fs from 'node:fs';
|
||||||
|
|
||||||
import { BrowserWindow, safeStorage } from 'electron';
|
import { BrowserWindow, safeStorage } from 'electron';
|
||||||
@@ -10,13 +11,37 @@ import { isDndProductKey } from '../../shared/license/productKey';
|
|||||||
import { normalizeLicenseTokenInput } from '../../shared/license/tokenFormat';
|
import { normalizeLicenseTokenInput } from '../../shared/license/tokenFormat';
|
||||||
|
|
||||||
import { getOrCreateDeviceId } from './deviceId';
|
import { getOrCreateDeviceId } from './deviceId';
|
||||||
import { licenseEncryptedPath, preferencesPath } from './paths';
|
import { licenseEncryptedPath, licenseFallbackSealedPath, preferencesPath } from './paths';
|
||||||
import { verifyLicenseToken } from './verifyLicenseToken';
|
import { verifyLicenseToken } from './verifyLicenseToken';
|
||||||
|
|
||||||
type Preferences = {
|
type Preferences = {
|
||||||
eulaAcceptedVersion?: number;
|
eulaAcceptedVersion?: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
type LicenseChangeListener = () => void;
|
||||||
|
|
||||||
|
const FALLBACK_MAGIC = Buffer.from('DNDLF1', 'ascii');
|
||||||
|
|
||||||
|
const licenseChangeListeners = new Set<LicenseChangeListener>();
|
||||||
|
|
||||||
|
/** Слушатели вызываются после смены состояния лицензии (сохранённый токен, EULA, отзыв). */
|
||||||
|
export function addLicenseChangeListener(fn: LicenseChangeListener): () => void {
|
||||||
|
licenseChangeListeners.add(fn);
|
||||||
|
return () => {
|
||||||
|
licenseChangeListeners.delete(fn);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function notifyLicenseChangeListeners(): void {
|
||||||
|
for (const fn of licenseChangeListeners) {
|
||||||
|
try {
|
||||||
|
fn();
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[license] change listener failed', err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function readPreferences(userData: string): Preferences {
|
function readPreferences(userData: string): Preferences {
|
||||||
try {
|
try {
|
||||||
const raw = fs.readFileSync(preferencesPath(userData), 'utf8');
|
const raw = fs.readFileSync(preferencesPath(userData), 'utf8');
|
||||||
@@ -35,6 +60,7 @@ function emitLicenseStatusChanged(): void {
|
|||||||
for (const win of BrowserWindow.getAllWindows()) {
|
for (const win of BrowserWindow.getAllWindows()) {
|
||||||
win.webContents.send(ipcChannels.license.statusChanged, {});
|
win.webContents.send(ipcChannels.license.statusChanged, {});
|
||||||
}
|
}
|
||||||
|
notifyLicenseChangeListeners();
|
||||||
}
|
}
|
||||||
|
|
||||||
export class LicenseService {
|
export class LicenseService {
|
||||||
@@ -52,23 +78,93 @@ export class LicenseService {
|
|||||||
return process.env.DND_SKIP_LICENSE === '1' || process.env.DND_SKIP_LICENSE === 'true';
|
return process.env.DND_SKIP_LICENSE === '1' || process.env.DND_SKIP_LICENSE === 'true';
|
||||||
}
|
}
|
||||||
|
|
||||||
private readSealedToken(): string | null {
|
/** Только для окружений без OS keychain (WSL и т.п.); слабее safeStorage — см. licensing-spec. */
|
||||||
const p = licenseEncryptedPath(this.userData);
|
private isInsecureFileStorageAllowed(): boolean {
|
||||||
if (!fs.existsSync(p)) return null;
|
const v = process.env.DND_LICENSE_INSECURE_FILE_STORAGE?.trim().toLowerCase();
|
||||||
if (!safeStorage.isEncryptionAvailable()) {
|
return v === '1' || v === 'true' || v === 'yes';
|
||||||
throw new Error('safeStorage недоступен: нельзя расшифровать лицензию на этой системе');
|
}
|
||||||
}
|
|
||||||
|
private deriveFallbackKey(): Buffer {
|
||||||
|
return crypto
|
||||||
|
.createHash('sha256')
|
||||||
|
.update('DNDGamePlayer.license.fallback.v1\0', 'utf8')
|
||||||
|
.update(this.deviceId, 'utf8')
|
||||||
|
.digest();
|
||||||
|
}
|
||||||
|
|
||||||
|
private readFallbackSealedToken(): string {
|
||||||
|
const p = licenseFallbackSealedPath(this.userData);
|
||||||
const buf = fs.readFileSync(p);
|
const buf = fs.readFileSync(p);
|
||||||
return safeStorage.decryptString(buf);
|
if (buf.length < FALLBACK_MAGIC.length + 12 + 16 + 1) {
|
||||||
|
throw new Error('license.fallback: файл повреждён или слишком короткий');
|
||||||
|
}
|
||||||
|
if (!buf.subarray(0, FALLBACK_MAGIC.length).equals(FALLBACK_MAGIC)) {
|
||||||
|
throw new Error('license.fallback: неверный формат');
|
||||||
|
}
|
||||||
|
const iv = buf.subarray(FALLBACK_MAGIC.length, FALLBACK_MAGIC.length + 12);
|
||||||
|
const tag = buf.subarray(FALLBACK_MAGIC.length + 12, FALLBACK_MAGIC.length + 12 + 16);
|
||||||
|
const data = buf.subarray(FALLBACK_MAGIC.length + 12 + 16);
|
||||||
|
const key = this.deriveFallbackKey();
|
||||||
|
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
|
||||||
|
decipher.setAuthTag(tag);
|
||||||
|
return Buffer.concat([decipher.update(data), decipher.final()]).toString('utf8');
|
||||||
|
}
|
||||||
|
|
||||||
|
private writeFallbackSealedToken(token: string): void {
|
||||||
|
const key = this.deriveFallbackKey();
|
||||||
|
const iv = crypto.randomBytes(12);
|
||||||
|
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
|
||||||
|
const enc = Buffer.concat([cipher.update(token, 'utf8'), cipher.final()]);
|
||||||
|
const tag = cipher.getAuthTag();
|
||||||
|
const payload = Buffer.concat([FALLBACK_MAGIC, iv, tag, enc]);
|
||||||
|
fs.writeFileSync(licenseFallbackSealedPath(this.userData), payload, { mode: 0o600 });
|
||||||
|
}
|
||||||
|
|
||||||
|
private readSealedToken(): string | null {
|
||||||
|
const sealedPath = licenseEncryptedPath(this.userData);
|
||||||
|
const fallbackPath = licenseFallbackSealedPath(this.userData);
|
||||||
|
|
||||||
|
if (fs.existsSync(sealedPath)) {
|
||||||
|
if (!safeStorage.isEncryptionAvailable()) {
|
||||||
|
throw new Error(
|
||||||
|
'safeStorage недоступен: есть license.sealed, но расшифровать нельзя (часто перенос профиля или WSL без keyring). Удалите файл лицензии в настройках приложения или используйте DND_LICENSE_INSECURE_FILE_STORAGE=1 и активируйте заново.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const buf = fs.readFileSync(sealedPath);
|
||||||
|
return safeStorage.decryptString(buf);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fs.existsSync(fallbackPath)) {
|
||||||
|
return this.readFallbackSealedToken();
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private writeSealedToken(token: string): void {
|
private writeSealedToken(token: string): void {
|
||||||
if (!safeStorage.isEncryptionAvailable()) {
|
|
||||||
throw new Error('safeStorage недоступен: нельзя сохранить лицензию на этой системе');
|
|
||||||
}
|
|
||||||
fs.mkdirSync(this.userData, { recursive: true });
|
fs.mkdirSync(this.userData, { recursive: true });
|
||||||
const enc = safeStorage.encryptString(token);
|
if (safeStorage.isEncryptionAvailable()) {
|
||||||
fs.writeFileSync(licenseEncryptedPath(this.userData), enc);
|
const enc = safeStorage.encryptString(token);
|
||||||
|
fs.writeFileSync(licenseEncryptedPath(this.userData), enc);
|
||||||
|
try {
|
||||||
|
fs.unlinkSync(licenseFallbackSealedPath(this.userData));
|
||||||
|
} catch {
|
||||||
|
/* ok */
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (this.isInsecureFileStorageAllowed()) {
|
||||||
|
this.writeFallbackSealedToken(token);
|
||||||
|
try {
|
||||||
|
fs.unlinkSync(licenseEncryptedPath(this.userData));
|
||||||
|
} catch {
|
||||||
|
/* ok */
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw new Error(
|
||||||
|
'safeStorage недоступен: нельзя сохранить лицензию на этой системе (типично WSL без gnome-keyring). Запустите с переменной DND_LICENSE_INSECURE_FILE_STORAGE=1 — токен будет сохранён в зашифрованном файле (слабее OS-хранилища); либо настройте Secret Service / gnome-keyring.',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
private clearSealedTokenFile(): void {
|
private clearSealedTokenFile(): void {
|
||||||
@@ -77,6 +173,11 @@ export class LicenseService {
|
|||||||
} catch {
|
} catch {
|
||||||
/* ok */
|
/* ok */
|
||||||
}
|
}
|
||||||
|
try {
|
||||||
|
fs.unlinkSync(licenseFallbackSealedPath(this.userData));
|
||||||
|
} catch {
|
||||||
|
/* ok */
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** База для `POST /v1/activate` (и при желании совпадает с сервером отзыва). */
|
/** База для `POST /v1/activate` (и при желании совпадает с сервером отзыва). */
|
||||||
|
|||||||
@@ -4,6 +4,11 @@ export function licenseEncryptedPath(userData: string): string {
|
|||||||
return path.join(userData, 'license.sealed');
|
return path.join(userData, 'license.sealed');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Fallback, если нет OS keychain (WSL без gnome-keyring и т.п.); только при DND_LICENSE_INSECURE_FILE_STORAGE=1. */
|
||||||
|
export function licenseFallbackSealedPath(userData: string): string {
|
||||||
|
return path.join(userData, 'license.sealed.fallback');
|
||||||
|
}
|
||||||
|
|
||||||
export function deviceIdPath(userData: string): string {
|
export function deviceIdPath(userData: string): string {
|
||||||
return path.join(userData, 'device.id');
|
return path.join(userData, 'device.id');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,15 +14,17 @@ void test('collectReferencedAssetIds: превью, видео и аудио', (
|
|||||||
scenes: {
|
scenes: {
|
||||||
s1: {
|
s1: {
|
||||||
previewAssetId: 'pr' as AssetId,
|
previewAssetId: 'pr' as AssetId,
|
||||||
|
previewThumbAssetId: 'th' as AssetId,
|
||||||
media: {
|
media: {
|
||||||
videos: ['v1' as AssetId],
|
videos: ['v1' as AssetId],
|
||||||
audios: [{ assetId: 'a1' as AssetId, autoplay: true, loop: true }],
|
audios: [{ assetId: 'a1' as AssetId, autoplay: true, loop: true }],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
campaignAudios: [{ assetId: 'ca1' as AssetId, autoplay: true, loop: true }],
|
||||||
} as unknown as Project;
|
} as unknown as Project;
|
||||||
const s = collectReferencedAssetIds(p);
|
const s = collectReferencedAssetIds(p);
|
||||||
assert.deepEqual([...s].sort(), ['a1', 'pr', 'v1'].sort());
|
assert.deepEqual([...s].sort(), ['a1', 'ca1', 'pr', 'th', 'v1'].sort());
|
||||||
});
|
});
|
||||||
|
|
||||||
void test('reconcileAssetFiles: снимает осиротевшие assets и удаляет файлы', async () => {
|
void test('reconcileAssetFiles: снимает осиротевшие assets и удаляет файлы', async () => {
|
||||||
@@ -62,11 +64,13 @@ void test('reconcileAssetFiles: снимает осиротевшие assets и
|
|||||||
const prev: Project = {
|
const prev: Project = {
|
||||||
...base,
|
...base,
|
||||||
scenes: {},
|
scenes: {},
|
||||||
|
campaignAudios: [],
|
||||||
assets: { orphan: asset } as Project['assets'],
|
assets: { orphan: asset } as Project['assets'],
|
||||||
};
|
};
|
||||||
const next: Project = {
|
const next: Project = {
|
||||||
...base,
|
...base,
|
||||||
scenes: {},
|
scenes: {},
|
||||||
|
campaignAudios: [],
|
||||||
assets: { orphan: asset } as Project['assets'],
|
assets: { orphan: asset } as Project['assets'],
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -111,7 +115,7 @@ void test('reconcileAssetFiles: удаляет файл при исключен
|
|||||||
} as unknown as Project;
|
} as unknown as Project;
|
||||||
|
|
||||||
const prev: Project = { ...base, assets: { gone: asset } as Project['assets'] };
|
const prev: Project = { ...base, assets: { gone: asset } as Project['assets'] };
|
||||||
const next: Project = { ...base, assets: {} as Project['assets'] };
|
const next: Project = { ...base, campaignAudios: [], assets: {} as Project['assets'] };
|
||||||
|
|
||||||
const out = await reconcileAssetFiles(prev, next, tmp);
|
const out = await reconcileAssetFiles(prev, next, tmp);
|
||||||
assert.deepEqual(out.assets, {});
|
assert.deepEqual(out.assets, {});
|
||||||
|
|||||||
@@ -9,9 +9,11 @@ export function collectReferencedAssetIds(p: Project): Set<AssetId> {
|
|||||||
const refs = new Set<AssetId>();
|
const refs = new Set<AssetId>();
|
||||||
for (const sc of Object.values(p.scenes)) {
|
for (const sc of Object.values(p.scenes)) {
|
||||||
if (sc.previewAssetId) refs.add(sc.previewAssetId);
|
if (sc.previewAssetId) refs.add(sc.previewAssetId);
|
||||||
|
if (sc.previewThumbAssetId) refs.add(sc.previewThumbAssetId);
|
||||||
for (const vid of sc.media.videos) refs.add(vid);
|
for (const vid of sc.media.videos) refs.add(vid);
|
||||||
for (const au of sc.media.audios) refs.add(au.assetId);
|
for (const au of sc.media.audios) refs.add(au.assetId);
|
||||||
}
|
}
|
||||||
|
for (const au of p.campaignAudios) refs.add(au.assetId);
|
||||||
return refs;
|
return refs;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,82 @@
|
|||||||
|
import crypto from 'node:crypto';
|
||||||
|
import fs from 'node:fs/promises';
|
||||||
|
import path from 'node:path';
|
||||||
|
|
||||||
|
import { readProjectJsonFromZip } from './yauzlProjectZip';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Подменяет файл `finalPath` готовым `completedSrc` (обычно `*.dnd.zip.tmp`).
|
||||||
|
* Нельзя сначала удалять `finalPath`: при сбое rename после rm проект теряется (Windows/антивирус).
|
||||||
|
*/
|
||||||
|
export async function replaceFileAtomic(completedSrc: string, finalPath: string): Promise<void> {
|
||||||
|
if (completedSrc === finalPath) return;
|
||||||
|
|
||||||
|
const stSrc = await fs.stat(completedSrc).catch(() => null);
|
||||||
|
if (!stSrc?.isFile() || stSrc.size === 0) {
|
||||||
|
throw new Error(`replaceFileAtomic: нет или пустой источник: ${completedSrc}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await fs.rename(completedSrc, finalPath);
|
||||||
|
return;
|
||||||
|
} catch (first: unknown) {
|
||||||
|
const c = (first as NodeJS.ErrnoException).code;
|
||||||
|
if (c === 'EXDEV') {
|
||||||
|
await fs.copyFile(completedSrc, finalPath);
|
||||||
|
await fs.unlink(completedSrc).catch(() => undefined);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Windows: чаще всего EEXIST — целевой файл есть, rename не перезаписывает; идём через backup ниже.
|
||||||
|
}
|
||||||
|
|
||||||
|
const stFinal = await fs.stat(finalPath).catch(() => null);
|
||||||
|
if (!stFinal?.isFile()) {
|
||||||
|
try {
|
||||||
|
await fs.rename(completedSrc, finalPath);
|
||||||
|
return;
|
||||||
|
} catch (again: unknown) {
|
||||||
|
throw again instanceof Error ? again : new Error(String(again));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const backupPath = `${finalPath}.bak.${Date.now().toString(36)}_${crypto.randomBytes(4).toString('hex')}`;
|
||||||
|
await fs.rename(finalPath, backupPath);
|
||||||
|
try {
|
||||||
|
await fs.rename(completedSrc, finalPath);
|
||||||
|
} catch (place: unknown) {
|
||||||
|
await fs.rename(backupPath, finalPath).catch(() => undefined);
|
||||||
|
throw place instanceof Error ? place : new Error(String(place));
|
||||||
|
}
|
||||||
|
await fs.unlink(backupPath).catch(() => undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Если сохранение оборвалось, остаётся только `*.dnd.zip.tmp` — восстанавливаем в `*.dnd.zip`. */
|
||||||
|
export async function recoverOrphanDndZipTmpInRoot(root: string): Promise<void> {
|
||||||
|
let names: string[];
|
||||||
|
try {
|
||||||
|
names = await fs.readdir(root);
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (const name of names) {
|
||||||
|
if (!name.endsWith('.dnd.zip.tmp')) continue;
|
||||||
|
const tmpPath = path.join(root, name);
|
||||||
|
const finalName = name.slice(0, -'.tmp'.length);
|
||||||
|
if (!finalName.endsWith('.dnd.zip')) continue;
|
||||||
|
const finalPath = path.join(root, finalName);
|
||||||
|
try {
|
||||||
|
await fs.access(finalPath);
|
||||||
|
continue;
|
||||||
|
} catch {
|
||||||
|
/* final отсутствует — пробуем поднять из tmp */
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const st = await fs.stat(tmpPath);
|
||||||
|
if (!st.isFile() || st.size < 22) continue;
|
||||||
|
await readProjectJsonFromZip(tmpPath);
|
||||||
|
await fs.rename(tmpPath, finalPath);
|
||||||
|
} catch {
|
||||||
|
/* битый tmp не трогаем */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import test from 'node:test';
|
||||||
|
|
||||||
|
import { rmWithRetries } from './fsRetry';
|
||||||
|
|
||||||
|
void test('rmWithRetries: retries on EPERM and then succeeds', async () => {
|
||||||
|
let calls = 0;
|
||||||
|
const rm = () => {
|
||||||
|
calls += 1;
|
||||||
|
if (calls < 3) {
|
||||||
|
const err = new Error('nope') as Error & { code: string };
|
||||||
|
err.code = 'EPERM';
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
return Promise.resolve();
|
||||||
|
};
|
||||||
|
await rmWithRetries(rm, 'x', { force: true }, 5);
|
||||||
|
assert.equal(calls, 3);
|
||||||
|
});
|
||||||
|
|
||||||
|
void test('rmWithRetries: does not retry on ENOENT', async () => {
|
||||||
|
let calls = 0;
|
||||||
|
const rm = () => {
|
||||||
|
calls += 1;
|
||||||
|
const err = new Error('missing') as Error & { code: string };
|
||||||
|
err.code = 'ENOENT';
|
||||||
|
return Promise.reject(err);
|
||||||
|
};
|
||||||
|
await assert.rejects(() => rmWithRetries(rm, 'x', { force: true }, 5), /missing/);
|
||||||
|
assert.equal(calls, 1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
type RmLike = (path: string, opts: { recursive?: boolean; force?: boolean }) => Promise<void>;
|
||||||
|
|
||||||
|
function isRetryableRmError(err: unknown): boolean {
|
||||||
|
if (!err || typeof err !== 'object') return false;
|
||||||
|
const code = (err as { code?: unknown }).code;
|
||||||
|
return code === 'EBUSY' || code === 'EPERM' || code === 'EACCES';
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function rmWithRetries(
|
||||||
|
rm: RmLike,
|
||||||
|
targetPath: string,
|
||||||
|
opts: { recursive?: boolean; force?: boolean },
|
||||||
|
retries = 6,
|
||||||
|
): Promise<void> {
|
||||||
|
let attempt = 0;
|
||||||
|
// Windows: file locks/antivirus/indexers can cause transient EPERM/EBUSY.
|
||||||
|
// We retry a few times before surfacing the error.
|
||||||
|
// Delays: 20, 40, 80, 160, 320, 640ms (capped by retries).
|
||||||
|
for (;;) {
|
||||||
|
try {
|
||||||
|
await rm(targetPath, opts);
|
||||||
|
return;
|
||||||
|
} catch (e) {
|
||||||
|
attempt += 1;
|
||||||
|
if (attempt > retries || !isRetryableRmError(e)) {
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
const delayMs = Math.min(800, 20 * 2 ** (attempt - 1));
|
||||||
|
await new Promise((r) => setTimeout(r, delayMs));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import type { Buffer } from 'node:buffer';
|
||||||
|
|
||||||
|
export type OptimizeImageImportResult = {
|
||||||
|
buffer: Buffer;
|
||||||
|
mime: string;
|
||||||
|
ext: string;
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
passthrough: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function optimizeImageBufferVisuallyLossless(
|
||||||
|
input: Buffer,
|
||||||
|
): Promise<OptimizeImageImportResult>;
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
/**
|
||||||
|
* Visually lossless re-encode for imported raster images (same pixel dimensions).
|
||||||
|
* Node-only; shared by the main app and ../project-converter (monorepo sibling).
|
||||||
|
*/
|
||||||
|
import sharp from 'sharp';
|
||||||
|
|
||||||
|
/** @typedef {import('node:buffer').Buffer} Buffer */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @typedef {Object} OptimizeImageImportResult
|
||||||
|
* @property {Buffer} buffer
|
||||||
|
* @property {string} mime
|
||||||
|
* @property {string} ext filename extension without dot (e.g. webp, jpg, png)
|
||||||
|
* @property {number} width
|
||||||
|
* @property {number} height
|
||||||
|
* @property {boolean} passthrough true if original bytes were kept
|
||||||
|
*/
|
||||||
|
|
||||||
|
const WEBP_EFFORT = 6;
|
||||||
|
const RASTER_QUALITY = 95;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {Buffer} buf
|
||||||
|
* @param {import('sharp').Metadata | null} meta
|
||||||
|
* @returns {OptimizeImageImportResult}
|
||||||
|
*/
|
||||||
|
function makePassthrough(buf, meta) {
|
||||||
|
const fmt = meta?.format;
|
||||||
|
if (fmt === 'jpeg' || fmt === 'jpg') {
|
||||||
|
return {
|
||||||
|
buffer: buf,
|
||||||
|
mime: 'image/jpeg',
|
||||||
|
ext: 'jpg',
|
||||||
|
width: meta?.width ?? 0,
|
||||||
|
height: meta?.height ?? 0,
|
||||||
|
passthrough: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (fmt === 'png') {
|
||||||
|
return {
|
||||||
|
buffer: buf,
|
||||||
|
mime: 'image/png',
|
||||||
|
ext: 'png',
|
||||||
|
width: meta?.width ?? 0,
|
||||||
|
height: meta?.height ?? 0,
|
||||||
|
passthrough: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (fmt === 'webp') {
|
||||||
|
return {
|
||||||
|
buffer: buf,
|
||||||
|
mime: 'image/webp',
|
||||||
|
ext: 'webp',
|
||||||
|
width: meta?.width ?? 0,
|
||||||
|
height: meta?.height ?? 0,
|
||||||
|
passthrough: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (fmt === 'gif') {
|
||||||
|
return {
|
||||||
|
buffer: buf,
|
||||||
|
mime: 'image/gif',
|
||||||
|
ext: 'gif',
|
||||||
|
width: meta?.width ?? 0,
|
||||||
|
height: meta?.height ?? 0,
|
||||||
|
passthrough: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (fmt === 'tiff' || fmt === 'tif') {
|
||||||
|
return {
|
||||||
|
buffer: buf,
|
||||||
|
mime: 'image/tiff',
|
||||||
|
ext: 'tiff',
|
||||||
|
width: meta?.width ?? 0,
|
||||||
|
height: meta?.height ?? 0,
|
||||||
|
passthrough: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (fmt === 'bmp') {
|
||||||
|
return {
|
||||||
|
buffer: buf,
|
||||||
|
mime: 'image/bmp',
|
||||||
|
ext: 'bmp',
|
||||||
|
width: meta?.width ?? 0,
|
||||||
|
height: meta?.height ?? 0,
|
||||||
|
passthrough: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
buffer: buf,
|
||||||
|
mime: 'application/octet-stream',
|
||||||
|
ext: 'bin',
|
||||||
|
width: meta?.width ?? 0,
|
||||||
|
height: meta?.height ?? 0,
|
||||||
|
passthrough: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {Buffer} outBuf
|
||||||
|
* @param {number} w0
|
||||||
|
* @param {number} h0
|
||||||
|
*/
|
||||||
|
async function sameDimensionsOrThrow(outBuf, w0, h0) {
|
||||||
|
const m = await sharp(outBuf).metadata();
|
||||||
|
if ((m.width ?? 0) !== w0 || (m.height ?? 0) !== h0) {
|
||||||
|
const err = new Error('encode changed dimensions');
|
||||||
|
err.code = 'DIM';
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {Buffer} src
|
||||||
|
* @returns {Promise<OptimizeImageImportResult>}
|
||||||
|
*/
|
||||||
|
export async function optimizeImageBufferVisuallyLossless(src) {
|
||||||
|
const input = Buffer.isBuffer(src) ? src : Buffer.from(src);
|
||||||
|
if (input.length === 0) {
|
||||||
|
return makePassthrough(input, { width: 0, height: 0, format: 'png' });
|
||||||
|
}
|
||||||
|
|
||||||
|
let meta0;
|
||||||
|
try {
|
||||||
|
meta0 = await sharp(input, { failOn: 'error', unlimited: true }).metadata();
|
||||||
|
} catch {
|
||||||
|
return makePassthrough(input, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
const width = meta0.width ?? 0;
|
||||||
|
const height = meta0.height ?? 0;
|
||||||
|
if (width <= 0 || height <= 0) {
|
||||||
|
return makePassthrough(input, meta0);
|
||||||
|
}
|
||||||
|
|
||||||
|
const pages = meta0.pages ?? 1;
|
||||||
|
if (pages > 1) {
|
||||||
|
return makePassthrough(input, meta0);
|
||||||
|
}
|
||||||
|
|
||||||
|
const rawFmt = meta0.format;
|
||||||
|
if (rawFmt === 'svg' || rawFmt === 'pdf' || rawFmt === 'heif' || rawFmt === 'jxl' || rawFmt === 'vips') {
|
||||||
|
return makePassthrough(input, meta0);
|
||||||
|
}
|
||||||
|
|
||||||
|
const hasAlpha = meta0.hasAlpha === true;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (hasAlpha) {
|
||||||
|
const webpLo = await sharp(input)
|
||||||
|
.rotate()
|
||||||
|
.ensureAlpha()
|
||||||
|
.webp({ lossless: true, effort: WEBP_EFFORT })
|
||||||
|
.toBuffer();
|
||||||
|
const pngOut = await sharp(input)
|
||||||
|
.rotate()
|
||||||
|
.ensureAlpha()
|
||||||
|
.png({ compressionLevel: 9, adaptiveFiltering: true })
|
||||||
|
.toBuffer();
|
||||||
|
await sameDimensionsOrThrow(webpLo, width, height);
|
||||||
|
await sameDimensionsOrThrow(pngOut, width, height);
|
||||||
|
|
||||||
|
const pickWebp = webpLo.length <= pngOut.length;
|
||||||
|
const outBuf = pickWebp ? webpLo : pngOut;
|
||||||
|
if (outBuf.length >= input.length) {
|
||||||
|
return makePassthrough(input, meta0);
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
buffer: outBuf,
|
||||||
|
mime: pickWebp ? 'image/webp' : 'image/png',
|
||||||
|
ext: pickWebp ? 'webp' : 'png',
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
passthrough: false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const webpColor = await sharp(input)
|
||||||
|
.rotate()
|
||||||
|
.webp({
|
||||||
|
quality: RASTER_QUALITY,
|
||||||
|
nearLossless: true,
|
||||||
|
effort: WEBP_EFFORT,
|
||||||
|
smartSubsample: false,
|
||||||
|
})
|
||||||
|
.toBuffer();
|
||||||
|
const jpegColor = await sharp(input)
|
||||||
|
.rotate()
|
||||||
|
.jpeg({
|
||||||
|
quality: RASTER_QUALITY,
|
||||||
|
chromaSubsampling: '4:4:4',
|
||||||
|
mozjpeg: true,
|
||||||
|
optimizeScans: true,
|
||||||
|
})
|
||||||
|
.toBuffer();
|
||||||
|
await sameDimensionsOrThrow(webpColor, width, height);
|
||||||
|
await sameDimensionsOrThrow(jpegColor, width, height);
|
||||||
|
|
||||||
|
const useWebp = webpColor.length <= jpegColor.length;
|
||||||
|
const outBuf = useWebp ? webpColor : jpegColor;
|
||||||
|
if (outBuf.length >= input.length) {
|
||||||
|
return makePassthrough(input, meta0);
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
buffer: outBuf,
|
||||||
|
mime: useWebp ? 'image/webp' : 'image/jpeg',
|
||||||
|
ext: useWebp ? 'webp' : 'jpg',
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
passthrough: false,
|
||||||
|
};
|
||||||
|
} catch (e) {
|
||||||
|
if (e && typeof e === 'object' && /** @type {{ code?: string }} */ (e).code === 'DIM') {
|
||||||
|
return makePassthrough(input, meta0);
|
||||||
|
}
|
||||||
|
return makePassthrough(input, meta0);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import test from 'node:test';
|
||||||
|
|
||||||
|
import sharp from 'sharp';
|
||||||
|
|
||||||
|
import { optimizeImageBufferVisuallyLossless } from './optimizeImageImport.lib.mjs';
|
||||||
|
|
||||||
|
void test('optimizeImageBufferVisuallyLossless: preserves dimensions for opaque RGB', async () => {
|
||||||
|
const input = await sharp({
|
||||||
|
create: {
|
||||||
|
width: 400,
|
||||||
|
height: 300,
|
||||||
|
channels: 3,
|
||||||
|
background: { r: 10, g: 100, b: 200 },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.png({ compressionLevel: 0 })
|
||||||
|
.toBuffer();
|
||||||
|
|
||||||
|
const out = await optimizeImageBufferVisuallyLossless(input);
|
||||||
|
assert.equal(out.passthrough, false);
|
||||||
|
assert.ok(out.buffer.length > 0);
|
||||||
|
assert.ok(out.buffer.length < input.length);
|
||||||
|
const meta = await sharp(out.buffer).metadata();
|
||||||
|
assert.equal(meta.width, 400);
|
||||||
|
assert.equal(meta.height, 300);
|
||||||
|
});
|
||||||
|
|
||||||
|
void test('optimizeImageBufferVisuallyLossless: preserves dimensions for alpha', async () => {
|
||||||
|
const input = await sharp({
|
||||||
|
create: {
|
||||||
|
width: 200,
|
||||||
|
height: 200,
|
||||||
|
channels: 4,
|
||||||
|
background: { r: 255, g: 0, b: 0, alpha: 0.5 },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.png({ compressionLevel: 0 })
|
||||||
|
.toBuffer();
|
||||||
|
|
||||||
|
const out = await optimizeImageBufferVisuallyLossless(input);
|
||||||
|
assert.equal(out.passthrough, false);
|
||||||
|
assert.ok(out.mime === 'image/webp' || out.mime === 'image/png');
|
||||||
|
assert.ok(out.buffer.length < input.length);
|
||||||
|
const meta = await sharp(out.buffer).metadata();
|
||||||
|
assert.equal(meta.width, 200);
|
||||||
|
assert.equal(meta.height, 200);
|
||||||
|
assert.equal(meta.hasAlpha, true);
|
||||||
|
});
|
||||||
|
|
||||||
|
void test('optimizeImageBufferVisuallyLossless: non-image buffer is passthrough', async () => {
|
||||||
|
const out = await optimizeImageBufferVisuallyLossless(Buffer.from('not an image'));
|
||||||
|
assert.equal(out.passthrough, true);
|
||||||
|
});
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import fs from 'node:fs/promises';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import test from 'node:test';
|
||||||
|
|
||||||
|
import { replaceFileAtomic } from './atomicReplace';
|
||||||
|
|
||||||
|
void test('replaceFileAtomic: replaces existing file without deleting before rename succeeds', async () => {
|
||||||
|
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'dnd-replace-'));
|
||||||
|
const finalPath = path.join(dir, 'out.bin');
|
||||||
|
const tmpPath = path.join(dir, 'out.bin.tmp');
|
||||||
|
await fs.writeFile(finalPath, 'previous', 'utf8');
|
||||||
|
await fs.writeFile(tmpPath, 'updated-content', 'utf8');
|
||||||
|
await replaceFileAtomic(tmpPath, finalPath);
|
||||||
|
assert.equal(await fs.readFile(finalPath, 'utf8'), 'updated-content');
|
||||||
|
await assert.rejects(() => fs.stat(tmpPath));
|
||||||
|
});
|
||||||
|
|
||||||
|
void test('replaceFileAtomic: rejects empty source', async () => {
|
||||||
|
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'dnd-replace-'));
|
||||||
|
const finalPath = path.join(dir, 'out.bin');
|
||||||
|
const tmpPath = path.join(dir, 'out.bin.tmp');
|
||||||
|
await fs.writeFile(finalPath, 'x', 'utf8');
|
||||||
|
await fs.writeFile(tmpPath, '', 'utf8');
|
||||||
|
await assert.rejects(() => replaceFileAtomic(tmpPath, finalPath));
|
||||||
|
assert.equal(await fs.readFile(finalPath, 'utf8'), 'x');
|
||||||
|
});
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import fs from 'node:fs/promises';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import test from 'node:test';
|
||||||
|
|
||||||
|
import sharp from 'sharp';
|
||||||
|
|
||||||
|
import { generateScenePreviewThumbnailBytes, SCENE_PREVIEW_THUMB_MAX_PX } from './scenePreviewThumbnail';
|
||||||
|
|
||||||
|
void test('generateScenePreviewThumbnailBytes: image scales to max edge', async () => {
|
||||||
|
const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'dnd-thumb-test-'));
|
||||||
|
const src = path.join(tmp, 'wide.png');
|
||||||
|
await sharp({
|
||||||
|
create: {
|
||||||
|
width: 800,
|
||||||
|
height: 400,
|
||||||
|
channels: 3,
|
||||||
|
background: { r: 200, g: 40, b: 40 },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.png()
|
||||||
|
.toFile(src);
|
||||||
|
|
||||||
|
const buf = await generateScenePreviewThumbnailBytes(src, 'image');
|
||||||
|
assert.ok(buf !== null);
|
||||||
|
assert.ok(buf.length > 0);
|
||||||
|
const meta = await sharp(buf).metadata();
|
||||||
|
assert.equal(typeof meta.width, 'number');
|
||||||
|
assert.equal(typeof meta.height, 'number');
|
||||||
|
assert.ok(meta.width > 0 && meta.height > 0);
|
||||||
|
assert.ok(Math.max(meta.width, meta.height) <= SCENE_PREVIEW_THUMB_MAX_PX);
|
||||||
|
|
||||||
|
await fs.rm(tmp, { recursive: true, force: true });
|
||||||
|
});
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
import { execFile } from 'node:child_process';
|
||||||
|
import fs from 'node:fs/promises';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { promisify } from 'node:util';
|
||||||
|
|
||||||
|
import ffmpegStatic from 'ffmpeg-static';
|
||||||
|
import sharp from 'sharp';
|
||||||
|
|
||||||
|
const execFileAsync = promisify(execFile);
|
||||||
|
|
||||||
|
/** Longest edge; presentation uses the original asset. */
|
||||||
|
export const SCENE_PREVIEW_THUMB_MAX_PX = 320;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds a small WebP still for graph/list previews. Returns null if generation fails (import still succeeds).
|
||||||
|
*/
|
||||||
|
export async function generateScenePreviewThumbnailBytes(
|
||||||
|
sourceAbsPath: string,
|
||||||
|
kind: 'image' | 'video',
|
||||||
|
): Promise<Buffer | null> {
|
||||||
|
try {
|
||||||
|
if (kind === 'image') {
|
||||||
|
return await sharp(sourceAbsPath)
|
||||||
|
.rotate()
|
||||||
|
.resize(SCENE_PREVIEW_THUMB_MAX_PX, SCENE_PREVIEW_THUMB_MAX_PX, {
|
||||||
|
fit: 'inside',
|
||||||
|
withoutEnlargement: true,
|
||||||
|
})
|
||||||
|
.webp({ quality: 82 })
|
||||||
|
.toBuffer();
|
||||||
|
}
|
||||||
|
|
||||||
|
const ffmpegPath = ffmpegStatic;
|
||||||
|
if (!ffmpegPath) return null;
|
||||||
|
|
||||||
|
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'dnd-thumb-'));
|
||||||
|
const tmpPng = path.join(tmpDir, 'frame.png');
|
||||||
|
try {
|
||||||
|
const seekSeconds = ['0.5', '0.25', '0'];
|
||||||
|
let extracted = false;
|
||||||
|
for (const ss of seekSeconds) {
|
||||||
|
await fs.rm(tmpPng, { force: true }).catch(() => undefined);
|
||||||
|
try {
|
||||||
|
await execFileAsync(
|
||||||
|
ffmpegPath,
|
||||||
|
[
|
||||||
|
'-hide_banner',
|
||||||
|
'-loglevel',
|
||||||
|
'error',
|
||||||
|
'-y',
|
||||||
|
'-ss',
|
||||||
|
ss,
|
||||||
|
'-i',
|
||||||
|
sourceAbsPath,
|
||||||
|
'-frames:v',
|
||||||
|
'1',
|
||||||
|
tmpPng,
|
||||||
|
],
|
||||||
|
{ maxBuffer: 16 * 1024 * 1024 },
|
||||||
|
);
|
||||||
|
const st = await fs.stat(tmpPng).catch(() => null);
|
||||||
|
if (st !== null && st.isFile() && st.size > 0) {
|
||||||
|
extracted = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* try next seek */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!extracted) return null;
|
||||||
|
|
||||||
|
return await sharp(tmpPng)
|
||||||
|
.resize(SCENE_PREVIEW_THUMB_MAX_PX, SCENE_PREVIEW_THUMB_MAX_PX, {
|
||||||
|
fit: 'inside',
|
||||||
|
withoutEnlargement: true,
|
||||||
|
})
|
||||||
|
.webp({ quality: 82 })
|
||||||
|
.toBuffer();
|
||||||
|
} finally {
|
||||||
|
await fs.rm(tmpDir, { recursive: true, force: true }).catch(() => undefined);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,12 +5,18 @@ import yauzl from 'yauzl';
|
|||||||
|
|
||||||
import type { Project } from '../../shared/types';
|
import type { Project } from '../../shared/types';
|
||||||
|
|
||||||
export function unzipToDir(zipPath: string, outDir: string): Promise<void> {
|
export function unzipToDir(
|
||||||
|
zipPath: string,
|
||||||
|
outDir: string,
|
||||||
|
onProgress?: (done: number, total: number) => void,
|
||||||
|
): Promise<void> {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
yauzl.open(zipPath, { lazyEntries: true }, (err, zip) => {
|
yauzl.open(zipPath, { lazyEntries: true }, (err, zip) => {
|
||||||
if (err) return reject(err);
|
if (err) return reject(err);
|
||||||
const zipFile = zip;
|
const zipFile = zip;
|
||||||
let settled = false;
|
let settled = false;
|
||||||
|
const total = zipFile.entryCount || 0;
|
||||||
|
let done = 0;
|
||||||
|
|
||||||
const safeClose = (): void => {
|
const safeClose = (): void => {
|
||||||
try {
|
try {
|
||||||
@@ -37,6 +43,14 @@ export function unzipToDir(zipPath: string, outDir: string): Promise<void> {
|
|||||||
zipFile.readEntry();
|
zipFile.readEntry();
|
||||||
zipFile.on('entry', (entry: yauzl.Entry) => {
|
zipFile.on('entry', (entry: yauzl.Entry) => {
|
||||||
if (settled) return;
|
if (settled) return;
|
||||||
|
done += 1;
|
||||||
|
if (onProgress && total > 0) {
|
||||||
|
try {
|
||||||
|
onProgress(done, total);
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
const filePath = path.join(outDir, entry.fileName);
|
const filePath = path.join(outDir, entry.fileName);
|
||||||
if (entry.fileName.endsWith('/')) {
|
if (entry.fileName.endsWith('/')) {
|
||||||
fssync.mkdirSync(filePath, { recursive: true });
|
fssync.mkdirSync(filePath, { recursive: true });
|
||||||
|
|||||||
@@ -51,3 +51,48 @@ void test('readProjectJsonFromZip: sequential reads close yauzl (no EMFILE)', as
|
|||||||
|
|
||||||
await fs.rm(tmp, { recursive: true, force: true });
|
await fs.rm(tmp, { recursive: true, force: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
void test('readProjectJsonFromZip: campaignAudios round-trips inside project.json', async () => {
|
||||||
|
const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'dnd-zip-campaign-'));
|
||||||
|
const zipPath = path.join(tmp, 'test.dnd.zip');
|
||||||
|
const assetId = 'audio_asset_1';
|
||||||
|
const minimal = {
|
||||||
|
id: 'p1',
|
||||||
|
meta: {
|
||||||
|
name: 'n',
|
||||||
|
fileBaseName: 'f',
|
||||||
|
createdAt: '2020-01-01',
|
||||||
|
updatedAt: '2020-01-01',
|
||||||
|
createdWithAppVersion: '1',
|
||||||
|
appVersion: '1',
|
||||||
|
schemaVersion: PROJECT_SCHEMA_VERSION,
|
||||||
|
},
|
||||||
|
scenes: {},
|
||||||
|
assets: {},
|
||||||
|
campaignAudios: [{ assetId, autoplay: true, loop: false }],
|
||||||
|
currentSceneId: null,
|
||||||
|
currentGraphNodeId: null,
|
||||||
|
sceneGraphNodes: [],
|
||||||
|
sceneGraphEdges: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
const zipfile = new ZipFile();
|
||||||
|
zipfile.addBuffer(Buffer.from(JSON.stringify(minimal), 'utf8'), 'project.json', { compressionLevel: 9 });
|
||||||
|
const out = fssync.createWriteStream(zipPath);
|
||||||
|
const done = new Promise<void>((resolve, reject) => {
|
||||||
|
out.on('close', resolve);
|
||||||
|
out.on('error', reject);
|
||||||
|
});
|
||||||
|
zipfile.outputStream.pipe(out);
|
||||||
|
zipfile.end();
|
||||||
|
await done;
|
||||||
|
|
||||||
|
const p = await readProjectJsonFromZip(zipPath);
|
||||||
|
assert.ok(Array.isArray((p as { campaignAudios?: unknown }).campaignAudios));
|
||||||
|
assert.deepEqual(
|
||||||
|
(p as { campaignAudios: typeof minimal.campaignAudios }).campaignAudios,
|
||||||
|
minimal.campaignAudios,
|
||||||
|
);
|
||||||
|
|
||||||
|
await fs.rm(tmp, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import test from 'node:test';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||||
|
|
||||||
|
void test('zipStore: deleteProjectById removes legacy sibling copies by entry.fileName', () => {
|
||||||
|
const src = fs.readFileSync(path.join(here, 'zipStore.ts'), 'utf8');
|
||||||
|
assert.match(src, /async deleteProjectById/);
|
||||||
|
assert.match(src, /for \(const legacyRoot of getLegacyProjectsRootDirs\(\)\)/);
|
||||||
|
assert.match(src, /path\.join\(legacyRoot, entry\.fileName\)/);
|
||||||
|
assert.match(src, /rmWithRetries\(fs\.rm, legacyZipPath, \{ force: true \}\)/);
|
||||||
|
});
|
||||||
|
|
||||||
|
void test('zipStore: legacy migration moves or copy\\+rm so deleted projects are not resurrected', () => {
|
||||||
|
const src = fs.readFileSync(path.join(here, 'zipStore.ts'), 'utf8');
|
||||||
|
assert.match(src, /migrateLegacyProjectZipsIfNeeded/);
|
||||||
|
assert.match(src, /if \(destZips\.has\(name\)\) continue/);
|
||||||
|
assert.match(src, /await fs\.rename\(from, to\)/);
|
||||||
|
assert.match(src, /await fs\.copyFile\(from, to\)/);
|
||||||
|
assert.match(src, /rmWithRetries\(fs\.rm, from, \{ force: true \}\)/);
|
||||||
|
assert.match(src, /не «возрождались»/);
|
||||||
|
});
|
||||||
|
|
||||||
|
void test('zipStore: openProjectById flushes pending saveNow before cache reset', () => {
|
||||||
|
const src = fs.readFileSync(path.join(here, 'zipStore.ts'), 'utf8');
|
||||||
|
// When switching projects we rm cacheDir and unzip zip; ensure pending debounced pack is flushed first.
|
||||||
|
assert.match(src, /async openProjectById/);
|
||||||
|
assert.match(src, /if \(this\.openProject\)\s*\{\s*await this\.saveNow\(\);\s*\}/);
|
||||||
|
assert.match(src, /await fs\.rm\(cacheDir, \{ recursive: true, force: true \}\)/);
|
||||||
|
assert.match(src, /await unzipToDir\(zipPath, cacheDir\)/);
|
||||||
|
});
|
||||||
|
|
||||||
|
void test('zipStore: exportProjectZipToPath flushes saveNow for currently open project', () => {
|
||||||
|
const src = fs.readFileSync(path.join(here, 'zipStore.ts'), 'utf8');
|
||||||
|
assert.match(src, /async exportProjectZipToPath/);
|
||||||
|
assert.match(src, /if \(this\.openProject\?\.id === projectId\)\s*\{\s*await this\.saveNow\(\);\s*\}/);
|
||||||
|
assert.match(src, /await fs\.copyFile\(src, dest\)/);
|
||||||
|
});
|
||||||
|
|
||||||
|
void test('zipStore: normalizeScene defaults previewThumbAssetId for older projects', () => {
|
||||||
|
const src = fs.readFileSync(path.join(here, 'zipStore.ts'), 'utf8');
|
||||||
|
assert.match(src, /previewThumbAssetId/);
|
||||||
|
assert.match(src, /function normalizeScene\(/);
|
||||||
|
});
|
||||||
|
|
||||||
|
void test('zipStore: listProjects skips unreadable archives', () => {
|
||||||
|
const src = fs.readFileSync(path.join(here, 'zipStore.ts'), 'utf8');
|
||||||
|
assert.match(
|
||||||
|
src,
|
||||||
|
/async listProjects[\s\S]+?for \(const filePath of files\)[\s\S]+?try \{[\s\S]+?readProjectJsonFromZip/,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
void test('atomicReplace: replaceFileAtomic must not rm destination before successful commit', () => {
|
||||||
|
const src = fs.readFileSync(path.join(here, 'atomicReplace.ts'), 'utf8');
|
||||||
|
const i = src.indexOf('export async function replaceFileAtomic');
|
||||||
|
assert.ok(i >= 0);
|
||||||
|
const j = src.indexOf('export async function recoverOrphanDndZipTmpInRoot', i);
|
||||||
|
assert.ok(j > i);
|
||||||
|
const block = src.slice(i, j);
|
||||||
|
assert.match(block, /rename\(finalPath, backupPath\)/);
|
||||||
|
assert.doesNotMatch(block, /\.rm\(\s*finalPath/);
|
||||||
|
});
|
||||||
+298
-55
@@ -24,7 +24,11 @@ import { asAssetId, asGraphNodeId, asProjectId } from '../../shared/types/ids';
|
|||||||
import { getAppSemanticVersion } from '../versionInfo';
|
import { getAppSemanticVersion } from '../versionInfo';
|
||||||
|
|
||||||
import { reconcileAssetFiles } from './assetPrune';
|
import { reconcileAssetFiles } from './assetPrune';
|
||||||
|
import { recoverOrphanDndZipTmpInRoot, replaceFileAtomic } from './atomicReplace';
|
||||||
|
import { rmWithRetries } from './fsRetry';
|
||||||
|
import { optimizeImageBufferVisuallyLossless } from './optimizeImageImport.lib.mjs';
|
||||||
import { getLegacyProjectsRootDirs, getProjectsCacheRootDir, getProjectsRootDir } from './paths';
|
import { getLegacyProjectsRootDirs, getProjectsCacheRootDir, getProjectsRootDir } from './paths';
|
||||||
|
import { generateScenePreviewThumbnailBytes } from './scenePreviewThumbnail';
|
||||||
import { readProjectJsonFromZip, unzipToDir } from './yauzlProjectZip';
|
import { readProjectJsonFromZip, unzipToDir } from './yauzlProjectZip';
|
||||||
|
|
||||||
type ProjectIndexEntry = {
|
type ProjectIndexEntry = {
|
||||||
@@ -72,6 +76,7 @@ export class ZipProjectStore {
|
|||||||
await fs.mkdir(getProjectsRootDir(), { recursive: true });
|
await fs.mkdir(getProjectsRootDir(), { recursive: true });
|
||||||
await fs.mkdir(getProjectsCacheRootDir(), { recursive: true });
|
await fs.mkdir(getProjectsCacheRootDir(), { recursive: true });
|
||||||
await this.migrateLegacyProjectZipsIfNeeded();
|
await this.migrateLegacyProjectZipsIfNeeded();
|
||||||
|
await recoverOrphanDndZipTmpInRoot(getProjectsRootDir());
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Копирует .dnd.zip из каталогов с «чужим» app name, если в текущем каталоге такого файла ещё нет. */
|
/** Копирует .dnd.zip из каталогов с «чужим» app name, если в текущем каталоге такого файла ещё нет. */
|
||||||
@@ -99,7 +104,21 @@ export class ZipProjectStore {
|
|||||||
try {
|
try {
|
||||||
const st = await fs.stat(from);
|
const st = await fs.stat(from);
|
||||||
if (!st.isFile()) continue;
|
if (!st.isFile()) continue;
|
||||||
await fs.copyFile(from, to);
|
// Переносим (а не копируем), чтобы:
|
||||||
|
// - не было дублей между разными appName
|
||||||
|
// - удалённые пользователем проекты не «возрождались» при следующем ensureRoots()
|
||||||
|
try {
|
||||||
|
await fs.rename(from, to);
|
||||||
|
} catch {
|
||||||
|
await fs.copyFile(from, to);
|
||||||
|
try {
|
||||||
|
await rmWithRetries(fs.rm, from, { force: true });
|
||||||
|
} catch {
|
||||||
|
// best effort: если zip уже скопирован в dest, миграцию считаем успешной;
|
||||||
|
// legacy-копия может остаться (например из-за lock/AV), но удаление проекта
|
||||||
|
// затем чистит legacy по fileName.
|
||||||
|
}
|
||||||
|
}
|
||||||
destZips.add(name);
|
destZips.add(name);
|
||||||
} catch {
|
} catch {
|
||||||
/* ignore */
|
/* ignore */
|
||||||
@@ -118,13 +137,17 @@ export class ZipProjectStore {
|
|||||||
|
|
||||||
const out: ProjectIndexEntry[] = [];
|
const out: ProjectIndexEntry[] = [];
|
||||||
for (const filePath of files) {
|
for (const filePath of files) {
|
||||||
const project = await readProjectJsonFromZip(filePath);
|
try {
|
||||||
out.push({
|
const project = await readProjectJsonFromZip(filePath);
|
||||||
id: project.id,
|
out.push({
|
||||||
name: project.meta.name,
|
id: project.id,
|
||||||
updatedAt: project.meta.updatedAt,
|
name: project.meta.name,
|
||||||
fileName: path.basename(filePath),
|
updatedAt: project.meta.updatedAt,
|
||||||
});
|
fileName: path.basename(filePath),
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
// Один битый архив не должен скрывать остальные проекты в списке.
|
||||||
|
}
|
||||||
}
|
}
|
||||||
out.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
|
out.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
|
||||||
return out;
|
return out;
|
||||||
@@ -150,6 +173,7 @@ export class ZipProjectStore {
|
|||||||
},
|
},
|
||||||
scenes: {},
|
scenes: {},
|
||||||
assets: {},
|
assets: {},
|
||||||
|
campaignAudios: [],
|
||||||
currentSceneId: null,
|
currentSceneId: null,
|
||||||
currentGraphNodeId: null,
|
currentGraphNodeId: null,
|
||||||
sceneGraphNodes: [],
|
sceneGraphNodes: [],
|
||||||
@@ -167,6 +191,11 @@ export class ZipProjectStore {
|
|||||||
|
|
||||||
async openProjectById(projectId: ProjectId): Promise<Project> {
|
async openProjectById(projectId: ProjectId): Promise<Project> {
|
||||||
await this.ensureRoots();
|
await this.ensureRoots();
|
||||||
|
// Mutations are persisted to cache immediately, but zip packing is debounced (queueSave).
|
||||||
|
// When switching projects we delete the cache and restore it from the zip, so flush pending saves first.
|
||||||
|
if (this.openProject) {
|
||||||
|
await this.saveNow();
|
||||||
|
}
|
||||||
this.projectSession += 1;
|
this.projectSession += 1;
|
||||||
const list = await this.listProjects();
|
const list = await this.listProjects();
|
||||||
const entry = list.find((p) => p.id === projectId);
|
const entry = list.find((p) => p.id === projectId);
|
||||||
@@ -192,6 +221,44 @@ export class ZipProjectStore {
|
|||||||
return project;
|
return project;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async openProjectByIdWithProgress(
|
||||||
|
projectId: ProjectId,
|
||||||
|
onUnzipPercent: (pct: number) => void,
|
||||||
|
): Promise<Project> {
|
||||||
|
await this.ensureRoots();
|
||||||
|
// Mutations are persisted to cache immediately, but zip packing is debounced (queueSave).
|
||||||
|
// When switching projects we delete the cache and restore it from the zip, so flush pending saves first.
|
||||||
|
if (this.openProject) {
|
||||||
|
await this.saveNow();
|
||||||
|
}
|
||||||
|
this.projectSession += 1;
|
||||||
|
const list = await this.listProjects();
|
||||||
|
const entry = list.find((p) => p.id === projectId);
|
||||||
|
if (!entry) {
|
||||||
|
throw new Error('Project not found');
|
||||||
|
}
|
||||||
|
const zipPath = path.join(getProjectsRootDir(), entry.fileName);
|
||||||
|
const cacheDir = path.join(getProjectsCacheRootDir(), projectId);
|
||||||
|
|
||||||
|
await fs.rm(cacheDir, { recursive: true, force: true });
|
||||||
|
await fs.mkdir(cacheDir, { recursive: true });
|
||||||
|
await unzipToDir(zipPath, cacheDir, (done, total) => {
|
||||||
|
const pct = total > 0 ? Math.round((done / total) * 100) : 0;
|
||||||
|
onUnzipPercent(Math.max(0, Math.min(100, pct)));
|
||||||
|
});
|
||||||
|
|
||||||
|
const projectPath = path.join(cacheDir, 'project.json');
|
||||||
|
const projectRaw = await fs.readFile(projectPath, 'utf8');
|
||||||
|
const parsed = JSON.parse(projectRaw) as unknown as Project;
|
||||||
|
const project = normalizeProject(parsed);
|
||||||
|
const fileBaseName = entry.fileName.replace(/\.dnd\.zip$/iu, '');
|
||||||
|
project.meta.fileBaseName = project.meta.fileBaseName.trim().length
|
||||||
|
? project.meta.fileBaseName
|
||||||
|
: fileBaseName;
|
||||||
|
this.openProject = { id: projectId, zipPath, cacheDir, projectPath, project };
|
||||||
|
return project;
|
||||||
|
}
|
||||||
|
|
||||||
getOpenProject(): Project | null {
|
getOpenProject(): Project | null {
|
||||||
return this.openProject?.project ?? null;
|
return this.openProject?.project ?? null;
|
||||||
}
|
}
|
||||||
@@ -224,35 +291,78 @@ export class ZipProjectStore {
|
|||||||
const sc = open.project.scenes[sceneId];
|
const sc = open.project.scenes[sceneId];
|
||||||
if (!sc) throw new Error('Scene not found');
|
if (!sc) throw new Error('Scene not found');
|
||||||
|
|
||||||
const kind = classifyMediaPath(filePath);
|
const kind0 = classifyMediaPath(filePath);
|
||||||
if (kind?.type !== 'image' && kind?.type !== 'video') {
|
if (!kind0 || (kind0.type !== 'image' && kind0.type !== 'video')) {
|
||||||
throw new Error('Файл превью должен быть изображением или видео');
|
throw new Error('Файл превью должен быть изображением или видео');
|
||||||
}
|
}
|
||||||
|
let kind: MediaKind = kind0;
|
||||||
|
|
||||||
const buf = await fs.readFile(filePath);
|
const buf = await fs.readFile(filePath);
|
||||||
const sha256 = crypto.createHash('sha256').update(buf).digest('hex');
|
|
||||||
const id = asAssetId(this.randomId());
|
const id = asAssetId(this.randomId());
|
||||||
const orig = path.basename(filePath);
|
const orig = path.basename(filePath);
|
||||||
const safeOrig = sanitizeFileName(orig);
|
let safeOrig = sanitizeFileName(orig);
|
||||||
const relPath = `assets/${id}_${safeOrig}`;
|
let relPath = `assets/${id}_${safeOrig}`;
|
||||||
const abs = path.join(open.cacheDir, relPath);
|
let abs = path.join(open.cacheDir, relPath);
|
||||||
|
let writeBuf = buf;
|
||||||
|
let storedOrig = orig;
|
||||||
|
|
||||||
|
if (kind.type === 'image') {
|
||||||
|
const opt = await optimizeImageBufferVisuallyLossless(buf);
|
||||||
|
if (!opt.passthrough) {
|
||||||
|
writeBuf = Buffer.from(opt.buffer);
|
||||||
|
kind = { type: 'image', mime: opt.mime };
|
||||||
|
safeOrig = sanitizeFileName(`${path.parse(orig).name}.${opt.ext}`);
|
||||||
|
relPath = `assets/${id}_${safeOrig}`;
|
||||||
|
abs = path.join(open.cacheDir, relPath);
|
||||||
|
storedOrig = `${path.parse(orig).name}.${opt.ext}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const sha256 = crypto.createHash('sha256').update(writeBuf).digest('hex');
|
||||||
await fs.mkdir(path.dirname(abs), { recursive: true });
|
await fs.mkdir(path.dirname(abs), { recursive: true });
|
||||||
await fs.copyFile(filePath, abs);
|
await fs.writeFile(abs, writeBuf);
|
||||||
const asset = buildMediaAsset(id, kind, orig, relPath, sha256, buf.length);
|
const asset = buildMediaAsset(id, kind, storedOrig, relPath, sha256, writeBuf.length);
|
||||||
|
|
||||||
|
const thumbKind = kind.type === 'image' ? 'image' : 'video';
|
||||||
|
const thumbBytes = await generateScenePreviewThumbnailBytes(abs, thumbKind);
|
||||||
|
let thumbAsset: MediaAsset | null = null;
|
||||||
|
let thumbId: AssetId | null = null;
|
||||||
|
if (thumbBytes !== null && thumbBytes.length > 0) {
|
||||||
|
thumbId = asAssetId(this.randomId());
|
||||||
|
const thumbRelPath = `assets/${thumbId}_preview_thumb.webp`;
|
||||||
|
const thumbAbs = path.join(open.cacheDir, thumbRelPath);
|
||||||
|
await fs.writeFile(thumbAbs, thumbBytes);
|
||||||
|
const thumbSha = crypto.createHash('sha256').update(thumbBytes).digest('hex');
|
||||||
|
const thumbOrigName = `${path.parse(safeOrig).name}_preview_thumb.webp`;
|
||||||
|
thumbAsset = buildMediaAsset(
|
||||||
|
thumbId,
|
||||||
|
{ type: 'image', mime: 'image/webp' },
|
||||||
|
thumbOrigName,
|
||||||
|
thumbRelPath,
|
||||||
|
thumbSha,
|
||||||
|
thumbBytes.length,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const oldPreviewId = sc.previewAssetId;
|
const oldPreviewId = sc.previewAssetId;
|
||||||
|
const oldThumbId = sc.previewThumbAssetId ?? null;
|
||||||
|
|
||||||
await this.updateProject((p) => {
|
await this.updateProject((p) => {
|
||||||
const scene = p.scenes[sceneId];
|
const scene = p.scenes[sceneId];
|
||||||
if (!scene) throw new Error('Scene not found');
|
if (!scene) throw new Error('Scene not found');
|
||||||
let assets: Record<AssetId, MediaAsset> = { ...p.assets };
|
let assets: Record<AssetId, MediaAsset> = { ...p.assets };
|
||||||
if (oldPreviewId) {
|
const drop = new Set<AssetId>();
|
||||||
assets = Object.fromEntries(Object.entries(assets).filter(([k]) => k !== oldPreviewId)) as Record<
|
if (oldPreviewId) drop.add(oldPreviewId);
|
||||||
AssetId,
|
if (oldThumbId) drop.add(oldThumbId);
|
||||||
MediaAsset
|
if (drop.size > 0) {
|
||||||
>;
|
assets = Object.fromEntries(
|
||||||
|
Object.entries(assets).filter(([k]) => !drop.has(k as AssetId)),
|
||||||
|
) as Record<AssetId, MediaAsset>;
|
||||||
}
|
}
|
||||||
assets[id] = asset;
|
assets[id] = asset;
|
||||||
|
if (thumbAsset !== null && thumbId !== null) {
|
||||||
|
assets[thumbId] = thumbAsset;
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
...p,
|
...p,
|
||||||
assets,
|
assets,
|
||||||
@@ -262,6 +372,7 @@ export class ZipProjectStore {
|
|||||||
...scene,
|
...scene,
|
||||||
previewAssetId: id,
|
previewAssetId: id,
|
||||||
previewAssetType: kind.type,
|
previewAssetType: kind.type,
|
||||||
|
previewThumbAssetId: thumbId,
|
||||||
previewVideoAutostart: kind.type === 'video' ? scene.previewVideoAutostart : false,
|
previewVideoAutostart: kind.type === 'video' ? scene.previewVideoAutostart : false,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -279,14 +390,17 @@ export class ZipProjectStore {
|
|||||||
const sc = open.project.scenes[sceneId];
|
const sc = open.project.scenes[sceneId];
|
||||||
if (!sc) throw new Error('Scene not found');
|
if (!sc) throw new Error('Scene not found');
|
||||||
const oldId = sc.previewAssetId;
|
const oldId = sc.previewAssetId;
|
||||||
if (!oldId) {
|
const oldThumbId = sc.previewThumbAssetId ?? null;
|
||||||
|
if (!oldId && !oldThumbId) {
|
||||||
return open.project;
|
return open.project;
|
||||||
}
|
}
|
||||||
await this.updateProject((p) => {
|
await this.updateProject((p) => {
|
||||||
const assets = Object.fromEntries(Object.entries(p.assets).filter(([k]) => k !== oldId)) as Record<
|
const drop = new Set<AssetId>();
|
||||||
AssetId,
|
if (oldId) drop.add(oldId);
|
||||||
MediaAsset
|
if (oldThumbId) drop.add(oldThumbId);
|
||||||
>;
|
const assets = Object.fromEntries(
|
||||||
|
Object.entries(p.assets).filter(([k]) => !drop.has(k as AssetId)),
|
||||||
|
) as Record<AssetId, MediaAsset>;
|
||||||
return {
|
return {
|
||||||
...p,
|
...p,
|
||||||
assets,
|
assets,
|
||||||
@@ -296,6 +410,7 @@ export class ZipProjectStore {
|
|||||||
...p.scenes[sceneId],
|
...p.scenes[sceneId],
|
||||||
previewAssetId: null,
|
previewAssetId: null,
|
||||||
previewAssetType: null,
|
previewAssetType: null,
|
||||||
|
previewThumbAssetId: null,
|
||||||
previewVideoAutostart: false,
|
previewVideoAutostart: false,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -334,6 +449,7 @@ export class ZipProjectStore {
|
|||||||
layout: { x: 0, y: 0 },
|
layout: { x: 0, y: 0 },
|
||||||
previewAssetId: null,
|
previewAssetId: null,
|
||||||
previewAssetType: null,
|
previewAssetType: null,
|
||||||
|
previewThumbAssetId: null,
|
||||||
previewVideoAutostart: false,
|
previewVideoAutostart: false,
|
||||||
previewRotationDeg: 0,
|
previewRotationDeg: 0,
|
||||||
} satisfies Scene);
|
} satisfies Scene);
|
||||||
@@ -344,6 +460,9 @@ export class ZipProjectStore {
|
|||||||
...(patch.description !== undefined ? { description: patch.description } : null),
|
...(patch.description !== undefined ? { description: patch.description } : null),
|
||||||
...(patch.previewAssetId !== undefined ? { previewAssetId: patch.previewAssetId } : null),
|
...(patch.previewAssetId !== undefined ? { previewAssetId: patch.previewAssetId } : null),
|
||||||
...(patch.previewAssetType !== undefined ? { previewAssetType: patch.previewAssetType } : null),
|
...(patch.previewAssetType !== undefined ? { previewAssetType: patch.previewAssetType } : null),
|
||||||
|
...(patch.previewThumbAssetId !== undefined
|
||||||
|
? { previewThumbAssetId: patch.previewThumbAssetId }
|
||||||
|
: null),
|
||||||
...(patch.previewVideoAutostart !== undefined
|
...(patch.previewVideoAutostart !== undefined
|
||||||
? { previewVideoAutostart: patch.previewVideoAutostart }
|
? { previewVideoAutostart: patch.previewVideoAutostart }
|
||||||
: null),
|
: null),
|
||||||
@@ -574,6 +693,61 @@ export class ZipProjectStore {
|
|||||||
return { project: latest, imported: staged };
|
return { project: latest, imported: staged };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Copies audio files into cache `assets/` and registers them on the project as campaign audio.
|
||||||
|
*/
|
||||||
|
async importCampaignAudioFiles(filePaths: string[]): Promise<{ project: Project; imported: MediaAsset[] }> {
|
||||||
|
const open = this.openProject;
|
||||||
|
if (!open) throw new Error('No open project');
|
||||||
|
if (filePaths.length === 0) {
|
||||||
|
return { project: open.project, imported: [] };
|
||||||
|
}
|
||||||
|
|
||||||
|
const staged: MediaAsset[] = [];
|
||||||
|
for (const filePath of filePaths) {
|
||||||
|
const kind = classifyMediaPath(filePath);
|
||||||
|
if (kind?.type !== 'audio') continue;
|
||||||
|
const buf = await fs.readFile(filePath);
|
||||||
|
const sha256 = crypto.createHash('sha256').update(buf).digest('hex');
|
||||||
|
const id = asAssetId(this.randomId());
|
||||||
|
const orig = path.basename(filePath);
|
||||||
|
const safeOrig = sanitizeFileName(orig);
|
||||||
|
const relPath = `assets/${id}_${safeOrig}`;
|
||||||
|
const abs = path.join(open.cacheDir, relPath);
|
||||||
|
await fs.mkdir(path.dirname(abs), { recursive: true });
|
||||||
|
await fs.copyFile(filePath, abs);
|
||||||
|
staged.push(buildMediaAsset(id, kind, orig, relPath, sha256, buf.length));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (staged.length === 0) {
|
||||||
|
return { project: open.project, imported: [] };
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.updateProject((p) => {
|
||||||
|
const assets = { ...p.assets };
|
||||||
|
const campaignAudios = [...p.campaignAudios];
|
||||||
|
for (const asset of staged) {
|
||||||
|
assets[asset.id] = asset;
|
||||||
|
if (asset.type !== 'audio') continue;
|
||||||
|
campaignAudios.push({ assetId: asset.id, autoplay: true, loop: true });
|
||||||
|
}
|
||||||
|
return { ...p, assets, campaignAudios };
|
||||||
|
});
|
||||||
|
|
||||||
|
const latest = this.getOpenProject();
|
||||||
|
if (!latest) throw new Error('No open project');
|
||||||
|
return { project: latest, imported: staged };
|
||||||
|
}
|
||||||
|
|
||||||
|
async setCampaignAudios(audios: Project['campaignAudios']): Promise<Project> {
|
||||||
|
const open = this.openProject;
|
||||||
|
if (!open) throw new Error('No open project');
|
||||||
|
await this.updateProject((p) => ({ ...p, campaignAudios: Array.isArray(audios) ? audios : [] }));
|
||||||
|
const latest = this.getOpenProject();
|
||||||
|
if (!latest) throw new Error('No open project');
|
||||||
|
return latest;
|
||||||
|
}
|
||||||
|
|
||||||
async saveNow(): Promise<void> {
|
async saveNow(): Promise<void> {
|
||||||
const open = this.openProject;
|
const open = this.openProject;
|
||||||
if (!open) return;
|
if (!open) return;
|
||||||
@@ -700,6 +874,11 @@ export class ZipProjectStore {
|
|||||||
const tmpPath = `${zipPath}.tmp`;
|
const tmpPath = `${zipPath}.tmp`;
|
||||||
await fs.mkdir(path.dirname(zipPath), { recursive: true });
|
await fs.mkdir(path.dirname(zipPath), { recursive: true });
|
||||||
await zipDir(cacheDir, tmpPath);
|
await zipDir(cacheDir, tmpPath);
|
||||||
|
const st = await fs.stat(tmpPath).catch(() => null);
|
||||||
|
if (!st?.isFile() || st.size < 22) {
|
||||||
|
await fs.unlink(tmpPath).catch(() => undefined);
|
||||||
|
throw new Error('Сборка архива проекта не удалась (пустой или повреждённый временный файл)');
|
||||||
|
}
|
||||||
await replaceFileAtomic(tmpPath, zipPath);
|
await replaceFileAtomic(tmpPath, zipPath);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -708,7 +887,10 @@ export class ZipProjectStore {
|
|||||||
* Если архив уже лежит в `projects`, только открывает.
|
* Если архив уже лежит в `projects`, только открывает.
|
||||||
* При конфликте `id` с другим файлом перезаписывает `project.json` в копии с новым id.
|
* При конфликте `id` с другим файлом перезаписывает `project.json` в копии с новым id.
|
||||||
*/
|
*/
|
||||||
async importProjectFromExternalZip(sourcePath: string): Promise<Project> {
|
async importProjectFromExternalZip(
|
||||||
|
sourcePath: string,
|
||||||
|
onProgress?: (p: { stage: 'copy' | 'unzip' | 'done'; percent: number; detail?: string }) => void,
|
||||||
|
): Promise<Project> {
|
||||||
await this.ensureRoots();
|
await this.ensureRoots();
|
||||||
const resolved = path.resolve(sourcePath);
|
const resolved = path.resolve(sourcePath);
|
||||||
const st = await fs.stat(resolved).catch(() => null);
|
const st = await fs.stat(resolved).catch(() => null);
|
||||||
@@ -733,7 +915,12 @@ export class ZipProjectStore {
|
|||||||
} else {
|
} else {
|
||||||
destFileName = await uniqueDndZipFileName(root, baseName);
|
destFileName = await uniqueDndZipFileName(root, baseName);
|
||||||
destPath = path.join(root, destFileName);
|
destPath = path.join(root, destFileName);
|
||||||
await fs.copyFile(resolved, destPath);
|
if (onProgress) onProgress({ stage: 'copy', percent: 1, detail: 'Копирование…' });
|
||||||
|
await copyFileWithProgress(resolved, destPath, (pct) => {
|
||||||
|
if (!onProgress) return;
|
||||||
|
// Copy is ~70% of the operation; unzip/open happens after.
|
||||||
|
onProgress({ stage: 'copy', percent: Math.max(1, Math.min(70, pct)), detail: 'Копирование…' });
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
let project = await readProjectJsonFromZip(destPath);
|
let project = await readProjectJsonFromZip(destPath);
|
||||||
@@ -756,12 +943,24 @@ export class ZipProjectStore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
this.projectSession += 1;
|
this.projectSession += 1;
|
||||||
return this.openProjectById(project.id);
|
const opened = await this.openProjectByIdWithProgress(project.id, (pct) => {
|
||||||
|
if (onProgress) onProgress({ stage: 'unzip', percent: pct, detail: 'Распаковка…' });
|
||||||
|
});
|
||||||
|
if (onProgress) onProgress({ stage: 'done', percent: 100, detail: 'Готово' });
|
||||||
|
return opened;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Копия файла проекта в указанный путь (полный путь к `.dnd.zip`). */
|
/** Копия файла проекта в указанный путь (полный путь к `.dnd.zip`). */
|
||||||
async exportProjectZipToPath(projectId: ProjectId, destinationPath: string): Promise<void> {
|
async exportProjectZipToPath(
|
||||||
|
projectId: ProjectId,
|
||||||
|
destinationPath: string,
|
||||||
|
onProgress?: (p: { stage: 'copy' | 'done'; percent: number; detail?: string }) => void,
|
||||||
|
): Promise<void> {
|
||||||
await this.ensureRoots();
|
await this.ensureRoots();
|
||||||
|
// If exporting the currently open project, make sure pending debounced pack is flushed.
|
||||||
|
if (this.openProject?.id === projectId) {
|
||||||
|
await this.saveNow();
|
||||||
|
}
|
||||||
const list = await this.listProjects();
|
const list = await this.listProjects();
|
||||||
const entry = list.find((p) => p.id === projectId);
|
const entry = list.find((p) => p.id === projectId);
|
||||||
if (!entry) {
|
if (!entry) {
|
||||||
@@ -770,7 +969,11 @@ export class ZipProjectStore {
|
|||||||
const src = path.join(getProjectsRootDir(), entry.fileName);
|
const src = path.join(getProjectsRootDir(), entry.fileName);
|
||||||
const dest = path.resolve(destinationPath);
|
const dest = path.resolve(destinationPath);
|
||||||
await fs.mkdir(path.dirname(dest), { recursive: true });
|
await fs.mkdir(path.dirname(dest), { recursive: true });
|
||||||
await fs.copyFile(src, dest);
|
if (onProgress) onProgress({ stage: 'copy', percent: 1, detail: 'Копирование…' });
|
||||||
|
await copyFileWithProgress(src, dest, (pct) => {
|
||||||
|
if (onProgress) onProgress({ stage: 'copy', percent: pct, detail: 'Копирование…' });
|
||||||
|
});
|
||||||
|
if (onProgress) onProgress({ stage: 'done', percent: 100, detail: 'Готово' });
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Удаляет архив проекта и кэш распаковки с диска. Если проект открыт — сбрасывает сессию. */
|
/** Удаляет архив проекта и кэш распаковки с диска. Если проект открыт — сбрасывает сессию. */
|
||||||
@@ -792,8 +995,20 @@ export class ZipProjectStore {
|
|||||||
this.projectSession += 1;
|
this.projectSession += 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
await fs.rm(zipPath, { force: true }).catch(() => undefined);
|
await rmWithRetries(fs.rm, zipPath, { force: true });
|
||||||
await fs.rm(cacheDir, { recursive: true, force: true }).catch(() => undefined);
|
await rmWithRetries(fs.rm, cacheDir, { recursive: true, force: true });
|
||||||
|
|
||||||
|
// Если проект подтянулся миграцией из legacy userData (другое имя приложения),
|
||||||
|
// то после удаления из текущей папки он может снова появиться при следующем ensureRoots().
|
||||||
|
// Поэтому удаляем и legacy-копии архива.
|
||||||
|
for (const legacyRoot of getLegacyProjectsRootDirs()) {
|
||||||
|
const legacyZipPath = path.join(legacyRoot, entry.fileName);
|
||||||
|
try {
|
||||||
|
await rmWithRetries(fs.rm, legacyZipPath, { force: true });
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private randomId(): string {
|
private randomId(): string {
|
||||||
@@ -901,6 +1116,8 @@ function normalizeScene(s: Scene): Scene {
|
|||||||
(s as unknown as { previewVideoAutostostart?: boolean; previewVideoAutostart?: boolean })
|
(s as unknown as { previewVideoAutostostart?: boolean; previewVideoAutostart?: boolean })
|
||||||
.previewVideoAutostart,
|
.previewVideoAutostart,
|
||||||
);
|
);
|
||||||
|
const previewThumbAssetId =
|
||||||
|
(s as unknown as { previewThumbAssetId?: AssetId | null }).previewThumbAssetId ?? null;
|
||||||
|
|
||||||
const rawAudios = Array.isArray(raw.audios) ? raw.audios : [];
|
const rawAudios = Array.isArray(raw.audios) ? raw.audios : [];
|
||||||
const audios = rawAudios
|
const audios = rawAudios
|
||||||
@@ -925,6 +1142,7 @@ function normalizeScene(s: Scene): Scene {
|
|||||||
...s,
|
...s,
|
||||||
previewAssetId: previewAssetId ?? null,
|
previewAssetId: previewAssetId ?? null,
|
||||||
previewAssetType,
|
previewAssetType,
|
||||||
|
previewThumbAssetId,
|
||||||
previewVideoAutostart,
|
previewVideoAutostart,
|
||||||
previewRotationDeg,
|
previewRotationDeg,
|
||||||
layout: layoutIn ?? { x: 0, y: 0 },
|
layout: layoutIn ?? { x: 0, y: 0 },
|
||||||
@@ -955,6 +1173,18 @@ function normalizeProject(p: Project): Project {
|
|||||||
}
|
}
|
||||||
sceneGraphNodes = normalizeSceneGraphNodeFlags(sceneGraphNodes);
|
sceneGraphNodes = normalizeSceneGraphNodeFlags(sceneGraphNodes);
|
||||||
const currentGraphNodeId = (p as { currentGraphNodeId?: GraphNodeId | null }).currentGraphNodeId ?? null;
|
const currentGraphNodeId = (p as { currentGraphNodeId?: GraphNodeId | null }).currentGraphNodeId ?? null;
|
||||||
|
const rawCampaignAudios = (p as unknown as { campaignAudios?: unknown[] }).campaignAudios;
|
||||||
|
const campaignAudios = (Array.isArray(rawCampaignAudios) ? rawCampaignAudios : [])
|
||||||
|
.map((a) => {
|
||||||
|
if (typeof a === 'string') return { assetId: a as AssetId, autoplay: false, loop: false };
|
||||||
|
if (a && typeof a === 'object') {
|
||||||
|
const obj = a as { assetId?: AssetId; autoplay?: boolean; loop?: boolean };
|
||||||
|
if (!obj.assetId) return null;
|
||||||
|
return { assetId: obj.assetId, autoplay: Boolean(obj.autoplay), loop: Boolean(obj.loop) };
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
})
|
||||||
|
.filter((x): x is { assetId: AssetId; autoplay: boolean; loop: boolean } => Boolean(x));
|
||||||
const metaRaw = p.meta as unknown as { createdWithAppVersion?: string; appVersion?: string };
|
const metaRaw = p.meta as unknown as { createdWithAppVersion?: string; appVersion?: string };
|
||||||
const createdWithAppVersion = (() => {
|
const createdWithAppVersion = (() => {
|
||||||
const c = metaRaw.createdWithAppVersion?.trim();
|
const c = metaRaw.createdWithAppVersion?.trim();
|
||||||
@@ -974,6 +1204,7 @@ function normalizeProject(p: Project): Project {
|
|||||||
schemaVersion: PROJECT_SCHEMA_VERSION,
|
schemaVersion: PROJECT_SCHEMA_VERSION,
|
||||||
},
|
},
|
||||||
scenes,
|
scenes,
|
||||||
|
campaignAudios,
|
||||||
sceneGraphNodes,
|
sceneGraphNodes,
|
||||||
sceneGraphEdges,
|
sceneGraphEdges,
|
||||||
currentGraphNodeId,
|
currentGraphNodeId,
|
||||||
@@ -1006,18 +1237,38 @@ async function uniqueDndZipFileName(root: string, preferredBaseFileName: string)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function replaceFileAtomic(srcPath: string, destPath: string): Promise<void> {
|
async function copyFileWithProgress(
|
||||||
try {
|
src: string,
|
||||||
await fs.rename(srcPath, destPath);
|
dest: string,
|
||||||
} catch {
|
onPercent: (pct: number) => void,
|
||||||
try {
|
): Promise<void> {
|
||||||
await fs.rm(destPath, { force: true });
|
const st = await fs.stat(src);
|
||||||
await fs.rename(srcPath, destPath);
|
const total = st.size || 0;
|
||||||
} catch (second: unknown) {
|
if (total <= 0) {
|
||||||
await fs.unlink(srcPath).catch(() => undefined);
|
await fs.copyFile(src, dest);
|
||||||
throw second instanceof Error ? second : new Error(String(second));
|
onPercent(100);
|
||||||
}
|
return;
|
||||||
}
|
}
|
||||||
|
await fs.mkdir(path.dirname(dest), { recursive: true });
|
||||||
|
await new Promise<void>((resolve, reject) => {
|
||||||
|
let done = 0;
|
||||||
|
const rs = fssync.createReadStream(src);
|
||||||
|
const ws = fssync.createWriteStream(dest);
|
||||||
|
const onErr = (e: unknown) => reject(e instanceof Error ? e : new Error(String(e)));
|
||||||
|
rs.on('error', onErr);
|
||||||
|
ws.on('error', onErr);
|
||||||
|
rs.on('data', (chunk: Buffer) => {
|
||||||
|
done += chunk.length;
|
||||||
|
const pct = Math.round((done / total) * 100);
|
||||||
|
try {
|
||||||
|
onPercent(Math.max(0, Math.min(100, pct)));
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
});
|
||||||
|
ws.on('close', () => resolve());
|
||||||
|
rs.pipe(ws);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
type MediaKind = { type: MediaAssetType; mime: string };
|
type MediaKind = { type: MediaAssetType; mime: string };
|
||||||
@@ -1034,6 +1285,8 @@ function classifyMediaPath(filePath: string): MediaKind | null {
|
|||||||
return { type: 'image', mime: 'image/webp' };
|
return { type: 'image', mime: 'image/webp' };
|
||||||
case '.gif':
|
case '.gif':
|
||||||
return { type: 'image', mime: 'image/gif' };
|
return { type: 'image', mime: 'image/gif' };
|
||||||
|
case '.bmp':
|
||||||
|
return { type: 'image', mime: 'image/bmp' };
|
||||||
case '.mp4':
|
case '.mp4':
|
||||||
return { type: 'video', mime: 'video/mp4' };
|
return { type: 'video', mime: 'video/mp4' };
|
||||||
case '.webm':
|
case '.webm':
|
||||||
@@ -1083,17 +1336,7 @@ async function atomicWriteFile(filePath: string, contents: string): Promise<void
|
|||||||
await fs.mkdir(dir, { recursive: true });
|
await fs.mkdir(dir, { recursive: true });
|
||||||
const tmp = path.join(dir, `.tmp_${path.basename(filePath)}_${crypto.randomBytes(8).toString('hex')}`);
|
const tmp = path.join(dir, `.tmp_${path.basename(filePath)}_${crypto.randomBytes(8).toString('hex')}`);
|
||||||
await fs.writeFile(tmp, contents, 'utf8');
|
await fs.writeFile(tmp, contents, 'utf8');
|
||||||
try {
|
await replaceFileAtomic(tmp, filePath);
|
||||||
await fs.rename(tmp, filePath);
|
|
||||||
} catch {
|
|
||||||
try {
|
|
||||||
await fs.rm(filePath, { force: true });
|
|
||||||
await fs.rename(tmp, filePath);
|
|
||||||
} catch (second: unknown) {
|
|
||||||
await fs.unlink(tmp).catch(() => undefined);
|
|
||||||
throw second instanceof Error ? second : new Error(String(second));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Уже сжатые контейнеры/кодеки — в ZIP кладём без deflate, качество не трогаем; project.json и сырьё — deflate 9. */
|
/** Уже сжатые контейнеры/кодеки — в ZIP кладём без deflate, качество не трогаем; project.json и сырьё — deflate 9. */
|
||||||
|
|||||||
@@ -0,0 +1,127 @@
|
|||||||
|
import { app, dialog } from 'electron';
|
||||||
|
import { autoUpdater } from 'electron-updater';
|
||||||
|
|
||||||
|
import {
|
||||||
|
ipcChannels,
|
||||||
|
type UpdaterCheckResponse,
|
||||||
|
type UpdaterDownloadResponse,
|
||||||
|
} from '../../shared/ipc/contracts';
|
||||||
|
import type { IpcRegisterHandler } from '../ipc/router';
|
||||||
|
import { addLicenseChangeListener } from '../license/licenseService';
|
||||||
|
import type { LicenseService } from '../license/licenseService';
|
||||||
|
|
||||||
|
const STARTUP_CHECK_DELAY_MS = 12_000;
|
||||||
|
/** Не дёргать сервер чаще (смена лицензии / повторные emit). */
|
||||||
|
const RE_CHECK_COOLDOWN_MS = 30_000;
|
||||||
|
|
||||||
|
let lastCheckAt = 0;
|
||||||
|
/** Ручная установка: не показывать второй диалог из `update-downloaded`. */
|
||||||
|
let suppressAutoInstallDialog = false;
|
||||||
|
|
||||||
|
type RegisterFn = IpcRegisterHandler;
|
||||||
|
|
||||||
|
function isLicensedForUpdates(licenseService: LicenseService): boolean {
|
||||||
|
const snap = licenseService.getStatusSync();
|
||||||
|
return snap.active;
|
||||||
|
}
|
||||||
|
|
||||||
|
function maybeCheckForUpdates(licenseService: LicenseService, ignoreCooldown: boolean): void {
|
||||||
|
if (!app.isPackaged) return;
|
||||||
|
if (!isLicensedForUpdates(licenseService)) return;
|
||||||
|
const now = Date.now();
|
||||||
|
if (!ignoreCooldown && now - lastCheckAt < RE_CHECK_COOLDOWN_MS) return;
|
||||||
|
lastCheckAt = now;
|
||||||
|
void autoUpdater.checkForUpdates().catch(() => undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runManualUpdaterCheck(licenseService: LicenseService): Promise<UpdaterCheckResponse> {
|
||||||
|
if (!app.isPackaged) {
|
||||||
|
return { outcome: 'not_packaged' };
|
||||||
|
}
|
||||||
|
if (!isLicensedForUpdates(licenseService)) {
|
||||||
|
return { outcome: 'no_license' };
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const result = await autoUpdater.checkForUpdates();
|
||||||
|
if (result && result.isUpdateAvailable && result.updateInfo.version) {
|
||||||
|
return { outcome: 'available', version: result.updateInfo.version };
|
||||||
|
}
|
||||||
|
return { outcome: 'current', currentVersion: app.getVersion() };
|
||||||
|
} catch (e) {
|
||||||
|
const message = e instanceof Error ? e.message : String(e);
|
||||||
|
return { outcome: 'error', message };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runManualDownloadAndRestart(): Promise<UpdaterDownloadResponse> {
|
||||||
|
if (!app.isPackaged) {
|
||||||
|
return { ok: false, message: 'NOT_PACKAGED' };
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
suppressAutoInstallDialog = true;
|
||||||
|
await autoUpdater.downloadUpdate();
|
||||||
|
autoUpdater.quitAndInstall(false, true);
|
||||||
|
return { ok: true };
|
||||||
|
} catch (e) {
|
||||||
|
suppressAutoInstallDialog = false;
|
||||||
|
const message = e instanceof Error ? e.message : String(e);
|
||||||
|
return { ok: false, message };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function registerUpdaterHandlers(register: RegisterFn, licenseService: LicenseService): void {
|
||||||
|
register(ipcChannels.updater.check, () => runManualUpdaterCheck(licenseService));
|
||||||
|
register(ipcChannels.updater.downloadAndRestart, () => runManualDownloadAndRestart());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Проверка обновлений: только упакованное приложение, только при активной лицензии.
|
||||||
|
* Канал и URL задаются при сборке (`publish` → `app-update.yml` внутри установки).
|
||||||
|
*/
|
||||||
|
export function installAutoUpdater(licenseService: LicenseService, register: RegisterFn): void {
|
||||||
|
registerUpdaterHandlers(register, licenseService);
|
||||||
|
|
||||||
|
if (!app.isPackaged) return;
|
||||||
|
|
||||||
|
const feedOverride = process.env.DND_UPDATE_FEED_URL?.trim();
|
||||||
|
if (feedOverride) {
|
||||||
|
const url = feedOverride.endsWith('/') ? feedOverride : `${feedOverride}/`;
|
||||||
|
autoUpdater.setFeedURL({ provider: 'generic', url });
|
||||||
|
}
|
||||||
|
|
||||||
|
autoUpdater.autoDownload = true;
|
||||||
|
autoUpdater.autoInstallOnAppQuit = true;
|
||||||
|
|
||||||
|
autoUpdater.on('update-downloaded', (info) => {
|
||||||
|
if (suppressAutoInstallDialog) {
|
||||||
|
suppressAutoInstallDialog = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
void dialog
|
||||||
|
.showMessageBox({
|
||||||
|
type: 'info',
|
||||||
|
title: 'DNDGamePlayer',
|
||||||
|
message: `Доступна новая версия ${info.version}. Установить и перезапустить?`,
|
||||||
|
buttons: ['Перезапустить сейчас', 'Позже'],
|
||||||
|
defaultId: 0,
|
||||||
|
cancelId: 1,
|
||||||
|
})
|
||||||
|
.then((r) => {
|
||||||
|
if (r.response === 0) {
|
||||||
|
autoUpdater.quitAndInstall(false, true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
autoUpdater.on('error', () => {
|
||||||
|
/* без console: в production main минифицируется с drop console */
|
||||||
|
});
|
||||||
|
|
||||||
|
addLicenseChangeListener(() => {
|
||||||
|
maybeCheckForUpdates(licenseService, false);
|
||||||
|
});
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
maybeCheckForUpdates(licenseService, true);
|
||||||
|
}, STARTUP_CHECK_DELAY_MS);
|
||||||
|
}
|
||||||
@@ -4,6 +4,8 @@ import { app, BrowserWindow } from 'electron';
|
|||||||
|
|
||||||
import { getAppSemanticVersion } from '../versionInfo';
|
import { getAppSemanticVersion } from '../versionInfo';
|
||||||
|
|
||||||
|
import { loadBrandingWindowIcon } from './brandingIcon';
|
||||||
|
|
||||||
let bootSplashRef: BrowserWindow | null = null;
|
let bootSplashRef: BrowserWindow | null = null;
|
||||||
|
|
||||||
export function getBootSplashWindow(): BrowserWindow | null {
|
export function getBootSplashWindow(): BrowserWindow | null {
|
||||||
@@ -37,6 +39,7 @@ function bootWebPreferences(): Electron.WebPreferences {
|
|||||||
* Показывать после `waitForBootWindowReady`.
|
* Показывать после `waitForBootWindowReady`.
|
||||||
*/
|
*/
|
||||||
export function createBootWindow(): BrowserWindow {
|
export function createBootWindow(): BrowserWindow {
|
||||||
|
const icon = loadBrandingWindowIcon();
|
||||||
const win = new BrowserWindow({
|
const win = new BrowserWindow({
|
||||||
width: 440,
|
width: 440,
|
||||||
height: 420,
|
height: 420,
|
||||||
@@ -50,8 +53,16 @@ export function createBootWindow(): BrowserWindow {
|
|||||||
transparent: false,
|
transparent: false,
|
||||||
backgroundColor: '#09090B',
|
backgroundColor: '#09090B',
|
||||||
roundedCorners: true,
|
roundedCorners: true,
|
||||||
|
...(icon ? { icon } : {}),
|
||||||
webPreferences: bootWebPreferences(),
|
webPreferences: bootWebPreferences(),
|
||||||
});
|
});
|
||||||
|
if (icon) {
|
||||||
|
try {
|
||||||
|
win.setIcon(icon);
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
bootSplashRef = win;
|
bootSplashRef = win;
|
||||||
win.once('closed', () => {
|
win.once('closed', () => {
|
||||||
|
|||||||
@@ -0,0 +1,114 @@
|
|||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
|
||||||
|
import { app, nativeImage } from 'electron';
|
||||||
|
|
||||||
|
let resolved = false;
|
||||||
|
let cached: Electron.NativeImage | undefined;
|
||||||
|
|
||||||
|
/** ICO рядом с exe (вне asar): надёжно для `nativeImage` / панели задач на Windows. */
|
||||||
|
function getPackagedBrandingIcoPath(): string | undefined {
|
||||||
|
if (!app.isPackaged) return undefined;
|
||||||
|
const p = path.join(process.resourcesPath, 'branding', 'icon.ico');
|
||||||
|
try {
|
||||||
|
if (fs.existsSync(p)) return p;
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function brandingPngPaths(): string[] {
|
||||||
|
const root = app.getAppPath();
|
||||||
|
const relPack = path.join('dist', 'renderer', 'app-pack-icon.png');
|
||||||
|
const relWindow = path.join('dist', 'renderer', 'app-window-icon.png');
|
||||||
|
const paths: string[] = [];
|
||||||
|
if (app.isPackaged) {
|
||||||
|
const unpacked = path.join(process.resourcesPath, 'app.asar.unpacked');
|
||||||
|
paths.push(path.join(unpacked, relPack), path.join(unpacked, relWindow));
|
||||||
|
}
|
||||||
|
paths.push(
|
||||||
|
path.join(root, relPack),
|
||||||
|
path.join(root, relWindow),
|
||||||
|
path.join(root, 'build', 'icon.png'),
|
||||||
|
path.join(root, 'app', 'renderer', 'public', 'app-window-icon.png'),
|
||||||
|
);
|
||||||
|
return paths;
|
||||||
|
}
|
||||||
|
|
||||||
|
function tryLoadImageFile(filePath: string): Electron.NativeImage | undefined {
|
||||||
|
try {
|
||||||
|
const buf = fs.readFileSync(filePath);
|
||||||
|
const fromBuf = nativeImage.createFromBuffer(buf);
|
||||||
|
if (!fromBuf.isEmpty()) return fromBuf;
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const fromPath = nativeImage.createFromPath(filePath);
|
||||||
|
if (!fromPath.isEmpty()) return fromPath;
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function tryLoadSvgFile(filePath: string): Electron.NativeImage | undefined {
|
||||||
|
try {
|
||||||
|
const fromPath = nativeImage.createFromPath(filePath);
|
||||||
|
if (!fromPath.isEmpty()) return fromPath;
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function tryDarwinSvgPaths(): Electron.NativeImage | undefined {
|
||||||
|
if (process.platform !== 'darwin') return undefined;
|
||||||
|
const root = app.getAppPath();
|
||||||
|
for (const p of [
|
||||||
|
path.join(root, 'dist', 'renderer', 'app-logo.svg'),
|
||||||
|
path.join(root, 'app', 'renderer', 'public', 'app-logo.svg'),
|
||||||
|
]) {
|
||||||
|
if (!fs.existsSync(p)) continue;
|
||||||
|
const img = tryLoadSvgFile(p);
|
||||||
|
if (img) return img;
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Иконка окна / дока. Сначала ICO из `extraResources` (реальный путь на диске), затем PNG
|
||||||
|
* через буфер — `createFromPath` к файлам внутри `app.asar` на Windows часто даёт пустой `NativeImage`.
|
||||||
|
*/
|
||||||
|
export function loadBrandingWindowIcon(): Electron.NativeImage | undefined {
|
||||||
|
if (resolved) return cached;
|
||||||
|
resolved = true;
|
||||||
|
|
||||||
|
const ico = getPackagedBrandingIcoPath();
|
||||||
|
if (ico) {
|
||||||
|
const img = tryLoadImageFile(ico);
|
||||||
|
if (img) {
|
||||||
|
cached = img;
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const p of brandingPngPaths()) {
|
||||||
|
if (!fs.existsSync(p)) continue;
|
||||||
|
const img = tryLoadImageFile(p);
|
||||||
|
if (img) {
|
||||||
|
cached = img;
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const svgIcon = tryDarwinSvgPaths();
|
||||||
|
if (svgIcon) {
|
||||||
|
cached = svgIcon;
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
cached = undefined;
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
@@ -22,10 +22,11 @@ void test('createWindows: закрытие редактора завершает
|
|||||||
|
|
||||||
void test('createWindows: иконка окна (pack PNG, затем window PNG; SVG только вне win32)', () => {
|
void test('createWindows: иконка окна (pack PNG, затем window PNG; SVG только вне win32)', () => {
|
||||||
const src = readCreateWindows();
|
const src = readCreateWindows();
|
||||||
assert.ok(src.includes('resolveWindowIconPath'));
|
assert.ok(src.includes('loadBrandingWindowIcon'));
|
||||||
assert.ok(src.includes('app-pack-icon.png'));
|
const branding = fs.readFileSync(path.join(here, 'brandingIcon.ts'), 'utf8');
|
||||||
assert.ok(src.includes('app-window-icon.png'));
|
assert.ok(branding.includes('app-pack-icon.png'));
|
||||||
assert.ok(src.includes('app-logo.svg'));
|
assert.ok(branding.includes('app-window-icon.png'));
|
||||||
|
assert.ok(branding.includes('tryDarwinSvgPaths'));
|
||||||
});
|
});
|
||||||
|
|
||||||
void test('createWindows: пульт поверх экрана просмотра (дочернее окно)', () => {
|
void test('createWindows: пульт поверх экрана просмотра (дочернее окно)', () => {
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
import fs from 'node:fs';
|
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
|
|
||||||
import { app, BrowserWindow, nativeImage, screen } from 'electron';
|
import { app, BrowserWindow, screen } from 'electron';
|
||||||
|
|
||||||
|
import { ipcChannels } from '../../shared/ipc/contracts';
|
||||||
|
|
||||||
import { getBootSplashWindow } from './bootWindow';
|
import { getBootSplashWindow } from './bootWindow';
|
||||||
|
import { loadBrandingWindowIcon } from './brandingIcon';
|
||||||
|
|
||||||
type WindowKind = 'editor' | 'presentation' | 'control';
|
type WindowKind = 'editor' | 'presentation' | 'control';
|
||||||
|
|
||||||
@@ -11,6 +13,19 @@ const windows = new Map<WindowKind, BrowserWindow>();
|
|||||||
|
|
||||||
let appQuitting = false;
|
let appQuitting = false;
|
||||||
|
|
||||||
|
/** Учитываем окна, которые уже уничтожены при каскадном закрытии (родитель → дочернее). */
|
||||||
|
function broadcastMultiWindowStateChanged(open: boolean): void {
|
||||||
|
for (const w of BrowserWindow.getAllWindows()) {
|
||||||
|
if (w.isDestroyed()) continue;
|
||||||
|
if (w.webContents.isDestroyed()) continue;
|
||||||
|
try {
|
||||||
|
w.webContents.send(ipcChannels.windows.multiWindowStateChanged, { open });
|
||||||
|
} catch {
|
||||||
|
/* окно могло закрыться между проверкой и send */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** Разрешает реальное закрытие окна редактора (выход из приложения). */
|
/** Разрешает реальное закрытие окна редактора (выход из приложения). */
|
||||||
export function markAppQuitting(): void {
|
export function markAppQuitting(): void {
|
||||||
appQuitting = true;
|
appQuitting = true;
|
||||||
@@ -54,82 +69,15 @@ function getPreloadPath(): string {
|
|||||||
return path.join(app.getAppPath(), 'dist', 'preload', 'index.cjs');
|
return path.join(app.getAppPath(), 'dist', 'preload', 'index.cjs');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** macOS: в Dock — тот же растр, что и у окон (ICO/PNG из brandingIcon). */
|
||||||
* PNG для иконки окна / дока: тот же растр, что electron-builder берёт из `build/icon.png`
|
|
||||||
* (копия в dist после сборки), затем окно 256px, затем dev-пути. SVG не используем для
|
|
||||||
* nativeImage на Windows — иначе пустая картинка и дефолтная иконка Electron вместо exe.
|
|
||||||
*/
|
|
||||||
function resolveBrandingPngPaths(): string[] {
|
|
||||||
const root = app.getAppPath();
|
|
||||||
return [
|
|
||||||
path.join(root, 'dist', 'renderer', 'app-pack-icon.png'),
|
|
||||||
path.join(root, 'dist', 'renderer', 'app-window-icon.png'),
|
|
||||||
path.join(root, 'build', 'icon.png'),
|
|
||||||
path.join(root, 'app', 'renderer', 'public', 'app-window-icon.png'),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolveWindowIconPath(): string | undefined {
|
|
||||||
for (const p of resolveBrandingPngPaths()) {
|
|
||||||
try {
|
|
||||||
if (fs.existsSync(p)) return p;
|
|
||||||
} catch {
|
|
||||||
/* ignore */
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const root = app.getAppPath();
|
|
||||||
const svgFallback = [
|
|
||||||
path.join(root, 'dist', 'renderer', 'app-logo.svg'),
|
|
||||||
path.join(root, 'app', 'renderer', 'public', 'app-logo.svg'),
|
|
||||||
];
|
|
||||||
for (const p of svgFallback) {
|
|
||||||
try {
|
|
||||||
if (fs.existsSync(p)) return p;
|
|
||||||
} catch {
|
|
||||||
/* ignore */
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolveWindowIcon(): Electron.NativeImage | undefined {
|
|
||||||
const tryPath = (filePath: string): Electron.NativeImage | undefined => {
|
|
||||||
try {
|
|
||||||
const img = nativeImage.createFromPath(filePath);
|
|
||||||
if (!img.isEmpty()) return img;
|
|
||||||
} catch {
|
|
||||||
/* ignore */
|
|
||||||
}
|
|
||||||
return undefined;
|
|
||||||
};
|
|
||||||
|
|
||||||
if (process.platform === 'win32' || process.platform === 'linux') {
|
|
||||||
for (const p of resolveBrandingPngPaths()) {
|
|
||||||
if (!fs.existsSync(p)) continue;
|
|
||||||
const img = tryPath(p);
|
|
||||||
if (img) return img;
|
|
||||||
}
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
const p = resolveWindowIconPath();
|
|
||||||
if (!p) return undefined;
|
|
||||||
return tryPath(p);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** macOS: в Dock показываем тот же PNG, что и у упакованного приложения на Windows (иконка exe). */
|
|
||||||
export function applyDockIconIfNeeded(): void {
|
export function applyDockIconIfNeeded(): void {
|
||||||
if (process.platform !== 'darwin' || !app.dock) return;
|
if (process.platform !== 'darwin' || !app.dock) return;
|
||||||
for (const p of resolveBrandingPngPaths()) {
|
const icon = loadBrandingWindowIcon();
|
||||||
if (!fs.existsSync(p)) continue;
|
if (!icon || icon.isEmpty()) return;
|
||||||
try {
|
try {
|
||||||
const img = nativeImage.createFromPath(p);
|
app.dock.setIcon(icon);
|
||||||
if (img.isEmpty()) continue;
|
} catch {
|
||||||
app.dock.setIcon(img);
|
/* ignore */
|
||||||
return;
|
|
||||||
} catch {
|
|
||||||
/* try next */
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -165,7 +113,7 @@ function ensureWindowBecomesVisible(win: BrowserWindow): void {
|
|||||||
|
|
||||||
function createWindow(kind: WindowKind, opts?: CreateWindowOpts): BrowserWindow {
|
function createWindow(kind: WindowKind, opts?: CreateWindowOpts): BrowserWindow {
|
||||||
const deferEditor = kind === 'editor' && opts?.deferVisibility === true;
|
const deferEditor = kind === 'editor' && opts?.deferVisibility === true;
|
||||||
const icon = resolveWindowIcon();
|
const icon = loadBrandingWindowIcon();
|
||||||
const win = new BrowserWindow({
|
const win = new BrowserWindow({
|
||||||
width: kind === 'editor' ? 1280 : kind === 'control' ? 1200 : 1280,
|
width: kind === 'editor' ? 1280 : kind === 'control' ? 1200 : 1280,
|
||||||
height: 800,
|
height: 800,
|
||||||
@@ -184,6 +132,13 @@ function createWindow(kind: WindowKind, opts?: CreateWindowOpts): BrowserWindow
|
|||||||
webSecurity: Boolean(process.env.VITE_DEV_SERVER_URL),
|
webSecurity: Boolean(process.env.VITE_DEV_SERVER_URL),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
if (icon) {
|
||||||
|
try {
|
||||||
|
win.setIcon(icon);
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
win.webContents.on('preload-error', (_event, preloadPath, error) => {
|
win.webContents.on('preload-error', (_event, preloadPath, error) => {
|
||||||
console.error(`[preload-error] ${preloadPath}:`, error);
|
console.error(`[preload-error] ${preloadPath}:`, error);
|
||||||
@@ -207,6 +162,11 @@ function createWindow(kind: WindowKind, opts?: CreateWindowOpts): BrowserWindow
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
win.on('closed', () => windows.delete(kind));
|
win.on('closed', () => windows.delete(kind));
|
||||||
|
win.on('closed', () => {
|
||||||
|
if (kind !== 'presentation' && kind !== 'control') return;
|
||||||
|
const open = windows.has('presentation') || windows.has('control');
|
||||||
|
broadcastMultiWindowStateChanged(open);
|
||||||
|
});
|
||||||
windows.set(kind, win);
|
windows.set(kind, win);
|
||||||
return win;
|
return win;
|
||||||
}
|
}
|
||||||
@@ -279,8 +239,11 @@ export function openMultiWindow() {
|
|||||||
presentation.maximize();
|
presentation.maximize();
|
||||||
}
|
}
|
||||||
if (!windows.has('control')) {
|
if (!windows.has('control')) {
|
||||||
createWindow('control', { parent: presentation });
|
// macOS: parent-child window binding moves child with the parent (unlike Windows behavior we want).
|
||||||
|
// Keep control window independent on darwin.
|
||||||
|
createWindow('control', process.platform === 'darwin' ? undefined : { parent: presentation });
|
||||||
}
|
}
|
||||||
|
broadcastMultiWindowStateChanged(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function closeMultiWindow(): void {
|
export function closeMultiWindow(): void {
|
||||||
@@ -290,6 +253,10 @@ export function closeMultiWindow(): void {
|
|||||||
if (ctrl) ctrl.close();
|
if (ctrl) ctrl.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function isMultiWindowOpen(): boolean {
|
||||||
|
return windows.has('presentation') || windows.has('control');
|
||||||
|
}
|
||||||
|
|
||||||
export function togglePresentationFullscreen(): boolean {
|
export function togglePresentationFullscreen(): boolean {
|
||||||
const pres = windows.get('presentation');
|
const pres = windows.get('presentation');
|
||||||
if (!pres) return false;
|
if (!pres) return false;
|
||||||
|
|||||||
+447
-105
@@ -4,6 +4,7 @@ import { pickEraseTargetId } from '../../shared/effectEraserHitTest';
|
|||||||
import { ipcChannels } from '../../shared/ipc/contracts';
|
import { ipcChannels } from '../../shared/ipc/contracts';
|
||||||
import type { SessionState } from '../../shared/ipc/contracts';
|
import type { SessionState } from '../../shared/ipc/contracts';
|
||||||
import type { GraphNodeId, Scene, SceneId } from '../../shared/types';
|
import type { GraphNodeId, Scene, SceneId } from '../../shared/types';
|
||||||
|
import { useEditorI18n } from '../editor/i18n/EditorI18nContext';
|
||||||
import { getDndApi } from '../shared/dndApi';
|
import { getDndApi } from '../shared/dndApi';
|
||||||
import { PixiEffectsOverlay } from '../shared/effects/PxiEffectsOverlay';
|
import { PixiEffectsOverlay } from '../shared/effects/PxiEffectsOverlay';
|
||||||
import { useEffectsState } from '../shared/effects/useEffectsState';
|
import { useEffectsState } from '../shared/effects/useEffectsState';
|
||||||
@@ -44,15 +45,26 @@ function playLightningEffectSound(): void {
|
|||||||
|
|
||||||
export function ControlApp() {
|
export function ControlApp() {
|
||||||
const api = getDndApi();
|
const api = getDndApi();
|
||||||
|
const { t } = useEditorI18n();
|
||||||
|
const tRef = useRef(t);
|
||||||
|
tRef.current = t;
|
||||||
const [fxState, fx] = useEffectsState();
|
const [fxState, fx] = useEffectsState();
|
||||||
const [session, setSession] = useState<SessionState | null>(null);
|
const [session, setSession] = useState<SessionState | null>(null);
|
||||||
const historyRef = useRef<GraphNodeId[]>([]);
|
const historyRef = useRef<GraphNodeId[]>([]);
|
||||||
const suppressNextHistoryPushRef = useRef(false);
|
const suppressNextHistoryPushRef = useRef(false);
|
||||||
const [history, setHistory] = useState<GraphNodeId[]>([]);
|
const [history, setHistory] = useState<GraphNodeId[]>([]);
|
||||||
const audioElsRef = useRef<Map<string, HTMLAudioElement>>(new Map());
|
const sceneAudioElsRef = useRef<Map<string, HTMLAudioElement>>(new Map());
|
||||||
const audioMetaRef = useRef<Map<string, { lastPlayError: string | null }>>(new Map());
|
const sceneAudioMetaRef = useRef<Map<string, { lastPlayError: string | null }>>(new Map());
|
||||||
const [audioStateTick, setAudioStateTick] = useState(0);
|
const [sceneAudioStateTick, setSceneAudioStateTick] = useState(0);
|
||||||
const audioLoadRunRef = useRef(0);
|
const sceneAudioLoadRunRef = useRef(0);
|
||||||
|
|
||||||
|
const campaignAudioElsRef = useRef<Map<string, HTMLAudioElement>>(new Map());
|
||||||
|
const campaignAudioMetaRef = useRef<Map<string, { lastPlayError: string | null }>>(new Map());
|
||||||
|
const [campaignAudioStateTick, setCampaignAudioStateTick] = useState(0);
|
||||||
|
const campaignAudioLoadRunRef = useRef(0);
|
||||||
|
/** Snapshot of `!el.paused` per assetId when scene music takes over; used to resume when `allowCampaignAudio` is true again. */
|
||||||
|
const campaignResumeAfterSceneRef = useRef<Map<string, boolean> | null>(null);
|
||||||
|
const allowCampaignAudioRef = useRef<boolean>(true);
|
||||||
const audioUnmountRef = useRef(false);
|
const audioUnmountRef = useRef(false);
|
||||||
const previewHostRef = useRef<HTMLDivElement | null>(null);
|
const previewHostRef = useRef<HTMLDivElement | null>(null);
|
||||||
const previewVideoRef = useRef<HTMLVideoElement | null>(null);
|
const previewVideoRef = useRef<HTMLVideoElement | null>(null);
|
||||||
@@ -137,6 +149,17 @@ export function ControlApp() {
|
|||||||
project && session?.currentSceneId ? project.scenes[session.currentSceneId] : undefined;
|
project && session?.currentSceneId ? project.scenes[session.currentSceneId] : undefined;
|
||||||
const isVideoPreviewScene = currentScene?.previewAssetType === 'video';
|
const isVideoPreviewScene = currentScene?.previewAssetType === 'video';
|
||||||
const sceneAudioRefs = useMemo(() => currentScene?.media.audios ?? [], [currentScene]);
|
const sceneAudioRefs = useMemo(() => currentScene?.media.audios ?? [], [currentScene]);
|
||||||
|
// Keep this memo as narrow as possible: project changes on scene switch,
|
||||||
|
// but campaign audio list/config often does not.
|
||||||
|
const campaignAudioRefs = useMemo(() => project?.campaignAudios ?? [], [project?.campaignAudios]);
|
||||||
|
const allowCampaignAudio = !sceneAudioRefs.some((a) => a.autoplay);
|
||||||
|
allowCampaignAudioRef.current = allowCampaignAudio;
|
||||||
|
|
||||||
|
const campaignAudioSpecKey = useMemo(
|
||||||
|
() =>
|
||||||
|
campaignAudioRefs.map((r) => `${r.assetId}:${r.loop ? '1' : '0'}:${r.autoplay ? '1' : '0'}`).join('|'),
|
||||||
|
[campaignAudioRefs],
|
||||||
|
);
|
||||||
|
|
||||||
const sceneAudios = useMemo(() => {
|
const sceneAudios = useMemo(() => {
|
||||||
if (!project) return [];
|
if (!project) return [];
|
||||||
@@ -150,14 +173,26 @@ export function ControlApp() {
|
|||||||
);
|
);
|
||||||
}, [project, sceneAudioRefs]);
|
}, [project, sceneAudioRefs]);
|
||||||
|
|
||||||
useEffect(() => {
|
const campaignAudios = useMemo(() => {
|
||||||
audioLoadRunRef.current += 1;
|
if (!project) return [];
|
||||||
const runId = audioLoadRunRef.current;
|
return campaignAudioRefs
|
||||||
|
.map((r) => {
|
||||||
|
const a = project.assets[r.assetId];
|
||||||
|
return a?.type === 'audio' ? { ref: r, asset: a } : null;
|
||||||
|
})
|
||||||
|
.filter((x): x is { ref: (typeof campaignAudioRefs)[number]; asset: NonNullable<typeof x>['asset'] } =>
|
||||||
|
Boolean(x),
|
||||||
|
);
|
||||||
|
}, [campaignAudioRefs, project]);
|
||||||
|
|
||||||
const oldEls = new Map(audioElsRef.current);
|
useEffect(() => {
|
||||||
audioElsRef.current = new Map();
|
sceneAudioLoadRunRef.current += 1;
|
||||||
audioMetaRef.current.clear();
|
const runId = sceneAudioLoadRunRef.current;
|
||||||
setAudioStateTick((x) => x + 1);
|
|
||||||
|
const oldEls = new Map(sceneAudioElsRef.current);
|
||||||
|
sceneAudioElsRef.current = new Map();
|
||||||
|
sceneAudioMetaRef.current.clear();
|
||||||
|
setSceneAudioStateTick((x) => x + 1);
|
||||||
|
|
||||||
const FADE_OUT_MS = 450;
|
const FADE_OUT_MS = 450;
|
||||||
const fadeOutCtl = { raf: 0, cancelled: false };
|
const fadeOutCtl = { raf: 0, cancelled: false };
|
||||||
@@ -213,24 +248,24 @@ export function ControlApp() {
|
|||||||
const loaded: { ref: (typeof sceneAudioRefs)[number]; el: HTMLAudioElement }[] = [];
|
const loaded: { ref: (typeof sceneAudioRefs)[number]; el: HTMLAudioElement }[] = [];
|
||||||
for (const item of sceneAudioRefs) {
|
for (const item of sceneAudioRefs) {
|
||||||
const r = await api.invoke(ipcChannels.project.assetFileUrl, { assetId: item.assetId });
|
const r = await api.invoke(ipcChannels.project.assetFileUrl, { assetId: item.assetId });
|
||||||
if (audioLoadRunRef.current !== runId) return;
|
if (sceneAudioLoadRunRef.current !== runId) return;
|
||||||
if (!r.url) continue;
|
if (!r.url) continue;
|
||||||
const el = new Audio(r.url);
|
const el = new Audio(r.url);
|
||||||
el.loop = item.loop;
|
el.loop = item.loop;
|
||||||
el.preload = 'auto';
|
el.preload = 'auto';
|
||||||
el.volume = item.autoplay ? 0 : 1;
|
el.volume = item.autoplay ? 0 : 1;
|
||||||
audioMetaRef.current.set(item.assetId, { lastPlayError: null });
|
sceneAudioMetaRef.current.set(item.assetId, { lastPlayError: null });
|
||||||
el.addEventListener('play', () => setAudioStateTick((x) => x + 1));
|
el.addEventListener('play', () => setSceneAudioStateTick((x) => x + 1));
|
||||||
el.addEventListener('pause', () => setAudioStateTick((x) => x + 1));
|
el.addEventListener('pause', () => setSceneAudioStateTick((x) => x + 1));
|
||||||
el.addEventListener('ended', () => setAudioStateTick((x) => x + 1));
|
el.addEventListener('ended', () => setSceneAudioStateTick((x) => x + 1));
|
||||||
el.addEventListener('canplay', () => setAudioStateTick((x) => x + 1));
|
el.addEventListener('canplay', () => setSceneAudioStateTick((x) => x + 1));
|
||||||
el.addEventListener('error', () => setAudioStateTick((x) => x + 1));
|
el.addEventListener('error', () => setSceneAudioStateTick((x) => x + 1));
|
||||||
loaded.push({ ref: item, el });
|
loaded.push({ ref: item, el });
|
||||||
audioElsRef.current.set(item.assetId, el);
|
sceneAudioElsRef.current.set(item.assetId, el);
|
||||||
}
|
}
|
||||||
setAudioStateTick((x) => x + 1);
|
setSceneAudioStateTick((x) => x + 1);
|
||||||
for (const { ref, el } of loaded) {
|
for (const { ref, el } of loaded) {
|
||||||
if (audioLoadRunRef.current !== runId) {
|
if (sceneAudioLoadRunRef.current !== runId) {
|
||||||
try {
|
try {
|
||||||
el.pause();
|
el.pause();
|
||||||
el.currentTime = 0;
|
el.currentTime = 0;
|
||||||
@@ -244,13 +279,12 @@ export function ControlApp() {
|
|||||||
try {
|
try {
|
||||||
await el.play();
|
await el.play();
|
||||||
} catch {
|
} catch {
|
||||||
const m = audioMetaRef.current.get(ref.assetId) ?? { lastPlayError: null };
|
const m = sceneAudioMetaRef.current.get(ref.assetId) ?? { lastPlayError: null };
|
||||||
audioMetaRef.current.set(ref.assetId, {
|
sceneAudioMetaRef.current.set(ref.assetId, {
|
||||||
...m,
|
...m,
|
||||||
lastPlayError:
|
lastPlayError: tRef.current('control.audioAutoplayBlocked'),
|
||||||
'Автозапуск заблокирован (нужно действие пользователя) или ошибка воспроизведения.',
|
|
||||||
});
|
});
|
||||||
setAudioStateTick((x) => x + 1);
|
setSceneAudioStateTick((x) => x + 1);
|
||||||
try {
|
try {
|
||||||
el.volume = 1;
|
el.volume = 1;
|
||||||
} catch {
|
} catch {
|
||||||
@@ -258,7 +292,7 @@ export function ControlApp() {
|
|||||||
}
|
}
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (audioLoadRunRef.current !== runId || audioUnmountRef.current) {
|
if (sceneAudioLoadRunRef.current !== runId || audioUnmountRef.current) {
|
||||||
try {
|
try {
|
||||||
el.volume = 1;
|
el.volume = 1;
|
||||||
} catch {
|
} catch {
|
||||||
@@ -268,7 +302,7 @@ export function ControlApp() {
|
|||||||
}
|
}
|
||||||
const tIn0 = performance.now();
|
const tIn0 = performance.now();
|
||||||
const tickIn = (now: number): void => {
|
const tickIn = (now: number): void => {
|
||||||
if (audioLoadRunRef.current !== runId || audioUnmountRef.current) {
|
if (sceneAudioLoadRunRef.current !== runId || audioUnmountRef.current) {
|
||||||
try {
|
try {
|
||||||
el.volume = 1;
|
el.volume = 1;
|
||||||
} catch {
|
} catch {
|
||||||
@@ -294,19 +328,202 @@ export function ControlApp() {
|
|||||||
};
|
};
|
||||||
}, [api, currentScene, project, sceneAudioRefs]);
|
}, [api, currentScene, project, sceneAudioRefs]);
|
||||||
|
|
||||||
|
// Campaign elements: lifecycle depends only on campaign track list/config, not scene or allowCampaignAudio
|
||||||
|
// (scene music uses allowCampaignAudioRef + separate pause/resume effect).
|
||||||
|
// Spec is encoded in campaignAudioSpecKey; campaignAudioRefs is intentionally omitted to avoid scene-switch churn.
|
||||||
|
useEffect(() => {
|
||||||
|
campaignAudioLoadRunRef.current += 1;
|
||||||
|
const runId = campaignAudioLoadRunRef.current;
|
||||||
|
|
||||||
|
const oldEls = new Map(campaignAudioElsRef.current);
|
||||||
|
campaignAudioElsRef.current = new Map();
|
||||||
|
campaignAudioMetaRef.current.clear();
|
||||||
|
setCampaignAudioStateTick((x) => x + 1);
|
||||||
|
|
||||||
|
for (const el of oldEls.values()) {
|
||||||
|
try {
|
||||||
|
el.pause();
|
||||||
|
el.volume = 1;
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (campaignAudioSpecKey === '') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
void (async () => {
|
||||||
|
const loaded: { ref: (typeof campaignAudioRefs)[number]; el: HTMLAudioElement }[] = [];
|
||||||
|
for (const item of campaignAudioRefs) {
|
||||||
|
const r = await api.invoke(ipcChannels.project.assetFileUrl, { assetId: item.assetId });
|
||||||
|
if (campaignAudioLoadRunRef.current !== runId) return;
|
||||||
|
if (!r.url) continue;
|
||||||
|
const el = new Audio(r.url);
|
||||||
|
el.loop = item.loop;
|
||||||
|
el.preload = 'auto';
|
||||||
|
el.volume = item.autoplay ? 0 : 1;
|
||||||
|
campaignAudioMetaRef.current.set(item.assetId, { lastPlayError: null });
|
||||||
|
el.addEventListener('play', () => setCampaignAudioStateTick((x) => x + 1));
|
||||||
|
el.addEventListener('pause', () => setCampaignAudioStateTick((x) => x + 1));
|
||||||
|
el.addEventListener('ended', () => setCampaignAudioStateTick((x) => x + 1));
|
||||||
|
el.addEventListener('canplay', () => setCampaignAudioStateTick((x) => x + 1));
|
||||||
|
el.addEventListener('error', () => setCampaignAudioStateTick((x) => x + 1));
|
||||||
|
loaded.push({ ref: item, el });
|
||||||
|
campaignAudioElsRef.current.set(item.assetId, el);
|
||||||
|
}
|
||||||
|
setCampaignAudioStateTick((x) => x + 1);
|
||||||
|
|
||||||
|
if (!allowCampaignAudioRef.current) return;
|
||||||
|
|
||||||
|
for (const { ref, el } of loaded) {
|
||||||
|
if (campaignAudioLoadRunRef.current !== runId) return;
|
||||||
|
if (!ref.autoplay) continue;
|
||||||
|
try {
|
||||||
|
await el.play();
|
||||||
|
} catch {
|
||||||
|
const m = campaignAudioMetaRef.current.get(ref.assetId) ?? { lastPlayError: null };
|
||||||
|
campaignAudioMetaRef.current.set(ref.assetId, {
|
||||||
|
...m,
|
||||||
|
lastPlayError: tRef.current('control.audioAutoplayBlocked'),
|
||||||
|
});
|
||||||
|
setCampaignAudioStateTick((x) => x + 1);
|
||||||
|
try {
|
||||||
|
el.volume = 1;
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (campaignAudioLoadRunRef.current !== runId || audioUnmountRef.current) {
|
||||||
|
try {
|
||||||
|
el.volume = 1;
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const tIn0 = performance.now();
|
||||||
|
const tickIn = (now: number): void => {
|
||||||
|
if (campaignAudioLoadRunRef.current !== runId || audioUnmountRef.current) {
|
||||||
|
try {
|
||||||
|
el.volume = 1;
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const u = Math.min(1, (now - tIn0) / 550);
|
||||||
|
try {
|
||||||
|
el.volume = u;
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
if (u < 1) window.requestAnimationFrame(tickIn);
|
||||||
|
};
|
||||||
|
window.requestAnimationFrame(tickIn);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
// Deps: api + campaignAudioSpecKey only; list iteration uses current campaignAudioRefs (stable while spec is stable).
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [api, campaignAudioSpecKey]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (allowCampaignAudio) {
|
||||||
|
const snap = campaignResumeAfterSceneRef.current;
|
||||||
|
campaignResumeAfterSceneRef.current = null;
|
||||||
|
if (snap && snap.size > 0) {
|
||||||
|
void (async () => {
|
||||||
|
for (const [assetId, wasPlaying] of snap) {
|
||||||
|
if (!wasPlaying) continue;
|
||||||
|
const el = campaignAudioElsRef.current.get(assetId) ?? null;
|
||||||
|
if (!el) continue;
|
||||||
|
try {
|
||||||
|
// If a track was created with autoplay volume ramp but never started yet,
|
||||||
|
// ensure it is audible on resume.
|
||||||
|
if (el.volume === 0) el.volume = 1;
|
||||||
|
await el.play();
|
||||||
|
} catch {
|
||||||
|
// ignore; user can press play
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setCampaignAudioStateTick((x) => x + 1);
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
// If we entered a scene that allows campaign audio and there was no "resume snapshot"
|
||||||
|
// (e.g. first scene had autoplay scene music so campaign autoplay was blocked),
|
||||||
|
// start campaign tracks that have autoplay enabled.
|
||||||
|
if (!snap || snap.size === 0) {
|
||||||
|
void (async () => {
|
||||||
|
for (const ref of campaignAudioRefs) {
|
||||||
|
if (!ref.autoplay) continue;
|
||||||
|
const el = campaignAudioElsRef.current.get(ref.assetId) ?? null;
|
||||||
|
if (!el) continue;
|
||||||
|
if (!el.paused) continue;
|
||||||
|
try {
|
||||||
|
el.volume = 0;
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await el.play();
|
||||||
|
} catch {
|
||||||
|
// ignore; user can press play
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const tIn0 = performance.now();
|
||||||
|
const tickIn = (now: number): void => {
|
||||||
|
if (!allowCampaignAudioRef.current || audioUnmountRef.current) return;
|
||||||
|
const u = Math.min(1, (now - tIn0) / 550);
|
||||||
|
try {
|
||||||
|
el.volume = u;
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
if (u < 1) window.requestAnimationFrame(tickIn);
|
||||||
|
};
|
||||||
|
window.requestAnimationFrame(tickIn);
|
||||||
|
}
|
||||||
|
setCampaignAudioStateTick((x) => x + 1);
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Scene has its own audio: remember what was playing, then pause campaign. (keep currentTime)
|
||||||
|
const snap = new Map<string, boolean>();
|
||||||
|
for (const [assetId, el] of campaignAudioElsRef.current) {
|
||||||
|
snap.set(assetId, !el.paused);
|
||||||
|
}
|
||||||
|
campaignResumeAfterSceneRef.current = snap;
|
||||||
|
for (const el of campaignAudioElsRef.current.values()) {
|
||||||
|
try {
|
||||||
|
el.pause();
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setCampaignAudioStateTick((x) => x + 1);
|
||||||
|
// Intentionally not depending on campaignAudioRefs: this effect is about scene-driven pausing/resuming.
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [allowCampaignAudio]);
|
||||||
|
|
||||||
const anyPlaying = useMemo(() => {
|
const anyPlaying = useMemo(() => {
|
||||||
for (const el of audioElsRef.current.values()) {
|
for (const el of sceneAudioElsRef.current.values()) {
|
||||||
|
if (!el.paused) return true;
|
||||||
|
}
|
||||||
|
for (const el of campaignAudioElsRef.current.values()) {
|
||||||
if (!el.paused) return true;
|
if (!el.paused) return true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [audioStateTick]);
|
}, [campaignAudioStateTick, sceneAudioStateTick]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!anyPlaying) return;
|
if (!anyPlaying) return;
|
||||||
let raf = 0;
|
let raf = 0;
|
||||||
const tick = () => {
|
const tick = () => {
|
||||||
setAudioStateTick((x) => x + 1);
|
setSceneAudioStateTick((x) => x + 1);
|
||||||
|
setCampaignAudioStateTick((x) => x + 1);
|
||||||
raf = window.requestAnimationFrame(tick);
|
raf = window.requestAnimationFrame(tick);
|
||||||
};
|
};
|
||||||
raf = window.requestAnimationFrame(tick);
|
raf = window.requestAnimationFrame(tick);
|
||||||
@@ -326,20 +543,26 @@ export function ControlApp() {
|
|||||||
return () => ro.disconnect();
|
return () => ro.disconnect();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
function audioStatus(assetId: string): { label: string; detail?: string } {
|
function audioStatus(group: 'scene' | 'campaign', assetId: string): { label: string; detail?: string } {
|
||||||
const el = audioElsRef.current.get(assetId) ?? null;
|
const el =
|
||||||
if (!el) return { label: 'URL не получен', detail: 'Не удалось получить dnd://asset URL для аудио.' };
|
group === 'scene'
|
||||||
const meta = audioMetaRef.current.get(assetId) ?? { lastPlayError: null };
|
? (sceneAudioElsRef.current.get(assetId) ?? null)
|
||||||
if (meta.lastPlayError) return { label: 'Ошибка/блок', detail: meta.lastPlayError };
|
: (campaignAudioElsRef.current.get(assetId) ?? null);
|
||||||
|
if (!el) return { label: t('control.audioNoUrl'), detail: t('control.audioNoUrlDetail') };
|
||||||
|
const meta =
|
||||||
|
group === 'scene'
|
||||||
|
? (sceneAudioMetaRef.current.get(assetId) ?? { lastPlayError: null })
|
||||||
|
: (campaignAudioMetaRef.current.get(assetId) ?? { lastPlayError: null });
|
||||||
|
if (meta.lastPlayError) return { label: t('control.audioBlocked'), detail: meta.lastPlayError };
|
||||||
if (el.error)
|
if (el.error)
|
||||||
return {
|
return {
|
||||||
label: 'Ошибка',
|
label: t('control.audioError'),
|
||||||
detail: `MediaError code=${String(el.error.code)} (1=ABORTED, 2=NETWORK, 3=DECODE, 4=SRC_NOT_SUPPORTED)`,
|
detail: t('control.audioMediaError', { code: String(el.error.code) }),
|
||||||
};
|
};
|
||||||
if (el.readyState < 2) return { label: 'Загрузка…' };
|
if (el.readyState < 2) return { label: t('control.audioLoading') };
|
||||||
if (!el.paused) return { label: 'Играет' };
|
if (!el.paused) return { label: t('control.audioPlaying') };
|
||||||
if (el.currentTime > 0) return { label: 'Пауза' };
|
if (el.currentTime > 0) return { label: t('control.audioPaused') };
|
||||||
return { label: 'Остановлено' };
|
return { label: t('control.audioStopped') };
|
||||||
}
|
}
|
||||||
const nextScenes = useMemo(() => {
|
const nextScenes = useMemo(() => {
|
||||||
if (!project) return [];
|
if (!project) return [];
|
||||||
@@ -734,21 +957,21 @@ export function ControlApp() {
|
|||||||
return (
|
return (
|
||||||
<div className={styles.page}>
|
<div className={styles.page}>
|
||||||
<Surface className={styles.remote}>
|
<Surface className={styles.remote}>
|
||||||
<div className={styles.remoteTitle}>ПУЛЬТ УПРАВЛЕНИЯ</div>
|
<div className={styles.remoteTitle}>{t('control.remoteTitle')}</div>
|
||||||
<div className={styles.spacer12} />
|
<div className={styles.spacer12} />
|
||||||
{!isVideoPreviewScene ? (
|
{!isVideoPreviewScene ? (
|
||||||
<>
|
<>
|
||||||
<div className={styles.sectionLabel}>ЭФФЕКТЫ</div>
|
<div className={styles.sectionLabel}>{t('control.effects')}</div>
|
||||||
<div className={styles.spacer8} />
|
<div className={styles.spacer8} />
|
||||||
<div className={styles.effectsStack}>
|
<div className={styles.effectsStack}>
|
||||||
<div className={styles.effectsGroup}>
|
<div className={styles.effectsGroup}>
|
||||||
<div className={styles.subsectionLabel}>Инструменты</div>
|
<div className={styles.subsectionLabel}>{t('control.tools')}</div>
|
||||||
<div className={styles.iconRow}>
|
<div className={styles.iconRow}>
|
||||||
<Button
|
<Button
|
||||||
variant={tool.tool === 'eraser' ? 'primary' : 'ghost'}
|
variant={tool.tool === 'eraser' ? 'primary' : 'ghost'}
|
||||||
iconOnly
|
iconOnly
|
||||||
title="Ластик"
|
title={t('control.eraser')}
|
||||||
ariaLabel="Ластик"
|
ariaLabel={t('control.eraser')}
|
||||||
onClick={() => void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'eraser' } })}
|
onClick={() => void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'eraser' } })}
|
||||||
>
|
>
|
||||||
<span className={styles.iconGlyph}>🧹</span>
|
<span className={styles.iconGlyph}>🧹</span>
|
||||||
@@ -756,8 +979,8 @@ export function ControlApp() {
|
|||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
iconOnly
|
iconOnly
|
||||||
title="Очистить эффекты"
|
title={t('control.clearEffects')}
|
||||||
ariaLabel="Очистить эффекты"
|
ariaLabel={t('control.clearEffects')}
|
||||||
onClick={() => void fx.dispatch({ kind: 'instances.clear' })}
|
onClick={() => void fx.dispatch({ kind: 'instances.clear' })}
|
||||||
>
|
>
|
||||||
<span className={styles.clearIcon}>
|
<span className={styles.clearIcon}>
|
||||||
@@ -778,13 +1001,13 @@ export function ControlApp() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className={styles.effectsGroup}>
|
<div className={styles.effectsGroup}>
|
||||||
<div className={styles.subsectionLabel}>Эффекты поля</div>
|
<div className={styles.subsectionLabel}>{t('control.fieldEffects')}</div>
|
||||||
<div className={styles.iconRow}>
|
<div className={styles.iconRow}>
|
||||||
<Button
|
<Button
|
||||||
variant={tool.tool === 'fog' ? 'primary' : 'ghost'}
|
variant={tool.tool === 'fog' ? 'primary' : 'ghost'}
|
||||||
iconOnly
|
iconOnly
|
||||||
title="Туман"
|
title={t('control.fog')}
|
||||||
ariaLabel="Туман"
|
ariaLabel={t('control.fog')}
|
||||||
onClick={() => void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'fog' } })}
|
onClick={() => void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'fog' } })}
|
||||||
>
|
>
|
||||||
<span className={styles.iconGlyph}>🌫️</span>
|
<span className={styles.iconGlyph}>🌫️</span>
|
||||||
@@ -792,8 +1015,8 @@ export function ControlApp() {
|
|||||||
<Button
|
<Button
|
||||||
variant={tool.tool === 'rain' ? 'primary' : 'ghost'}
|
variant={tool.tool === 'rain' ? 'primary' : 'ghost'}
|
||||||
iconOnly
|
iconOnly
|
||||||
title="Дождь"
|
title={t('control.rain')}
|
||||||
ariaLabel="Дождь"
|
ariaLabel={t('control.rain')}
|
||||||
onClick={() => void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'rain' } })}
|
onClick={() => void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'rain' } })}
|
||||||
>
|
>
|
||||||
<span className={styles.iconGlyph}>🌧️</span>
|
<span className={styles.iconGlyph}>🌧️</span>
|
||||||
@@ -801,8 +1024,8 @@ export function ControlApp() {
|
|||||||
<Button
|
<Button
|
||||||
variant={tool.tool === 'fire' ? 'primary' : 'ghost'}
|
variant={tool.tool === 'fire' ? 'primary' : 'ghost'}
|
||||||
iconOnly
|
iconOnly
|
||||||
title="Огонь"
|
title={t('control.fire')}
|
||||||
ariaLabel="Огонь"
|
ariaLabel={t('control.fire')}
|
||||||
onClick={() => void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'fire' } })}
|
onClick={() => void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'fire' } })}
|
||||||
>
|
>
|
||||||
<span className={styles.iconGlyph}>🔥</span>
|
<span className={styles.iconGlyph}>🔥</span>
|
||||||
@@ -810,8 +1033,8 @@ export function ControlApp() {
|
|||||||
<Button
|
<Button
|
||||||
variant={tool.tool === 'water' ? 'primary' : 'ghost'}
|
variant={tool.tool === 'water' ? 'primary' : 'ghost'}
|
||||||
iconOnly
|
iconOnly
|
||||||
title="Вода"
|
title={t('control.water')}
|
||||||
ariaLabel="Вода"
|
ariaLabel={t('control.water')}
|
||||||
onClick={() => void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'water' } })}
|
onClick={() => void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'water' } })}
|
||||||
>
|
>
|
||||||
<span className={styles.iconGlyph}>💧</span>
|
<span className={styles.iconGlyph}>💧</span>
|
||||||
@@ -819,13 +1042,13 @@ export function ControlApp() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className={styles.effectsGroup}>
|
<div className={styles.effectsGroup}>
|
||||||
<div className={styles.subsectionLabel}>Эффекты действий</div>
|
<div className={styles.subsectionLabel}>{t('control.actionEffects')}</div>
|
||||||
<div className={styles.iconRow}>
|
<div className={styles.iconRow}>
|
||||||
<Button
|
<Button
|
||||||
variant={tool.tool === 'lightning' ? 'primary' : 'ghost'}
|
variant={tool.tool === 'lightning' ? 'primary' : 'ghost'}
|
||||||
iconOnly
|
iconOnly
|
||||||
title="Молния"
|
title={t('control.lightning')}
|
||||||
ariaLabel="Молния"
|
ariaLabel={t('control.lightning')}
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'lightning' } })
|
void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'lightning' } })
|
||||||
}
|
}
|
||||||
@@ -835,8 +1058,8 @@ export function ControlApp() {
|
|||||||
<Button
|
<Button
|
||||||
variant={tool.tool === 'sunbeam' ? 'primary' : 'ghost'}
|
variant={tool.tool === 'sunbeam' ? 'primary' : 'ghost'}
|
||||||
iconOnly
|
iconOnly
|
||||||
title="Луч света"
|
title={t('control.sunbeam')}
|
||||||
ariaLabel="Луч света"
|
ariaLabel={t('control.sunbeam')}
|
||||||
onClick={() => void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'sunbeam' } })}
|
onClick={() => void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'sunbeam' } })}
|
||||||
>
|
>
|
||||||
<span className={styles.iconGlyph}>☀️</span>
|
<span className={styles.iconGlyph}>☀️</span>
|
||||||
@@ -844,8 +1067,8 @@ export function ControlApp() {
|
|||||||
<Button
|
<Button
|
||||||
variant={tool.tool === 'freeze' ? 'primary' : 'ghost'}
|
variant={tool.tool === 'freeze' ? 'primary' : 'ghost'}
|
||||||
iconOnly
|
iconOnly
|
||||||
title="Заморозка"
|
title={t('control.freeze')}
|
||||||
ariaLabel="Заморозка"
|
ariaLabel={t('control.freeze')}
|
||||||
onClick={() => void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'freeze' } })}
|
onClick={() => void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'freeze' } })}
|
||||||
>
|
>
|
||||||
<span className={styles.iconGlyph}>❄️</span>
|
<span className={styles.iconGlyph}>❄️</span>
|
||||||
@@ -853,8 +1076,8 @@ export function ControlApp() {
|
|||||||
<Button
|
<Button
|
||||||
variant={tool.tool === 'poisonCloud' ? 'primary' : 'ghost'}
|
variant={tool.tool === 'poisonCloud' ? 'primary' : 'ghost'}
|
||||||
iconOnly
|
iconOnly
|
||||||
title="Облако яда"
|
title={t('control.poisonCloud')}
|
||||||
ariaLabel="Облако яда"
|
ariaLabel={t('control.poisonCloud')}
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'poisonCloud' } })
|
void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'poisonCloud' } })
|
||||||
}
|
}
|
||||||
@@ -864,7 +1087,7 @@ export function ControlApp() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className={styles.radiusRow}>
|
<div className={styles.radiusRow}>
|
||||||
<div className={styles.radiusLabel}>Радиус кисти</div>
|
<div className={styles.radiusLabel}>{t('control.brushRadius')}</div>
|
||||||
<input
|
<input
|
||||||
type="range"
|
type="range"
|
||||||
min={0.015}
|
min={0.015}
|
||||||
@@ -877,7 +1100,7 @@ export function ControlApp() {
|
|||||||
void fx.dispatch({ kind: 'tool.set', tool: { ...tool, radiusN: next } });
|
void fx.dispatch({ kind: 'tool.set', tool: { ...tool, radiusN: next } });
|
||||||
}}
|
}}
|
||||||
className={styles.range}
|
className={styles.range}
|
||||||
aria-label="Радиус кисти"
|
aria-label={t('control.brushRadius')}
|
||||||
/>
|
/>
|
||||||
<div className={styles.radiusValue}>{Math.round(tool.radiusN * 100)}</div>
|
<div className={styles.radiusValue}>{Math.round(tool.radiusN * 100)}</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -886,7 +1109,7 @@ export function ControlApp() {
|
|||||||
</>
|
</>
|
||||||
) : null}
|
) : null}
|
||||||
<div className={styles.storyWrap}>
|
<div className={styles.storyWrap}>
|
||||||
<div className={styles.sectionLabel}>СЮЖЕТНАЯ ЛИНИЯ</div>
|
<div className={styles.sectionLabel}>{t('control.storyLine')}</div>
|
||||||
<div className={styles.spacer10} />
|
<div className={styles.spacer10} />
|
||||||
<div className={styles.storyScroll}>
|
<div className={styles.storyScroll}>
|
||||||
{history.map((gnId, idx) => {
|
{history.map((gnId, idx) => {
|
||||||
@@ -901,7 +1124,7 @@ export function ControlApp() {
|
|||||||
className={[styles.historyBtn, isCurrent ? styles.historyBtnCurrent : '']
|
className={[styles.historyBtn, isCurrent ? styles.historyBtnCurrent : '']
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
.join(' ')}
|
.join(' ')}
|
||||||
title={project && !isCurrent ? 'Перейти к этой сцене' : undefined}
|
title={project && !isCurrent ? t('control.gotoScene') : undefined}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
if (!project) return;
|
if (!project) return;
|
||||||
if (isCurrent) return;
|
if (isCurrent) return;
|
||||||
@@ -911,15 +1134,17 @@ export function ControlApp() {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{isCurrent ? (
|
{isCurrent ? (
|
||||||
<div className={styles.historyBadge}>ТЕКУЩАЯ СЦЕНА</div>
|
<div className={styles.historyBadge}>{t('control.currentSceneBadge')}</div>
|
||||||
) : (
|
) : (
|
||||||
<div className={styles.historyMuted}>Пройдено</div>
|
<div className={styles.historyMuted}>{t('control.passed')}</div>
|
||||||
)}
|
)}
|
||||||
<div className={styles.historyTitle}>{s?.title ?? (gn ? String(gn.sceneId) : gnId)}</div>
|
<div className={styles.historyTitle}>{s?.title ?? (gn ? String(gn.sceneId) : gnId)}</div>
|
||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
{history.length === 0 ? <div className={styles.emptyStory}>Нет активной сцены.</div> : null}
|
{history.length === 0 ? (
|
||||||
|
<div className={styles.emptyStory}>{t('control.noActiveScene')}</div>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</Surface>
|
</Surface>
|
||||||
@@ -927,20 +1152,15 @@ export function ControlApp() {
|
|||||||
<div className={styles.rightStack}>
|
<div className={styles.rightStack}>
|
||||||
<Surface className={styles.surfacePad}>
|
<Surface className={styles.surfacePad}>
|
||||||
<div className={styles.previewHeader}>
|
<div className={styles.previewHeader}>
|
||||||
<div className={styles.previewTitle}>Предпросмотр экрана</div>
|
<div className={styles.previewTitle}>{t('control.screenPreview')}</div>
|
||||||
<div className={styles.previewActions}>
|
<div className={styles.previewActions}>
|
||||||
<Button onClick={() => void api.invoke(ipcChannels.windows.closeMultiWindow, {})}>
|
<Button onClick={() => void api.invoke(ipcChannels.windows.closeMultiWindow, {})}>
|
||||||
Выключить демонстрацию
|
{t('control.stopPresentation')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className={styles.spacer10} />
|
<div className={styles.spacer10} />
|
||||||
{isVideoPreviewScene ? (
|
{isVideoPreviewScene ? <div className={styles.videoHint}>{t('control.videoBrushHint')}</div> : null}
|
||||||
<div className={styles.videoHint}>
|
|
||||||
Видео-превью: кисть эффектов отключена (как на экране демонстрации — оверлей только для
|
|
||||||
изображения).
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
<div className={styles.spacer10} />
|
<div className={styles.spacer10} />
|
||||||
<div className={styles.previewFrame}>
|
<div className={styles.previewFrame}>
|
||||||
<div ref={previewHostRef} className={styles.previewHost}>
|
<div ref={previewHostRef} className={styles.previewHost}>
|
||||||
@@ -1037,33 +1257,33 @@ export function ControlApp() {
|
|||||||
</Surface>
|
</Surface>
|
||||||
|
|
||||||
<Surface className={styles.surfacePad}>
|
<Surface className={styles.surfacePad}>
|
||||||
<div className={styles.branchTitle}>Варианты ветвления</div>
|
<div className={styles.branchTitle}>{t('control.branches')}</div>
|
||||||
<div className={styles.branchGrid}>
|
<div className={styles.branchGrid}>
|
||||||
{nextScenes.map((o, i) => (
|
{nextScenes.map((o, i) => (
|
||||||
<div key={o.graphNodeId} className={styles.branchCard}>
|
<div key={o.graphNodeId} className={styles.branchCard}>
|
||||||
<div className={styles.branchCardHeader}>
|
<div className={styles.branchCardHeader}>
|
||||||
<div className={styles.branchOption}>ОПЦИЯ {String(i + 1)}</div>
|
<div className={styles.branchOption}>{t('control.option', { n: String(i + 1) })}</div>
|
||||||
</div>
|
</div>
|
||||||
<div className={styles.branchName}>{o.scene.title || 'Без названия'}</div>
|
<div className={styles.branchName}>{o.scene.title || t('control.unnamed')}</div>
|
||||||
<Button
|
<Button
|
||||||
variant="primary"
|
variant="primary"
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
void api.invoke(ipcChannels.project.setCurrentGraphNode, { graphNodeId: o.graphNodeId })
|
void api.invoke(ipcChannels.project.setCurrentGraphNode, { graphNodeId: o.graphNodeId })
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
Переключить
|
{t('control.switchScene')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
{nextScenes.length === 0 ? (
|
{nextScenes.length === 0 ? (
|
||||||
<div className={styles.branchEmpty}>
|
<div className={styles.branchEmpty}>
|
||||||
<div>Нет вариантов перехода.</div>
|
<div>{t('control.noBranches')}</div>
|
||||||
<Button
|
<Button
|
||||||
variant="primary"
|
variant="primary"
|
||||||
disabled={!session?.project?.currentGraphNodeId}
|
disabled={!session?.project?.currentGraphNodeId}
|
||||||
onClick={() => void api.invoke(ipcChannels.windows.closeMultiWindow, {})}
|
onClick={() => void api.invoke(ipcChannels.windows.closeMultiWindow, {})}
|
||||||
>
|
>
|
||||||
Завершить показ
|
{t('control.endPresentation')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
@@ -1072,16 +1292,19 @@ export function ControlApp() {
|
|||||||
|
|
||||||
<Surface className={styles.surfacePad}>
|
<Surface className={styles.surfacePad}>
|
||||||
<div className={styles.musicHeader}>
|
<div className={styles.musicHeader}>
|
||||||
<div className={styles.previewTitle}>Музыка</div>
|
<div className={styles.previewTitle}>{t('control.music')}</div>
|
||||||
</div>
|
</div>
|
||||||
<div className={styles.spacer10} />
|
<div className={styles.spacer10} />
|
||||||
|
<div className={styles.sectionLabel}>{t('control.sceneMusic')}</div>
|
||||||
|
<div className={styles.spacer10} />
|
||||||
{sceneAudios.length === 0 ? (
|
{sceneAudios.length === 0 ? (
|
||||||
<div className={styles.musicEmpty}>В текущей сцене нет аудио.</div>
|
<div className={styles.musicEmpty}>{t('control.noSceneAudio')}</div>
|
||||||
) : (
|
) : null}
|
||||||
|
{sceneAudios.length > 0 ? (
|
||||||
<div className={styles.audioList}>
|
<div className={styles.audioList}>
|
||||||
{sceneAudios.map(({ ref, asset }) => {
|
{sceneAudios.map(({ ref, asset }) => {
|
||||||
const el = audioElsRef.current.get(ref.assetId) ?? null;
|
const el = sceneAudioElsRef.current.get(ref.assetId) ?? null;
|
||||||
const st = audioStatus(ref.assetId);
|
const st = audioStatus('scene', ref.assetId);
|
||||||
const dur = el?.duration && Number.isFinite(el.duration) ? el.duration : 0;
|
const dur = el?.duration && Number.isFinite(el.duration) ? el.duration : 0;
|
||||||
const cur = el?.currentTime && Number.isFinite(el.currentTime) ? el.currentTime : 0;
|
const cur = el?.currentTime && Number.isFinite(el.currentTime) ? el.currentTime : 0;
|
||||||
const pct = dur > 0 ? Math.max(0, Math.min(1, cur / dur)) : 0;
|
const pct = dur > 0 ? Math.max(0, Math.min(1, cur / dur)) : 0;
|
||||||
@@ -1090,8 +1313,8 @@ export function ControlApp() {
|
|||||||
<div className={styles.audioMeta}>
|
<div className={styles.audioMeta}>
|
||||||
<div className={styles.audioName}>{asset.originalName}</div>
|
<div className={styles.audioName}>{asset.originalName}</div>
|
||||||
<div className={styles.audioBadges}>
|
<div className={styles.audioBadges}>
|
||||||
<div>{ref.autoplay ? 'Авто' : 'Ручн.'}</div>
|
<div>{ref.autoplay ? t('control.modeAuto') : t('control.modeManual')}</div>
|
||||||
<div>{ref.loop ? 'Цикл' : 'Один раз'}</div>
|
<div>{ref.loop ? t('control.loop') : t('control.once')}</div>
|
||||||
<div title={st.detail}>{st.label}</div>
|
<div title={st.detail}>{st.label}</div>
|
||||||
</div>
|
</div>
|
||||||
<div className={styles.spacer10} />
|
<div className={styles.spacer10} />
|
||||||
@@ -1106,7 +1329,7 @@ export function ControlApp() {
|
|||||||
if (!dur) return;
|
if (!dur) return;
|
||||||
if (e.key === 'ArrowLeft') el.currentTime = Math.max(0, el.currentTime - 5);
|
if (e.key === 'ArrowLeft') el.currentTime = Math.max(0, el.currentTime - 5);
|
||||||
if (e.key === 'ArrowRight') el.currentTime = Math.min(dur, el.currentTime + 5);
|
if (e.key === 'ArrowRight') el.currentTime = Math.min(dur, el.currentTime + 5);
|
||||||
setAudioStateTick((x) => x + 1);
|
setSceneAudioStateTick((x) => x + 1);
|
||||||
}}
|
}}
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
if (!el) return;
|
if (!el) return;
|
||||||
@@ -1114,13 +1337,13 @@ export function ControlApp() {
|
|||||||
const rect = (e.currentTarget as HTMLDivElement).getBoundingClientRect();
|
const rect = (e.currentTarget as HTMLDivElement).getBoundingClientRect();
|
||||||
const next = (e.clientX - rect.left) / rect.width;
|
const next = (e.clientX - rect.left) / rect.width;
|
||||||
el.currentTime = Math.max(0, Math.min(dur, next * dur));
|
el.currentTime = Math.max(0, Math.min(dur, next * dur));
|
||||||
setAudioStateTick((x) => x + 1);
|
setSceneAudioStateTick((x) => x + 1);
|
||||||
}}
|
}}
|
||||||
className={[
|
className={[
|
||||||
styles.audioScrub,
|
styles.audioScrub,
|
||||||
dur > 0 ? styles.audioScrubPointer : styles.audioScrubDefault,
|
dur > 0 ? styles.audioScrubPointer : styles.audioScrubDefault,
|
||||||
].join(' ')}
|
].join(' ')}
|
||||||
title={dur > 0 ? 'Клик — перемотка' : 'Длительность неизвестна'}
|
title={dur > 0 ? t('control.scrubSeek') : t('control.durationUnknown')}
|
||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
className={styles.scrubFill}
|
className={styles.scrubFill}
|
||||||
@@ -1137,15 +1360,17 @@ export function ControlApp() {
|
|||||||
variant="primary"
|
variant="primary"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
if (!el) return;
|
if (!el) return;
|
||||||
const m = audioMetaRef.current.get(ref.assetId) ?? { lastPlayError: null };
|
const m = sceneAudioMetaRef.current.get(ref.assetId) ?? { lastPlayError: null };
|
||||||
audioMetaRef.current.set(ref.assetId, { ...m, lastPlayError: null });
|
sceneAudioMetaRef.current.set(ref.assetId, { ...m, lastPlayError: null });
|
||||||
void el.play().catch(() => {
|
void el.play().catch(() => {
|
||||||
const mm = audioMetaRef.current.get(ref.assetId) ?? { lastPlayError: null };
|
const mm =
|
||||||
audioMetaRef.current.set(ref.assetId, {
|
sceneAudioMetaRef.current.get(ref.assetId) ??
|
||||||
|
({ lastPlayError: null } as const);
|
||||||
|
sceneAudioMetaRef.current.set(ref.assetId, {
|
||||||
...mm,
|
...mm,
|
||||||
lastPlayError: 'Не удалось запустить.',
|
lastPlayError: t('control.playFailed'),
|
||||||
});
|
});
|
||||||
setAudioStateTick((x) => x + 1);
|
setSceneAudioStateTick((x) => x + 1);
|
||||||
});
|
});
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
@@ -1164,7 +1389,124 @@ export function ControlApp() {
|
|||||||
if (!el) return;
|
if (!el) return;
|
||||||
el.pause();
|
el.pause();
|
||||||
el.currentTime = 0;
|
el.currentTime = 0;
|
||||||
setAudioStateTick((x) => x + 1);
|
setSceneAudioStateTick((x) => x + 1);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
■
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<div className={styles.spacer12} />
|
||||||
|
<div className={styles.sectionLabel}>{t('control.gameMusic')}</div>
|
||||||
|
<div className={styles.spacer10} />
|
||||||
|
{campaignAudios.length === 0 ? (
|
||||||
|
<div className={styles.musicEmpty}>{t('control.noGameAudio')}</div>
|
||||||
|
) : (
|
||||||
|
<div className={styles.audioList}>
|
||||||
|
{campaignAudios.map(({ ref, asset }) => {
|
||||||
|
const el = campaignAudioElsRef.current.get(ref.assetId) ?? null;
|
||||||
|
const st = audioStatus('campaign', ref.assetId);
|
||||||
|
const dur = el?.duration && Number.isFinite(el.duration) ? el.duration : 0;
|
||||||
|
const cur = el?.currentTime && Number.isFinite(el.currentTime) ? el.currentTime : 0;
|
||||||
|
const pct = dur > 0 ? Math.max(0, Math.min(1, cur / dur)) : 0;
|
||||||
|
return (
|
||||||
|
<div key={ref.assetId} className={styles.audioCard}>
|
||||||
|
<div className={styles.audioMeta}>
|
||||||
|
<div className={styles.audioName}>{asset.originalName}</div>
|
||||||
|
<div className={styles.audioBadges}>
|
||||||
|
<div>{ref.autoplay ? t('control.modeAuto') : t('control.modeManual')}</div>
|
||||||
|
<div>{ref.loop ? t('control.loop') : t('control.once')}</div>
|
||||||
|
<div title={st.detail}>{st.label}</div>
|
||||||
|
{!allowCampaignAudio ? (
|
||||||
|
<div title={t('control.pauseSceneMusicTitle')}>{t('control.pauseSceneMusic')}</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
<div className={styles.spacer10} />
|
||||||
|
<div
|
||||||
|
role="slider"
|
||||||
|
aria-valuemin={0}
|
||||||
|
aria-valuemax={dur > 0 ? Math.round(dur) : 0}
|
||||||
|
aria-valuenow={Math.round(cur)}
|
||||||
|
tabIndex={0}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (!el) return;
|
||||||
|
if (!dur) return;
|
||||||
|
if (e.key === 'ArrowLeft') el.currentTime = Math.max(0, el.currentTime - 5);
|
||||||
|
if (e.key === 'ArrowRight') el.currentTime = Math.min(dur, el.currentTime + 5);
|
||||||
|
setCampaignAudioStateTick((x) => x + 1);
|
||||||
|
}}
|
||||||
|
onClick={(e) => {
|
||||||
|
if (!el) return;
|
||||||
|
if (!dur) return;
|
||||||
|
const rect = (e.currentTarget as HTMLDivElement).getBoundingClientRect();
|
||||||
|
const next = (e.clientX - rect.left) / rect.width;
|
||||||
|
el.currentTime = Math.max(0, Math.min(dur, next * dur));
|
||||||
|
setCampaignAudioStateTick((x) => x + 1);
|
||||||
|
}}
|
||||||
|
className={[
|
||||||
|
styles.audioScrub,
|
||||||
|
dur > 0 ? styles.audioScrubPointer : styles.audioScrubDefault,
|
||||||
|
].join(' ')}
|
||||||
|
title={dur > 0 ? t('control.scrubSeek') : t('control.durationUnknown')}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className={styles.scrubFill}
|
||||||
|
style={{ width: `${String(Math.round(pct * 100))}%` }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className={styles.timeRow}>
|
||||||
|
<div>{formatTime(cur)}</div>
|
||||||
|
<div>{dur ? formatTime(dur) : '—:—'}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className={styles.audioTransport}>
|
||||||
|
<Button
|
||||||
|
variant="primary"
|
||||||
|
title={!allowCampaignAudio ? t('control.pauseCampaignTitle') : undefined}
|
||||||
|
onClick={() => {
|
||||||
|
if (!el) return;
|
||||||
|
const m = campaignAudioMetaRef.current.get(ref.assetId) ?? { lastPlayError: null };
|
||||||
|
campaignAudioMetaRef.current.set(ref.assetId, { ...m, lastPlayError: null });
|
||||||
|
// If this track was created for autoplay but autoplay was blocked (e.g. scene music),
|
||||||
|
// it might still be at volume 0. Ensure manual play is audible.
|
||||||
|
try {
|
||||||
|
if (el.volume === 0) el.volume = 1;
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
void el.play().catch(() => {
|
||||||
|
const mm =
|
||||||
|
campaignAudioMetaRef.current.get(ref.assetId) ??
|
||||||
|
({ lastPlayError: null } as const);
|
||||||
|
campaignAudioMetaRef.current.set(ref.assetId, {
|
||||||
|
...mm,
|
||||||
|
lastPlayError: t('control.playFailed'),
|
||||||
|
});
|
||||||
|
setCampaignAudioStateTick((x) => x + 1);
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
▶
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={() => {
|
||||||
|
if (!el) return;
|
||||||
|
el.pause();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
❚❚
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={() => {
|
||||||
|
if (!el) return;
|
||||||
|
el.pause();
|
||||||
|
el.currentTime = 0;
|
||||||
|
setCampaignAudioStateTick((x) => x + 1);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
■
|
■
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import React, { useEffect, useMemo, useState } from 'react';
|
|||||||
|
|
||||||
import { computeTimeSec } from '../../main/video/videoPlaybackStore';
|
import { computeTimeSec } from '../../main/video/videoPlaybackStore';
|
||||||
import type { SessionState } from '../../shared/ipc/contracts';
|
import type { SessionState } from '../../shared/ipc/contracts';
|
||||||
|
import { useEditorI18n } from '../editor/i18n/EditorI18nContext';
|
||||||
import { RotatedImage } from '../shared/RotatedImage';
|
import { RotatedImage } from '../shared/RotatedImage';
|
||||||
import { useAssetUrl } from '../shared/useAssetImageUrl';
|
import { useAssetUrl } from '../shared/useAssetImageUrl';
|
||||||
import { useVideoPlaybackState } from '../shared/video/useVideoPlaybackState';
|
import { useVideoPlaybackState } from '../shared/video/useVideoPlaybackState';
|
||||||
@@ -23,6 +24,7 @@ function fmt(sec: number): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function ControlScenePreview({ session, videoRef, onContentRectChange }: Props) {
|
export function ControlScenePreview({ session, videoRef, onContentRectChange }: Props) {
|
||||||
|
const { t } = useEditorI18n();
|
||||||
const [vp, video] = useVideoPlaybackState();
|
const [vp, video] = useVideoPlaybackState();
|
||||||
const scene =
|
const scene =
|
||||||
session?.project && session.currentSceneId ? session.project.scenes[session.currentSceneId] : undefined;
|
session?.project && session.currentSceneId ? session.project.scenes[session.currentSceneId] : undefined;
|
||||||
@@ -30,6 +32,7 @@ export function ControlScenePreview({ session, videoRef, onContentRectChange }:
|
|||||||
const rot = scene?.previewRotationDeg ?? 0;
|
const rot = scene?.previewRotationDeg ?? 0;
|
||||||
const isVideo = scene?.previewAssetType === 'video';
|
const isVideo = scene?.previewAssetType === 'video';
|
||||||
const assetId = scene?.previewAssetType === 'video' ? scene.previewAssetId : null;
|
const assetId = scene?.previewAssetType === 'video' ? scene.previewAssetId : null;
|
||||||
|
const autostart = scene?.previewVideoAutostart ?? false;
|
||||||
|
|
||||||
const [tick, setTick] = useState(0);
|
const [tick, setTick] = useState(0);
|
||||||
const dur = useMemo(
|
const dur = useMemo(
|
||||||
@@ -38,7 +41,7 @@ export function ControlScenePreview({ session, videoRef, onContentRectChange }:
|
|||||||
if (!v) return 0;
|
if (!v) return 0;
|
||||||
return Number.isFinite(v.duration) ? v.duration : 0;
|
return Number.isFinite(v.duration) ? v.duration : 0;
|
||||||
},
|
},
|
||||||
// tick: перечитываем duration из video ref на каждом кадре RAF
|
// tick: timeupdate / loadedmetadata перечитывают duration и currentTime
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- намеренно
|
// eslint-disable-next-line react-hooks/exhaustive-deps -- намеренно
|
||||||
[tick, videoRef],
|
[tick, videoRef],
|
||||||
);
|
);
|
||||||
@@ -55,23 +58,15 @@ export function ControlScenePreview({ session, videoRef, onContentRectChange }:
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isVideo) return;
|
if (!isVideo) return;
|
||||||
let raf = 0;
|
if (!assetId) return;
|
||||||
const loop = () => {
|
// `target.set` bumps revision and resets anchors; avoid firing on every render.
|
||||||
setTick((x) => x + 1);
|
if (vp?.targetAssetId === assetId) return;
|
||||||
raf = window.requestAnimationFrame(loop);
|
|
||||||
};
|
|
||||||
raf = window.requestAnimationFrame(loop);
|
|
||||||
return () => window.cancelAnimationFrame(raf);
|
|
||||||
}, [isVideo]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!isVideo) return;
|
|
||||||
void video.dispatch({
|
void video.dispatch({
|
||||||
kind: 'target.set',
|
kind: 'target.set',
|
||||||
assetId,
|
assetId,
|
||||||
autostart: scene.previewVideoAutostart,
|
autostart,
|
||||||
});
|
});
|
||||||
}, [assetId, isVideo, scene, video]);
|
}, [assetId, isVideo, autostart, vp?.targetAssetId, video]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const v = videoRef.current;
|
const v = videoRef.current;
|
||||||
@@ -88,7 +83,8 @@ export function ControlScenePreview({ session, videoRef, onContentRectChange }:
|
|||||||
} else {
|
} else {
|
||||||
v.pause();
|
v.pause();
|
||||||
}
|
}
|
||||||
}, [assetId, vp, videoRef]);
|
// eslint-disable-next-line react-hooks/exhaustive-deps -- avoid reruns on 500ms heartbeats (serverNowMs-only updates)
|
||||||
|
}, [assetId, url, vp?.revision, vp?.targetAssetId, vp?.playing, vp?.playbackRate, videoRef]);
|
||||||
|
|
||||||
const scrubClass = [styles.scrub, dur ? styles.scrubPointer : styles.scrubDefault].join(' ');
|
const scrubClass = [styles.scrub, dur ? styles.scrubPointer : styles.scrubDefault].join(' ');
|
||||||
|
|
||||||
@@ -105,8 +101,10 @@ export function ControlScenePreview({ session, videoRef, onContentRectChange }:
|
|||||||
src={url}
|
src={url}
|
||||||
playsInline
|
playsInline
|
||||||
preload="auto"
|
preload="auto"
|
||||||
|
onTimeUpdate={() => setTick((x) => x + 1)}
|
||||||
|
onLoadedMetadata={() => setTick((x) => x + 1)}
|
||||||
>
|
>
|
||||||
<track kind="captions" srcLang="ru" label="Превью без субтитров" />
|
<track kind="captions" srcLang="ru" label={t('control.previewTrackLabel')} />
|
||||||
</video>
|
</video>
|
||||||
) : (
|
) : (
|
||||||
<div className={styles.placeholder} />
|
<div className={styles.placeholder} />
|
||||||
@@ -136,7 +134,7 @@ export function ControlScenePreview({ session, videoRef, onContentRectChange }:
|
|||||||
void video.dispatch({ kind: 'seek', timeSec: Math.min(dur, cur + 5) });
|
void video.dispatch({ kind: 'seek', timeSec: Math.min(dur, cur + 5) });
|
||||||
if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') setTick((x) => x + 1);
|
if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') setTick((x) => x + 1);
|
||||||
}}
|
}}
|
||||||
title="Клик — перемотка"
|
title={t('control.scrubSeek')}
|
||||||
>
|
>
|
||||||
<div className={styles.scrubFill} style={{ width: `${String(Math.round(pct * 100))}%` }} />
|
<div className={styles.scrubFill} style={{ width: `${String(Math.round(pct * 100))}%` }} />
|
||||||
</div>
|
</div>
|
||||||
@@ -146,7 +144,7 @@ export function ControlScenePreview({ session, videoRef, onContentRectChange }:
|
|||||||
type="button"
|
type="button"
|
||||||
className={styles.transportBtn}
|
className={styles.transportBtn}
|
||||||
onClick={() => void video.dispatch({ kind: 'play' })}
|
onClick={() => void video.dispatch({ kind: 'play' })}
|
||||||
title="Play"
|
title={t('control.transportPlay')}
|
||||||
>
|
>
|
||||||
▶
|
▶
|
||||||
</button>
|
</button>
|
||||||
@@ -154,7 +152,7 @@ export function ControlScenePreview({ session, videoRef, onContentRectChange }:
|
|||||||
type="button"
|
type="button"
|
||||||
className={styles.transportBtn}
|
className={styles.transportBtn}
|
||||||
onClick={() => void video.dispatch({ kind: 'pause' })}
|
onClick={() => void video.dispatch({ kind: 'pause' })}
|
||||||
title="Pause"
|
title={t('control.transportPause')}
|
||||||
>
|
>
|
||||||
❚❚
|
❚❚
|
||||||
</button>
|
</button>
|
||||||
@@ -165,7 +163,7 @@ export function ControlScenePreview({ session, videoRef, onContentRectChange }:
|
|||||||
void video.dispatch({ kind: 'stop' });
|
void video.dispatch({ kind: 'stop' });
|
||||||
setTick((x) => x + 1);
|
setTick((x) => x + 1);
|
||||||
}}
|
}}
|
||||||
title="Stop"
|
title={t('control.transportStop')}
|
||||||
>
|
>
|
||||||
■
|
■
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -47,28 +47,28 @@ void test('ControlApp: звук облака яда (public/oblako-yada.mp3)', (
|
|||||||
|
|
||||||
void test('ControlApp: эффекты в пульте, иконки с тултипами и подписью для a11y', () => {
|
void test('ControlApp: эффекты в пульте, иконки с тултипами и подписью для a11y', () => {
|
||||||
const src = readControlApp();
|
const src = readControlApp();
|
||||||
assert.ok(src.includes('ЭФФЕКТЫ'));
|
assert.ok(src.includes("t('control.effects')"));
|
||||||
assert.ok(src.includes('Инструменты'));
|
assert.ok(src.includes("t('control.tools')"));
|
||||||
assert.ok(src.includes('Эффекты поля'));
|
assert.ok(src.includes("t('control.fieldEffects')"));
|
||||||
assert.ok(src.includes('Эффекты действий'));
|
assert.ok(src.includes("t('control.actionEffects')"));
|
||||||
assert.ok(src.includes('Луч света'));
|
assert.ok(src.includes("t('control.sunbeam')"));
|
||||||
assert.ok(src.includes('title="Вода"'));
|
assert.ok(src.includes("title={t('control.water')}"));
|
||||||
assert.ok(src.includes('title="Облако яда"'));
|
assert.ok(src.includes("title={t('control.poisonCloud')}"));
|
||||||
assert.ok(src.includes('title="Туман"'));
|
assert.ok(src.includes("title={t('control.fog')}"));
|
||||||
assert.ok(src.includes('ariaLabel="Туман"'));
|
assert.ok(src.includes("ariaLabel={t('control.fog')}"));
|
||||||
assert.ok(src.includes('iconOnly'));
|
assert.ok(src.includes('iconOnly'));
|
||||||
assert.ok(src.includes('title="Очистить эффекты"'));
|
assert.ok(src.includes("title={t('control.clearEffects')}"));
|
||||||
assert.ok(src.includes('ariaLabel="Очистить эффекты"'));
|
assert.ok(src.includes("ariaLabel={t('control.clearEffects')}"));
|
||||||
assert.ok(src.includes('#e5484d'));
|
assert.ok(src.includes('#e5484d'));
|
||||||
const fx = src.indexOf('ЭФФЕКТЫ');
|
const fx = src.indexOf("t('control.effects')");
|
||||||
const story = src.indexOf('СЮЖЕТНАЯ ЛИНИЯ');
|
const story = src.indexOf("t('control.storyLine')");
|
||||||
assert.ok(fx !== -1 && story !== -1 && fx < story, 'Блок эффектов должен быть выше сюжетной линии');
|
assert.ok(fx !== -1 && story !== -1 && fx < story, 'Блок эффектов должен быть выше сюжетной линии');
|
||||||
});
|
});
|
||||||
|
|
||||||
void test('ControlApp: сюжетная линия — колонка сверху вниз и фон как у карточек ветвления', () => {
|
void test('ControlApp: сюжетная линия — колонка сверху вниз и фон как у карточек ветвления', () => {
|
||||||
const src = readControlApp();
|
const src = readControlApp();
|
||||||
const css = readControlAppCss();
|
const css = readControlAppCss();
|
||||||
const story = src.indexOf('СЮЖЕТНАЯ ЛИНИЯ');
|
const story = src.indexOf("t('control.storyLine')");
|
||||||
assert.ok(story !== -1);
|
assert.ok(story !== -1);
|
||||||
assert.ok(src.includes('className={styles.storyScroll}'));
|
assert.ok(src.includes('className={styles.storyScroll}'));
|
||||||
assert.match(css, /\.storyScroll[\s\S]*?justify-content:\s*flex-start/);
|
assert.match(css, /\.storyScroll[\s\S]*?justify-content:\s*flex-start/);
|
||||||
@@ -86,11 +86,46 @@ void test('ControlApp: слой кисти не использует курсо
|
|||||||
|
|
||||||
void test('ControlApp: радиус кисти не в блоке предпросмотра', () => {
|
void test('ControlApp: радиус кисти не в блоке предпросмотра', () => {
|
||||||
const src = readControlApp();
|
const src = readControlApp();
|
||||||
const previewLabel = src.indexOf('Предпросмотр экрана');
|
const previewLabel = src.indexOf("t('control.screenPreview')");
|
||||||
const radius = src.indexOf('Радиус кисти');
|
const radius = src.indexOf("t('control.brushRadius')");
|
||||||
assert.ok(previewLabel !== -1 && radius !== -1);
|
assert.ok(previewLabel !== -1 && radius !== -1);
|
||||||
assert.ok(
|
assert.ok(
|
||||||
radius < previewLabel,
|
radius < previewLabel,
|
||||||
'Слайдер радиуса должен быть в пульте (файл: выше заголовка предпросмотра)',
|
'Слайдер радиуса должен быть в пульте (файл: выше заголовка предпросмотра)',
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
void test('ControlApp: музыка разделена на сцену и кампанию', () => {
|
||||||
|
const src = readControlApp();
|
||||||
|
assert.ok(src.includes("t('control.sceneMusic')"));
|
||||||
|
assert.ok(src.includes("t('control.gameMusic')"));
|
||||||
|
// при музыке сцены — кампанию ставим на паузу
|
||||||
|
assert.ok(src.includes('allowCampaignAudio'));
|
||||||
|
assert.ok(
|
||||||
|
src.includes('campaignAudioSpecKey'),
|
||||||
|
'кампания: перезагрузка аудио привязана к списку треков, не к смене сцены',
|
||||||
|
);
|
||||||
|
assert.match(src, /pause campaign\./i);
|
||||||
|
});
|
||||||
|
|
||||||
|
void test('ControlApp: загрузка камп. аудио — useEffect зависит только от api и campaignAudioSpecKey', () => {
|
||||||
|
const src = readControlApp();
|
||||||
|
const re = /\/\/ Campaign elements:[\s\S]*?useEffect\(\(\) => \{[\s\S]*?\}\s*,\s*\[([^\]]*)\]\s*\)\s*;/;
|
||||||
|
const m = re.exec(src);
|
||||||
|
assert.ok(m, 'ожидается useEffect загрузки кампании после комментария Campaign elements');
|
||||||
|
const depList = m[1];
|
||||||
|
assert.ok(depList !== undefined);
|
||||||
|
const deps = depList
|
||||||
|
.split(',')
|
||||||
|
.map((s) => s.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
assert.deepEqual(
|
||||||
|
deps,
|
||||||
|
['api', 'campaignAudioSpecKey'],
|
||||||
|
'смена сцены / allowCampaignAudio / campaignAudioRefs не должны перезапускать загрузку кампании',
|
||||||
|
);
|
||||||
|
assert.ok(!/\ballowCampaignAudio\b/.test(depList));
|
||||||
|
assert.ok(!/\bcurrentScene\b/.test(depList));
|
||||||
|
assert.ok(!/\bproject\b/.test(depList));
|
||||||
|
assert.ok(!/\bcampaignAudioRefs\b/.test(depList));
|
||||||
|
});
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ import React from 'react';
|
|||||||
import { createRoot } from 'react-dom/client';
|
import { createRoot } from 'react-dom/client';
|
||||||
|
|
||||||
import '../shared/ui/globals.css';
|
import '../shared/ui/globals.css';
|
||||||
|
import { EditorI18nProvider } from '../editor/i18n/EditorI18nContext';
|
||||||
|
|
||||||
import { ControlApp } from './ControlApp';
|
import { ControlApp } from './ControlApp';
|
||||||
|
|
||||||
const rootEl = document.getElementById('root');
|
const rootEl = document.getElementById('root');
|
||||||
@@ -11,6 +13,8 @@ if (!rootEl) {
|
|||||||
|
|
||||||
createRoot(rootEl).render(
|
createRoot(rootEl).render(
|
||||||
<React.StrictMode>
|
<React.StrictMode>
|
||||||
<ControlApp />
|
<EditorI18nProvider>
|
||||||
|
<ControlApp />
|
||||||
|
</EditorI18nProvider>
|
||||||
</React.StrictMode>,
|
</React.StrictMode>,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -100,6 +100,10 @@
|
|||||||
height: 14px;
|
height: 14px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.spacer18 {
|
||||||
|
height: 18px;
|
||||||
|
}
|
||||||
|
|
||||||
.sidebarScroll {
|
.sidebarScroll {
|
||||||
overflow: auto;
|
overflow: auto;
|
||||||
padding-right: 2px;
|
padding-right: 2px;
|
||||||
@@ -120,6 +124,84 @@
|
|||||||
background: var(--bg0);
|
background: var(--bg0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.progressOverlay {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
background: rgba(0, 0, 0, 0.55);
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
z-index: 10000;
|
||||||
|
}
|
||||||
|
|
||||||
|
.editorLockOverlay {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
background: rgba(0, 0, 0, 0.35);
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
z-index: 11000;
|
||||||
|
}
|
||||||
|
|
||||||
|
.editorLockModal {
|
||||||
|
width: min(520px, calc(100vw - 32px));
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 14px;
|
||||||
|
background: rgba(25, 28, 38, 0.92);
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.12);
|
||||||
|
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.55);
|
||||||
|
display: grid;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.editorLockTitle {
|
||||||
|
font-weight: 800;
|
||||||
|
opacity: 0.95;
|
||||||
|
}
|
||||||
|
|
||||||
|
.editorLockText {
|
||||||
|
opacity: 0.85;
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 1.45;
|
||||||
|
}
|
||||||
|
|
||||||
|
.progressModal {
|
||||||
|
width: min(520px, calc(100vw - 32px));
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 14px;
|
||||||
|
background: rgba(25, 28, 38, 0.92);
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.12);
|
||||||
|
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.55);
|
||||||
|
}
|
||||||
|
|
||||||
|
.progressTitle {
|
||||||
|
font-weight: 700;
|
||||||
|
margin-bottom: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.progressBar {
|
||||||
|
height: 10px;
|
||||||
|
border-radius: 999px;
|
||||||
|
overflow: hidden;
|
||||||
|
background: rgba(255, 255, 255, 0.08);
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.progressFill {
|
||||||
|
height: 100%;
|
||||||
|
width: 0%;
|
||||||
|
background: rgba(167, 139, 250, 0.85);
|
||||||
|
}
|
||||||
|
|
||||||
|
.progressMeta {
|
||||||
|
margin-top: 10px;
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
opacity: 0.9;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
.inspectorTitle {
|
.inspectorTitle {
|
||||||
font-weight: 800;
|
font-weight: 800;
|
||||||
margin-bottom: 12px;
|
margin-bottom: 12px;
|
||||||
@@ -161,6 +243,33 @@
|
|||||||
font: inherit;
|
font: inherit;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.fileMenuSubHost {
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
.fileMenuItemExpand {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.fileMenuSub {
|
||||||
|
position: absolute;
|
||||||
|
left: calc(100% + 6px);
|
||||||
|
top: 0;
|
||||||
|
min-width: 200px;
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
border: 1px solid var(--stroke);
|
||||||
|
background: var(--color-surface-elevated-2);
|
||||||
|
box-shadow: var(--shadow-lg);
|
||||||
|
padding: 6px;
|
||||||
|
display: grid;
|
||||||
|
gap: 4px;
|
||||||
|
z-index: calc(var(--z-file-menu) + 1);
|
||||||
|
}
|
||||||
|
|
||||||
.modalBackdrop {
|
.modalBackdrop {
|
||||||
position: fixed;
|
position: fixed;
|
||||||
inset: 0;
|
inset: 0;
|
||||||
@@ -408,10 +517,55 @@
|
|||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
background: var(--color-overlay-dark-3);
|
background: var(--color-overlay-dark-3);
|
||||||
aspect-ratio: 16 / 9;
|
aspect-ratio: 16 / 9;
|
||||||
max-height: 140px;
|
width: 100%;
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
.previewFill {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.previewBusyOverlay {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
background: rgba(0, 0, 0, 0.55);
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.previewBusyModal {
|
||||||
|
display: grid;
|
||||||
|
justify-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
color: var(--text1);
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.previewBusyText {
|
||||||
|
font-size: var(--text-xs);
|
||||||
|
font-weight: 700;
|
||||||
|
color: rgba(255, 255, 255, 0.92);
|
||||||
|
}
|
||||||
|
|
||||||
|
.previewSpinner {
|
||||||
|
width: 26px;
|
||||||
|
height: 26px;
|
||||||
|
border-radius: 999px;
|
||||||
|
border: 3px solid rgba(255, 255, 255, 0.25);
|
||||||
|
border-top-color: rgba(255, 255, 255, 0.9);
|
||||||
|
animation: previewSpin 0.9s linear infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes previewSpin {
|
||||||
|
to {
|
||||||
|
transform: rotate(360deg);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.videoCover {
|
.videoCover {
|
||||||
|
|||||||
+938
-222
File diff suppressed because it is too large
Load Diff
@@ -20,8 +20,10 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.cardActive {
|
.cardActive {
|
||||||
border-color: var(--graph-node-active-border);
|
border-color: rgba(167, 139, 250, 0.95);
|
||||||
box-shadow: 0 25px 50px -12px rgba(139, 92, 246, 0.1);
|
box-shadow:
|
||||||
|
0 0 0 2px rgba(167, 139, 250, 0.35),
|
||||||
|
0 25px 50px -12px rgba(167, 139, 250, 0.12);
|
||||||
}
|
}
|
||||||
|
|
||||||
.previewShell {
|
.previewShell {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';
|
||||||
import { createPortal } from 'react-dom';
|
import { createPortal } from 'react-dom';
|
||||||
import ReactFlow, {
|
import ReactFlow, {
|
||||||
Background,
|
Background,
|
||||||
@@ -19,19 +19,30 @@ import ReactFlow, {
|
|||||||
import 'reactflow/dist/style.css';
|
import 'reactflow/dist/style.css';
|
||||||
|
|
||||||
import { isSceneGraphEdgeRejected } from '../../../shared/graph/sceneGraphEdgeRules';
|
import { isSceneGraphEdgeRejected } from '../../../shared/graph/sceneGraphEdgeRules';
|
||||||
import type {
|
import type { AssetId, GraphNodeId, SceneGraphEdge, SceneGraphNode, SceneId } from '../../../shared/types';
|
||||||
AssetId,
|
|
||||||
GraphNodeId,
|
|
||||||
Scene,
|
|
||||||
SceneGraphEdge,
|
|
||||||
SceneGraphNode,
|
|
||||||
SceneId,
|
|
||||||
} from '../../../shared/types';
|
|
||||||
import { RotatedImage } from '../../shared/RotatedImage';
|
import { RotatedImage } from '../../shared/RotatedImage';
|
||||||
import { useAssetUrl } from '../../shared/useAssetImageUrl';
|
import { useAssetUrl } from '../../shared/useAssetImageUrl';
|
||||||
|
|
||||||
import styles from './SceneGraph.module.css';
|
import styles from './SceneGraph.module.css';
|
||||||
|
|
||||||
|
/** Поля сцены, нужные только для карточки узла графа (без описания и прочего). */
|
||||||
|
export type SceneGraphSceneAudioSummary = {
|
||||||
|
assetId: AssetId;
|
||||||
|
loop: boolean;
|
||||||
|
autoplay: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type SceneGraphSceneCard = {
|
||||||
|
title: string;
|
||||||
|
previewAssetId: AssetId | null;
|
||||||
|
previewThumbAssetId: AssetId | null;
|
||||||
|
previewAssetType: 'image' | 'video' | null;
|
||||||
|
previewVideoAutostart: boolean;
|
||||||
|
previewRotationDeg: 0 | 90 | 180 | 270;
|
||||||
|
loopVideo: boolean;
|
||||||
|
audios: readonly SceneGraphSceneAudioSummary[];
|
||||||
|
};
|
||||||
|
|
||||||
/** MIME для перетаскивания сцены из списка на граф (см. EditorApp). */
|
/** MIME для перетаскивания сцены из списка на граф (см. EditorApp). */
|
||||||
export const DND_SCENE_ID_MIME = 'application/x-dnd-scene-id';
|
export const DND_SCENE_ID_MIME = 'application/x-dnd-scene-id';
|
||||||
|
|
||||||
@@ -39,11 +50,53 @@ export const DND_SCENE_ID_MIME = 'application/x-dnd-scene-id';
|
|||||||
const SCENE_CARD_W = 220;
|
const SCENE_CARD_W = 220;
|
||||||
const SCENE_CARD_H = 248;
|
const SCENE_CARD_H = 248;
|
||||||
|
|
||||||
|
/** UI strings for the scene graph (passed from editor i18n). */
|
||||||
|
export type SceneGraphUiStrings = {
|
||||||
|
badgeStart: string;
|
||||||
|
untitled: string;
|
||||||
|
videoBadge: string;
|
||||||
|
audioBadge: string;
|
||||||
|
loop: string;
|
||||||
|
autoplay: string;
|
||||||
|
previewAutostart: string;
|
||||||
|
videoLoop: string;
|
||||||
|
zoomBar: string;
|
||||||
|
zoomIn: string;
|
||||||
|
zoomOut: string;
|
||||||
|
fitAll: string;
|
||||||
|
closeMenu: string;
|
||||||
|
startScene: string;
|
||||||
|
unsetStartScene: string;
|
||||||
|
delete: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const DEFAULT_SCENE_GRAPH_UI: SceneGraphUiStrings = {
|
||||||
|
badgeStart: 'НАЧАЛО',
|
||||||
|
untitled: 'Без названия',
|
||||||
|
videoBadge: 'Видео',
|
||||||
|
audioBadge: 'Аудио',
|
||||||
|
loop: 'Цикл',
|
||||||
|
autoplay: 'Автостарт',
|
||||||
|
previewAutostart: 'Авто превью',
|
||||||
|
videoLoop: 'Цикл видео',
|
||||||
|
zoomBar: 'Масштаб графа',
|
||||||
|
zoomIn: 'Увеличить',
|
||||||
|
zoomOut: 'Уменьшить',
|
||||||
|
fitAll: 'Показать всё',
|
||||||
|
closeMenu: 'Закрыть меню',
|
||||||
|
startScene: 'Начальная сцена',
|
||||||
|
unsetStartScene: 'Снять метку «Начальная сцена»',
|
||||||
|
delete: 'Удалить',
|
||||||
|
};
|
||||||
|
|
||||||
|
const GraphUiContext = createContext<SceneGraphUiStrings>(DEFAULT_SCENE_GRAPH_UI);
|
||||||
|
|
||||||
export type SceneGraphProps = {
|
export type SceneGraphProps = {
|
||||||
sceneGraphNodes: SceneGraphNode[];
|
sceneGraphNodes: SceneGraphNode[];
|
||||||
sceneGraphEdges: SceneGraphEdge[];
|
sceneGraphEdges: SceneGraphEdge[];
|
||||||
sceneById: Record<SceneId, Scene>;
|
sceneCardById: Record<SceneId, SceneGraphSceneCard>;
|
||||||
currentSceneId: SceneId | null;
|
currentSceneId: SceneId | null;
|
||||||
|
graphUi?: SceneGraphUiStrings;
|
||||||
onCurrentSceneChange: (id: SceneId) => void;
|
onCurrentSceneChange: (id: SceneId) => void;
|
||||||
onConnect: (sourceGraphNodeId: GraphNodeId, targetGraphNodeId: GraphNodeId) => void;
|
onConnect: (sourceGraphNodeId: GraphNodeId, targetGraphNodeId: GraphNodeId) => void;
|
||||||
onDisconnect: (edgeId: string) => void;
|
onDisconnect: (edgeId: string) => void;
|
||||||
@@ -59,6 +112,7 @@ type SceneCardData = {
|
|||||||
title: string;
|
title: string;
|
||||||
active: boolean;
|
active: boolean;
|
||||||
previewAssetId: AssetId | null;
|
previewAssetId: AssetId | null;
|
||||||
|
previewThumbAssetId: AssetId | null;
|
||||||
previewAssetType: 'image' | 'video' | null;
|
previewAssetType: 'image' | 'video' | null;
|
||||||
previewVideoAutostart: boolean;
|
previewVideoAutostart: boolean;
|
||||||
previewRotationDeg: 0 | 90 | 180 | 270;
|
previewRotationDeg: 0 | 90 | 180 | 270;
|
||||||
@@ -119,7 +173,9 @@ function IconVideoPreviewAutostart() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function SceneCardNode({ data }: NodeProps<SceneCardData>) {
|
function SceneCardNode({ data }: NodeProps<SceneCardData>) {
|
||||||
const url = useAssetUrl(data.previewAssetId);
|
const ui = useContext(GraphUiContext);
|
||||||
|
const thumbUrl = useAssetUrl(data.previewThumbAssetId);
|
||||||
|
const previewUrl = useAssetUrl(data.previewAssetId);
|
||||||
const cardClass = [styles.card, data.active ? styles.cardActive : ''].filter(Boolean).join(' ');
|
const cardClass = [styles.card, data.active ? styles.cardActive : ''].filter(Boolean).join(' ');
|
||||||
const showCornerVideo = data.previewIsVideo;
|
const showCornerVideo = data.previewIsVideo;
|
||||||
const showCornerAudio = data.hasSceneAudio;
|
const showCornerAudio = data.hasSceneAudio;
|
||||||
@@ -128,23 +184,54 @@ function SceneCardNode({ data }: NodeProps<SceneCardData>) {
|
|||||||
<Handle type="target" position={Position.Top} className={styles.handle} />
|
<Handle type="target" position={Position.Top} className={styles.handle} />
|
||||||
<div className={cardClass}>
|
<div className={cardClass}>
|
||||||
<div className={styles.previewShell}>
|
<div className={styles.previewShell}>
|
||||||
{data.isStartScene ? <div className={styles.badgeStart}>НАЧАЛО</div> : null}
|
{data.isStartScene ? <div className={styles.badgeStart}>{ui.badgeStart}</div> : null}
|
||||||
{url && data.previewAssetType === 'image' ? (
|
{thumbUrl ? (
|
||||||
<div className={styles.previewFill}>
|
<div className={styles.previewFill}>
|
||||||
{data.previewRotationDeg === 0 ? (
|
{data.previewRotationDeg === 0 ? (
|
||||||
<img src={url} alt="" className={styles.imageCover} draggable={false} />
|
<img
|
||||||
|
src={thumbUrl}
|
||||||
|
alt=""
|
||||||
|
className={styles.imageCover}
|
||||||
|
draggable={false}
|
||||||
|
loading="lazy"
|
||||||
|
decoding="async"
|
||||||
|
/>
|
||||||
) : (
|
) : (
|
||||||
<RotatedImage
|
<RotatedImage
|
||||||
url={url}
|
url={thumbUrl}
|
||||||
rotationDeg={data.previewRotationDeg}
|
rotationDeg={data.previewRotationDeg}
|
||||||
mode="cover"
|
mode="cover"
|
||||||
|
loading="lazy"
|
||||||
|
decoding="async"
|
||||||
style={{ width: '100%', height: '100%' }}
|
style={{ width: '100%', height: '100%' }}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
) : url && data.previewAssetType === 'video' ? (
|
) : previewUrl && data.previewAssetType === 'image' ? (
|
||||||
|
<div className={styles.previewFill}>
|
||||||
|
{data.previewRotationDeg === 0 ? (
|
||||||
|
<img
|
||||||
|
src={previewUrl}
|
||||||
|
alt=""
|
||||||
|
className={styles.imageCover}
|
||||||
|
draggable={false}
|
||||||
|
loading="lazy"
|
||||||
|
decoding="async"
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<RotatedImage
|
||||||
|
url={previewUrl}
|
||||||
|
rotationDeg={data.previewRotationDeg}
|
||||||
|
mode="cover"
|
||||||
|
loading="lazy"
|
||||||
|
decoding="async"
|
||||||
|
style={{ width: '100%', height: '100%' }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
) : previewUrl && data.previewAssetType === 'video' ? (
|
||||||
<video
|
<video
|
||||||
src={url}
|
src={previewUrl}
|
||||||
muted
|
muted
|
||||||
playsInline
|
playsInline
|
||||||
preload="metadata"
|
preload="metadata"
|
||||||
@@ -165,12 +252,12 @@ function SceneCardNode({ data }: NodeProps<SceneCardData>) {
|
|||||||
{showCornerVideo || showCornerAudio ? (
|
{showCornerVideo || showCornerAudio ? (
|
||||||
<div className={styles.cornerBadges}>
|
<div className={styles.cornerBadges}>
|
||||||
{showCornerVideo ? (
|
{showCornerVideo ? (
|
||||||
<span className={styles.mediaBadge} title="Видео">
|
<span className={styles.mediaBadge} title={ui.videoBadge}>
|
||||||
<IconVideoBadge />
|
<IconVideoBadge />
|
||||||
</span>
|
</span>
|
||||||
) : null}
|
) : null}
|
||||||
{showCornerAudio ? (
|
{showCornerAudio ? (
|
||||||
<span className={styles.mediaBadge} title="Аудио">
|
<span className={styles.mediaBadge} title={ui.audioBadge}>
|
||||||
<IconAudioBadge />
|
<IconAudioBadge />
|
||||||
</span>
|
</span>
|
||||||
) : null}
|
) : null}
|
||||||
@@ -178,19 +265,19 @@ function SceneCardNode({ data }: NodeProps<SceneCardData>) {
|
|||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
<div className={styles.nodeBody}>
|
<div className={styles.nodeBody}>
|
||||||
<div className={styles.title}>{data.title || 'Без названия'}</div>
|
<div className={styles.title}>{data.title || ui.untitled}</div>
|
||||||
{data.hasAnyAudioLoop || data.hasAnyAudioAutoplay ? (
|
{data.hasAnyAudioLoop || data.hasAnyAudioAutoplay ? (
|
||||||
<div className={styles.musicParams}>
|
<div className={styles.musicParams}>
|
||||||
{data.hasAnyAudioLoop ? (
|
{data.hasAnyAudioLoop ? (
|
||||||
<div className={styles.musicParam}>
|
<div className={styles.musicParam}>
|
||||||
<IconLoopParam />
|
<IconLoopParam />
|
||||||
<span>Цикл</span>
|
<span>{ui.loop}</span>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
{data.hasAnyAudioAutoplay ? (
|
{data.hasAnyAudioAutoplay ? (
|
||||||
<div className={styles.musicParam}>
|
<div className={styles.musicParam}>
|
||||||
<IconAutoplayParam />
|
<IconAutoplayParam />
|
||||||
<span>Автостарт</span>
|
<span>{ui.autoplay}</span>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
@@ -200,13 +287,13 @@ function SceneCardNode({ data }: NodeProps<SceneCardData>) {
|
|||||||
{data.showPreviewVideoAutostart ? (
|
{data.showPreviewVideoAutostart ? (
|
||||||
<div className={styles.musicParam}>
|
<div className={styles.musicParam}>
|
||||||
<IconVideoPreviewAutostart />
|
<IconVideoPreviewAutostart />
|
||||||
<span>Авто превью</span>
|
<span>{ui.previewAutostart}</span>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
{data.showPreviewVideoLoop ? (
|
{data.showPreviewVideoLoop ? (
|
||||||
<div className={styles.musicParam}>
|
<div className={styles.musicParam}>
|
||||||
<IconLoopParam />
|
<IconLoopParam />
|
||||||
<span>Цикл видео</span>
|
<span>{ui.videoLoop}</span>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
@@ -221,18 +308,19 @@ function SceneCardNode({ data }: NodeProps<SceneCardData>) {
|
|||||||
const nodeTypes = { sceneCard: SceneCardNode };
|
const nodeTypes = { sceneCard: SceneCardNode };
|
||||||
|
|
||||||
function GraphZoomToolbar() {
|
function GraphZoomToolbar() {
|
||||||
|
const ui = useContext(GraphUiContext);
|
||||||
const { zoomIn, zoomOut, fitView } = useReactFlow();
|
const { zoomIn, zoomOut, fitView } = useReactFlow();
|
||||||
const zoom = useStore((s) => s.transform[2]);
|
const zoom = useStore((s) => s.transform[2]);
|
||||||
const pct = Math.max(1, Math.round(zoom * 100));
|
const pct = Math.max(1, Math.round(zoom * 100));
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Panel position="bottom-center" className={styles.zoomPanel}>
|
<Panel position="bottom-center" className={styles.zoomPanel}>
|
||||||
<div className={styles.zoomBar} role="toolbar" aria-label="Масштаб графа">
|
<div className={styles.zoomBar} role="toolbar" aria-label={ui.zoomBar}>
|
||||||
<button type="button" className={styles.zoomBtn} onClick={() => zoomIn()} aria-label="Увеличить">
|
<button type="button" className={styles.zoomBtn} onClick={() => zoomIn()} aria-label={ui.zoomIn}>
|
||||||
+
|
+
|
||||||
</button>
|
</button>
|
||||||
<span className={styles.zoomPct}>{pct}%</span>
|
<span className={styles.zoomPct}>{pct}%</span>
|
||||||
<button type="button" className={styles.zoomBtn} onClick={() => zoomOut()} aria-label="Уменьшить">
|
<button type="button" className={styles.zoomBtn} onClick={() => zoomOut()} aria-label={ui.zoomOut}>
|
||||||
−
|
−
|
||||||
</button>
|
</button>
|
||||||
<span className={styles.zoomDivider} aria-hidden />
|
<span className={styles.zoomDivider} aria-hidden />
|
||||||
@@ -240,8 +328,8 @@ function GraphZoomToolbar() {
|
|||||||
type="button"
|
type="button"
|
||||||
className={styles.zoomBtn}
|
className={styles.zoomBtn}
|
||||||
onClick={() => fitView({ padding: 0.25 })}
|
onClick={() => fitView({ padding: 0.25 })}
|
||||||
aria-label="Показать всё"
|
aria-label={ui.fitAll}
|
||||||
title="Показать всё"
|
title={ui.fitAll}
|
||||||
>
|
>
|
||||||
<svg className={styles.zoomFitIcon} viewBox="0 0 24 24" width={18} height={18} aria-hidden>
|
<svg className={styles.zoomFitIcon} viewBox="0 0 24 24" width={18} height={18} aria-hidden>
|
||||||
<path
|
<path
|
||||||
@@ -261,8 +349,9 @@ function GraphZoomToolbar() {
|
|||||||
function SceneGraphCanvas({
|
function SceneGraphCanvas({
|
||||||
sceneGraphNodes,
|
sceneGraphNodes,
|
||||||
sceneGraphEdges,
|
sceneGraphEdges,
|
||||||
sceneById,
|
sceneCardById,
|
||||||
currentSceneId,
|
currentSceneId,
|
||||||
|
graphUi,
|
||||||
onCurrentSceneChange,
|
onCurrentSceneChange,
|
||||||
onConnect,
|
onConnect,
|
||||||
onDisconnect,
|
onDisconnect,
|
||||||
@@ -272,6 +361,7 @@ function SceneGraphCanvas({
|
|||||||
onSetGraphNodeStart,
|
onSetGraphNodeStart,
|
||||||
onDropSceneFromList,
|
onDropSceneFromList,
|
||||||
}: SceneGraphProps) {
|
}: SceneGraphProps) {
|
||||||
|
const ui = graphUi ?? DEFAULT_SCENE_GRAPH_UI;
|
||||||
const { screenToFlowPosition } = useReactFlow();
|
const { screenToFlowPosition } = useReactFlow();
|
||||||
const [menu, setMenu] = useState<{ x: number; y: number; graphNodeId: GraphNodeId } | null>(null);
|
const [menu, setMenu] = useState<{ x: number; y: number; graphNodeId: GraphNodeId } | null>(null);
|
||||||
|
|
||||||
@@ -291,45 +381,66 @@ function SceneGraphCanvas({
|
|||||||
|
|
||||||
const desiredNodes = useMemo<Node<SceneCardData>[]>(() => {
|
const desiredNodes = useMemo<Node<SceneCardData>[]>(() => {
|
||||||
return sceneGraphNodes.map((gn) => {
|
return sceneGraphNodes.map((gn) => {
|
||||||
const s = sceneById[gn.sceneId];
|
const c = sceneCardById[gn.sceneId];
|
||||||
const active = gn.sceneId === currentSceneId;
|
const active = gn.sceneId === currentSceneId;
|
||||||
const audios = s?.media.audios ?? [];
|
const audios = c?.audios ?? [];
|
||||||
return {
|
return {
|
||||||
id: gn.id,
|
id: gn.id,
|
||||||
type: 'sceneCard',
|
type: 'sceneCard',
|
||||||
position: { x: gn.x, y: gn.y },
|
position: { x: gn.x, y: gn.y },
|
||||||
data: {
|
data: {
|
||||||
sceneId: gn.sceneId,
|
sceneId: gn.sceneId,
|
||||||
title: s?.title ?? '',
|
title: c?.title ?? '',
|
||||||
active,
|
active,
|
||||||
previewAssetId: s?.previewAssetId ?? null,
|
previewAssetId: c?.previewAssetId ?? null,
|
||||||
previewAssetType: s?.previewAssetType ?? null,
|
previewThumbAssetId: c?.previewThumbAssetId ?? null,
|
||||||
previewVideoAutostart: s?.previewVideoAutostart ?? false,
|
previewAssetType: c?.previewAssetType ?? null,
|
||||||
previewRotationDeg: s?.previewRotationDeg ?? 0,
|
previewVideoAutostart: c?.previewVideoAutostart ?? false,
|
||||||
|
previewRotationDeg: c?.previewRotationDeg ?? 0,
|
||||||
isStartScene: gn.isStartScene,
|
isStartScene: gn.isStartScene,
|
||||||
hasSceneAudio: audios.length >= 1,
|
hasSceneAudio: audios.length >= 1,
|
||||||
previewIsVideo: s?.previewAssetType === 'video',
|
previewIsVideo: c?.previewAssetType === 'video',
|
||||||
hasAnyAudioLoop: audios.some((a) => a.loop),
|
hasAnyAudioLoop: audios.some((a) => a.loop),
|
||||||
hasAnyAudioAutoplay: audios.some((a) => a.autoplay),
|
hasAnyAudioAutoplay: audios.some((a) => a.autoplay),
|
||||||
showPreviewVideoAutostart: s?.previewAssetType === 'video' ? s.previewVideoAutostart : false,
|
showPreviewVideoAutostart: c?.previewAssetType === 'video' ? c.previewVideoAutostart : false,
|
||||||
showPreviewVideoLoop: s?.previewAssetType === 'video' ? s.settings.loopVideo : false,
|
showPreviewVideoLoop: c?.previewAssetType === 'video' ? c.loopVideo : false,
|
||||||
},
|
},
|
||||||
style: { padding: 0, background: 'transparent', border: 'none' },
|
style: { padding: 0, background: 'transparent', border: 'none' },
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
}, [currentSceneId, sceneById, sceneGraphNodes]);
|
}, [currentSceneId, sceneCardById, sceneGraphNodes]);
|
||||||
|
|
||||||
const desiredEdges = useMemo<Edge[]>(() => {
|
const desiredEdges = useMemo<Edge[]>(() => {
|
||||||
|
const selectedGraphNodeIds = new Set<GraphNodeId>();
|
||||||
|
if (currentSceneId) {
|
||||||
|
for (const gn of sceneGraphNodes) {
|
||||||
|
if (gn.sceneId === currentSceneId) selectedGraphNodeIds.add(gn.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const hasSelection = selectedGraphNodeIds.size > 0;
|
||||||
return sceneGraphEdges.map((e) => ({
|
return sceneGraphEdges.map((e) => ({
|
||||||
|
...(hasSelection
|
||||||
|
? {
|
||||||
|
style:
|
||||||
|
selectedGraphNodeIds.has(e.sourceGraphNodeId) || selectedGraphNodeIds.has(e.targetGraphNodeId)
|
||||||
|
? { stroke: 'rgba(167,139,250,0.95)', strokeWidth: 3 }
|
||||||
|
: { stroke: 'rgba(255,255,255,0.10)', strokeWidth: 2 },
|
||||||
|
markerEnd:
|
||||||
|
selectedGraphNodeIds.has(e.sourceGraphNodeId) || selectedGraphNodeIds.has(e.targetGraphNodeId)
|
||||||
|
? { type: MarkerType.ArrowClosed, color: 'rgba(167,139,250,0.95)', strokeWidth: 2 }
|
||||||
|
: { type: MarkerType.ArrowClosed, color: 'rgba(255,255,255,0.18)', strokeWidth: 2 },
|
||||||
|
}
|
||||||
|
: {
|
||||||
|
style: { stroke: 'rgba(167,139,250,0.55)', strokeWidth: 2 },
|
||||||
|
markerEnd: { type: MarkerType.ArrowClosed, color: 'rgba(167,139,250,0.85)', strokeWidth: 2 },
|
||||||
|
}),
|
||||||
id: e.id,
|
id: e.id,
|
||||||
source: e.sourceGraphNodeId,
|
source: e.sourceGraphNodeId,
|
||||||
target: e.targetGraphNodeId,
|
target: e.targetGraphNodeId,
|
||||||
type: 'smoothstep',
|
type: 'smoothstep',
|
||||||
animated: false,
|
animated: false,
|
||||||
style: { stroke: 'rgba(167,139,250,0.55)', strokeWidth: 2 },
|
|
||||||
markerEnd: { type: MarkerType.ArrowClosed, color: 'rgba(167,139,250,0.85)', strokeWidth: 2 },
|
|
||||||
}));
|
}));
|
||||||
}, [sceneGraphEdges]);
|
}, [currentSceneId, sceneGraphEdges, sceneGraphNodes]);
|
||||||
|
|
||||||
const [nodes, setNodes, onNodesChange] = useNodesState<Node<SceneCardData>>([]);
|
const [nodes, setNodes, onNodesChange] = useNodesState<Node<SceneCardData>>([]);
|
||||||
const [edges, setEdges, onEdgesChange] = useEdgesState<Edge>([]);
|
const [edges, setEdges, onEdgesChange] = useEdgesState<Edge>([]);
|
||||||
@@ -381,109 +492,111 @@ function SceneGraphCanvas({
|
|||||||
}, [menu]);
|
}, [menu]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={styles.canvasWrap}>
|
<GraphUiContext.Provider value={ui}>
|
||||||
<ReactFlow
|
<div className={styles.canvasWrap}>
|
||||||
nodes={nodes}
|
<ReactFlow
|
||||||
edges={edges}
|
nodes={nodes}
|
||||||
nodeTypes={nodeTypes}
|
edges={edges}
|
||||||
onNodesChange={onNodesChange}
|
nodeTypes={nodeTypes}
|
||||||
onNodeDragStop={(_, node) => {
|
onNodesChange={onNodesChange}
|
||||||
onNodePositionCommit(node.id as GraphNodeId, node.position.x, node.position.y);
|
onNodeDragStop={(_, node) => {
|
||||||
}}
|
onNodePositionCommit(node.id as GraphNodeId, node.position.x, node.position.y);
|
||||||
onEdgesChange={onEdgesChange}
|
}}
|
||||||
isValidConnection={isValidConnection}
|
onEdgesChange={onEdgesChange}
|
||||||
onConnect={onConnectInternal}
|
isValidConnection={isValidConnection}
|
||||||
onEdgesDelete={(eds) => {
|
onConnect={onConnectInternal}
|
||||||
for (const ed of eds) {
|
onEdgesDelete={(eds) => {
|
||||||
onDisconnect(ed.id);
|
for (const ed of eds) {
|
||||||
}
|
onDisconnect(ed.id);
|
||||||
}}
|
}
|
||||||
onEdgeClick={(_, edge) => {
|
}}
|
||||||
onDisconnect(edge.id);
|
onEdgeClick={(_, edge) => {
|
||||||
}}
|
onDisconnect(edge.id);
|
||||||
onNodesDelete={(nds) => {
|
}}
|
||||||
onRemoveGraphNodes(nds.map((n) => n.id as GraphNodeId));
|
onNodesDelete={(nds) => {
|
||||||
}}
|
onRemoveGraphNodes(nds.map((n) => n.id as GraphNodeId));
|
||||||
onNodeClick={(_, node) => {
|
}}
|
||||||
setMenu(null);
|
onNodeClick={(_, node) => {
|
||||||
const d = node.data as SceneCardData;
|
setMenu(null);
|
||||||
onCurrentSceneChange(d.sceneId);
|
const d = node.data as SceneCardData;
|
||||||
}}
|
onCurrentSceneChange(d.sceneId);
|
||||||
onNodeContextMenu={(e, node) => {
|
}}
|
||||||
e.preventDefault();
|
onNodeContextMenu={(e, node) => {
|
||||||
setMenu({ x: e.clientX, y: e.clientY, graphNodeId: node.id as GraphNodeId });
|
e.preventDefault();
|
||||||
}}
|
setMenu({ x: e.clientX, y: e.clientY, graphNodeId: node.id as GraphNodeId });
|
||||||
onPaneClick={() => {
|
}}
|
||||||
setMenu(null);
|
onPaneClick={() => {
|
||||||
}}
|
setMenu(null);
|
||||||
onPaneContextMenu={(e) => {
|
}}
|
||||||
e.preventDefault();
|
onPaneContextMenu={(e) => {
|
||||||
setMenu(null);
|
e.preventDefault();
|
||||||
}}
|
setMenu(null);
|
||||||
onInit={(instance) => {
|
}}
|
||||||
instance.fitView({ padding: 0.25 });
|
onInit={(instance) => {
|
||||||
}}
|
instance.fitView({ padding: 0.25 });
|
||||||
onDragOver={onDragOver}
|
}}
|
||||||
onDrop={onDrop}
|
onDragOver={onDragOver}
|
||||||
panOnScroll
|
onDrop={onDrop}
|
||||||
selectionOnDrag={false}
|
panOnScroll
|
||||||
deleteKeyCode={['Backspace', 'Delete']}
|
selectionOnDrag={false}
|
||||||
proOptions={{ hideAttribution: true }}
|
deleteKeyCode={['Backspace', 'Delete']}
|
||||||
>
|
proOptions={{ hideAttribution: true }}
|
||||||
<Background gap={18} size={1} color="rgba(255,255,255,0.06)" />
|
>
|
||||||
<GraphZoomToolbar />
|
<Background gap={18} size={1} color="rgba(255,255,255,0.06)" />
|
||||||
</ReactFlow>
|
<GraphZoomToolbar />
|
||||||
{menu && menuPosition
|
</ReactFlow>
|
||||||
? createPortal(
|
{menu && menuPosition
|
||||||
<>
|
? createPortal(
|
||||||
<button
|
<>
|
||||||
type="button"
|
|
||||||
aria-label="Закрыть меню"
|
|
||||||
className={styles.menuBackdrop}
|
|
||||||
onClick={() => setMenu(null)}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
role="menu"
|
|
||||||
tabIndex={-1}
|
|
||||||
className={styles.ctxMenu}
|
|
||||||
style={{ left: menuPosition.x, top: menuPosition.y }}
|
|
||||||
onClick={(e) => e.stopPropagation()}
|
|
||||||
onKeyDown={(e) => {
|
|
||||||
if (e.key === 'Escape') setMenu(null);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
role="menuitem"
|
aria-label={ui.closeMenu}
|
||||||
className={styles.ctxItem}
|
className={styles.menuBackdrop}
|
||||||
onClick={() => {
|
onClick={() => setMenu(null)}
|
||||||
if (menuNodeIsStart) {
|
/>
|
||||||
onSetGraphNodeStart(null);
|
<div
|
||||||
} else {
|
role="menu"
|
||||||
onSetGraphNodeStart(menu.graphNodeId);
|
tabIndex={-1}
|
||||||
}
|
className={styles.ctxMenu}
|
||||||
setMenu(null);
|
style={{ left: menuPosition.x, top: menuPosition.y }}
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Escape') setMenu(null);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{menuNodeIsStart ? 'Снять метку «Начальная сцена»' : 'Начальная сцена'}
|
<button
|
||||||
</button>
|
type="button"
|
||||||
<button
|
role="menuitem"
|
||||||
type="button"
|
className={styles.ctxItem}
|
||||||
role="menuitem"
|
onClick={() => {
|
||||||
className={styles.ctxItemDanger}
|
if (menuNodeIsStart) {
|
||||||
onClick={() => {
|
onSetGraphNodeStart(null);
|
||||||
onRemoveGraphNode(menu.graphNodeId);
|
} else {
|
||||||
setMenu(null);
|
onSetGraphNodeStart(menu.graphNodeId);
|
||||||
}}
|
}
|
||||||
>
|
setMenu(null);
|
||||||
Удалить
|
}}
|
||||||
</button>
|
>
|
||||||
</div>
|
{menuNodeIsStart ? ui.unsetStartScene : ui.startScene}
|
||||||
</>,
|
</button>
|
||||||
document.body,
|
<button
|
||||||
)
|
type="button"
|
||||||
: null}
|
role="menuitem"
|
||||||
</div>
|
className={styles.ctxItemDanger}
|
||||||
|
onClick={() => {
|
||||||
|
onRemoveGraphNode(menu.graphNodeId);
|
||||||
|
setMenu(null);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{ui.delete}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</>,
|
||||||
|
document.body,
|
||||||
|
)
|
||||||
|
: null}
|
||||||
|
</div>
|
||||||
|
</GraphUiContext.Provider>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,103 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import test from 'node:test';
|
||||||
|
|
||||||
|
import type { Project } from '../../../shared/types';
|
||||||
|
import type { AssetId, SceneId } from '../../../shared/types/ids';
|
||||||
|
|
||||||
|
import { buildNextSceneCardById } from './sceneCardById';
|
||||||
|
|
||||||
|
function minimalProject(overrides: Partial<Project>): Project {
|
||||||
|
return {
|
||||||
|
id: 'p1' as unknown as Project['id'],
|
||||||
|
meta: {
|
||||||
|
name: 'n',
|
||||||
|
fileBaseName: 'f',
|
||||||
|
createdAt: '',
|
||||||
|
updatedAt: '',
|
||||||
|
createdWithAppVersion: '1',
|
||||||
|
appVersion: '1',
|
||||||
|
schemaVersion: 1 as unknown as Project['meta']['schemaVersion'],
|
||||||
|
},
|
||||||
|
scenes: {},
|
||||||
|
assets: {},
|
||||||
|
campaignAudios: [],
|
||||||
|
currentSceneId: null,
|
||||||
|
currentGraphNodeId: null,
|
||||||
|
sceneGraphNodes: [],
|
||||||
|
sceneGraphEdges: [],
|
||||||
|
...overrides,
|
||||||
|
} as unknown as Project;
|
||||||
|
}
|
||||||
|
|
||||||
|
void test('buildNextSceneCardById: does not change refs when irrelevant fields change', () => {
|
||||||
|
const sid = 's1' as SceneId;
|
||||||
|
const base = minimalProject({
|
||||||
|
scenes: {
|
||||||
|
[sid]: {
|
||||||
|
id: sid,
|
||||||
|
title: 'T',
|
||||||
|
description: 'A',
|
||||||
|
media: { videos: [], audios: [{ assetId: 'a1' as AssetId, autoplay: false, loop: true }] },
|
||||||
|
settings: { autoplayVideo: false, autoplayAudio: false, loopVideo: false, loopAudio: false },
|
||||||
|
connections: [],
|
||||||
|
layout: { x: 0, y: 0 },
|
||||||
|
previewAssetId: null,
|
||||||
|
previewThumbAssetId: null,
|
||||||
|
previewAssetType: null,
|
||||||
|
previewVideoAutostart: false,
|
||||||
|
previewRotationDeg: 0,
|
||||||
|
},
|
||||||
|
} as unknown as Project['scenes'],
|
||||||
|
});
|
||||||
|
|
||||||
|
const first = buildNextSceneCardById({}, base);
|
||||||
|
const card1 = first[sid];
|
||||||
|
assert.ok(card1);
|
||||||
|
|
||||||
|
const changedOnlyDescription = minimalProject({
|
||||||
|
...base,
|
||||||
|
scenes: {
|
||||||
|
...base.scenes,
|
||||||
|
[sid]: { ...base.scenes[sid], description: 'B' },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const second = buildNextSceneCardById(first, changedOnlyDescription);
|
||||||
|
|
||||||
|
assert.equal(second, first, 'record identity should be reused');
|
||||||
|
assert.equal(second[sid], card1, 'card identity should be reused');
|
||||||
|
});
|
||||||
|
|
||||||
|
void test('buildNextSceneCardById: changes card when title changes', () => {
|
||||||
|
const sid = 's1' as SceneId;
|
||||||
|
const base = minimalProject({
|
||||||
|
scenes: {
|
||||||
|
[sid]: {
|
||||||
|
id: sid,
|
||||||
|
title: 'T',
|
||||||
|
description: '',
|
||||||
|
media: { videos: [], audios: [] },
|
||||||
|
settings: { autoplayVideo: false, autoplayAudio: false, loopVideo: false, loopAudio: false },
|
||||||
|
connections: [],
|
||||||
|
layout: { x: 0, y: 0 },
|
||||||
|
previewAssetId: null,
|
||||||
|
previewThumbAssetId: null,
|
||||||
|
previewAssetType: null,
|
||||||
|
previewVideoAutostart: false,
|
||||||
|
previewRotationDeg: 0,
|
||||||
|
},
|
||||||
|
} as unknown as Project['scenes'],
|
||||||
|
});
|
||||||
|
const first = buildNextSceneCardById({}, base);
|
||||||
|
const card1 = first[sid];
|
||||||
|
|
||||||
|
const changedTitle = minimalProject({
|
||||||
|
...base,
|
||||||
|
scenes: {
|
||||||
|
...base.scenes,
|
||||||
|
[sid]: { ...base.scenes[sid], title: 'T2' },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const second = buildNextSceneCardById(first, changedTitle);
|
||||||
|
|
||||||
|
assert.notEqual(second[sid], card1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import type { Project } from '../../../shared/types';
|
||||||
|
import type { SceneId } from '../../../shared/types/ids';
|
||||||
|
|
||||||
|
import type { SceneGraphSceneAudioSummary, SceneGraphSceneCard } from './SceneGraph';
|
||||||
|
|
||||||
|
export function stableSceneGraphAudios(
|
||||||
|
prevCard: SceneGraphSceneCard | undefined,
|
||||||
|
nextRaw: SceneGraphSceneAudioSummary[],
|
||||||
|
): readonly SceneGraphSceneAudioSummary[] {
|
||||||
|
if (!prevCard) return nextRaw;
|
||||||
|
const pa = prevCard.audios;
|
||||||
|
if (pa.length !== nextRaw.length) return nextRaw;
|
||||||
|
for (let i = 0; i < nextRaw.length; i++) {
|
||||||
|
const p = pa[i];
|
||||||
|
const n = nextRaw[i];
|
||||||
|
if (p?.assetId !== n?.assetId || p?.loop !== n?.loop || p?.autoplay !== n?.autoplay) return nextRaw;
|
||||||
|
}
|
||||||
|
return pa;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildNextSceneCardById(
|
||||||
|
prevRecord: Record<SceneId, SceneGraphSceneCard>,
|
||||||
|
project: Project,
|
||||||
|
): Record<SceneId, SceneGraphSceneCard> {
|
||||||
|
const nextMap: Record<SceneId, SceneGraphSceneCard> = {};
|
||||||
|
|
||||||
|
for (const id of Object.keys(project.scenes) as SceneId[]) {
|
||||||
|
const s = project.scenes[id];
|
||||||
|
if (!s) continue;
|
||||||
|
const prevCard = prevRecord[id];
|
||||||
|
const nextAudiosRaw: SceneGraphSceneAudioSummary[] = s.media.audios.map((a) => ({
|
||||||
|
assetId: a.assetId,
|
||||||
|
loop: a.loop,
|
||||||
|
autoplay: a.autoplay,
|
||||||
|
}));
|
||||||
|
const audios = stableSceneGraphAudios(prevCard, nextAudiosRaw);
|
||||||
|
const loopVideo = s.settings.loopVideo;
|
||||||
|
if (
|
||||||
|
prevCard?.title === s.title &&
|
||||||
|
prevCard.previewAssetId === s.previewAssetId &&
|
||||||
|
prevCard.previewThumbAssetId === s.previewThumbAssetId &&
|
||||||
|
prevCard.previewAssetType === s.previewAssetType &&
|
||||||
|
prevCard.previewVideoAutostart === s.previewVideoAutostart &&
|
||||||
|
prevCard.previewRotationDeg === s.previewRotationDeg &&
|
||||||
|
prevCard.loopVideo === loopVideo &&
|
||||||
|
prevCard.audios === audios
|
||||||
|
) {
|
||||||
|
nextMap[id] = prevCard;
|
||||||
|
} else {
|
||||||
|
nextMap[id] = {
|
||||||
|
title: s.title,
|
||||||
|
previewAssetId: s.previewAssetId,
|
||||||
|
previewThumbAssetId: s.previewThumbAssetId,
|
||||||
|
previewAssetType: s.previewAssetType,
|
||||||
|
previewVideoAutostart: s.previewVideoAutostart,
|
||||||
|
previewRotationDeg: s.previewRotationDeg,
|
||||||
|
loopVideo,
|
||||||
|
audios,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const prevKeys = Object.keys(prevRecord);
|
||||||
|
const nextKeys = Object.keys(nextMap);
|
||||||
|
const reuseRecord =
|
||||||
|
prevKeys.length === nextKeys.length &&
|
||||||
|
nextKeys.every((k) => prevRecord[k as SceneId] === nextMap[k as SceneId]);
|
||||||
|
|
||||||
|
return reuseRecord ? prevRecord : nextMap;
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import React, { createContext, useCallback, useContext, useMemo, useState } from 'react';
|
||||||
|
|
||||||
|
import {
|
||||||
|
EDITOR_LOCALE_STORAGE_KEY,
|
||||||
|
inferEditorLocaleFromSystem,
|
||||||
|
normalizeEditorLocale,
|
||||||
|
translateEditorMessage,
|
||||||
|
type EditorLocale,
|
||||||
|
} from './editorMessages';
|
||||||
|
|
||||||
|
type EditorI18nContextValue = {
|
||||||
|
locale: EditorLocale;
|
||||||
|
setLocale: (next: EditorLocale) => void;
|
||||||
|
t: (key: string, vars?: Record<string, string | number>) => string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const EditorI18nContext = createContext<EditorI18nContextValue | null>(null);
|
||||||
|
|
||||||
|
function readInitialLocale(): EditorLocale {
|
||||||
|
try {
|
||||||
|
return normalizeEditorLocale(localStorage.getItem(EDITOR_LOCALE_STORAGE_KEY));
|
||||||
|
} catch {
|
||||||
|
return inferEditorLocaleFromSystem();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function EditorI18nProvider({ children }: { children: React.ReactNode }) {
|
||||||
|
const [locale, setLocaleState] = useState<EditorLocale>(readInitialLocale);
|
||||||
|
|
||||||
|
const setLocale = useCallback((next: EditorLocale) => {
|
||||||
|
setLocaleState(next);
|
||||||
|
try {
|
||||||
|
localStorage.setItem(EDITOR_LOCALE_STORAGE_KEY, next);
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const t = useCallback(
|
||||||
|
(key: string, vars?: Record<string, string | number>) => translateEditorMessage(locale, key, vars),
|
||||||
|
[locale],
|
||||||
|
);
|
||||||
|
|
||||||
|
const value = useMemo<EditorI18nContextValue>(() => ({ locale, setLocale, t }), [locale, setLocale, t]);
|
||||||
|
|
||||||
|
return <EditorI18nContext.Provider value={value}>{children}</EditorI18nContext.Provider>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useEditorI18n(): EditorI18nContextValue {
|
||||||
|
const ctx = useContext(EditorI18nContext);
|
||||||
|
if (!ctx) {
|
||||||
|
throw new Error('useEditorI18n must be used within EditorI18nProvider');
|
||||||
|
}
|
||||||
|
return ctx;
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import test from 'node:test';
|
||||||
|
|
||||||
|
import { inferEditorLocaleFromSystem, normalizeEditorLocale } from './editorMessages';
|
||||||
|
|
||||||
|
void test('inferEditorLocaleFromSystem: en-* wins when listed first', () => {
|
||||||
|
assert.equal(inferEditorLocaleFromSystem(['en-GB', 'ru-RU']), 'en');
|
||||||
|
});
|
||||||
|
|
||||||
|
void test('inferEditorLocaleFromSystem: ru-* wins when listed first', () => {
|
||||||
|
assert.equal(inferEditorLocaleFromSystem(['ru-RU', 'en-US']), 'ru');
|
||||||
|
});
|
||||||
|
|
||||||
|
void test('inferEditorLocaleFromSystem: unknown tags fall back to ru', () => {
|
||||||
|
assert.equal(inferEditorLocaleFromSystem(['de-DE', 'fr']), 'ru');
|
||||||
|
});
|
||||||
|
|
||||||
|
void test('inferEditorLocaleFromSystem: empty list → ru', () => {
|
||||||
|
assert.equal(inferEditorLocaleFromSystem([]), 'ru');
|
||||||
|
});
|
||||||
|
|
||||||
|
void test('normalizeEditorLocale: trims stored en/ru', () => {
|
||||||
|
assert.equal(normalizeEditorLocale(' EN '), 'en');
|
||||||
|
assert.equal(normalizeEditorLocale('ru '), 'ru');
|
||||||
|
});
|
||||||
|
|
||||||
|
void test('normalizeEditorLocale: blank or invalid defers to infer (explicit list)', () => {
|
||||||
|
assert.equal(normalizeEditorLocale(''), inferEditorLocaleFromSystem([]));
|
||||||
|
assert.equal(normalizeEditorLocale('xx'), inferEditorLocaleFromSystem([]));
|
||||||
|
});
|
||||||
@@ -0,0 +1,522 @@
|
|||||||
|
export type EditorLocale = 'ru' | 'en';
|
||||||
|
|
||||||
|
export const EDITOR_LOCALE_STORAGE_KEY = 'dnd_editor_locale';
|
||||||
|
|
||||||
|
function primaryLanguageTag(lang: string): string {
|
||||||
|
const trimmed = lang.trim().toLowerCase();
|
||||||
|
if (!trimmed) return '';
|
||||||
|
const sep = trimmed.search(/[-_]/);
|
||||||
|
return sep === -1 ? trimmed : trimmed.slice(0, sep);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Выбор `ru` / `en` по языку ОС/браузера, если пользователь ещё не сохранил язык в `localStorage`.
|
||||||
|
* В Electron совпадает с локалью системы (Chromium подставляет `navigator.languages`).
|
||||||
|
*/
|
||||||
|
export function inferEditorLocaleFromSystem(languages?: readonly string[]): EditorLocale {
|
||||||
|
let list: string[];
|
||||||
|
if (languages !== undefined) {
|
||||||
|
list = [...languages];
|
||||||
|
} else if (typeof navigator !== 'undefined') {
|
||||||
|
list = [...navigator.languages];
|
||||||
|
if (navigator.language) {
|
||||||
|
list.push(navigator.language);
|
||||||
|
}
|
||||||
|
list = list.filter((x) => x.trim() !== '');
|
||||||
|
} else {
|
||||||
|
list = [];
|
||||||
|
}
|
||||||
|
for (const lang of list) {
|
||||||
|
const tag = primaryLanguageTag(lang);
|
||||||
|
if (tag === 'en') return 'en';
|
||||||
|
if (tag === 'ru') return 'ru';
|
||||||
|
}
|
||||||
|
return 'ru';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normalizeEditorLocale(raw: string | null | undefined): EditorLocale {
|
||||||
|
if (raw == null) {
|
||||||
|
return inferEditorLocaleFromSystem();
|
||||||
|
}
|
||||||
|
const trimmed = raw.trim();
|
||||||
|
if (trimmed === '') {
|
||||||
|
return inferEditorLocaleFromSystem();
|
||||||
|
}
|
||||||
|
const s = trimmed.toLowerCase();
|
||||||
|
if (s === 'en') return 'en';
|
||||||
|
if (s === 'ru') return 'ru';
|
||||||
|
return inferEditorLocaleFromSystem();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Flat message table; `{name}` placeholders supported in `translate`. */
|
||||||
|
export const EDITOR_MESSAGES: Record<EditorLocale, Record<string, string>> = {
|
||||||
|
ru: {
|
||||||
|
'common.close': 'Закрыть',
|
||||||
|
'common.cancel': 'Отмена',
|
||||||
|
'common.save': 'Сохранить',
|
||||||
|
'common.understood': 'Понятно',
|
||||||
|
'common.message': 'Сообщение',
|
||||||
|
'common.error': 'Ошибка',
|
||||||
|
'common.delete': 'Удалить',
|
||||||
|
'common.closeMenu': 'Закрыть меню',
|
||||||
|
|
||||||
|
'notice.campaignAudioEmpty': 'Аудио не добавлено. Проверьте формат файла.',
|
||||||
|
|
||||||
|
'license.checkingTitle': 'Проверка лицензии…',
|
||||||
|
'license.checkingWait': 'Подождите.',
|
||||||
|
'license.requiredTitle': 'Требуется лицензия',
|
||||||
|
'license.requiredHint':
|
||||||
|
'Укажите ключ в меню «Настройки» → «Указать ключ». До активации доступно только меню «Настройки».',
|
||||||
|
'license.tokenTitle': 'Указать ключ',
|
||||||
|
'license.tokenKey': 'КЛЮЧ',
|
||||||
|
'license.tokenPlaceholder': 'Продуктовый ключ DND-...',
|
||||||
|
'license.tokenSaving': 'Сохранение…',
|
||||||
|
'license.eulaTitle': 'Лицензионное соглашение',
|
||||||
|
'license.eulaReject': 'Не принимаю',
|
||||||
|
'license.eulaAccept': 'Принимаю условия',
|
||||||
|
'license.eulaNoteEn':
|
||||||
|
'The binding legal text below is in Russian. If you need an English summary, contact support.',
|
||||||
|
'license.aboutTitle': 'О лицензии',
|
||||||
|
'license.aboutDevSkip': 'Режим разработки: проверка лицензии отключена (DND_SKIP_LICENSE).',
|
||||||
|
'license.aboutStatus': 'СТАТУС',
|
||||||
|
'license.aboutProduct': 'ПРОДУКТ',
|
||||||
|
'license.aboutLicenseId': 'ID ЛИЦЕНЗИИ',
|
||||||
|
'license.aboutExpiry': 'ОКОНЧАНИЕ',
|
||||||
|
'license.aboutDevice': 'УСТРОЙСТВО',
|
||||||
|
'license.aboutNoData': 'Нет данных лицензии.',
|
||||||
|
'license.reason.ok': 'Активна',
|
||||||
|
'license.reason.none': 'Ключ не указан',
|
||||||
|
'license.reason.expired': 'Срок действия истёк',
|
||||||
|
'license.reason.bad_signature': 'Недействительная подпись',
|
||||||
|
'license.reason.bad_payload': 'Неверный формат токена',
|
||||||
|
'license.reason.malformed': 'Повреждённый токен',
|
||||||
|
'license.reason.not_yet_valid': 'Ещё не действует',
|
||||||
|
'license.reason.wrong_device': 'Другой привязанный компьютер',
|
||||||
|
'license.reason.revoked_remote': 'Отозвана на сервере',
|
||||||
|
|
||||||
|
'presentation.overlay': 'Презентация запущена',
|
||||||
|
'presentation.title': 'Презентация запущена',
|
||||||
|
'presentation.body':
|
||||||
|
'Редактор заблокирован. Закройте окна «Презентация» и «Панель управления», чтобы продолжить.',
|
||||||
|
|
||||||
|
'zip.progress': 'Прогресс операции',
|
||||||
|
'zip.importTitle': 'Импорт проекта',
|
||||||
|
'zip.exportTitle': 'Экспорт проекта',
|
||||||
|
|
||||||
|
'top.settings': 'Настройки',
|
||||||
|
'top.project': 'Проект',
|
||||||
|
'top.file': 'Файл',
|
||||||
|
'top.backToProjects': 'К списку проектов',
|
||||||
|
'top.appVersion': 'Версия приложения',
|
||||||
|
'top.run': 'Запустить',
|
||||||
|
'top.afterLicense': 'Доступно после активации лицензии',
|
||||||
|
'top.setStartScene': 'Назначьте начальную сцену на графе (ПКМ по узлу)',
|
||||||
|
|
||||||
|
'menu.enterKey': 'Указать ключ',
|
||||||
|
'menu.aboutLicense': 'О лицензии',
|
||||||
|
'menu.checkUpdates': 'Проверить обновления',
|
||||||
|
'menu.language': 'Язык',
|
||||||
|
'menu.langRu': 'Русский',
|
||||||
|
'menu.langEn': 'English',
|
||||||
|
|
||||||
|
'updates.dialogTitle': 'Обновления',
|
||||||
|
'updates.checking': 'Проверка наличия обновлений…',
|
||||||
|
'updates.available': 'Доступна новая версия {version}.',
|
||||||
|
'updates.current': 'У вас установлена актуальная версия ({version}).',
|
||||||
|
'updates.error': 'Не удалось проверить обновления: {message}',
|
||||||
|
'updates.notPackaged': 'Проверка доступна только в установленной версии приложения.',
|
||||||
|
'updates.noLicense': 'Нужна активная лицензия.',
|
||||||
|
'updates.download': 'Обновить',
|
||||||
|
'updates.downloading': 'Загрузка…',
|
||||||
|
|
||||||
|
'projectMenu.home': 'Начальный экран',
|
||||||
|
'projectMenu.import': 'Импорт',
|
||||||
|
'projectMenu.export': 'Экспорт',
|
||||||
|
'projectMenu.noProjects': 'Нет сохранённых проектов',
|
||||||
|
|
||||||
|
'fileMenu.rename': 'Переименовать проект',
|
||||||
|
|
||||||
|
'scenes.search': 'Поиск сцен…',
|
||||||
|
'scenes.new': '+ Новая сцена',
|
||||||
|
'scenes.inspectorGame': 'Свойства игры',
|
||||||
|
'scenes.inspectorScene': 'Свойства сцены',
|
||||||
|
'scenes.selectHint': 'Выберите сцену слева, чтобы редактировать её свойства.',
|
||||||
|
'scenes.openProjectHint': 'Откройте проект, чтобы редактировать кампанию и сцены.',
|
||||||
|
|
||||||
|
'rename.title': 'Переименовать проект',
|
||||||
|
'rename.projectName': 'НАЗВАНИЕ ПРОЕКТА',
|
||||||
|
'rename.projectPlaceholder': 'Название проекта…',
|
||||||
|
'rename.projectMin': 'Минимум 3 символа.',
|
||||||
|
'rename.projectDup': 'Проект с таким названием уже существует.',
|
||||||
|
'rename.fileName': 'НАЗВАНИЕ ФАЙЛА ПРОЕКТА',
|
||||||
|
'rename.fileInvalid': 'Минимум 3 символа, без символов <>:"/\\|?*',
|
||||||
|
'rename.fileDup': 'Файл проекта с таким названием уже существует.',
|
||||||
|
'rename.saving': 'Сохранение…',
|
||||||
|
|
||||||
|
'export.title': 'Экспорт проекта',
|
||||||
|
'export.project': 'ПРОЕКТ',
|
||||||
|
'export.hint':
|
||||||
|
'Далее откроется окно сохранения: укажите имя и папку для файла .dnd.zip — будет создана копия архива проекта.',
|
||||||
|
'export.exporting': 'Экспорт…',
|
||||||
|
'export.saveAs': 'Сохранить как…',
|
||||||
|
|
||||||
|
'confirmDelete.title': 'Удаление проекта',
|
||||||
|
'confirmDelete.body': 'Удалить проект «{name}» безвозвратно? Файл и кэш будут стёрты с диска.',
|
||||||
|
'confirmDelete.failedTitle': 'Не удалось удалить',
|
||||||
|
|
||||||
|
'picker.title': 'Проекты',
|
||||||
|
'picker.newPlaceholder': 'Название нового проекта…',
|
||||||
|
'picker.create': 'Создать проект',
|
||||||
|
'picker.existing': 'СУЩЕСТВУЮЩИЕ',
|
||||||
|
'picker.lockedHint':
|
||||||
|
'Открытие и создание — после активации лицензии. Список показывает файлы в папке приложения.',
|
||||||
|
'picker.empty': 'Пока нет проектов.',
|
||||||
|
'picker.projectMenu': 'Меню проекта',
|
||||||
|
'picker.openDisabled': 'Открытие проекта — после активации лицензии',
|
||||||
|
'picker.defaultName': 'Моя кампания',
|
||||||
|
|
||||||
|
'campaign.label': 'АУДИО ИГРЫ',
|
||||||
|
'campaign.noFiles': 'Файлов пока нет. Добавьте аудио.',
|
||||||
|
'campaign.auto': 'Авто',
|
||||||
|
'campaign.loop': 'Цикл',
|
||||||
|
'campaign.removeTitle': 'Убрать из кампании',
|
||||||
|
'campaign.upload': 'Загрузить',
|
||||||
|
|
||||||
|
'scene.title': 'НАЗВАНИЕ СЦЕНЫ',
|
||||||
|
'scene.description': 'ОПИСАНИЕ',
|
||||||
|
'scene.preview': 'ПРЕВЬЮ СЦЕНЫ',
|
||||||
|
'scene.previewHint': 'Файл изображения (PNG, JPG, WebP, GIF и т.д.).',
|
||||||
|
'scene.previewEmpty': 'Превью не задано',
|
||||||
|
'scene.previewBusy': 'Загрузка и оптимизация изображения…',
|
||||||
|
'scene.change': 'Изменить',
|
||||||
|
'scene.clear': 'Очистить',
|
||||||
|
'scene.autostart': 'Автостарт',
|
||||||
|
'scene.rotate': 'Повернуть',
|
||||||
|
'scene.audio': 'АУДИО СЦЕНЫ',
|
||||||
|
'scene.removeTitle': 'Убрать из сцены',
|
||||||
|
'scene.branching': 'ВЕТВЛЕНИЯ',
|
||||||
|
'scene.branchingHint':
|
||||||
|
'Перетащите сцену из списка на граф. С одной карточки можно задать несколько вариантов — по одной связи на каждую целевую сцену. Повторно к той же сцене (включая вторую карточку той же сцены на графе) подключить нельзя.',
|
||||||
|
|
||||||
|
'sceneCard.current': 'ТЕКУЩАЯ',
|
||||||
|
'sceneCard.menu': 'Меню сцены',
|
||||||
|
|
||||||
|
'graph.badgeStart': 'НАЧАЛО',
|
||||||
|
'graph.untitled': 'Без названия',
|
||||||
|
'graph.videoBadge': 'Видео',
|
||||||
|
'graph.audioBadge': 'Аудио',
|
||||||
|
'graph.loop': 'Цикл',
|
||||||
|
'graph.autoplay': 'Автостарт',
|
||||||
|
'graph.previewAutostart': 'Авто превью',
|
||||||
|
'graph.videoLoop': 'Цикл видео',
|
||||||
|
'graph.zoomBar': 'Масштаб графа',
|
||||||
|
'graph.zoomIn': 'Увеличить',
|
||||||
|
'graph.zoomOut': 'Уменьшить',
|
||||||
|
'graph.fitAll': 'Показать всё',
|
||||||
|
'graph.startScene': 'Начальная сцена',
|
||||||
|
'graph.unsetStartScene': 'Снять метку «Начальная сцена»',
|
||||||
|
|
||||||
|
'control.remoteTitle': 'ПУЛЬТ УПРАВЛЕНИЯ',
|
||||||
|
'control.effects': 'ЭФФЕКТЫ',
|
||||||
|
'control.tools': 'Инструменты',
|
||||||
|
'control.fieldEffects': 'Эффекты поля',
|
||||||
|
'control.actionEffects': 'Эффекты действий',
|
||||||
|
'control.eraser': 'Ластик',
|
||||||
|
'control.clearEffects': 'Очистить эффекты',
|
||||||
|
'control.fog': 'Туман',
|
||||||
|
'control.rain': 'Дождь',
|
||||||
|
'control.fire': 'Огонь',
|
||||||
|
'control.water': 'Вода',
|
||||||
|
'control.lightning': 'Молния',
|
||||||
|
'control.sunbeam': 'Луч света',
|
||||||
|
'control.freeze': 'Заморозка',
|
||||||
|
'control.poisonCloud': 'Облако яда',
|
||||||
|
'control.brushRadius': 'Радиус кисти',
|
||||||
|
'control.storyLine': 'СЮЖЕТНАЯ ЛИНИЯ',
|
||||||
|
'control.gotoScene': 'Перейти к этой сцене',
|
||||||
|
'control.currentSceneBadge': 'ТЕКУЩАЯ СЦЕНА',
|
||||||
|
'control.passed': 'Пройдено',
|
||||||
|
'control.noActiveScene': 'Нет активной сцены.',
|
||||||
|
'control.screenPreview': 'Предпросмотр экрана',
|
||||||
|
'control.stopPresentation': 'Выключить демонстрацию',
|
||||||
|
'control.videoBrushHint':
|
||||||
|
'Видео-превью: кисть эффектов отключена (как на экране демонстрации — оверлей только для изображения).',
|
||||||
|
'control.branches': 'Варианты ветвления',
|
||||||
|
'control.option': 'ОПЦИЯ {n}',
|
||||||
|
'control.unnamed': 'Без названия',
|
||||||
|
'control.switchScene': 'Переключить',
|
||||||
|
'control.noBranches': 'Нет вариантов перехода.',
|
||||||
|
'control.endPresentation': 'Завершить показ',
|
||||||
|
'control.music': 'Музыка',
|
||||||
|
'control.sceneMusic': 'МУЗЫКА СЦЕНЫ',
|
||||||
|
'control.gameMusic': 'МУЗЫКА ИГРЫ',
|
||||||
|
'control.noSceneAudio': 'В текущей сцене нет аудио.',
|
||||||
|
'control.noGameAudio': 'В игре нет аудио.',
|
||||||
|
'control.modeAuto': 'Авто',
|
||||||
|
'control.modeManual': 'Ручн.',
|
||||||
|
'control.once': 'Один раз',
|
||||||
|
'control.loop': 'Цикл',
|
||||||
|
'control.scrubSeek': 'Клик — перемотка',
|
||||||
|
'control.durationUnknown': 'Длительность неизвестна',
|
||||||
|
'control.pauseSceneMusic': 'Пауза (сцена)',
|
||||||
|
'control.pauseSceneMusicTitle': 'В сцене есть музыка',
|
||||||
|
'control.pauseCampaignTitle': 'Пауза: в сцене есть музыка',
|
||||||
|
'control.playFailed': 'Не удалось запустить.',
|
||||||
|
'control.audioAutoplayBlocked':
|
||||||
|
'Автозапуск заблокирован (нужно действие пользователя) или ошибка воспроизведения.',
|
||||||
|
'control.audioNoUrl': 'URL не получен',
|
||||||
|
'control.audioNoUrlDetail': 'Не удалось получить dnd://asset URL для аудио.',
|
||||||
|
'control.audioBlocked': 'Ошибка/блок',
|
||||||
|
'control.audioError': 'Ошибка',
|
||||||
|
'control.audioMediaError': 'MediaError code={code} (1=ABORTED, 2=NETWORK, 3=DECODE, 4=SRC_NOT_SUPPORTED)',
|
||||||
|
'control.audioLoading': 'Загрузка…',
|
||||||
|
'control.audioPlaying': 'Играет',
|
||||||
|
'control.audioPaused': 'Пауза',
|
||||||
|
'control.audioStopped': 'Остановлено',
|
||||||
|
'control.previewTrackLabel': 'Превью без субтитров',
|
||||||
|
'control.transportPlay': 'Воспроизведение',
|
||||||
|
'control.transportPause': 'Пауза',
|
||||||
|
'control.transportStop': 'Стоп',
|
||||||
|
},
|
||||||
|
en: {
|
||||||
|
'common.close': 'Close',
|
||||||
|
'common.cancel': 'Cancel',
|
||||||
|
'common.save': 'Save',
|
||||||
|
'common.understood': 'OK',
|
||||||
|
'common.message': 'Message',
|
||||||
|
'common.error': 'Error',
|
||||||
|
'common.delete': 'Delete',
|
||||||
|
'common.closeMenu': 'Close menu',
|
||||||
|
|
||||||
|
'notice.campaignAudioEmpty': 'No audio was added. Check the file format.',
|
||||||
|
|
||||||
|
'license.checkingTitle': 'Checking license…',
|
||||||
|
'license.checkingWait': 'Please wait.',
|
||||||
|
'license.requiredTitle': 'License required',
|
||||||
|
'license.requiredHint':
|
||||||
|
'Enter your key via Settings → Enter license key. Until activation, only Settings is available.',
|
||||||
|
'license.tokenTitle': 'Enter license key',
|
||||||
|
'license.tokenKey': 'KEY',
|
||||||
|
'license.tokenPlaceholder': 'DND product key…',
|
||||||
|
'license.tokenSaving': 'Saving…',
|
||||||
|
'license.eulaTitle': 'End User License Agreement',
|
||||||
|
'license.eulaReject': 'Decline',
|
||||||
|
'license.eulaAccept': 'I accept the terms',
|
||||||
|
'license.eulaNoteEn':
|
||||||
|
'The binding legal text below is in Russian. If you need an English summary, contact support.',
|
||||||
|
'license.aboutTitle': 'About license',
|
||||||
|
'license.aboutDevSkip': 'Development mode: license checks are disabled (DND_SKIP_LICENSE).',
|
||||||
|
'license.aboutStatus': 'STATUS',
|
||||||
|
'license.aboutProduct': 'PRODUCT',
|
||||||
|
'license.aboutLicenseId': 'LICENSE ID',
|
||||||
|
'license.aboutExpiry': 'EXPIRES',
|
||||||
|
'license.aboutDevice': 'DEVICE',
|
||||||
|
'license.aboutNoData': 'No license data.',
|
||||||
|
'license.reason.ok': 'Active',
|
||||||
|
'license.reason.none': 'No key provided',
|
||||||
|
'license.reason.expired': 'Expired',
|
||||||
|
'license.reason.bad_signature': 'Invalid signature',
|
||||||
|
'license.reason.bad_payload': 'Invalid token format',
|
||||||
|
'license.reason.malformed': 'Malformed token',
|
||||||
|
'license.reason.not_yet_valid': 'Not yet valid',
|
||||||
|
'license.reason.wrong_device': 'Wrong bound device',
|
||||||
|
'license.reason.revoked_remote': 'Revoked on server',
|
||||||
|
|
||||||
|
'presentation.overlay': 'Presentation running',
|
||||||
|
'presentation.title': 'Presentation running',
|
||||||
|
'presentation.body': 'The editor is locked. Close the Presentation and Control windows to continue.',
|
||||||
|
|
||||||
|
'zip.progress': 'Operation progress',
|
||||||
|
'zip.importTitle': 'Import project',
|
||||||
|
'zip.exportTitle': 'Export project',
|
||||||
|
|
||||||
|
'top.settings': 'Settings',
|
||||||
|
'top.project': 'Project',
|
||||||
|
'top.file': 'File',
|
||||||
|
'top.backToProjects': 'Back to projects',
|
||||||
|
'top.appVersion': 'App version',
|
||||||
|
'top.run': 'Run',
|
||||||
|
'top.afterLicense': 'Available after license activation',
|
||||||
|
'top.setStartScene': 'Set a start scene on the graph (right‑click a node)',
|
||||||
|
|
||||||
|
'menu.enterKey': 'Enter license key',
|
||||||
|
'menu.aboutLicense': 'About license',
|
||||||
|
'menu.checkUpdates': 'Check for updates',
|
||||||
|
'menu.language': 'Language',
|
||||||
|
'menu.langRu': 'Русский',
|
||||||
|
'menu.langEn': 'English',
|
||||||
|
|
||||||
|
'updates.dialogTitle': 'Updates',
|
||||||
|
'updates.checking': 'Checking for updates…',
|
||||||
|
'updates.available': 'A new version is available: {version}.',
|
||||||
|
'updates.current': 'You have the latest version ({version}).',
|
||||||
|
'updates.error': 'Could not check for updates: {message}',
|
||||||
|
'updates.notPackaged': 'Updates can only be checked in the installed application.',
|
||||||
|
'updates.noLicense': 'An active license is required.',
|
||||||
|
'updates.download': 'Update',
|
||||||
|
'updates.downloading': 'Downloading…',
|
||||||
|
|
||||||
|
'projectMenu.home': 'Home',
|
||||||
|
'projectMenu.import': 'Import',
|
||||||
|
'projectMenu.export': 'Export',
|
||||||
|
'projectMenu.noProjects': 'No saved projects',
|
||||||
|
|
||||||
|
'fileMenu.rename': 'Rename project',
|
||||||
|
|
||||||
|
'scenes.search': 'Search scenes…',
|
||||||
|
'scenes.new': '+ New scene',
|
||||||
|
'scenes.inspectorGame': 'Game properties',
|
||||||
|
'scenes.inspectorScene': 'Scene properties',
|
||||||
|
'scenes.selectHint': 'Select a scene on the left to edit its properties.',
|
||||||
|
'scenes.openProjectHint': 'Open a project to edit the campaign and scenes.',
|
||||||
|
|
||||||
|
'rename.title': 'Rename project',
|
||||||
|
'rename.projectName': 'PROJECT NAME',
|
||||||
|
'rename.projectPlaceholder': 'Project name…',
|
||||||
|
'rename.projectMin': 'At least 3 characters.',
|
||||||
|
'rename.projectDup': 'A project with this name already exists.',
|
||||||
|
'rename.fileName': 'PROJECT FILE NAME',
|
||||||
|
'rename.fileInvalid': 'At least 3 characters; forbidden characters <>:"/\\|?*',
|
||||||
|
'rename.fileDup': 'A project file with this name already exists.',
|
||||||
|
'rename.saving': 'Saving…',
|
||||||
|
|
||||||
|
'export.title': 'Export project',
|
||||||
|
'export.project': 'PROJECT',
|
||||||
|
'export.hint':
|
||||||
|
'A save dialog will open: choose a name and folder for the .dnd.zip file — a copy of the project archive will be created.',
|
||||||
|
'export.exporting': 'Exporting…',
|
||||||
|
'export.saveAs': 'Save as…',
|
||||||
|
|
||||||
|
'confirmDelete.title': 'Delete project',
|
||||||
|
'confirmDelete.body':
|
||||||
|
'Permanently delete project “{name}”? The file and cache will be removed from disk.',
|
||||||
|
'confirmDelete.failedTitle': 'Could not delete',
|
||||||
|
|
||||||
|
'picker.title': 'Projects',
|
||||||
|
'picker.newPlaceholder': 'New project name…',
|
||||||
|
'picker.create': 'Create project',
|
||||||
|
'picker.existing': 'EXISTING',
|
||||||
|
'picker.lockedHint':
|
||||||
|
'Opening and creating projects require an active license. The list still shows files in the app folder.',
|
||||||
|
'picker.empty': 'No projects yet.',
|
||||||
|
'picker.projectMenu': 'Project menu',
|
||||||
|
'picker.openDisabled': 'Open project — after license activation',
|
||||||
|
'picker.defaultName': 'My campaign',
|
||||||
|
|
||||||
|
'campaign.label': 'GAME AUDIO',
|
||||||
|
'campaign.noFiles': 'No files yet. Add audio.',
|
||||||
|
'campaign.auto': 'Auto',
|
||||||
|
'campaign.loop': 'Loop',
|
||||||
|
'campaign.removeTitle': 'Remove from campaign',
|
||||||
|
'campaign.upload': 'Upload',
|
||||||
|
|
||||||
|
'scene.title': 'SCENE TITLE',
|
||||||
|
'scene.description': 'DESCRIPTION',
|
||||||
|
'scene.preview': 'SCENE PREVIEW',
|
||||||
|
'scene.previewHint': 'Image file (PNG, JPG, WebP, GIF, etc.).',
|
||||||
|
'scene.previewEmpty': 'No preview',
|
||||||
|
'scene.previewBusy': 'Loading and optimizing image…',
|
||||||
|
'scene.change': 'Change',
|
||||||
|
'scene.clear': 'Clear',
|
||||||
|
'scene.autostart': 'Autostart',
|
||||||
|
'scene.rotate': 'Rotate',
|
||||||
|
'scene.audio': 'SCENE AUDIO',
|
||||||
|
'scene.removeTitle': 'Remove from scene',
|
||||||
|
'scene.branching': 'BRANCHING',
|
||||||
|
'scene.branchingHint':
|
||||||
|
'Drag a scene from the list onto the graph. One card can branch to several targets — one link per target scene. You cannot link twice to the same target (including a second card of the same scene).',
|
||||||
|
|
||||||
|
'sceneCard.current': 'CURRENT',
|
||||||
|
'sceneCard.menu': 'Scene menu',
|
||||||
|
|
||||||
|
'graph.badgeStart': 'START',
|
||||||
|
'graph.untitled': 'Untitled',
|
||||||
|
'graph.videoBadge': 'Video',
|
||||||
|
'graph.audioBadge': 'Audio',
|
||||||
|
'graph.loop': 'Loop',
|
||||||
|
'graph.autoplay': 'Autoplay',
|
||||||
|
'graph.previewAutostart': 'Preview autostart',
|
||||||
|
'graph.videoLoop': 'Video loop',
|
||||||
|
'graph.zoomBar': 'Graph zoom',
|
||||||
|
'graph.zoomIn': 'Zoom in',
|
||||||
|
'graph.zoomOut': 'Zoom out',
|
||||||
|
'graph.fitAll': 'Fit view',
|
||||||
|
'graph.startScene': 'Start scene',
|
||||||
|
'graph.unsetStartScene': 'Clear start scene mark',
|
||||||
|
|
||||||
|
'control.remoteTitle': 'CONTROL PANEL',
|
||||||
|
'control.effects': 'EFFECTS',
|
||||||
|
'control.tools': 'Tools',
|
||||||
|
'control.fieldEffects': 'Field effects',
|
||||||
|
'control.actionEffects': 'Action effects',
|
||||||
|
'control.eraser': 'Eraser',
|
||||||
|
'control.clearEffects': 'Clear effects',
|
||||||
|
'control.fog': 'Fog',
|
||||||
|
'control.rain': 'Rain',
|
||||||
|
'control.fire': 'Fire',
|
||||||
|
'control.water': 'Water',
|
||||||
|
'control.lightning': 'Lightning',
|
||||||
|
'control.sunbeam': 'Sunbeam',
|
||||||
|
'control.freeze': 'Freeze',
|
||||||
|
'control.poisonCloud': 'Poison cloud',
|
||||||
|
'control.brushRadius': 'Brush radius',
|
||||||
|
'control.storyLine': 'STORYLINE',
|
||||||
|
'control.gotoScene': 'Go to this scene',
|
||||||
|
'control.currentSceneBadge': 'CURRENT SCENE',
|
||||||
|
'control.passed': 'Visited',
|
||||||
|
'control.noActiveScene': 'No active scene.',
|
||||||
|
'control.screenPreview': 'Screen preview',
|
||||||
|
'control.stopPresentation': 'Stop presentation',
|
||||||
|
'control.videoBrushHint':
|
||||||
|
'Video preview: effect brush is disabled (like on the presentation screen — overlay is for images only).',
|
||||||
|
'control.branches': 'Branch options',
|
||||||
|
'control.option': 'OPTION {n}',
|
||||||
|
'control.unnamed': 'Untitled',
|
||||||
|
'control.switchScene': 'Switch',
|
||||||
|
'control.noBranches': 'No transitions available.',
|
||||||
|
'control.endPresentation': 'End presentation',
|
||||||
|
'control.music': 'Music',
|
||||||
|
'control.sceneMusic': 'SCENE MUSIC',
|
||||||
|
'control.gameMusic': 'GAME MUSIC',
|
||||||
|
'control.noSceneAudio': 'No audio in the current scene.',
|
||||||
|
'control.noGameAudio': 'No game audio.',
|
||||||
|
'control.modeAuto': 'Auto',
|
||||||
|
'control.modeManual': 'Manual',
|
||||||
|
'control.once': 'Once',
|
||||||
|
'control.loop': 'Loop',
|
||||||
|
'control.scrubSeek': 'Click to seek',
|
||||||
|
'control.durationUnknown': 'Duration unknown',
|
||||||
|
'control.pauseSceneMusic': 'Paused (scene)',
|
||||||
|
'control.pauseSceneMusicTitle': 'Scene has music',
|
||||||
|
'control.pauseCampaignTitle': 'Paused: scene has music',
|
||||||
|
'control.playFailed': 'Could not start playback.',
|
||||||
|
'control.audioAutoplayBlocked': 'Autoplay was blocked (user gesture required) or playback failed.',
|
||||||
|
'control.audioNoUrl': 'No URL',
|
||||||
|
'control.audioNoUrlDetail': 'Could not get dnd://asset URL for audio.',
|
||||||
|
'control.audioBlocked': 'Error / blocked',
|
||||||
|
'control.audioError': 'Error',
|
||||||
|
'control.audioMediaError': 'MediaError code={code} (1=ABORTED, 2=NETWORK, 3=DECODE, 4=SRC_NOT_SUPPORTED)',
|
||||||
|
'control.audioLoading': 'Loading…',
|
||||||
|
'control.audioPlaying': 'Playing',
|
||||||
|
'control.audioPaused': 'Paused',
|
||||||
|
'control.audioStopped': 'Stopped',
|
||||||
|
'control.previewTrackLabel': 'Preview (no captions)',
|
||||||
|
'control.transportPlay': 'Play',
|
||||||
|
'control.transportPause': 'Pause',
|
||||||
|
'control.transportStop': 'Stop',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export function translateEditorMessage(
|
||||||
|
locale: EditorLocale,
|
||||||
|
key: string,
|
||||||
|
vars?: Record<string, string | number>,
|
||||||
|
): string {
|
||||||
|
let s = EDITOR_MESSAGES[locale][key] ?? EDITOR_MESSAGES.ru[key] ?? key;
|
||||||
|
if (vars) {
|
||||||
|
for (const [k, v] of Object.entries(vars)) {
|
||||||
|
s = s.split(`{${k}}`).join(String(v));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return s;
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@ import { EULA_RU_MARKDOWN } from '../../legal/eulaRu';
|
|||||||
import { getDndApi } from '../../shared/dndApi';
|
import { getDndApi } from '../../shared/dndApi';
|
||||||
import { Button } from '../../shared/ui/controls';
|
import { Button } from '../../shared/ui/controls';
|
||||||
import styles from '../EditorApp.module.css';
|
import styles from '../EditorApp.module.css';
|
||||||
|
import { useEditorI18n } from '../i18n/EditorI18nContext';
|
||||||
|
|
||||||
type LicenseTokenModalProps = {
|
type LicenseTokenModalProps = {
|
||||||
open: boolean;
|
open: boolean;
|
||||||
@@ -16,6 +17,7 @@ type LicenseTokenModalProps = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export function LicenseTokenModal({ open, onClose, onSaved }: LicenseTokenModalProps) {
|
export function LicenseTokenModal({ open, onClose, onSaved }: LicenseTokenModalProps) {
|
||||||
|
const { t } = useEditorI18n();
|
||||||
const [token, setToken] = useState('');
|
const [token, setToken] = useState('');
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
@@ -40,28 +42,38 @@ export function LicenseTokenModal({ open, onClose, onSaved }: LicenseTokenModalP
|
|||||||
|
|
||||||
return createPortal(
|
return createPortal(
|
||||||
<>
|
<>
|
||||||
<button type="button" aria-label="Закрыть" onClick={onClose} className={styles.modalBackdrop} />
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label={t('common.close')}
|
||||||
|
onClick={onClose}
|
||||||
|
className={styles.modalBackdrop}
|
||||||
|
/>
|
||||||
<div role="dialog" aria-modal="true" className={styles.modalDialog}>
|
<div role="dialog" aria-modal="true" className={styles.modalDialog}>
|
||||||
<div className={styles.modalHeader}>
|
<div className={styles.modalHeader}>
|
||||||
<div className={styles.modalTitle}>Указать ключ</div>
|
<div className={styles.modalTitle}>{t('license.tokenTitle')}</div>
|
||||||
<button type="button" aria-label="Закрыть" onClick={onClose} className={styles.modalClose}>
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label={t('common.close')}
|
||||||
|
onClick={onClose}
|
||||||
|
className={styles.modalClose}
|
||||||
|
>
|
||||||
×
|
×
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div className={styles.fieldGrid}>
|
<div className={styles.fieldGrid}>
|
||||||
<div className={styles.fieldLabel}>КЛЮЧ</div>
|
<div className={styles.fieldLabel}>{t('license.tokenKey')}</div>
|
||||||
<textarea
|
<textarea
|
||||||
className={styles.licenseTextarea}
|
className={styles.licenseTextarea}
|
||||||
value={token}
|
value={token}
|
||||||
onChange={(e) => setToken(e.target.value)}
|
onChange={(e) => setToken(e.target.value)}
|
||||||
placeholder="Продуктовый ключ DND-..."
|
placeholder={t('license.tokenPlaceholder')}
|
||||||
spellCheck={false}
|
spellCheck={false}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
{error ? <div className={styles.fieldError}>{error}</div> : null}
|
{error ? <div className={styles.fieldError}>{error}</div> : null}
|
||||||
<div className={styles.modalFooter}>
|
<div className={styles.modalFooter}>
|
||||||
<Button onClick={onClose} disabled={saving}>
|
<Button onClick={onClose} disabled={saving}>
|
||||||
Отмена
|
{t('common.cancel')}
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
variant="primary"
|
variant="primary"
|
||||||
@@ -82,7 +94,7 @@ export function LicenseTokenModal({ open, onClose, onSaved }: LicenseTokenModalP
|
|||||||
})();
|
})();
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
Сохранить
|
{t('common.save')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -98,6 +110,7 @@ type EulaModalProps = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export function EulaModal({ open, onClose, onAccepted }: EulaModalProps) {
|
export function EulaModal({ open, onClose, onAccepted }: EulaModalProps) {
|
||||||
|
const { t, locale } = useEditorI18n();
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -113,18 +126,29 @@ export function EulaModal({ open, onClose, onAccepted }: EulaModalProps) {
|
|||||||
|
|
||||||
return createPortal(
|
return createPortal(
|
||||||
<>
|
<>
|
||||||
<button type="button" aria-label="Закрыть" onClick={onClose} className={styles.modalBackdrop} />
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label={t('common.close')}
|
||||||
|
onClick={onClose}
|
||||||
|
className={styles.modalBackdrop}
|
||||||
|
/>
|
||||||
<div role="dialog" aria-modal="true" className={styles.modalDialog}>
|
<div role="dialog" aria-modal="true" className={styles.modalDialog}>
|
||||||
<div className={styles.modalHeader}>
|
<div className={styles.modalHeader}>
|
||||||
<div className={styles.modalTitle}>Лицензионное соглашение</div>
|
<div className={styles.modalTitle}>{t('license.eulaTitle')}</div>
|
||||||
<button type="button" aria-label="Закрыть" onClick={onClose} className={styles.modalClose}>
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label={t('common.close')}
|
||||||
|
onClick={onClose}
|
||||||
|
className={styles.modalClose}
|
||||||
|
>
|
||||||
×
|
×
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
{locale === 'en' ? <div className={styles.muted}>{t('license.eulaNoteEn')}</div> : null}
|
||||||
<div className={styles.eulaScroll}>{EULA_RU_MARKDOWN}</div>
|
<div className={styles.eulaScroll}>{EULA_RU_MARKDOWN}</div>
|
||||||
<div className={styles.modalFooter}>
|
<div className={styles.modalFooter}>
|
||||||
<Button onClick={onClose} disabled={saving}>
|
<Button onClick={onClose} disabled={saving}>
|
||||||
Не принимаю
|
{t('license.eulaReject')}
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
variant="primary"
|
variant="primary"
|
||||||
@@ -144,7 +168,7 @@ export function EulaModal({ open, onClose, onAccepted }: EulaModalProps) {
|
|||||||
})();
|
})();
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
Принимаю условия
|
{t('license.eulaAccept')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -159,32 +183,16 @@ type LicenseAboutModalProps = {
|
|||||||
snapshot: LicenseSnapshot | null;
|
snapshot: LicenseSnapshot | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
function reasonLabel(reason: LicenseSnapshot['reason']): string {
|
function licenseReasonLabel(t: (key: string) => string, reason: LicenseSnapshot['reason']): string {
|
||||||
switch (reason) {
|
const key = `license.reason.${reason}`;
|
||||||
case 'ok':
|
const label = t(key);
|
||||||
return 'Активна';
|
return label === key ? reason : label;
|
||||||
case 'none':
|
|
||||||
return 'Ключ не указан';
|
|
||||||
case 'expired':
|
|
||||||
return 'Срок действия истёк';
|
|
||||||
case 'bad_signature':
|
|
||||||
return 'Недействительная подпись';
|
|
||||||
case 'bad_payload':
|
|
||||||
return 'Неверный формат токена';
|
|
||||||
case 'malformed':
|
|
||||||
return 'Повреждённый токен';
|
|
||||||
case 'not_yet_valid':
|
|
||||||
return 'Ещё не действует';
|
|
||||||
case 'wrong_device':
|
|
||||||
return 'Другой привязанный компьютер';
|
|
||||||
case 'revoked_remote':
|
|
||||||
return 'Отозвана на сервере';
|
|
||||||
default:
|
|
||||||
return reason;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function LicenseAboutModal({ open, onClose, snapshot }: LicenseAboutModalProps) {
|
export function LicenseAboutModal({ open, onClose, snapshot }: LicenseAboutModalProps) {
|
||||||
|
const { t, locale } = useEditorI18n();
|
||||||
|
const dateLocale = locale === 'en' ? 'en-US' : 'ru-RU';
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!open) return;
|
if (!open) return;
|
||||||
const onKey = (e: KeyboardEvent) => {
|
const onKey = (e: KeyboardEvent) => {
|
||||||
@@ -198,7 +206,7 @@ export function LicenseAboutModal({ open, onClose, snapshot }: LicenseAboutModal
|
|||||||
|
|
||||||
const expText =
|
const expText =
|
||||||
snapshot?.summary?.exp != null
|
snapshot?.summary?.exp != null
|
||||||
? new Date(snapshot.summary.exp * 1000).toLocaleString('ru-RU', {
|
? new Date(snapshot.summary.exp * 1000).toLocaleString(dateLocale, {
|
||||||
dateStyle: 'long',
|
dateStyle: 'long',
|
||||||
timeStyle: 'short',
|
timeStyle: 'short',
|
||||||
})
|
})
|
||||||
@@ -206,48 +214,54 @@ export function LicenseAboutModal({ open, onClose, snapshot }: LicenseAboutModal
|
|||||||
|
|
||||||
return createPortal(
|
return createPortal(
|
||||||
<>
|
<>
|
||||||
<button type="button" aria-label="Закрыть" onClick={onClose} className={styles.modalBackdrop} />
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label={t('common.close')}
|
||||||
|
onClick={onClose}
|
||||||
|
className={styles.modalBackdrop}
|
||||||
|
/>
|
||||||
<div role="dialog" aria-modal="true" className={styles.modalDialog}>
|
<div role="dialog" aria-modal="true" className={styles.modalDialog}>
|
||||||
<div className={styles.modalHeader}>
|
<div className={styles.modalHeader}>
|
||||||
<div className={styles.modalTitle}>О лицензии</div>
|
<div className={styles.modalTitle}>{t('license.aboutTitle')}</div>
|
||||||
<button type="button" aria-label="Закрыть" onClick={onClose} className={styles.modalClose}>
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label={t('common.close')}
|
||||||
|
onClick={onClose}
|
||||||
|
className={styles.modalClose}
|
||||||
|
>
|
||||||
×
|
×
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
{snapshot?.devSkip ? (
|
{snapshot?.devSkip ? <div className={styles.fieldError}>{t('license.aboutDevSkip')}</div> : null}
|
||||||
<div className={styles.fieldError}>
|
|
||||||
Режим разработки: проверка лицензии отключена (DND_SKIP_LICENSE).
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
<div className={styles.fieldGrid}>
|
<div className={styles.fieldGrid}>
|
||||||
<div className={styles.fieldLabel}>СТАТУС</div>
|
<div className={styles.fieldLabel}>{t('license.aboutStatus')}</div>
|
||||||
<div>{snapshot ? reasonLabel(snapshot.reason) : '—'}</div>
|
<div>{snapshot ? licenseReasonLabel(t, snapshot.reason) : '—'}</div>
|
||||||
</div>
|
</div>
|
||||||
{snapshot?.summary ? (
|
{snapshot?.summary ? (
|
||||||
<>
|
<>
|
||||||
<div className={styles.fieldGrid}>
|
<div className={styles.fieldGrid}>
|
||||||
<div className={styles.fieldLabel}>ПРОДУКТ</div>
|
<div className={styles.fieldLabel}>{t('license.aboutProduct')}</div>
|
||||||
<div>{snapshot.summary.pid}</div>
|
<div>{snapshot.summary.pid}</div>
|
||||||
</div>
|
</div>
|
||||||
<div className={styles.fieldGrid}>
|
<div className={styles.fieldGrid}>
|
||||||
<div className={styles.fieldLabel}>ID ЛИЦЕНЗИИ</div>
|
<div className={styles.fieldLabel}>{t('license.aboutLicenseId')}</div>
|
||||||
<div style={{ wordBreak: 'break-all' }}>{snapshot.summary.sub}</div>
|
<div style={{ wordBreak: 'break-all' }}>{snapshot.summary.sub}</div>
|
||||||
</div>
|
</div>
|
||||||
<div className={styles.fieldGrid}>
|
<div className={styles.fieldGrid}>
|
||||||
<div className={styles.fieldLabel}>ОКОНЧАНИЕ</div>
|
<div className={styles.fieldLabel}>{t('license.aboutExpiry')}</div>
|
||||||
<div>{expText}</div>
|
<div>{expText}</div>
|
||||||
</div>
|
</div>
|
||||||
<div className={styles.fieldGrid}>
|
<div className={styles.fieldGrid}>
|
||||||
<div className={styles.fieldLabel}>УСТРОЙСТВО</div>
|
<div className={styles.fieldLabel}>{t('license.aboutDevice')}</div>
|
||||||
<div style={{ wordBreak: 'break-all' }}>{snapshot.deviceId}</div>
|
<div style={{ wordBreak: 'break-all' }}>{snapshot.deviceId}</div>
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<div className={styles.muted}>Нет данных лицензии.</div>
|
<div className={styles.muted}>{t('license.aboutNoData')}</div>
|
||||||
)}
|
)}
|
||||||
<div className={styles.modalFooter}>
|
<div className={styles.modalFooter}>
|
||||||
<Button variant="primary" onClick={onClose}>
|
<Button variant="primary" onClick={onClose}>
|
||||||
Закрыть
|
{t('common.close')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { createRoot } from 'react-dom/client';
|
|||||||
|
|
||||||
import '../shared/ui/globals.css';
|
import '../shared/ui/globals.css';
|
||||||
import { EditorApp } from './EditorApp';
|
import { EditorApp } from './EditorApp';
|
||||||
|
import { EditorI18nProvider } from './i18n/EditorI18nContext';
|
||||||
|
|
||||||
const rootEl = document.getElementById('root');
|
const rootEl = document.getElementById('root');
|
||||||
if (!rootEl) {
|
if (!rootEl) {
|
||||||
@@ -11,6 +12,8 @@ if (!rootEl) {
|
|||||||
|
|
||||||
createRoot(rootEl).render(
|
createRoot(rootEl).render(
|
||||||
<React.StrictMode>
|
<React.StrictMode>
|
||||||
<EditorApp />
|
<EditorI18nProvider>
|
||||||
|
<EditorApp />
|
||||||
|
</EditorI18nProvider>
|
||||||
</React.StrictMode>,
|
</React.StrictMode>,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import test from 'node:test';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||||
|
|
||||||
|
void test('projectState: list/get after delete invalidates in-flight initial load (epoch guard)', () => {
|
||||||
|
const src = fs.readFileSync(path.join(here, 'projectState.ts'), 'utf8');
|
||||||
|
assert.match(src, /projectDataEpochRef/);
|
||||||
|
assert.match(src, /const epoch = \+\+projectDataEpochRef\.current/);
|
||||||
|
assert.match(src, /if \(projectDataEpochRef\.current !== epoch\) return/);
|
||||||
|
assert.match(
|
||||||
|
src,
|
||||||
|
/const deleteProject = async[\s\S]+?projectDataEpochRef\.current \+= 1[\s\S]+?await api\.invoke/,
|
||||||
|
);
|
||||||
|
assert.match(
|
||||||
|
src,
|
||||||
|
/const openProject = async[\s\S]+?projectDataEpochRef\.current \+= 1[\s\S]+?await api\.invoke/,
|
||||||
|
);
|
||||||
|
assert.match(src, /const refreshProjects = async \(\) => \{[\s\S]+?projectDataEpochRef\.current \+= 1/);
|
||||||
|
});
|
||||||
|
|
||||||
|
void test('ipc router: project.list does not require license', () => {
|
||||||
|
const routerSrc = fs.readFileSync(path.join(here, '..', '..', '..', 'main', 'ipc', 'router.ts'), 'utf8');
|
||||||
|
assert.match(routerSrc, /if \(channel === ipcChannels\.project\.list\) return false/);
|
||||||
|
});
|
||||||
@@ -10,6 +10,7 @@ type State = {
|
|||||||
projects: ProjectSummary[];
|
projects: ProjectSummary[];
|
||||||
project: Project | null;
|
project: Project | null;
|
||||||
selectedSceneId: SceneId | null;
|
selectedSceneId: SceneId | null;
|
||||||
|
zipProgress: { kind: 'import' | 'export'; percent: number; stage: string; detail?: string } | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
type Actions = {
|
type Actions = {
|
||||||
@@ -19,12 +20,15 @@ type Actions = {
|
|||||||
closeProject: () => Promise<void>;
|
closeProject: () => Promise<void>;
|
||||||
createScene: () => Promise<void>;
|
createScene: () => Promise<void>;
|
||||||
selectScene: (id: SceneId) => Promise<void>;
|
selectScene: (id: SceneId) => Promise<void>;
|
||||||
|
importCampaignAudio: () => Promise<void>;
|
||||||
|
updateCampaignAudios: (next: Project['campaignAudios']) => Promise<void>;
|
||||||
updateScene: (
|
updateScene: (
|
||||||
sceneId: SceneId,
|
sceneId: SceneId,
|
||||||
patch: {
|
patch: {
|
||||||
title?: string;
|
title?: string;
|
||||||
description?: string;
|
description?: string;
|
||||||
previewAssetId?: AssetId | null;
|
previewAssetId?: AssetId | null;
|
||||||
|
previewThumbAssetId?: AssetId | null;
|
||||||
previewAssetType?: 'image' | 'video' | null;
|
previewAssetType?: 'image' | 'video' | null;
|
||||||
previewVideoAutostart?: boolean;
|
previewVideoAutostart?: boolean;
|
||||||
previewRotationDeg?: 0 | 90 | 180 | 270;
|
previewRotationDeg?: 0 | 90 | 180 | 270;
|
||||||
@@ -54,16 +58,71 @@ function randomId(prefix: string): string {
|
|||||||
return `${prefix}_${Math.random().toString(16).slice(2)}_${Date.now().toString(16)}`;
|
return `${prefix}_${Math.random().toString(16).slice(2)}_${Date.now().toString(16)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useProjectState(licenseActive: boolean): readonly [State, Actions] {
|
export type ProjectNoticeCode = 'campaign_audio_empty';
|
||||||
|
|
||||||
|
export type ProjectStateOpts = {
|
||||||
|
onNotice?: (code: ProjectNoticeCode) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function useProjectState(licenseActive: boolean, opts?: ProjectStateOpts): readonly [State, Actions] {
|
||||||
const api = getDndApi();
|
const api = getDndApi();
|
||||||
const [state, setState] = useState<State>({ projects: [], project: null, selectedSceneId: null });
|
const onNoticeRef = useRef(opts?.onNotice);
|
||||||
|
useEffect(() => {
|
||||||
|
onNoticeRef.current = opts?.onNotice;
|
||||||
|
}, [opts?.onNotice]);
|
||||||
|
const [state, setState] = useState<State>({
|
||||||
|
projects: [],
|
||||||
|
project: null,
|
||||||
|
selectedSceneId: null,
|
||||||
|
zipProgress: null,
|
||||||
|
});
|
||||||
const projectRef = useRef<Project | null>(null);
|
const projectRef = useRef<Project | null>(null);
|
||||||
|
/** Bumps on mutations / refresh; initial license load only applies if still current (avoids racing late list/get over newer state). */
|
||||||
|
const projectDataEpochRef = useRef(0);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
projectRef.current = state.project;
|
projectRef.current = state.project;
|
||||||
}, [state.project]);
|
}, [state.project]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const offImport = api.on(ipcChannels.project.importZipProgress, (evt) => {
|
||||||
|
const e = evt as unknown as { percent: number; stage: string; detail?: string };
|
||||||
|
setState((s) => ({
|
||||||
|
...s,
|
||||||
|
zipProgress: {
|
||||||
|
kind: 'import',
|
||||||
|
percent: e.percent,
|
||||||
|
stage: e.stage,
|
||||||
|
...(e.detail ? { detail: e.detail } : null),
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
if (e.stage === 'done' || e.percent >= 100) {
|
||||||
|
setTimeout(() => setState((s) => ({ ...s, zipProgress: null })), 450);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const offExport = api.on(ipcChannels.project.exportZipProgress, (evt) => {
|
||||||
|
const e = evt as unknown as { percent: number; stage: string; detail?: string };
|
||||||
|
setState((s) => ({
|
||||||
|
...s,
|
||||||
|
zipProgress: {
|
||||||
|
kind: 'export',
|
||||||
|
percent: e.percent,
|
||||||
|
stage: e.stage,
|
||||||
|
...(e.detail ? { detail: e.detail } : null),
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
if (e.stage === 'done' || e.percent >= 100) {
|
||||||
|
setTimeout(() => setState((s) => ({ ...s, zipProgress: null })), 450);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
offImport();
|
||||||
|
offExport();
|
||||||
|
};
|
||||||
|
}, [api]);
|
||||||
|
|
||||||
const actions = useMemo<Actions>(() => {
|
const actions = useMemo<Actions>(() => {
|
||||||
const refreshProjects = async () => {
|
const refreshProjects = async () => {
|
||||||
|
projectDataEpochRef.current += 1;
|
||||||
const res = await api.invoke(ipcChannels.project.list, {});
|
const res = await api.invoke(ipcChannels.project.list, {});
|
||||||
setState((s) => ({ ...s, projects: res.projects }));
|
setState((s) => ({ ...s, projects: res.projects }));
|
||||||
};
|
};
|
||||||
@@ -75,13 +134,14 @@ export function useProjectState(licenseActive: boolean): readonly [State, Action
|
|||||||
};
|
};
|
||||||
|
|
||||||
const openProject = async (id: ProjectId) => {
|
const openProject = async (id: ProjectId) => {
|
||||||
|
projectDataEpochRef.current += 1;
|
||||||
const res = await api.invoke(ipcChannels.project.open, { projectId: id });
|
const res = await api.invoke(ipcChannels.project.open, { projectId: id });
|
||||||
setState((s) => ({ ...s, project: res.project, selectedSceneId: res.project.currentSceneId }));
|
setState((s) => ({ ...s, project: res.project, selectedSceneId: res.project.currentSceneId }));
|
||||||
};
|
};
|
||||||
|
|
||||||
const closeProject = async () => {
|
const closeProject = async () => {
|
||||||
setState((s) => ({ ...s, project: null, selectedSceneId: null }));
|
setState((s) => ({ ...s, project: null, selectedSceneId: null }));
|
||||||
if (licenseActive) await refreshProjects();
|
await refreshProjects();
|
||||||
};
|
};
|
||||||
|
|
||||||
const createScene = async () => {
|
const createScene = async () => {
|
||||||
@@ -93,6 +153,7 @@ export function useProjectState(licenseActive: boolean): readonly [State, Action
|
|||||||
title: `Новая сцена`,
|
title: `Новая сцена`,
|
||||||
description: '',
|
description: '',
|
||||||
previewAssetId: null,
|
previewAssetId: null,
|
||||||
|
previewThumbAssetId: null,
|
||||||
previewAssetType: null,
|
previewAssetType: null,
|
||||||
previewVideoAutostart: false,
|
previewVideoAutostart: false,
|
||||||
previewRotationDeg: 0,
|
previewRotationDeg: 0,
|
||||||
@@ -125,12 +186,29 @@ export function useProjectState(licenseActive: boolean): readonly [State, Action
|
|||||||
await api.invoke(ipcChannels.project.setCurrentScene, { sceneId: id });
|
await api.invoke(ipcChannels.project.setCurrentScene, { sceneId: id });
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const importCampaignAudio = async () => {
|
||||||
|
const res = await api.invoke(ipcChannels.project.importCampaignAudio, {});
|
||||||
|
if (res.canceled) return;
|
||||||
|
if (res.imported.length === 0) {
|
||||||
|
onNoticeRef.current?.('campaign_audio_empty');
|
||||||
|
}
|
||||||
|
setState((s) => ({ ...s, project: res.project }));
|
||||||
|
await refreshProjects();
|
||||||
|
};
|
||||||
|
|
||||||
|
const updateCampaignAudios = async (next: Project['campaignAudios']) => {
|
||||||
|
const res = await api.invoke(ipcChannels.project.updateCampaignAudios, { audios: next });
|
||||||
|
setState((s) => ({ ...s, project: res.project }));
|
||||||
|
await refreshProjects();
|
||||||
|
};
|
||||||
|
|
||||||
const updateScene = async (
|
const updateScene = async (
|
||||||
sceneId: SceneId,
|
sceneId: SceneId,
|
||||||
patch: {
|
patch: {
|
||||||
title?: string;
|
title?: string;
|
||||||
description?: string;
|
description?: string;
|
||||||
previewAssetId?: AssetId | null;
|
previewAssetId?: AssetId | null;
|
||||||
|
previewThumbAssetId?: AssetId | null;
|
||||||
previewAssetType?: 'image' | 'video' | null;
|
previewAssetType?: 'image' | 'video' | null;
|
||||||
previewVideoAutostart?: boolean;
|
previewVideoAutostart?: boolean;
|
||||||
previewRotationDeg?: 0 | 90 | 180 | 270;
|
previewRotationDeg?: 0 | 90 | 180 | 270;
|
||||||
@@ -149,6 +227,9 @@ export function useProjectState(licenseActive: boolean): readonly [State, Action
|
|||||||
...(patch.title !== undefined ? { title: patch.title } : null),
|
...(patch.title !== undefined ? { title: patch.title } : null),
|
||||||
...(patch.description !== undefined ? { description: patch.description } : null),
|
...(patch.description !== undefined ? { description: patch.description } : null),
|
||||||
...(patch.previewAssetId !== undefined ? { previewAssetId: patch.previewAssetId } : null),
|
...(patch.previewAssetId !== undefined ? { previewAssetId: patch.previewAssetId } : null),
|
||||||
|
...(patch.previewThumbAssetId !== undefined
|
||||||
|
? { previewThumbAssetId: patch.previewThumbAssetId }
|
||||||
|
: null),
|
||||||
...(patch.previewAssetType !== undefined ? { previewAssetType: patch.previewAssetType } : null),
|
...(patch.previewAssetType !== undefined ? { previewAssetType: patch.previewAssetType } : null),
|
||||||
...(patch.previewVideoAutostart !== undefined
|
...(patch.previewVideoAutostart !== undefined
|
||||||
? { previewVideoAutostart: patch.previewVideoAutostart }
|
? { previewVideoAutostart: patch.previewVideoAutostart }
|
||||||
@@ -276,6 +357,7 @@ export function useProjectState(licenseActive: boolean): readonly [State, Action
|
|||||||
};
|
};
|
||||||
|
|
||||||
const deleteProject = async (projectId: ProjectId) => {
|
const deleteProject = async (projectId: ProjectId) => {
|
||||||
|
projectDataEpochRef.current += 1;
|
||||||
await api.invoke(ipcChannels.project.deleteProject, { projectId });
|
await api.invoke(ipcChannels.project.deleteProject, { projectId });
|
||||||
const listRes = await api.invoke(ipcChannels.project.list, {});
|
const listRes = await api.invoke(ipcChannels.project.list, {});
|
||||||
const res = await api.invoke(ipcChannels.project.get, {});
|
const res = await api.invoke(ipcChannels.project.get, {});
|
||||||
@@ -294,6 +376,8 @@ export function useProjectState(licenseActive: boolean): readonly [State, Action
|
|||||||
closeProject,
|
closeProject,
|
||||||
createScene,
|
createScene,
|
||||||
selectScene,
|
selectScene,
|
||||||
|
importCampaignAudio,
|
||||||
|
updateCampaignAudios,
|
||||||
updateScene,
|
updateScene,
|
||||||
updateConnections,
|
updateConnections,
|
||||||
importMediaToScene,
|
importMediaToScene,
|
||||||
@@ -311,20 +395,37 @@ export function useProjectState(licenseActive: boolean): readonly [State, Action
|
|||||||
exportProject,
|
exportProject,
|
||||||
deleteProject,
|
deleteProject,
|
||||||
};
|
};
|
||||||
}, [api, licenseActive]);
|
}, [api]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!licenseActive) {
|
const epoch = ++projectDataEpochRef.current;
|
||||||
queueMicrotask(() => {
|
|
||||||
setState({ projects: [], project: null, selectedSceneId: null });
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
void (async () => {
|
void (async () => {
|
||||||
const listRes = await api.invoke(ipcChannels.project.list, {});
|
try {
|
||||||
setState((s) => ({ ...s, projects: listRes.projects }));
|
const listRes = await api.invoke(ipcChannels.project.list, {});
|
||||||
const res = await api.invoke(ipcChannels.project.get, {});
|
if (projectDataEpochRef.current !== epoch) return;
|
||||||
setState((s) => ({ ...s, project: res.project, selectedSceneId: res.project?.currentSceneId ?? null }));
|
if (!licenseActive) {
|
||||||
|
setState((s) => ({
|
||||||
|
...s,
|
||||||
|
projects: listRes.projects,
|
||||||
|
project: null,
|
||||||
|
selectedSceneId: null,
|
||||||
|
}));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setState((s) => ({ ...s, projects: listRes.projects }));
|
||||||
|
const res = await api.invoke(ipcChannels.project.get, {});
|
||||||
|
if (projectDataEpochRef.current !== epoch) return;
|
||||||
|
setState((s) => ({
|
||||||
|
...s,
|
||||||
|
project: res.project,
|
||||||
|
selectedSceneId: res.project?.currentSceneId ?? null,
|
||||||
|
}));
|
||||||
|
} catch {
|
||||||
|
if (projectDataEpochRef.current !== epoch) return;
|
||||||
|
if (!licenseActive) {
|
||||||
|
setState((s) => ({ ...s, project: null, selectedSceneId: null }));
|
||||||
|
}
|
||||||
|
}
|
||||||
})();
|
})();
|
||||||
}, [licenseActive, api]);
|
}, [licenseActive, api]);
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import React, { useEffect, useRef } from 'react';
|
import React, { useEffect, useRef, useState } from 'react';
|
||||||
|
|
||||||
import { computeTimeSec } from '../../main/video/videoPlaybackStore';
|
import { computeTimeSec } from '../../main/video/videoPlaybackStore';
|
||||||
import type { SessionState } from '../../shared/ipc/contracts';
|
import type { SessionState } from '../../shared/ipc/contracts';
|
||||||
@@ -32,9 +32,39 @@ export function PresentationView({
|
|||||||
);
|
);
|
||||||
const scene =
|
const scene =
|
||||||
session?.project && session.currentSceneId ? session.project.scenes[session.currentSceneId] : undefined;
|
session?.project && session.currentSceneId ? session.project.scenes[session.currentSceneId] : undefined;
|
||||||
const previewUrl = useAssetUrl(scene?.previewAssetId ?? null);
|
const originalUrl = useAssetUrl(scene?.previewAssetId ?? null);
|
||||||
|
const thumbUrl = useAssetUrl(scene?.previewThumbAssetId ?? null);
|
||||||
|
const [shownImageUrl, setShownImageUrl] = useState<string | null>(null);
|
||||||
const rot = scene?.previewRotationDeg ?? 0;
|
const rot = scene?.previewRotationDeg ?? 0;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!scene) {
|
||||||
|
setShownImageUrl(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (scene.previewAssetType !== 'image') {
|
||||||
|
setShownImageUrl(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Show thumbnail instantly (if exists) to avoid stutter on slide switch, then swap to original when loaded.
|
||||||
|
setShownImageUrl(thumbUrl ?? originalUrl);
|
||||||
|
if (!thumbUrl || !originalUrl || thumbUrl === originalUrl) return;
|
||||||
|
let cancelled = false;
|
||||||
|
const img = new Image();
|
||||||
|
img.decoding = 'async';
|
||||||
|
img.onload = () => {
|
||||||
|
if (cancelled) return;
|
||||||
|
setShownImageUrl(originalUrl);
|
||||||
|
};
|
||||||
|
img.onerror = () => {
|
||||||
|
// keep thumbnail
|
||||||
|
};
|
||||||
|
img.src = originalUrl;
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
}, [originalUrl, scene, thumbUrl]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const el = videoElRef.current;
|
const el = videoElRef.current;
|
||||||
if (!el) return;
|
if (!el) return;
|
||||||
@@ -53,24 +83,33 @@ export function PresentationView({
|
|||||||
} else {
|
} else {
|
||||||
el.pause();
|
el.pause();
|
||||||
}
|
}
|
||||||
}, [scene?.previewAssetId, scene?.previewAssetType, vp]);
|
// eslint-disable-next-line react-hooks/exhaustive-deps -- avoid reruns on 500ms heartbeats (serverNowMs-only updates)
|
||||||
|
}, [
|
||||||
|
scene?.previewAssetId,
|
||||||
|
scene?.previewAssetType,
|
||||||
|
originalUrl,
|
||||||
|
vp?.revision,
|
||||||
|
vp?.targetAssetId,
|
||||||
|
vp?.playing,
|
||||||
|
vp?.playbackRate,
|
||||||
|
]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={styles.root}>
|
<div className={styles.root}>
|
||||||
{previewUrl && scene?.previewAssetType === 'image' ? (
|
{shownImageUrl && scene?.previewAssetType === 'image' ? (
|
||||||
<div className={styles.fill}>
|
<div className={styles.fill}>
|
||||||
<RotatedImage
|
<RotatedImage
|
||||||
url={previewUrl}
|
url={shownImageUrl}
|
||||||
rotationDeg={rot}
|
rotationDeg={rot}
|
||||||
mode="contain"
|
mode="contain"
|
||||||
onContentRectChange={setContentRect}
|
onContentRectChange={setContentRect}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
) : previewUrl && scene?.previewAssetType === 'video' ? (
|
) : originalUrl && scene?.previewAssetType === 'video' ? (
|
||||||
<video
|
<video
|
||||||
ref={videoElRef}
|
ref={videoElRef}
|
||||||
className={styles.video}
|
className={styles.video}
|
||||||
src={previewUrl}
|
src={originalUrl}
|
||||||
muted
|
muted
|
||||||
playsInline
|
playsInline
|
||||||
loop={false}
|
loop={false}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
import React, { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||||
|
|
||||||
import styles from './RotatedImage.module.css';
|
import styles from './RotatedImage.module.css';
|
||||||
|
|
||||||
@@ -9,6 +9,8 @@ type RotatedImageProps = {
|
|||||||
rotationDeg: 0 | 90 | 180 | 270;
|
rotationDeg: 0 | 90 | 180 | 270;
|
||||||
mode: Mode;
|
mode: Mode;
|
||||||
alt?: string;
|
alt?: string;
|
||||||
|
loading?: React.ImgHTMLAttributes<HTMLImageElement>['loading'];
|
||||||
|
decoding?: React.ImgHTMLAttributes<HTMLImageElement>['decoding'];
|
||||||
/** Высота/ширина полностью контролируются родителем. */
|
/** Высота/ширина полностью контролируются родителем. */
|
||||||
style?: React.CSSProperties;
|
style?: React.CSSProperties;
|
||||||
/** Прямоугольник видимого контента (contain/cover) внутри контейнера. */
|
/** Прямоугольник видимого контента (contain/cover) внутри контейнера. */
|
||||||
@@ -22,13 +24,15 @@ function useElementSize<T extends HTMLElement>() {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const el = ref.current;
|
const el = ref.current;
|
||||||
if (!el) return;
|
if (!el) return;
|
||||||
|
// clientWidth/Height — локальная вёрстка; getBoundingClientRect учитывает transform предков (React Flow zoom).
|
||||||
|
const readLayoutSize = () => {
|
||||||
|
setSize({ w: el.clientWidth, h: el.clientHeight });
|
||||||
|
};
|
||||||
const ro = new ResizeObserver(() => {
|
const ro = new ResizeObserver(() => {
|
||||||
const r = el.getBoundingClientRect();
|
readLayoutSize();
|
||||||
setSize({ w: r.width, h: r.height });
|
|
||||||
});
|
});
|
||||||
ro.observe(el);
|
ro.observe(el);
|
||||||
const r = el.getBoundingClientRect();
|
readLayoutSize();
|
||||||
setSize({ w: r.width, h: r.height });
|
|
||||||
return () => ro.disconnect();
|
return () => ro.disconnect();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
@@ -40,23 +44,26 @@ export function RotatedImage({
|
|||||||
rotationDeg,
|
rotationDeg,
|
||||||
mode,
|
mode,
|
||||||
alt = '',
|
alt = '',
|
||||||
|
loading,
|
||||||
|
decoding,
|
||||||
style,
|
style,
|
||||||
onContentRectChange,
|
onContentRectChange,
|
||||||
}: RotatedImageProps) {
|
}: RotatedImageProps) {
|
||||||
const [ref, size] = useElementSize<HTMLDivElement>();
|
const [ref, size] = useElementSize<HTMLDivElement>();
|
||||||
const [imgSize, setImgSize] = useState<{ w: number; h: number } | null>(null);
|
const [imgSize, setImgSize] = useState<{ w: number; h: number } | null>(null);
|
||||||
|
const imgRef = useRef<HTMLImageElement | null>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useLayoutEffect(() => {
|
||||||
let cancelled = false;
|
// If the image is served from cache, onLoad may fire before listeners attach.
|
||||||
const img = new Image();
|
// Reading from the <img> element itself is the most reliable source.
|
||||||
img.onload = () => {
|
const el = imgRef.current;
|
||||||
if (cancelled) return;
|
if (!el) return;
|
||||||
setImgSize({ w: img.naturalWidth || 1, h: img.naturalHeight || 1 });
|
if (!el.complete) return;
|
||||||
};
|
const w0 = el.naturalWidth || 0;
|
||||||
img.src = url;
|
const h0 = el.naturalHeight || 0;
|
||||||
return () => {
|
if (w0 <= 0 || h0 <= 0) return;
|
||||||
cancelled = true;
|
// eslint-disable-next-line react-hooks/set-state-in-effect, @typescript-eslint/prefer-optional-chain -- read cached <img> dimensions when onLoad may not fire
|
||||||
};
|
setImgSize((prev) => (prev && prev.w === w0 && prev.h === h0 ? prev : { w: w0, h: h0 }));
|
||||||
}, [url]);
|
}, [url]);
|
||||||
|
|
||||||
const scale = useMemo(() => {
|
const scale = useMemo(() => {
|
||||||
@@ -89,9 +96,23 @@ export function RotatedImage({
|
|||||||
return (
|
return (
|
||||||
<div ref={ref} className={styles.root} style={style}>
|
<div ref={ref} className={styles.root} style={style}>
|
||||||
<img
|
<img
|
||||||
|
ref={imgRef}
|
||||||
alt={alt}
|
alt={alt}
|
||||||
src={url}
|
src={url}
|
||||||
|
loading={loading}
|
||||||
|
decoding={decoding}
|
||||||
className={styles.img}
|
className={styles.img}
|
||||||
|
onLoad={(e) => {
|
||||||
|
const el = e.currentTarget;
|
||||||
|
const w0 = el.naturalWidth || 0;
|
||||||
|
const h0 = el.naturalHeight || 0;
|
||||||
|
if (w0 <= 0 || h0 <= 0) return;
|
||||||
|
setImgSize((prev) => {
|
||||||
|
// eslint-disable-next-line @typescript-eslint/prefer-optional-chain -- rule can misfire on React state unions
|
||||||
|
if (prev && prev.w === w0 && prev.h === h0) return prev;
|
||||||
|
return { w: w0, h: h0 };
|
||||||
|
});
|
||||||
|
}}
|
||||||
style={{
|
style={{
|
||||||
width: w ?? '100%',
|
width: w ?? '100%',
|
||||||
height: h ?? '100%',
|
height: h ?? '100%',
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||||
|
|
||||||
import { ipcChannels } from '../../../shared/ipc/contracts';
|
import { ipcChannels } from '../../../shared/ipc/contracts';
|
||||||
import type { VideoPlaybackEvent, VideoPlaybackState } from '../../../shared/types';
|
import type { VideoPlaybackEvent, VideoPlaybackState } from '../../../shared/types';
|
||||||
@@ -9,31 +9,36 @@ export function useVideoPlaybackState(): readonly [
|
|||||||
{ dispatch: (event: VideoPlaybackEvent) => Promise<void> },
|
{ dispatch: (event: VideoPlaybackEvent) => Promise<void> },
|
||||||
] {
|
] {
|
||||||
const api = getDndApi();
|
const api = getDndApi();
|
||||||
const [state, setState] = useState<VideoPlaybackState | null>(null);
|
const [playback, setPlayback] = useState<VideoPlaybackState | null>(null);
|
||||||
const [timeOffsetMs, setTimeOffsetMs] = useState(0);
|
/** serverNowMs − Date.now() at last IPC sync; lets us compute a live clock without React timers. */
|
||||||
const [clientNowMs, setClientNowMs] = useState(() => Date.now());
|
const timeOffsetMsRef = useRef(0);
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!state) return;
|
|
||||||
const id = window.setInterval(() => {
|
|
||||||
setClientNowMs(Date.now());
|
|
||||||
}, 250);
|
|
||||||
return () => window.clearInterval(id);
|
|
||||||
}, [state]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void api.invoke(ipcChannels.video.getState, {}).then((r) => {
|
void api.invoke(ipcChannels.video.getState, {}).then((r) => {
|
||||||
setState(r.state);
|
timeOffsetMsRef.current = r.state.serverNowMs - Date.now();
|
||||||
setTimeOffsetMs(r.state.serverNowMs - Date.now());
|
setPlayback(r.state);
|
||||||
});
|
});
|
||||||
return api.on(ipcChannels.video.stateChanged, ({ state: next }) => {
|
return api.on(ipcChannels.video.stateChanged, ({ state: next }) => {
|
||||||
setState(next);
|
timeOffsetMsRef.current = next.serverNowMs - Date.now();
|
||||||
setTimeOffsetMs(next.serverNowMs - Date.now());
|
setPlayback((prev) => {
|
||||||
|
if (prev?.revision === next.revision) return prev;
|
||||||
|
return next;
|
||||||
|
});
|
||||||
});
|
});
|
||||||
}, [api]);
|
}, [api]);
|
||||||
|
|
||||||
|
const state = useMemo((): VideoPlaybackState | null => {
|
||||||
|
if (!playback) return null;
|
||||||
|
return {
|
||||||
|
...playback,
|
||||||
|
get serverNowMs(): number {
|
||||||
|
return Date.now() + timeOffsetMsRef.current;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}, [playback]);
|
||||||
|
|
||||||
return [
|
return [
|
||||||
state ? { ...state, serverNowMs: clientNowMs + timeOffsetMs } : null,
|
state,
|
||||||
{
|
{
|
||||||
dispatch: async (event) => {
|
dispatch: async (event) => {
|
||||||
await api.invoke(ipcChannels.video.dispatch, { event });
|
await api.invoke(ipcChannels.video.dispatch, { event });
|
||||||
|
|||||||
@@ -18,6 +18,10 @@ export const ipcChannels = {
|
|||||||
quit: 'app.quit',
|
quit: 'app.quit',
|
||||||
getVersion: 'app.getVersion',
|
getVersion: 'app.getVersion',
|
||||||
},
|
},
|
||||||
|
updater: {
|
||||||
|
check: 'updater.check',
|
||||||
|
downloadAndRestart: 'updater.downloadAndRestart',
|
||||||
|
},
|
||||||
project: {
|
project: {
|
||||||
list: 'project.list',
|
list: 'project.list',
|
||||||
create: 'project.create',
|
create: 'project.create',
|
||||||
@@ -29,6 +33,8 @@ export const ipcChannels = {
|
|||||||
setCurrentScene: 'project.setCurrentScene',
|
setCurrentScene: 'project.setCurrentScene',
|
||||||
setCurrentGraphNode: 'project.setCurrentGraphNode',
|
setCurrentGraphNode: 'project.setCurrentGraphNode',
|
||||||
importMedia: 'project.importMedia',
|
importMedia: 'project.importMedia',
|
||||||
|
importCampaignAudio: 'project.importCampaignAudio',
|
||||||
|
updateCampaignAudios: 'project.updateCampaignAudios',
|
||||||
importScenePreview: 'project.importScenePreview',
|
importScenePreview: 'project.importScenePreview',
|
||||||
clearScenePreview: 'project.clearScenePreview',
|
clearScenePreview: 'project.clearScenePreview',
|
||||||
assetFileUrl: 'project.assetFileUrl',
|
assetFileUrl: 'project.assetFileUrl',
|
||||||
@@ -43,11 +49,15 @@ export const ipcChannels = {
|
|||||||
importZip: 'project.importZip',
|
importZip: 'project.importZip',
|
||||||
exportZip: 'project.exportZip',
|
exportZip: 'project.exportZip',
|
||||||
deleteProject: 'project.deleteProject',
|
deleteProject: 'project.deleteProject',
|
||||||
|
importZipProgress: 'project.importZipProgress',
|
||||||
|
exportZipProgress: 'project.exportZipProgress',
|
||||||
},
|
},
|
||||||
windows: {
|
windows: {
|
||||||
openMultiWindow: 'windows.openMultiWindow',
|
openMultiWindow: 'windows.openMultiWindow',
|
||||||
closeMultiWindow: 'windows.closeMultiWindow',
|
closeMultiWindow: 'windows.closeMultiWindow',
|
||||||
togglePresentationFullscreen: 'windows.togglePresentationFullscreen',
|
togglePresentationFullscreen: 'windows.togglePresentationFullscreen',
|
||||||
|
getMultiWindowState: 'windows.getMultiWindowState',
|
||||||
|
multiWindowStateChanged: 'windows.multiWindowStateChanged',
|
||||||
},
|
},
|
||||||
session: {
|
session: {
|
||||||
stateChanged: 'session.stateChanged',
|
stateChanged: 'session.stateChanged',
|
||||||
@@ -71,6 +81,32 @@ export const ipcChannels = {
|
|||||||
},
|
},
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
|
export type ZipProgressEvent = {
|
||||||
|
kind: 'import' | 'export';
|
||||||
|
stage: 'copy' | 'unzip' | 'zip' | 'done';
|
||||||
|
percent: number; // 0..100
|
||||||
|
detail?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type UpdaterCheckResponse =
|
||||||
|
| { outcome: 'not_packaged' }
|
||||||
|
| { outcome: 'no_license' }
|
||||||
|
| { outcome: 'current'; currentVersion: string }
|
||||||
|
| { outcome: 'available'; version: string }
|
||||||
|
| { outcome: 'error'; message: string };
|
||||||
|
|
||||||
|
export type UpdaterDownloadResponse = { ok: true } | { ok: false; message: string };
|
||||||
|
|
||||||
|
export type IpcEventMap = {
|
||||||
|
[ipcChannels.session.stateChanged]: { state: SessionState };
|
||||||
|
[ipcChannels.effects.stateChanged]: { state: EffectsState };
|
||||||
|
[ipcChannels.video.stateChanged]: { state: VideoPlaybackState };
|
||||||
|
[ipcChannels.license.statusChanged]: { snapshot: LicenseSnapshot };
|
||||||
|
[ipcChannels.windows.multiWindowStateChanged]: { open: boolean };
|
||||||
|
[ipcChannels.project.importZipProgress]: ZipProgressEvent;
|
||||||
|
[ipcChannels.project.exportZipProgress]: ZipProgressEvent;
|
||||||
|
};
|
||||||
|
|
||||||
export type IpcInvokeMap = {
|
export type IpcInvokeMap = {
|
||||||
[ipcChannels.app.quit]: {
|
[ipcChannels.app.quit]: {
|
||||||
req: Record<string, never>;
|
req: Record<string, never>;
|
||||||
@@ -78,7 +114,15 @@ export type IpcInvokeMap = {
|
|||||||
};
|
};
|
||||||
[ipcChannels.app.getVersion]: {
|
[ipcChannels.app.getVersion]: {
|
||||||
req: Record<string, never>;
|
req: Record<string, never>;
|
||||||
res: { version: string; buildNumber: string | null };
|
res: { version: string; buildNumber: string | null; packaged: boolean };
|
||||||
|
};
|
||||||
|
[ipcChannels.updater.check]: {
|
||||||
|
req: Record<string, never>;
|
||||||
|
res: UpdaterCheckResponse;
|
||||||
|
};
|
||||||
|
[ipcChannels.updater.downloadAndRestart]: {
|
||||||
|
req: Record<string, never>;
|
||||||
|
res: UpdaterDownloadResponse;
|
||||||
};
|
};
|
||||||
[ipcChannels.project.list]: {
|
[ipcChannels.project.list]: {
|
||||||
req: Record<string, never>;
|
req: Record<string, never>;
|
||||||
@@ -120,6 +164,14 @@ export type IpcInvokeMap = {
|
|||||||
req: { sceneId: SceneId };
|
req: { sceneId: SceneId };
|
||||||
res: { project: Project; imported: MediaAsset[] };
|
res: { project: Project; imported: MediaAsset[] };
|
||||||
};
|
};
|
||||||
|
[ipcChannels.project.importCampaignAudio]: {
|
||||||
|
req: Record<string, never>;
|
||||||
|
res: { canceled: boolean; project: Project; imported: MediaAsset[] };
|
||||||
|
};
|
||||||
|
[ipcChannels.project.updateCampaignAudios]: {
|
||||||
|
req: { audios: Project['campaignAudios'] };
|
||||||
|
res: { project: Project };
|
||||||
|
};
|
||||||
[ipcChannels.project.importScenePreview]: {
|
[ipcChannels.project.importScenePreview]: {
|
||||||
req: { sceneId: SceneId };
|
req: { sceneId: SceneId };
|
||||||
res: { project: Project };
|
res: { project: Project };
|
||||||
@@ -188,6 +240,10 @@ export type IpcInvokeMap = {
|
|||||||
req: Record<string, never>;
|
req: Record<string, never>;
|
||||||
res: { ok: true; isFullScreen: boolean };
|
res: { ok: true; isFullScreen: boolean };
|
||||||
};
|
};
|
||||||
|
[ipcChannels.windows.getMultiWindowState]: {
|
||||||
|
req: Record<string, never>;
|
||||||
|
res: { open: boolean };
|
||||||
|
};
|
||||||
[ipcChannels.effects.getState]: {
|
[ipcChannels.effects.getState]: {
|
||||||
req: Record<string, never>;
|
req: Record<string, never>;
|
||||||
res: { state: EffectsState };
|
res: { state: EffectsState };
|
||||||
@@ -227,7 +283,7 @@ export type SessionState = {
|
|||||||
currentSceneId: SceneId | null;
|
currentSceneId: SceneId | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type IpcEventMap = {
|
export type LegacyIpcEventMap = {
|
||||||
[ipcChannels.session.stateChanged]: { state: SessionState };
|
[ipcChannels.session.stateChanged]: { state: SessionState };
|
||||||
[ipcChannels.effects.stateChanged]: { state: EffectsState };
|
[ipcChannels.effects.stateChanged]: { state: EffectsState };
|
||||||
[ipcChannels.video.stateChanged]: { state: VideoPlaybackState };
|
[ipcChannels.video.stateChanged]: { state: VideoPlaybackState };
|
||||||
@@ -239,6 +295,7 @@ export type ScenePatch = {
|
|||||||
description?: string;
|
description?: string;
|
||||||
previewAssetId?: AssetId | null;
|
previewAssetId?: AssetId | null;
|
||||||
previewAssetType?: 'image' | 'video' | null;
|
previewAssetType?: 'image' | 'video' | null;
|
||||||
|
previewThumbAssetId?: AssetId | null;
|
||||||
previewVideoAutostart?: boolean;
|
previewVideoAutostart?: boolean;
|
||||||
previewRotationDeg?: 0 | 90 | 180 | 270;
|
previewRotationDeg?: 0 | 90 | 180 | 270;
|
||||||
settings?: Partial<Scene['settings']>;
|
settings?: Partial<Scene['settings']>;
|
||||||
|
|||||||
@@ -6,13 +6,16 @@ import { fileURLToPath } from 'node:url';
|
|||||||
|
|
||||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
|
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
|
||||||
|
|
||||||
void test('package.json: конфиг electron-builder (mac/win)', () => {
|
void test('package.json: конфиг electron-builder (mac/win/linux)', () => {
|
||||||
const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')) as {
|
const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')) as {
|
||||||
build: {
|
build: {
|
||||||
appId: string;
|
appId: string;
|
||||||
asar: boolean;
|
asar: boolean;
|
||||||
asarUnpack: string[];
|
asarUnpack: string[];
|
||||||
|
extraResources: { from: string; to: string }[];
|
||||||
mac: { target: unknown };
|
mac: { target: unknown };
|
||||||
|
linux: { target: unknown };
|
||||||
|
appImage?: { artifactName?: string };
|
||||||
files: string[];
|
files: string[];
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
@@ -21,6 +24,22 @@ void test('package.json: конфиг electron-builder (mac/win)', () => {
|
|||||||
assert.equal(pkg.build.asar, true, 'релизный артефакт: app.asar без «голого» дерева dist в .app/.exe');
|
assert.equal(pkg.build.asar, true, 'релизный артефакт: app.asar без «голого» дерева dist в .app/.exe');
|
||||||
assert.ok(Array.isArray(pkg.build.asarUnpack));
|
assert.ok(Array.isArray(pkg.build.asarUnpack));
|
||||||
assert.ok(pkg.build.asarUnpack.some((p) => p.includes('preload')));
|
assert.ok(pkg.build.asarUnpack.some((p) => p.includes('preload')));
|
||||||
|
assert.ok(Array.isArray(pkg.build.extraResources));
|
||||||
|
assert.ok(
|
||||||
|
pkg.build.extraResources.some(
|
||||||
|
(e: unknown) =>
|
||||||
|
typeof e === 'object' &&
|
||||||
|
e !== null &&
|
||||||
|
'to' in e &&
|
||||||
|
typeof (e as { to: unknown }).to === 'string' &&
|
||||||
|
(e as { to: string }).to.includes('branding'),
|
||||||
|
),
|
||||||
|
);
|
||||||
assert.ok(Array.isArray(pkg.build.mac.target));
|
assert.ok(Array.isArray(pkg.build.mac.target));
|
||||||
|
assert.ok(Array.isArray(pkg.build.linux.target));
|
||||||
|
const linuxTargets = pkg.build.linux.target as { target: string; arch: string[] }[];
|
||||||
|
assert.ok(linuxTargets.some((t) => t.target === 'AppImage'));
|
||||||
|
assert.ok(linuxTargets.some((t) => t.arch.includes('x64') && t.arch.includes('arm64')));
|
||||||
|
assert.ok(pkg.build.appImage?.artifactName?.includes('${arch}'));
|
||||||
assert.ok(pkg.build.files.includes('dist/**/*'));
|
assert.ok(pkg.build.files.includes('dist/**/*'));
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -84,6 +84,8 @@ export type Scene = {
|
|||||||
/** Превью ассет (изображение или видео). */
|
/** Превью ассет (изображение или видео). */
|
||||||
previewAssetId: AssetId | null;
|
previewAssetId: AssetId | null;
|
||||||
previewAssetType: 'image' | 'video' | null;
|
previewAssetType: 'image' | 'video' | null;
|
||||||
|
/** Уменьшенное изображение для графа/списков; оригинал — в `previewAssetId`. */
|
||||||
|
previewThumbAssetId: AssetId | null;
|
||||||
/** Для видео-превью: автозапуск (в редакторе/списках/на графе). */
|
/** Для видео-превью: автозапуск (в редакторе/списках/на графе). */
|
||||||
previewVideoAutostart: boolean;
|
previewVideoAutostart: boolean;
|
||||||
/** Поворот превью в градусах (0/90/180/270). */
|
/** Поворот превью в градусах (0/90/180/270). */
|
||||||
@@ -112,6 +114,8 @@ export type Project = {
|
|||||||
meta: ProjectMeta;
|
meta: ProjectMeta;
|
||||||
scenes: Record<SceneId, Scene>;
|
scenes: Record<SceneId, Scene>;
|
||||||
assets: Record<AssetId, MediaAsset>;
|
assets: Record<AssetId, MediaAsset>;
|
||||||
|
/** Аудио кампании: играет в пульте на протяжении всей презентации, если в сцене нет своей музыки. */
|
||||||
|
campaignAudios: SceneAudioRef[];
|
||||||
currentSceneId: SceneId | null;
|
currentSceneId: SceneId | null;
|
||||||
/** Текущая нода графа (важно, когда одна сцена имеет несколько нод). */
|
/** Текущая нода графа (важно, когда одна сцена имеет несколько нод). */
|
||||||
currentGraphNodeId: GraphNodeId | null;
|
currentGraphNodeId: GraphNodeId | null;
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import test from 'node:test';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '..');
|
||||||
|
|
||||||
|
void test('video playback: control preview does not dispatch target.set on every render', () => {
|
||||||
|
const src = fs.readFileSync(
|
||||||
|
path.join(root, 'app', 'renderer', 'control', 'ControlScenePreview.tsx'),
|
||||||
|
'utf8',
|
||||||
|
);
|
||||||
|
// Регресс: зависимость `[... , scene, ...]` заставляла эффект с `target.set` срабатывать постоянно,
|
||||||
|
// сбрасывая видео (доля секунды проигрывается и начинается сначала).
|
||||||
|
assert.doesNotMatch(src, /\]\s*,\s*\[\s*[^\]]*\bscene\b/);
|
||||||
|
});
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import test from 'node:test';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '..');
|
||||||
|
|
||||||
|
void test('video playback: renderer hooks/components do not tick React each frame', () => {
|
||||||
|
const hookSrc = fs.readFileSync(
|
||||||
|
path.join(root, 'app', 'renderer', 'shared', 'video', 'useVideoPlaybackState.ts'),
|
||||||
|
'utf8',
|
||||||
|
);
|
||||||
|
// Регресс: раньше был setInterval(250ms) для clientNowMs, который заставлял перерисовываться окна.
|
||||||
|
assert.doesNotMatch(hookSrc, /\bsetInterval\s*\(/);
|
||||||
|
|
||||||
|
const previewSrc = fs.readFileSync(
|
||||||
|
path.join(root, 'app', 'renderer', 'control', 'ControlScenePreview.tsx'),
|
||||||
|
'utf8',
|
||||||
|
);
|
||||||
|
// Регресс: раньше был RAF loop с setState на каждом кадре.
|
||||||
|
assert.doesNotMatch(previewSrc, /\brequestAnimationFrame\s*\(\s*loop\s*\)/);
|
||||||
|
assert.doesNotMatch(previewSrc, /\brequestAnimationFrame\s*\(\s*loop\b/);
|
||||||
|
});
|
||||||
@@ -0,0 +1,482 @@
|
|||||||
|
# Автообновление через Gitea (приватный код + публичный feed)
|
||||||
|
|
||||||
|
Исходники остаются в **закрытом** репозитории с игрой. Файлы обновлений (`latest.yml`, установщики) лежат в **отдельном публичном** репозитории — по HTTPS их скачивает `electron-updater`.
|
||||||
|
|
||||||
|
## Твой публичный репозиторий (уже есть)
|
||||||
|
|
||||||
|
- Клон: `https://git.mailib.ru/ifontosh/DndGamePlayerUpdates.git`
|
||||||
|
- Владелец/репо для секретов: **`ifontosh/DndGamePlayerUpdates`**
|
||||||
|
- Базовый URL feed (вшивается в сборку и должен совпадать с secret **`DND_UPDATE_FEED_URL`**):
|
||||||
|
|
||||||
|
**`https://git.mailib.ru/ifontosh/DndGamePlayerUpdates/raw/branch/updates/`**
|
||||||
|
|
||||||
|
Обрати внимание: слово **`branch`** в пути — это часть URL Gitea, не имя ветки. Имя ветки — в конце: **`updates`**.
|
||||||
|
|
||||||
|
В `package.json` уже указан этот же `build.publish.url` (для локального `npm run pack` и метаданных electron-builder).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Шаг 0 — репозиторий сейчас пустой (важно)
|
||||||
|
|
||||||
|
На странице репо написано, что **контента нет**. Пока нет **ни одного коммита**, CI не сможет сделать `git clone`.
|
||||||
|
|
||||||
|
Сделай так (любой способ):
|
||||||
|
|
||||||
|
1. На сайте открой `ifontosh/DndGamePlayerUpdates` → кнопка вроде **«Инициализировать репозиторий»** / **«Добавить файл»** → создай файл `README.md` с парой строк и закоммить **в ветку по умолчанию** (часто `main`).
|
||||||
|
2. Либо с компьютера:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone https://git.mailib.ru/ifontosh/DndGamePlayerUpdates.git
|
||||||
|
cd DndGamePlayerUpdates
|
||||||
|
echo "# DndGamePlayer updates feed" > README.md
|
||||||
|
git add README.md
|
||||||
|
git commit -m "init"
|
||||||
|
git push origin main
|
||||||
|
```
|
||||||
|
|
||||||
|
(Если ветка по умолчанию у тебя `master` — подставь её вместо `main`.)
|
||||||
|
|
||||||
|
После этого репозиторий **не пустой** — workflow сможет клонировать и создать ветку **`updates`**.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Шаг 1 — токен для записи в публичный репозиторий
|
||||||
|
|
||||||
|
Нужен **персональный токен** (PAT), с которым CI сможет **пушить** в `DndGamePlayerUpdates`.
|
||||||
|
|
||||||
|
В Gitea на русском обычно так (названия могут чуть отличаться в твоей теме):
|
||||||
|
|
||||||
|
1. Вверху справа **аватар** → **Настройки** (или «Параметры»).
|
||||||
|
2. Слева найди раздел вроде **«Приложения»** / **«Токены доступа»** / **«Токены»** (в англ. интерфейсе: **Settings → Applications → Generate New Token**).
|
||||||
|
3. Создай новый токен:
|
||||||
|
- имя: например `dnd-release-ci`;
|
||||||
|
- права: достаточно доступа к репозиторию с **записью** (для пуша в `DndGamePlayerUpdates`). Если есть галочки — включи что-то вроде **«Запись в репозиторий»** / **write:repository** / полный доступ к репо.
|
||||||
|
4. **Скопируй токен один раз** и сохрани в менеджере паролей — потом Gitea его не покажет.
|
||||||
|
|
||||||
|
Этот токен пойдёт в secret **`DND_UPDATES_PUSH_TOKEN`** (см. ниже). **Не вставляй токен в код и не коммить его.**
|
||||||
|
|
||||||
|
> На **git.mailib.ru** имена секретов **не могут начинаться с `GITEA_`** (зарезервировано). Поэтому в workflow используются `DND_UPDATES_*`, а не `GITEA_*`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Шаг 2 — секреты в приватном репозитории с кодом (`dnd_player`)
|
||||||
|
|
||||||
|
Открой **приватный** репозиторий, где лежит исходник игры (не `DndGamePlayerUpdates`).
|
||||||
|
|
||||||
|
Дальше (русский Gitea 1.26, ориентир по меню):
|
||||||
|
|
||||||
|
1. Вкладка **«Настройки»** репозитория (вверху рядом с «Код», «Задачи» — иногда шестерёнка **«Настройки»**).
|
||||||
|
2. Слева раздел **«Секреты»** / **«Действия»** → **«Секреты»** (в англ. UI: **Settings → Actions → Secrets**). Если видишь **«Переменные»** — секреты обычно рядом; нам нужны именно **секреты** (скрытые значения).
|
||||||
|
|
||||||
|
Добавь **четыре** секрета (имя **точно** как в таблице — workflow их читает):
|
||||||
|
|
||||||
|
| Имя секрета | Что вписать в значение |
|
||||||
|
| ------------------------ | -------------------------------------------------------------------------------------------------------- |
|
||||||
|
| `DND_UPDATE_FEED_URL` | `https://git.mailib.ru/ifontosh/DndGamePlayerUpdates/raw/branch/updates/` (обязательно **слэш в конце**) |
|
||||||
|
| `DND_UPDATES_SERVER` | `https://git.mailib.ru` (**без** слэша в конце) |
|
||||||
|
| `UPDATES_REPO` | `ifontosh/DndGamePlayerUpdates` |
|
||||||
|
| `DND_UPDATES_PUSH_TOKEN` | токен из шага 1 (одна длинная строка) |
|
||||||
|
|
||||||
|
Сохрани каждый секрет кнопкой вроде **«Сохранить»** / **«Добавить»**.
|
||||||
|
|
||||||
|
Если раньше создавал секреты `GITEA_SERVER` / `GITEA_TOKEN` — их workflow **не читает**; удали или оставь, но **обязательно** заведи новые имена из таблицы.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Раннер act_runner — без этого «Всего: 0» и сборки не будет
|
||||||
|
|
||||||
|
Gitea **не запускает** workflow на своём процессе: нужна **отдельная машина** (VPS, сервер или **WSL2 Ubuntu** на твоём ПК), на которой крутится **[act_runner](https://docs.gitea.com/usage/actions/act-runner)** и которая видит `git.mailib.ru` по сети.
|
||||||
|
|
||||||
|
Пока в **«Настройки» → «Действия» → «Раннеры»** написано **«Всего: 0»**, workflow **висит в ожидании** — нечему выполнять шаги.
|
||||||
|
|
||||||
|
### Важно: это не тот токен, что для пуша в `DndGamePlayerUpdates`
|
||||||
|
|
||||||
|
| Токен | Где взять | Зачем |
|
||||||
|
| --------------------------------------------------- | -------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
|
||||||
|
| **Регистрация раннера** (короткая случайная строка) | **Настройки репо** → **Действия** → **Раннеры** → **Создать новый раннер** | Только для команды **`act_runner register`** (один раз на каталог с раннером) |
|
||||||
|
| **`DND_UPDATES_PUSH_TOKEN`** (PAT) | **Аватар** → **Настройки пользователя** → токены доступа | Для CI: пуш в публичный репо обновлений (см. шаг 1 выше) |
|
||||||
|
|
||||||
|
Если Gitea показала **только длинную строку** — это почти наверняка **токен регистрации раннера**. URL инстанса ты знаешь сам: **`https://git.mailib.ru`** (без пути к репозиторию).
|
||||||
|
|
||||||
|
### Требования к машине под наш `release.yml`
|
||||||
|
|
||||||
|
В workflow для job **`ubuntu-22.04`** идут **`sudo apt-get`** (пакеты **`nsis`**, **`wine64`**) на **Linux**. Multiarch **i386** намеренно не включается — на Debian с репозиториями только под amd64 (nginx, sury и т.п.) установка **wine32** часто падает с «unmet dependencies». После установки **`wine64`** в CI создаётся скрипт **`/usr/local/bin/wine`** с **`exec` по полному пути** к **`wine64`** (в job у act_runner иногда пустой/урезанный `PATH`, тогда имя `wine64` без пути не находится). electron-builder проверяет именно команду **`wine`** в `PATH`. Поэтому:
|
||||||
|
|
||||||
|
- Нужен **Linux x86_64** (идеально **Ubuntu 22.04**), либо **WSL2** с Ubuntu 22.04 на Windows.
|
||||||
|
- Запускать раннер на «голом» Windows с меткой `ubuntu-22.04` **бессмысленно** — шаги с `apt` не выполнятся.
|
||||||
|
|
||||||
|
### Шаг A — получить токен регистрации в Gitea
|
||||||
|
|
||||||
|
1. Открой репозиторий с кодом (**DndGamePlayer** или как он у тебя называется).
|
||||||
|
2. **Настройки** → **Действия** → **Раннеры** → **Создать новый раннер**.
|
||||||
|
3. Выбери тип **репозитория** (repository runner), ОС **Linux**.
|
||||||
|
4. **Скопируй токен** (и при желании подсказку с URL инстанса, если она есть). Команду из мастера можно **не копировать**, если ниже удобнее готовая.
|
||||||
|
|
||||||
|
### Шаг B — скачать act_runner (бинарник)
|
||||||
|
|
||||||
|
Официальные сборки: **[релизы act_runner на gitea.com](https://gitea.com/gitea/act_runner/releases)**.
|
||||||
|
|
||||||
|
1. Открой страницу релизов и посмотри **последний стабильный** тег, например **`v1.0.2`**.
|
||||||
|
2. В списке файлов скачай **`gitea-runner-ВЕРСИЯ-linux-amd64`** — это один исполняемый файл **без** расширения `.zip` (не путай с `darwin` / `arm64`, если у тебя обычный ПК/сервер Intel/AMD).
|
||||||
|
|
||||||
|
**Прямая ссылка (подставь свою версию из релиза):**
|
||||||
|
|
||||||
|
`https://gitea.com/gitea/act_runner/releases/download/v1.0.2/gitea-runner-1.0.2-linux-amd64`
|
||||||
|
|
||||||
|
В URL после `download/` идёт тег с **`v`**, в имени файла версия **без `v`**.
|
||||||
|
|
||||||
|
**Скачать с Linux/WSL одной командой** (замени `1.0.2` на актуальную версию с сайта):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mkdir -p ~/gitea-act-runner && cd ~/gitea-act-runner
|
||||||
|
VERSION="1.0.2"
|
||||||
|
curl -fL -o act_runner "https://gitea.com/gitea/act_runner/releases/download/v${VERSION}/gitea-runner-${VERSION}-linux-amd64"
|
||||||
|
chmod +x act_runner
|
||||||
|
./act_runner --version
|
||||||
|
```
|
||||||
|
|
||||||
|
Если `curl` ругается на сертификат — обнови CA или скачай тот же файл через браузер и положи в папку, затем `chmod +x`.
|
||||||
|
|
||||||
|
### Шаг C — регистрация (подставь свой токен)
|
||||||
|
|
||||||
|
В каталоге, где лежит `act_runner`, выполни **одну** команду (токен — тот, что выдала Gitea при создании раннера):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd ~/gitea-act-runner
|
||||||
|
|
||||||
|
./act_runner register --no-interactive \
|
||||||
|
--instance "https://git.mailib.ru" \
|
||||||
|
--token "ВСТАВЬ_СЮДА_ТОКЕН_ИЗ_МАСТЕРА_GITEA" \
|
||||||
|
--name "dnd-release-runner" \
|
||||||
|
--labels "ubuntu-22.04:host"
|
||||||
|
```
|
||||||
|
|
||||||
|
Пояснения:
|
||||||
|
|
||||||
|
- **`--instance`** — корень твоего Gitea (**без** `/ifontosh/...`).
|
||||||
|
- **`--labels "ubuntu-22.04:host"`** — job в **`.gitea/workflows/release.yml`** имеет `runs-on: ubuntu-22.04`, а **`:host`** означает выполнение **на самой машине**, с настоящим `apt` и Wine (см. [документацию по меткам](https://docs.gitea.com/usage/actions/act-runner#labels)). Если при регистрации оставить **дефолтные** метки с **`docker://`**, шаги тоже могут сработать, но образ другой; для предсказуемости лучше **`ubuntu-22.04:host`** на чистой Ubuntu 22.04.
|
||||||
|
- После успешной регистрации в этой папке появится файл **`.runner`** — его не удаляй и не коммить.
|
||||||
|
|
||||||
|
Если Gitea пишет ошибку регистрации — часто неверный **токен** (устарел после «сброса» в UI) или выбран не тот уровень (инстанс/организация/репозиторий). Создай раннера заново и возьми **новый** токен.
|
||||||
|
|
||||||
|
### Шаг D — запуск вручную (для проверки)
|
||||||
|
|
||||||
|
В той же папке:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./act_runner daemon
|
||||||
|
```
|
||||||
|
|
||||||
|
Окно терминала должно остаться **открытым**. Остановка — `Ctrl+C`. Когда убедишься, что в Gitea раннер **online**, лучше перейти на **systemd** (шаг ниже).
|
||||||
|
|
||||||
|
### Шаг D1 — systemd: автозапуск после перезагрузки (подробно)
|
||||||
|
|
||||||
|
Идея: **systemd** сам поднимает `act_runner daemon` при загрузке системы и перезапускает процесс при падении. Рабочая директория должна быть **та же**, где лежат **`act_runner`** и зарегистрированный файл **`.runner`** (обычно `~/gitea-act-runner`).
|
||||||
|
|
||||||
|
#### 0) Подготовка
|
||||||
|
|
||||||
|
1. Регистрация (**шаг C**) уже выполнена, в каталоге есть **`.runner`**.
|
||||||
|
2. Узнай **точный путь** к каталогу (systemd не понимает `~`):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd ~/gitea-act-runner && pwd
|
||||||
|
```
|
||||||
|
|
||||||
|
Запомни вывод, например **`/home/ivan/gitea-act-runner`**. Имя пользователя Linux:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
whoami
|
||||||
|
```
|
||||||
|
|
||||||
|
Дальше в примерах: **`/home/ivan/gitea-act-runner`** и пользователь **`ivan`** — замени на свои.
|
||||||
|
|
||||||
|
#### 1) Останови ручной запуск
|
||||||
|
|
||||||
|
Если где-то в терминале уже крутится `./act_runner daemon` — заверши **Ctrl+C**, иначе два процесса будут мешать друг другу.
|
||||||
|
|
||||||
|
#### 2) Создай unit-файл службы
|
||||||
|
|
||||||
|
На **VPS / обычной Ubuntu** с правами root:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo nano /etc/systemd/system/gitea-act-runner.service
|
||||||
|
```
|
||||||
|
|
||||||
|
Вставь текст **целиком** (подставь свои `User`, `Group`, `WorkingDirectory`, `ExecStart`):
|
||||||
|
|
||||||
|
```ini
|
||||||
|
[Unit]
|
||||||
|
Description=Gitea Actions act_runner
|
||||||
|
Documentation=https://docs.gitea.com/usage/actions/act-runner
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
User=ivan
|
||||||
|
Group=ivan
|
||||||
|
WorkingDirectory=/home/ivan/gitea-act-runner
|
||||||
|
ExecStart=/home/ivan/gitea-act-runner/act_runner daemon
|
||||||
|
Restart=always
|
||||||
|
RestartSec=10
|
||||||
|
|
||||||
|
# Логи в journald (см. ниже как читать)
|
||||||
|
StandardOutput=journal
|
||||||
|
StandardError=journal
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
```
|
||||||
|
|
||||||
|
Сохрани файл: в **nano** — **Ctrl+O**, Enter, **Ctrl+X**.
|
||||||
|
|
||||||
|
Пояснения:
|
||||||
|
|
||||||
|
- **`User` / `Group`** — под этим пользователем ты делал `register` и владеешь папкой (проверка: `ls -la ~/gitea-act-runner` — владелец должен совпадать).
|
||||||
|
- **`WorkingDirectory`** — каталог с **`.runner`**; без него раннер может не найти регистрацию.
|
||||||
|
- **`ExecStart`** — полный путь к бинарнику **`act_runner`** (тот, что скачал и сделал `chmod +x`).
|
||||||
|
- Блок **`After=network-online.target`** — старт после сети (удобно для `git`/`npm` в CI). Если вдруг зависнет старт из‑за сетевого таргета, можно временно заменить на **`After=network.target`**.
|
||||||
|
|
||||||
|
Официальный пример с отдельным пользователем `act_runner` и `config.yaml`: [Start the runner with Systemd](https://docs.gitea.com/usage/actions/act-runner#start-the-runner-with-systemd) — у нас проще: один пользователь и без отдельного `config.yaml`, пока дефолты устраивают.
|
||||||
|
|
||||||
|
#### 3) Включи и запусти службу
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo systemctl daemon-reload
|
||||||
|
sudo systemctl enable gitea-act-runner.service
|
||||||
|
sudo systemctl start gitea-act-runner.service
|
||||||
|
sudo systemctl status gitea-act-runner.service
|
||||||
|
```
|
||||||
|
|
||||||
|
В **`status`** должно быть **`active (running)`** зелёным. Если **`failed`** — смотри лог (шаг 5).
|
||||||
|
|
||||||
|
Полезные команды:
|
||||||
|
|
||||||
|
| Действие | Команда |
|
||||||
|
| --------------------- | ------------------------------------------------------------- |
|
||||||
|
| Остановить | `sudo systemctl stop gitea-act-runner` |
|
||||||
|
| Запустить снова | `sudo systemctl start gitea-act-runner` |
|
||||||
|
| Перезапуск | `sudo systemctl restart gitea-act-runner` |
|
||||||
|
| Выключить автозапуск | `sudo systemctl disable gitea-act-runner` |
|
||||||
|
| Проверка после ребута | перезагрузи машину, затем `systemctl status gitea-act-runner` |
|
||||||
|
|
||||||
|
#### 4) Проверка в Gitea
|
||||||
|
|
||||||
|
Как в **шаге E**: раннер снова **online** (иногда 10–30 секунд после `start`).
|
||||||
|
|
||||||
|
#### 5) Логи, если что-то не так
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo journalctl -u gitea-act-runner -e --no-pager
|
||||||
|
```
|
||||||
|
|
||||||
|
В реальном времени:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo journalctl -u gitea-act-runner -f
|
||||||
|
```
|
||||||
|
|
||||||
|
Типичные ошибки: неверный **`User`** (нет прав на каталог), **`WorkingDirectory`** не тот (нет **`.runner`**), бинарник не исполняемый (`chmod +x`), или старый процесс `act_runner` ещё запущен вручную.
|
||||||
|
|
||||||
|
#### WSL2 (Ubuntu в Windows)
|
||||||
|
|
||||||
|
Если раннер стоит **внутри WSL2**:
|
||||||
|
|
||||||
|
1. На современных WSL **systemd уже может быть включён**. Проверка: `systemctl status` — без ошибки «running in chroot».
|
||||||
|
2. Если `systemctl` недоступен: в файле **`/etc/wsl.conf`** внутри дистрибутива добавь блок **`[boot]`** с **`systemd=true`**, затем из **PowerShell** Windows выполни **`wsl --shutdown`**, снова зайди в Ubuntu и повтори шаги 2–3. Подробнее: [документация Microsoft про systemd в WSL](https://learn.microsoft.com/en-us/windows/wsl/systemd).
|
||||||
|
|
||||||
|
После **`wsl --shutdown`** раннер на WSL не работает, пока ты снова не откроешь WSL (это нормально для «домашнего» CI).
|
||||||
|
|
||||||
|
### Шаг E — проверка в веб-интерфейсе
|
||||||
|
|
||||||
|
Обнови **Настройки → Действия → Раннеры**: должен быть **1** раннер, статус **online**. У него в метках должно быть что-то вроде **`ubuntu-22.04`** (в связке с **host**).
|
||||||
|
|
||||||
|
### Если у тебя только Windows
|
||||||
|
|
||||||
|
Установи **WSL2** и дистрибутив **Ubuntu 22.04**, открой терминал Ubuntu и выполни шаги B–D **там** (это уже Linux). Файловую систему Windows из WSL видно как `/mnt/d/...`, но проще держать каталог раннера в домашнем каталоге Linux (`~/gitea-act-runner`).
|
||||||
|
|
||||||
|
Официальная документация: [Gitea — Act Runner](https://docs.gitea.com/usage/actions/act-runner).
|
||||||
|
|
||||||
|
Если раннер заводит **админ инстанса** — логика та же: раннер должен быть **online** и иметь метку, подходящую под **`runs-on`** в `release.yml` (сейчас **`ubuntu-22.04`**; при **`ubuntu-22.04:host`** в Gitea это сопоставляется с `runs-on: ubuntu-22.04`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Шаг 3 — включить Actions (если ещё не включены)
|
||||||
|
|
||||||
|
1. В том же **приватном** репозитории: **«Настройки»**.
|
||||||
|
2. Раздел **«Действия»** / **«Actions»** — включи использование Actions для этого репозитория, если Gitea это спрашивает.
|
||||||
|
3. Убедись, что в корне репозитория есть файл **`.gitea/workflows/release.yml`** (он уже в проекте `dnd_player`).
|
||||||
|
|
||||||
|
Бегунки Gitea должны иметь доступ в интернет (для `npm ci`, `actions/checkout` и т.д.) — это настраивает админ сервера.
|
||||||
|
|
||||||
|
### Метки `runs-on` (если раннер уже есть, но job не берётся)
|
||||||
|
|
||||||
|
- В списке раннеров посмотри **метки** у online-раннера.
|
||||||
|
- В **`.gitea/workflows/release.yml`** в `runs-on:` должна совпадать **именно метка `ubuntu-22.04`** (Gitea сопоставляет её и с **`ubuntu-22.04:host`**, и с **`ubuntu-22.04:docker://...`** — см. [Labels](https://docs.gitea.com/usage/actions/act-runner#labels) в документации act_runner).
|
||||||
|
- Если при регистрации указал только **`self-hosted`** — добавь **`ubuntu-22.04:host`** (или поменяй `runs-on` в workflow на твои метки и закоммить).
|
||||||
|
|
||||||
|
Сборка **Windows (NSIS)** и **Linux (AppImage x64 + arm64)** в CI идёт **на одном** `ubuntu-22.04`: NSIS + `wine64` для Win, `qemu-user-static` для кросс-сборки arm64 AppImage на amd64 (см. `release.yml`). **macOS** в этом job не собирается (ручная выкладка или отдельный раннер — см. `docs/MANUAL_MAC_UPDATE_UPLOAD.md`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Linux: AppImage и автообновление
|
||||||
|
|
||||||
|
- В ветке **`updates`** рядом с Windows лежат **`latest-linux.yml`** и файлы **`*.AppImage`** (x64 и arm64). Скрипт **`scripts/sync-update-feed.mjs`** делает **merge-копирование**: файлы других ОС в репозитории **не удаляются**, обновляются только имена, пришедшие из текущего CI-прогона.
|
||||||
|
- **Базовый дистрибутив для бинарников:** сборка на **Ubuntu 22.04 (glibc 2.35)** — совместимость с «максимумом» настольных дистрибутивов с glibc не старее целевого; **Alpine/musl** без отдельной сборки не гарантируется.
|
||||||
|
- **Запуск AppImage:** на части систем нужен **FUSE** (например `libfuse2` для старых форматов / документация дистрибутива). Подпись пакетов в первом варианте **не** используется (как договорённость по проекту).
|
||||||
|
- Правила **electron-updater** в приложении те же: упакованная сборка и **активная лицензия** (`installAutoUpdater.ts`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Шаг 4 — выпуск версии
|
||||||
|
|
||||||
|
1. В `package.json` версия должна совпасть с тегом (workflow при пуше тега делает `npm version` из имени тега — удобно).
|
||||||
|
2. Закоммить все изменения в **приватный** репо, затем:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git tag v1.0.1
|
||||||
|
git push origin main
|
||||||
|
git push origin v1.0.1
|
||||||
|
```
|
||||||
|
|
||||||
|
(ветка может быть не `main` — подставь свою.)
|
||||||
|
|
||||||
|
3. Открой в Gitea **«Действия»** у приватного репо — должен появиться запуск **Release**. Дождись успеха job **`release`** (после появления раннера, см. раздел выше).
|
||||||
|
|
||||||
|
4. После успеха открой **публичный** `DndGamePlayerUpdates` → ветка **`updates`** — в корне должны появиться `latest.yml`, установщики и т.д.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Контрольный чеклист
|
||||||
|
|
||||||
|
1. **`package.json` → `build.publish.url`** =
|
||||||
|
`https://git.mailib.ru/ifontosh/DndGamePlayerUpdates/raw/branch/updates/`
|
||||||
|
Совпадает с **`DND_UPDATE_FEED_URL`** (со слэшем в конце).
|
||||||
|
2. В **DndGamePlayerUpdates** есть хотя бы один коммит (не пустой репо).
|
||||||
|
3. В приватном репо заданы **все четыре** секрета из таблицы шага 2 (имена **не** начинаются с `GITEA_`).
|
||||||
|
4. В репо с кодом есть **`.gitea/workflows/release.yml`**.
|
||||||
|
5. Релиз: пуш тега `v*` → в Actions job **`release`**: сборка **Windows** + **Linux AppImage** и push feed; в публичном репо ветка **`updates`** содержит `latest.yml`, `latest-linux.yml`, установщики Windows и **`.AppImage`** для Linux (нужен online-раннер `ubuntu-22.04`, см. раздел про act_runner). Скрипт sync **не затирает** артефакты других платформ при обновлении.
|
||||||
|
6. В приложении: обновления только **`app.isPackaged`** и при **активной лицензии** (см. `app/main/update/installAutoUpdater.ts`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Если `git push` в `updates` падает: `remote end hung up` / таймаут
|
||||||
|
|
||||||
|
Один коммит с **Windows + два AppImage** может быть **сотни МБ** — HTTPS-push иногда рвётся из‑за лимита буфера Git или таймаута **nginx / reverse proxy** перед Gitea.
|
||||||
|
|
||||||
|
**В репозитории с кодом** скрипт `scripts/sync-update-feed.mjs` уже выставляет в клоне feed-репо:
|
||||||
|
|
||||||
|
- `http.postBuffer` **2 GiB**;
|
||||||
|
- отключение «медленной передачи» (`http.lowSpeedLimit` / `http.lowSpeedTime`);
|
||||||
|
- до **3** повторов `git push` с паузой 20 с (переменная **`DND_GIT_PUSH_RETRIES`**, максимум 5).
|
||||||
|
|
||||||
|
Если ошибка сохраняется — на **сервере** (nginx и т.п.) проверьте, например:
|
||||||
|
|
||||||
|
- `client_max_body_size` — не меньше размера push (или `0` для безлимита, если политика безопасности позволяет);
|
||||||
|
- `proxy_read_timeout` / `proxy_send_timeout` — **несколько минут** и больше для больших загрузок;
|
||||||
|
- лимиты самого **Gitea** (`[repository.upload]`, `APP_MAX_FILE_SIZE` в зависимости от версии) — в документации вашей сборки Gitea.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Линейная история в `UPDATES_REPO` (например DndGamePlayerUpdates)
|
||||||
|
|
||||||
|
Переписывается **только** публичный репозиторий из секрета **`UPDATES_REPO`**, ветка **`updates`**. Репозиторий с исходниками игры (**DndGamePlayer**) и его теги **не меняются**.
|
||||||
|
|
||||||
|
В workflow задано **`DND_UPDATES_SQUASH_HISTORY=1`**: после merge и подкладки артефактов скрипт делает **`git checkout --orphan`** и собирает историю **только текущего релиза**. Чтобы не отправлять один огромный pack (~700+ MiB) и не ловить `curl 55 Broken pipe`, загрузка идёт через временную ветку **`updates-upload-*`**: сначала small files, затем каждый большой файл отдельным push (порог **`DND_FEED_LARGE_FILE_BYTES`**, по умолчанию 64 MiB). Ветка **`updates`** передвигается на готовый финальный коммит только в конце через **`--force-with-lease`** (если ветка уже была) или обычный первый push. Пользователи не видят «полурелиз», потому что `updates` меняется только после полной загрузки.
|
||||||
|
|
||||||
|
На **сервере Gitea** старые объекты коммитов остаются «висячими», пока не отработает **сборка мусора** репозитория (настройки сервера / ручной `git gc` в bare-репо). Для пользователей приложения важны только URL **`latest*.yml`** и установщиков — они не меняются по смыслу.
|
||||||
|
|
||||||
|
Не запускайте **два релиза**, которые одновременно пушат feed, — возможна гонка и отказ **`--force-with-lease`**.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Если push отклонён: `(fetch first)` / `rejected`
|
||||||
|
|
||||||
|
Пока job собирает артефакты, в **`updates`** мог успеть попасть **другой** коммит (второй релиз, ручная выкладка). Скрипт `sync-update-feed.mjs` перед push (в режиме **без** squash) делает **`git fetch` + `git merge origin/updates`** (и после клона — то же в начале), плюс shallow **глубина** (`DND_UPDATES_CLONE_DEPTH`: по умолчанию **40**, при **`DND_UPDATES_SQUASH_HISTORY=1`** в скрипте по умолчанию **8**). В режиме **squash** перед финальным push merge **не** выполняется — уже смерженное дерево отправляется через временную ветку и затем публикуется force-with-lease. Не запускайте **два релиза одного и того же репо одновременно** по двум тегам — возможны конфликты merge.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ENOSPC / «no space left on device» при sync
|
||||||
|
|
||||||
|
Частая причина: **дублирование** артефактов (`release/` → `_linux`/`_win` → временный клон в **`/tmp`**) на раннере с маленьким root. Сейчас CI **не копирует** в `_win`/`_linux`: `ARTIFACT_WIN` и `ARTIFACT_LINUX` указывают на **`release/`**, а временный клон feed создаётся под **`DND_FEED_TMP_ROOT`** (в workflow — `${{ github.workspace }}/.dnd-feed-tmp`). Скрипт по возможности делает **`rename`** файлов в клон (без второй полной копии на том же диске).
|
||||||
|
|
||||||
|
Если ошибка остаётся — на машине раннера нужно **освободить место** или увеличить диск / вынести workspace на больший том.
|
||||||
|
|
||||||
|
Перед `git clone` скрипт проверяет **свободное место на томе**, где лежит `DND_FEED_TMP_ROOT` (оценка: артефакты × 2.5 + ~1 GiB запас, минимум ~2 GiB). Если проверка мешает (редкий ложный срабатывание), можно задать **`DND_FEED_SKIP_DISK_CHECK=1`** (лучше всё же поправить диск).
|
||||||
|
|
||||||
|
Несколько **неудачных** `git fetch` подряд (обрыв TLS) могли раньше забивать диск частично распакованными pack-файлами; между попытками вызывается **`git gc --prune=now`**.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Сбой fetch: `GnuTLS recv error` / `early EOF`
|
||||||
|
|
||||||
|
Сеть или TLS к серверу Gitea. Скрипт делает **несколько повторов** `git fetch` (`DND_GIT_FETCH_RETRIES`, по умолчанию **6**), между попытками — **`git gc --prune=now`**, для clone/fetch задано **`http.version=HTTP/1.1`** (иногда стабильнее за прокси). Если ветки **`updates` на сервере ещё нет**, merge **намеренно** пропускается (первый push feed); при **любой другой** ошибке fetch job **завершится ошибкой** — не будет «тихого» продолжения с последующим `ENOSPC` на `git add`.
|
||||||
|
|
||||||
|
При стабильных обрывах проверьте прокси/MTU/антивирус на раннере и лимиты прокси к Gitea.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Поведение приложения
|
||||||
|
|
||||||
|
- Проверка только в **собранной** установке (`app.isPackaged`).
|
||||||
|
- Только если **лицензия активна**.
|
||||||
|
- Первый запрос примерно через **12 с** после старта; при смене лицензии — снова (не чаще **30 с**).
|
||||||
|
- Для отладки можно задать переменную окружения **`DND_UPDATE_FEED_URL`** при запуске приложения (Windows / Linux / macOS) — переопределит feed.
|
||||||
|
|
||||||
|
Подпись кода в CI отключена: `CSC_IDENTITY_AUTO_DISCOVERY=false` (в т.ч. Linux AppImage без репозитория подписи).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Локальная отладка feed
|
||||||
|
|
||||||
|
Запуск установленного приложения с другим URL (без пересборки): задать **`DND_UPDATE_FEED_URL`** в ярлыке или системных переменных окружения.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Как сделать так, чтобы ассистент в Cursor мог «выпустить релиз»
|
||||||
|
|
||||||
|
У ассистента **нет своего аккаунта** на `git.mailib.ru`. Релиз = **появление тега `v*`** на нужном коммите в **приватном** репозитории с кодом → Gitea Actions собирает и пушит feed. Ниже два рабочих варианта.
|
||||||
|
|
||||||
|
### Вариант A — Gitea MCP (удобно из чата)
|
||||||
|
|
||||||
|
У тебя уже подключён MCP **user-gitea-mailib** с инструментом **`create_tag`**: по API создаётся тег на сервере (аналог `git tag` + `git push` тега).
|
||||||
|
|
||||||
|
**Что сделать один раз:**
|
||||||
|
|
||||||
|
1. В Cursor MCP для Gitea должен быть **включён и залогинен** под учёткой, у которой есть право **создавать теги** в приватном репо с `dnd_player`.
|
||||||
|
2. Знать **`owner`** и **`repo`** этого репозитория (как в URL: `https://git.mailib.ru/OWNER/REPO`).
|
||||||
|
|
||||||
|
**Как просить в чате:**
|
||||||
|
«Создай тег `v1.0.2` в репозитории `OWNER/REPO` с целевой веткой `main`» (или укажи SHA коммита). Перед этим **весь код релиза уже должен быть запушен** в эту ветку — тег вешается на последний коммит (или на явный `target`).
|
||||||
|
|
||||||
|
После создания тега зайди в **Действия** репозитория и проверь workflow **Release**.
|
||||||
|
|
||||||
|
_(Отдельно: `create_release` в MCP создаёт **запись релиза** на Gitea; сборку у тебя запускает именно **тег** и `release.yml`.)_
|
||||||
|
|
||||||
|
### Вариант B — команды `git` в терминале Cursor
|
||||||
|
|
||||||
|
Ассистент может выполнить у тебя локально:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git fetch origin
|
||||||
|
git tag v1.0.2 origin/main # или другая ветка / коммит
|
||||||
|
git push origin v1.0.2
|
||||||
|
```
|
||||||
|
|
||||||
|
**Что сделать один раз:**
|
||||||
|
|
||||||
|
1. Чтобы `git push` **не спрашивал пароль** каждый раз: настроить **учётные данные** (Windows: диспетчер учётных данных / `git credential-manager`; либо **SSH-ключ** и remote `git@git.mailib.ru:...`).
|
||||||
|
2. Убедиться, что из того же окружения, где работает Cursor, `git push` в приватный репо уже проходил успешно.
|
||||||
|
|
||||||
|
Тогда в чате можно написать: «Поставь тег `v1.0.2` на `origin/main` и запушь тег» — ассистент выполнит команды в `dnd_player`.
|
||||||
|
|
||||||
|
### Ограничения
|
||||||
|
|
||||||
|
- Ассистент **не видит** твои пароли и не обходит Gitea: всё упирается в **MCP-токен** или **твои локальные git credentials**.
|
||||||
|
- Если MCP отключён и git без настроенного доступа — релиз тегом придётся пушить **тебе** вручную (как в шаге 4 выше).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Про коммит и пуш кода (не тег)
|
||||||
|
|
||||||
|
Закоммитить и запушить **изменения в файлах** ассистент может через те же механизмы: либо ты делаешь `git push` после правок, либо настроенный **git** / отдельный скрипт. Без доступа к remote ассистент только правит файлы в рабочей копии.
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
# Ручная выкладка macOS-обновлений в публичный feed
|
||||||
|
|
||||||
|
Инструкция для случая, когда **сборка делается на вашем Mac вручную**, а файлы для `electron-updater` нужно **вручную** положить в публичный репозиторий обновлений.
|
||||||
|
|
||||||
|
Общая схема проекта: приватный репозиторий с кодом, публичный **`DndGamePlayerUpdates`**, ветка **`updates`**, URL feed как в `package.json`:
|
||||||
|
|
||||||
|
`https://git.mailib.ru/ifontosh/DndGamePlayerUpdates/raw/branch/updates/`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Что собрать на Mac
|
||||||
|
|
||||||
|
В каталоге проекта `dnd_player`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd /путь/к/dnd_player
|
||||||
|
npm ci
|
||||||
|
npm run build
|
||||||
|
```
|
||||||
|
|
||||||
|
Сборка установщиков только под macOS (без публикации в сеть, только файлы в `release/`):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx electron-builder --mac --publish never \
|
||||||
|
--config.publish.provider=generic \
|
||||||
|
--config.publish.url="https://git.mailib.ru/ifontosh/DndGamePlayerUpdates/raw/branch/updates/"
|
||||||
|
```
|
||||||
|
|
||||||
|
**Важно:** значение `--config.publish.url=...` должно совпадать с `package.json` → `build.publish.url` (**со слэшем в конце**). Так внутри приложения и в `latest-mac.yml` будет корректный базовый URL для скачивания.
|
||||||
|
|
||||||
|
После сборки откройте папку **`release/`** в корне проекта. Там должны быть, среди прочего:
|
||||||
|
|
||||||
|
- **`latest-mac.yml`** — обязателен для `electron-updater` на Mac;
|
||||||
|
- **`.dmg`** и/или **`.zip`** — то, на что ссылается `latest-mac.yml`;
|
||||||
|
- при необходимости **`.blockmap`** (если electron-builder их создал) — заливайте с теми же именами, что указаны в `latest-mac.yml`.
|
||||||
|
|
||||||
|
Имена файлов зависят от версии и архитектур (в конфиге dmg и zip для **x64** и **arm64**). На Apple Silicon без дополнительных шагов часто получается только **arm64**; для отдельного Intel-сборщика нужна своя машина или параметры arch — ориентируйтесь на фактический список файлов в `release/`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Куда заливать
|
||||||
|
|
||||||
|
Файлы должны оказаться в **публичном** репозитории:
|
||||||
|
|
||||||
|
| Параметр | Значение |
|
||||||
|
| ------------ | ------------------------------------------------------------------------- |
|
||||||
|
| Репозиторий | `ifontosh/DndGamePlayerUpdates` (подставьте свой owner/repo, если другой) |
|
||||||
|
| Ветка | `updates` |
|
||||||
|
| Расположение | **корень ветки** (не подпапка) |
|
||||||
|
|
||||||
|
Проверка: в браузере должен открываться, например:
|
||||||
|
|
||||||
|
`https://git.mailib.ru/ifontosh/DndGamePlayerUpdates/raw/branch/updates/latest-mac.yml`
|
||||||
|
|
||||||
|
Файлы Windows (`latest.yml`, `.exe`, …), которые кладёт CI, должны **остаться** в том же корне. Вы **добавляете или обновляете** только macOS-артефакты и **`latest-mac.yml`**, не удаляя артефакты Windows (если не делаете осознанную зачистку старых версий).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Способ A — через `git` (удобно для больших dmg)
|
||||||
|
|
||||||
|
### 3.1. Клон и ветка `updates`
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd ~/где-удобно
|
||||||
|
git clone https://git.mailib.ru/ifontosh/DndGamePlayerUpdates.git
|
||||||
|
cd DndGamePlayerUpdates
|
||||||
|
git fetch origin
|
||||||
|
git checkout updates
|
||||||
|
```
|
||||||
|
|
||||||
|
Если ветки `updates` ещё нет:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git checkout main
|
||||||
|
git pull
|
||||||
|
git checkout -b updates
|
||||||
|
git push -u origin updates
|
||||||
|
```
|
||||||
|
|
||||||
|
Дальше для каждой выкладки работайте в ветке **`updates`**.
|
||||||
|
|
||||||
|
### 3.2. Актуализировать локальную копию
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git checkout updates
|
||||||
|
git pull origin updates
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.3. Скопировать файлы из `release/` в корень клона
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cp /путь/к/dnd_player/release/latest-mac.yml .
|
||||||
|
cp /путь/к/dnd_player/release/*.dmg .
|
||||||
|
cp /путь/к/dnd_player/release/*.zip .
|
||||||
|
# blockmap, если есть:
|
||||||
|
cp /путь/к/dnd_player/release/*.blockmap . 2>/dev/null || true
|
||||||
|
```
|
||||||
|
|
||||||
|
Проверка, что Windows-файлы на месте:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ls -la
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.4. Коммит и push
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add latest-mac.yml *.dmg *.zip
|
||||||
|
git add *.blockmap 2>/dev/null || true
|
||||||
|
git status
|
||||||
|
git commit -m "mac: DNDGamePlayer vX.Y.Z (ручная выкладка)"
|
||||||
|
git push origin updates
|
||||||
|
```
|
||||||
|
|
||||||
|
Для HTTPS обычно используют **персональный токен (PAT)** Gitea вместо пароля, либо настроенный **SSH** (`git@git.mailib.ru:ifontosh/DndGamePlayerUpdates.git`).
|
||||||
|
|
||||||
|
### 3.5. Проверка
|
||||||
|
|
||||||
|
- Откройте `latest-mac.yml` по raw-URL (см. выше).
|
||||||
|
- Откройте в браузере прямую ссылку на один из `.dmg` из этого YAML — не должно быть 404.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Способ B — через веб-интерфейс Gitea
|
||||||
|
|
||||||
|
Подходит для редких правок; для больших **dmg** удобнее git.
|
||||||
|
|
||||||
|
1. Репозиторий `DndGamePlayerUpdates` → ветка **`updates`**.
|
||||||
|
2. Загрузить или изменить **`latest-mac.yml`** и бинарники (**имена как в `release/`**).
|
||||||
|
3. Не удалять при этом файлы Windows в корне, если они нужны для PC-обновлений.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Версии и Windows
|
||||||
|
|
||||||
|
- В **`latest-mac.yml`** и в именах файлов должна быть та **версия приложения**, которую вы отдаёте пользователям Mac (как в `package.json` на момент сборки).
|
||||||
|
- **`latest.yml`** (Windows) и **`latest-mac.yml`** (Mac) — разные файлы; версии на платформах могут совпадать или нет. Каждая ОС читает свой YAML.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Подпись кода (кратко)
|
||||||
|
|
||||||
|
Без **Developer ID** и при необходимости **нотаризации** macOS может ограничивать запуск после скачивания. На процедуру «залить файлы в репо» это не влияет, но влияет на UX после автообновления. Для продакшена имеет смысл позже настроить `CSC_LINK`, `CSC_KEY_PASSWORD` и нотаризацию по [документации electron-builder](https://www.electron.build/).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Чеклист
|
||||||
|
|
||||||
|
1. Локально собрали Mac с `--publish never` и верным `publish.url`.
|
||||||
|
2. В `release/` есть **`latest-mac.yml`** и все объекты, на которые он ссылается.
|
||||||
|
3. В ветке **`updates`** в корне репозитория обновили/добавили эти файлы, не снеся Windows-артефакты без необходимости.
|
||||||
|
4. Проверили raw-URL **`latest-mac.yml`** и ссылку на dmg.
|
||||||
|
5. В **упакованном** приложении с **активной лицензией** сработает существующий `electron-updater` (задержка первой проверки и cooldown — см. `app/main/update/installAutoUpdater.ts`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Связанные документы
|
||||||
|
|
||||||
|
- Общая схема Gitea, секреты, раннер: [GITEA_AUTO_UPDATE.md](./GITEA_AUTO_UPDATE.md).
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
## План оптимизации редактора (агент)
|
||||||
|
|
||||||
|
Цель: убрать лаги визуального редактора на проектах 20+ сцен (пан/зум графа, drag, создание связей) и снизить влияние тяжёлых ассетов (изображения/видео) на редактор.
|
||||||
|
|
||||||
|
### Этап 0 — Замер и воспроизведение
|
||||||
|
|
||||||
|
- **Сценарии**: пан/зум графа, drag узлов, создание/удаление связей, работа со списком сцен, редактирование свойств сцены.
|
||||||
|
- **Сбор данных**: DevTools Performance (CPU/Rendering), наблюдение нагрузки (GPU/Video Decode), фиксация “где именно тормозит”.
|
||||||
|
|
||||||
|
**Результат**: подтверждены основные “горячие места” (граф/рендер/медиа/IPC).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Этап 1 — Быстрый выигрыш без изменения формата проекта (минимально и безопасно)
|
||||||
|
|
||||||
|
#### 1.1 Lazy/async для изображений в карточках
|
||||||
|
|
||||||
|
- Для `<img>` в карточках графа и списка сцен применить:
|
||||||
|
- `loading="lazy"`
|
||||||
|
- `decoding="async"`
|
||||||
|
- Убедиться, что контейнеры превью не провоцируют лишние перерасчёты размеров/перерисовки.
|
||||||
|
|
||||||
|
#### 1.2 Снижение перерисовок графа (минимально и безопасно)
|
||||||
|
|
||||||
|
- **Стабилизировать входные данные** графа:
|
||||||
|
- вместо передачи “всего `project.scenes`” подготовить “лёгкое” представление сцен, содержащее только поля, нужные для карточек (title, preview refs, флаги).
|
||||||
|
- Цель: изменения в инспекторе (описание/аудио/и т.п.) не должны заставлять ReactFlow пересобирать все `nodes/edges`.
|
||||||
|
|
||||||
|
#### 1.3 Ограничить частоту тяжёлых обновлений при действиях в графе
|
||||||
|
|
||||||
|
- Проверить, чтобы обновления позиций/связей не вызывали лишних “полных” пересборок и не инициировали дорогие операции чаще, чем нужно.
|
||||||
|
|
||||||
|
**Критерий готовности**: на проекте с 22 сценами взаимодействие с графом заметно плавнее, задержка при создании связей снижается.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Этап 2 — Самое эффективное: thumbnails вместо оригиналов
|
||||||
|
|
||||||
|
#### 2.1 Модель данных для миниатюр
|
||||||
|
|
||||||
|
- Для превью/медиа хранить:
|
||||||
|
- **original asset** (как сейчас) — для просмотра/презентации
|
||||||
|
- **thumbnail asset** — для графа и списков
|
||||||
|
- Миниатюра — отдельный asset в `project.assets`, связанный с оригиналом (через поле в сцене или метаданные asset).
|
||||||
|
|
||||||
|
#### 2.2 Генерация thumbnail при импорте изображений
|
||||||
|
|
||||||
|
- При импорте превью/изображений:
|
||||||
|
- ресайз до ~**320px по длинной стороне**
|
||||||
|
- кодек: **WebP** (или JPEG)
|
||||||
|
- Сохранять thumbnail как отдельный файл/asset.
|
||||||
|
|
||||||
|
#### 2.3 Генерация thumbnail для видео по первому кадру
|
||||||
|
|
||||||
|
- При импорте видео:
|
||||||
|
- извлечь кадр (0.5–1s если на 0s чёрный)
|
||||||
|
- сохранить как **image/webp/jpeg** thumbnail
|
||||||
|
- В UI использовать thumbnail как постер для карточек.
|
||||||
|
|
||||||
|
#### 2.4 Использование thumbnails в UI
|
||||||
|
|
||||||
|
- **Граф сцен**: показывает только thumbnail.
|
||||||
|
- **Список сцен**: показывает только thumbnail.
|
||||||
|
- **Инспектор**: по желанию — только thumbnail.
|
||||||
|
- **Презентация/просмотр**: оригинал.
|
||||||
|
|
||||||
|
#### 2.5 Обратная совместимость
|
||||||
|
|
||||||
|
- Старые проекты без thumbnails:
|
||||||
|
- “ленивая” догенерация в фоне при первом отображении,
|
||||||
|
- или отдельная команда “Оптимизировать проект (создать миниатюры)”.
|
||||||
|
|
||||||
|
**Критерий готовности**: тяжёлые исходники почти не влияют на редактор; масштабируемость по сценам растёт.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Этап 3 — Дополнительные ускорения (по ситуации)
|
||||||
|
|
||||||
|
- **3.1 Виртуализация списка сцен** (если список остаётся тяжёлым при 50+ сценах).
|
||||||
|
- **3.2 Дифф‑обновление `nodes/edges`** в ReactFlow вместо “пересборки целиком” (для 100+ сцен).
|
||||||
|
- **3.3 LOD‑поведение**: при сильном зуме карточки упрощаются (только заголовок/иконки), thumbnails отключаются.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Приоритизация
|
||||||
|
|
||||||
|
- **Сразу**: Этап 1.
|
||||||
|
- **Максимальный эффект**: Этап 2.
|
||||||
|
- **Для больших проектов**: Этап 3.
|
||||||
|
|
||||||
@@ -20,6 +20,18 @@
|
|||||||
|
|
||||||
Токен не хранится открытым текстом в JSON userData: используется **Electron `safeStorage`** (на macOS — связка с Keychain, на Windows — DPAPI). Идентификатор устройства — отдельный файл `device.id` (не секрет). Принятие EULA — `preferences.json` (версия текста).
|
Токен не хранится открытым текстом в JSON userData: используется **Electron `safeStorage`** (на macOS — связка с Keychain, на Windows — DPAPI). Идентификатор устройства — отдельный файл `device.id` (не секрет). Принятие EULA — `preferences.json` (версия текста).
|
||||||
|
|
||||||
|
### Linux / WSL без keyring
|
||||||
|
|
||||||
|
На Linux `safeStorage` обычно требует **Secret Service** (например `gnome-keyring` + D-Bus). В **WSL** без keyring `safeStorage.isEncryptionAvailable()` часто **false**, и сохранить токен нельзя.
|
||||||
|
|
||||||
|
Явный обход (только если осознанно нужен запуск без OS-хранилища): переменная окружения **`DND_LICENSE_INSECURE_FILE_STORAGE=1`**. Тогда токен пишется в файл **`license.sealed.fallback`** (AES-256-GCM, ключ от `deviceId` + константа приложения). Это **слабее**, чем связка с ОС: при копировании `userData` + знании формата теоретически проще атаковать офлайн. Для обычного десктопа Linux с рабочим сеансом переменную не задавайте.
|
||||||
|
|
||||||
|
Пример запуска AppImage:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
DND_LICENSE_INSECURE_FILE_STORAGE=1 ./DNDGamePlayer-1.0.12-x64.AppImage --no-sandbox --appimage-extract-and-run
|
||||||
|
```
|
||||||
|
|
||||||
## Юридическое (D9)
|
## Юридическое (D9)
|
||||||
|
|
||||||
Текст EULA в приложении (`app/renderer/legal/eulaRu.ts`) и формулировки про активацию/отзыв/устройства. Перед первым вводом ключа пользователь принимает EULA (версия `EULA_CURRENT_VERSION` в `app/shared/license/eulaVersion.ts`).
|
Текст EULA в приложении (`app/renderer/legal/eulaRu.ts`) и формулировки про активацию/отзыв/устройства. Перед первым вводом ключа пользователь принимает EULA (версия `EULA_CURRENT_VERSION` в `app/shared/license/eulaVersion.ts`).
|
||||||
|
|||||||
+11
-1
@@ -12,7 +12,17 @@ const tsProject = ['./tsconfig.eslint.json'];
|
|||||||
|
|
||||||
export default tseslint.config(
|
export default tseslint.config(
|
||||||
{
|
{
|
||||||
ignores: ['dist/**', 'release/**', 'node_modules/**', '.cursor/**', 'scripts/**', 'eslint.config.js'],
|
ignores: [
|
||||||
|
'dist/**',
|
||||||
|
'release/**',
|
||||||
|
'node_modules/**',
|
||||||
|
'.cursor/**',
|
||||||
|
'scripts/**',
|
||||||
|
'eslint.config.js',
|
||||||
|
// Plain ESM; shared with sibling ../project-converter (not parsed as TS project file).
|
||||||
|
'app/main/project/optimizeImageImport.lib.mjs',
|
||||||
|
'app/main/project/optimizeImageImport.lib.d.mts',
|
||||||
|
],
|
||||||
},
|
},
|
||||||
js.configs.recommended,
|
js.configs.recommended,
|
||||||
...tseslint.configs.strictTypeChecked,
|
...tseslint.configs.strictTypeChecked,
|
||||||
|
|||||||
Generated
+1957
-49
File diff suppressed because it is too large
Load Diff
+47
-6
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "DndGamePlayer",
|
"name": "DndGamePlayer",
|
||||||
"version": "1.0.0",
|
"version": "1.0.13",
|
||||||
"description": "DNDGamePlayer — редактор и проигрыватель игр",
|
"description": "DNDGamePlayer — редактор и проигрыватель игр",
|
||||||
"main": "dist/main/index.cjs",
|
"main": "dist/main/index.cjs",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -10,14 +10,16 @@
|
|||||||
"build:obfuscate": "node scripts/build.mjs --production --obfuscate",
|
"build:obfuscate": "node scripts/build.mjs --production --obfuscate",
|
||||||
"lint": "eslint . --max-warnings 0",
|
"lint": "eslint . --max-warnings 0",
|
||||||
"typecheck": "tsc -p tsconfig.eslint.json --noEmit",
|
"typecheck": "tsc -p tsconfig.eslint.json --noEmit",
|
||||||
"test": "tsx --test app/renderer/shared/ui/controls.tooltip.test.ts app/shared/ipc/contracts.mediaRemoval.test.ts app/shared/effectEraserHitTest.test.ts app/renderer/control/controlApp.effectsPanel.test.ts app/renderer/shared/effects/PxiEffectsOverlay.pointer.test.ts app/main/windows/createWindows.editorClose.test.ts app/main/windows/bootWindow.test.ts app/main/effects/effectsStore.test.ts app/main/project/assetPrune.test.ts app/main/project/zipRead.test.ts app/shared/package.build.test.ts app/shared/license/canonicalJson.test.ts app/shared/license/productKey.test.ts app/shared/license/licenseService.networkRegression.test.ts app/main/license/verifyLicenseToken.test.ts && node --test scripts/build-env.test.mjs scripts/obfuscate-main.test.mjs",
|
"test": "tsx --test app/renderer/shared/ui/controls.tooltip.test.ts app/renderer/editor/state/projectState.race.test.ts app/renderer/editor/graph/sceneCardById.test.ts app/renderer/editor/i18n/editorMessages.locale.test.ts app/shared/ipc/contracts.mediaRemoval.test.ts app/shared/effectEraserHitTest.test.ts app/renderer/control/controlApp.effectsPanel.test.ts app/renderer/shared/effects/PxiEffectsOverlay.pointer.test.ts app/main/windows/createWindows.editorClose.test.ts app/main/windows/bootWindow.test.ts app/main/effects/effectsStore.test.ts app/main/project/assetPrune.test.ts app/main/project/optimizeImageImport.test.ts app/main/project/scenePreviewThumbnail.test.ts app/main/project/fsRetry.test.ts app/main/project/zipRead.test.ts app/main/project/replaceFileAtomic.test.ts app/main/project/zipStore.legacyContract.test.ts app/shared/package.build.test.ts app/shared/license/canonicalJson.test.ts app/shared/license/productKey.test.ts app/shared/license/licenseService.networkRegression.test.ts app/shared/video/videoPlaybackPerf.networkRegression.test.ts app/shared/video/videoPlaybackLoop.networkRegression.test.ts app/main/license/verifyLicenseToken.test.ts && node --test scripts/build-env.test.mjs scripts/obfuscate-main.test.mjs",
|
||||||
"format": "prettier . --check",
|
"format": "prettier . --check",
|
||||||
"format:write": "prettier . --write",
|
"format:write": "prettier . --write",
|
||||||
|
"postinstall": "patch-package",
|
||||||
"release:info": "node scripts/print-release-info.mjs",
|
"release:info": "node scripts/print-release-info.mjs",
|
||||||
"pack": "npm run build && node scripts/release-win-prep.mjs && electron-builder",
|
"pack": "npm run build && node scripts/release-win-prep.mjs && electron-builder",
|
||||||
"pack:dir": "npm run build && node scripts/release-win-prep.mjs && electron-builder --dir",
|
"pack:dir": "npm run build && node scripts/release-win-prep.mjs && electron-builder --dir",
|
||||||
"pack:mac": "npm run build && electron-builder --mac",
|
"pack:mac": "npm run build && electron-builder --mac",
|
||||||
"pack:win": "npm run build && node scripts/release-win-prep.mjs && electron-builder --win"
|
"pack:win": "npm run build && node scripts/release-win-prep.mjs && electron-builder --win",
|
||||||
|
"pack:linux": "npm run build && electron-builder --linux"
|
||||||
},
|
},
|
||||||
"keywords": [],
|
"keywords": [],
|
||||||
"author": "",
|
"author": "",
|
||||||
@@ -25,10 +27,13 @@
|
|||||||
"type": "module",
|
"type": "module",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@fontsource/inter": "^5.2.8",
|
"@fontsource/inter": "^5.2.8",
|
||||||
|
"electron-updater": "^6.6.2",
|
||||||
|
"ffmpeg-static": "^5.3.0",
|
||||||
"pixi.js": "^8.18.1",
|
"pixi.js": "^8.18.1",
|
||||||
"react": "^19.2.5",
|
"react": "^19.2.5",
|
||||||
"react-dom": "^19.2.5",
|
"react-dom": "^19.2.5",
|
||||||
"reactflow": "^11.11.4"
|
"reactflow": "^11.11.4",
|
||||||
|
"sharp": "^0.34.5"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^9.39.4",
|
"@eslint/js": "^9.39.4",
|
||||||
@@ -54,7 +59,9 @@
|
|||||||
"eslint-plugin-react-hooks": "^7.0.1",
|
"eslint-plugin-react-hooks": "^7.0.1",
|
||||||
"eslint-plugin-unicorn": "^64.0.0",
|
"eslint-plugin-unicorn": "^64.0.0",
|
||||||
"javascript-obfuscator": "^4.2.2",
|
"javascript-obfuscator": "^4.2.2",
|
||||||
|
"patch-package": "^8.0.1",
|
||||||
"prettier": "^3.8.3",
|
"prettier": "^3.8.3",
|
||||||
|
"to-ico": "^1.1.2",
|
||||||
"tsx": "^4.21.0",
|
"tsx": "^4.21.0",
|
||||||
"typescript": "^6.0.2",
|
"typescript": "^6.0.2",
|
||||||
"typescript-eslint": "^8.58.2",
|
"typescript-eslint": "^8.58.2",
|
||||||
@@ -70,13 +77,24 @@
|
|||||||
"output": "release",
|
"output": "release",
|
||||||
"buildResources": "build"
|
"buildResources": "build"
|
||||||
},
|
},
|
||||||
|
"extraResources": [
|
||||||
|
{
|
||||||
|
"from": "build/icon.ico",
|
||||||
|
"to": "branding/icon.ico"
|
||||||
|
}
|
||||||
|
],
|
||||||
"files": [
|
"files": [
|
||||||
"dist/**/*",
|
"dist/**/*",
|
||||||
"package.json"
|
"package.json"
|
||||||
],
|
],
|
||||||
"asar": true,
|
"asar": true,
|
||||||
"asarUnpack": [
|
"asarUnpack": [
|
||||||
"dist/preload/**"
|
"dist/preload/**",
|
||||||
|
"dist/renderer/app-pack-icon.png",
|
||||||
|
"dist/renderer/app-window-icon.png",
|
||||||
|
"node_modules/sharp/**",
|
||||||
|
"node_modules/@img/**",
|
||||||
|
"node_modules/ffmpeg-static/**"
|
||||||
],
|
],
|
||||||
"mac": {
|
"mac": {
|
||||||
"category": "public.app-category.games",
|
"category": "public.app-category.games",
|
||||||
@@ -113,12 +131,35 @@
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
|
"icon": "build/icon.ico"
|
||||||
|
},
|
||||||
|
"linux": {
|
||||||
|
"target": [
|
||||||
|
{
|
||||||
|
"target": "AppImage",
|
||||||
|
"arch": [
|
||||||
|
"x64",
|
||||||
|
"arm64"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"category": "Game",
|
||||||
|
"maintainer": "DNDGamePlayer",
|
||||||
|
"synopsis": "DNDGamePlayer — редактор и проигрыватель игр",
|
||||||
"icon": "build/icon.png"
|
"icon": "build/icon.png"
|
||||||
},
|
},
|
||||||
|
"appImage": {
|
||||||
|
"artifactName": "${productName}-${version}-${arch}.${ext}"
|
||||||
|
},
|
||||||
"nsis": {
|
"nsis": {
|
||||||
"oneClick": false,
|
"oneClick": false,
|
||||||
"allowToChangeInstallationDirectory": true,
|
"allowToChangeInstallationDirectory": true,
|
||||||
"deleteAppDataOnUninstall": false
|
"deleteAppDataOnUninstall": false,
|
||||||
|
"artifactName": "${productName}-Setup-${version}.${ext}"
|
||||||
|
},
|
||||||
|
"publish": {
|
||||||
|
"provider": "generic",
|
||||||
|
"url": "https://git.mailib.ru/ifontosh/DndGamePlayerUpdates/raw/branch/updates/"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
diff --git a/node_modules/app-builder-lib/out/targets/nsis/NsisTarget.js b/node_modules/app-builder-lib/out/targets/nsis/NsisTarget.js
|
||||||
|
index 1e4ef94..5f64a59 100644
|
||||||
|
--- a/node_modules/app-builder-lib/out/targets/nsis/NsisTarget.js
|
||||||
|
+++ b/node_modules/app-builder-lib/out/targets/nsis/NsisTarget.js
|
||||||
|
@@ -367,7 +367,12 @@ class NsisTarget extends core_1.Target {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
- await (0, wine_1.execWine)(installerPath, null, [], { env: { __COMPAT_LAYER: "RunAsInvoker" } });
|
||||||
|
+ try {
|
||||||
|
+ await nsisUtil_1.UninstallerReader.exec(installerPath, uninstallerPath);
|
||||||
|
+ }
|
||||||
|
+ catch (_error) {
|
||||||
|
+ await (0, wine_1.execWine)(installerPath, null, [], { env: { __COMPAT_LAYER: "RunAsInvoker" } });
|
||||||
|
+ }
|
||||||
|
}
|
||||||
|
await packager.signIf(uninstallerPath);
|
||||||
|
delete defines.BUILD_UNINSTALLER;
|
||||||
+1
-1
@@ -62,7 +62,7 @@ async function buildNodeTargets() {
|
|||||||
bundle: true,
|
bundle: true,
|
||||||
minify: isProd,
|
minify: isProd,
|
||||||
sourcemap: !isProd,
|
sourcemap: !isProd,
|
||||||
external: ['electron'],
|
external: ['electron', 'electron-updater', 'sharp', 'ffmpeg-static'],
|
||||||
define,
|
define,
|
||||||
drop: isProd ? ['console', 'debugger'] : [],
|
drop: isProd ? ['console', 'debugger'] : [],
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
/**
|
/**
|
||||||
* Растеризует app-logo.svg в app-window-icon.png для nativeImage (Windows).
|
* Растеризует app-logo.svg в app-window-icon.png для nativeImage (Windows).
|
||||||
|
* Пишет build/icon.png (macOS / fallback) и build/icon.ico — для exe/NSIS и «Программы и компоненты».
|
||||||
* Запуск: node scripts/gen-window-icon.mjs
|
* Запуск: node scripts/gen-window-icon.mjs
|
||||||
*/
|
*/
|
||||||
import fs from 'node:fs';
|
import fs from 'node:fs';
|
||||||
@@ -7,6 +8,7 @@ import path from 'node:path';
|
|||||||
import { fileURLToPath } from 'node:url';
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
import { Resvg } from '@resvg/resvg-js';
|
import { Resvg } from '@resvg/resvg-js';
|
||||||
|
import toIco from 'to-ico';
|
||||||
|
|
||||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||||
const root = path.join(__dirname, '..');
|
const root = path.join(__dirname, '..');
|
||||||
@@ -29,4 +31,18 @@ const resvg512 = new Resvg(svg, {
|
|||||||
});
|
});
|
||||||
const packOut = resvg512.render();
|
const packOut = resvg512.render();
|
||||||
fs.writeFileSync(packIconPath, packOut.asPng());
|
fs.writeFileSync(packIconPath, packOut.asPng());
|
||||||
console.log('wrote', packIconPath, packOut.width, 'x', packOut.height, '(electron-builder)');
|
console.log('wrote', packIconPath, packOut.width, 'x', packOut.height, '(electron-builder mac / fallback)');
|
||||||
|
|
||||||
|
function renderPngForWidth(width) {
|
||||||
|
const r = new Resvg(svg, {
|
||||||
|
fitTo: { mode: 'width', value: width },
|
||||||
|
});
|
||||||
|
return Buffer.from(r.render().asPng());
|
||||||
|
}
|
||||||
|
|
||||||
|
const icoSizes = [16, 24, 32, 48, 64, 128, 256];
|
||||||
|
const icoPngs = icoSizes.map((w) => renderPngForWidth(w));
|
||||||
|
const icoBuf = await toIco(icoPngs);
|
||||||
|
const icoPath = path.join(buildDir, 'icon.ico');
|
||||||
|
fs.writeFileSync(icoPath, icoBuf);
|
||||||
|
console.log('wrote', icoPath, '(electron-builder win)');
|
||||||
|
|||||||
@@ -0,0 +1,447 @@
|
|||||||
|
/**
|
||||||
|
* Складывает артефакты electron-builder (win + mac + linux) в публичный репозиторий,
|
||||||
|
* ветка `updates`, чтобы generic URL …/raw/branch/updates/ указывал на актуальные latest*.yml и установщики.
|
||||||
|
*
|
||||||
|
* Копирование **merge**: существующие файлы в ветке (другие ОС) не удаляются — обновляются только
|
||||||
|
* те имена, которые пришли из переданных каталогов артефактов.
|
||||||
|
*
|
||||||
|
* Переменные окружения:
|
||||||
|
* DND_UPDATES_SERVER — https://git.example.com (без слэша в конце)
|
||||||
|
* UPDATES_REPO — owner/repo (публичный репозиторий)
|
||||||
|
* DND_UPDATES_PUSH_TOKEN — PAT с правом push в UPDATES_REPO
|
||||||
|
* ARTIFACT_WIN — каталог с файлами Windows (можно пустой / отсутствует — пропуск)
|
||||||
|
* ARTIFACT_MAC — каталог с файлами macOS
|
||||||
|
* ARTIFACT_LINUX — каталог с файлами Linux (AppImage и т.д.)
|
||||||
|
* GIT_COMMIT_TAG — опционально, для сообщения коммита
|
||||||
|
* DND_GIT_PUSH_RETRIES — опционально, число попыток git push (1–5, по умолчанию 3)
|
||||||
|
* DND_UPDATES_CLONE_DEPTH — опционально, глубина shallow clone (2–200, по умолчанию 40), чтобы merge с remote был надёжнее
|
||||||
|
* DND_FEED_TMP_ROOT — каталог для временного клона feed (по умолчанию GITHUB_WORKSPACE / TMPDIR / os.tmpdir); не используйте узкий /tmp на раннере
|
||||||
|
* DND_GIT_FETCH_RETRIES — число попыток git fetch (1–6, по умолчанию 6); между попытками — git gc --prune=now (освобождение после обрыва TLS/unpack)
|
||||||
|
* DND_FEED_SKIP_DISK_CHECK — если "1", не проверять свободное место на томе DND_FEED_TMP_ROOT перед clone
|
||||||
|
* DND_UPDATES_SQUASH_HISTORY — если "1", после каждого релиза ветка updates в UPDATES_REPO переписывается на историю только текущего релиза (orphan + временная ветка + force-with-lease)
|
||||||
|
* DND_FEED_LARGE_FILE_BYTES — порог "большого" файла для дробления push в squash-режиме (по умолчанию 64 MiB)
|
||||||
|
*/
|
||||||
|
import { execFileSync, spawnSync } from 'node:child_process';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||||
|
|
||||||
|
const ALLOWED_EXT = new Set(['.yml', '.yaml', '.exe', '.blockmap', '.zip', '.dmg', '.pkg', '.appimage']);
|
||||||
|
|
||||||
|
/** Нет ветки updates на сервере — не путать с обрывом TLS. */
|
||||||
|
const GIT_FETCH_MISSING_UPDATES_REF_RE = /couldn't find remote ref updates\b/i;
|
||||||
|
|
||||||
|
/** Одинаковые флаги для clone (до появления .git/config) и согласованы с configureGitHttp. */
|
||||||
|
function gitHttpInlineFlags() {
|
||||||
|
return [
|
||||||
|
'-c',
|
||||||
|
'http.version=HTTP/1.1',
|
||||||
|
'-c',
|
||||||
|
'http.postBuffer=2147483648',
|
||||||
|
'-c',
|
||||||
|
'http.lowSpeedLimit=0',
|
||||||
|
'-c',
|
||||||
|
'http.lowSpeedTime=0',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function estimateArtifactBytes(winDir, macDir, linuxDir) {
|
||||||
|
const dirs = [...new Set([winDir, macDir, linuxDir].filter(Boolean))];
|
||||||
|
let total = 0;
|
||||||
|
for (const fromDir of dirs) {
|
||||||
|
if (!fromDir || !fs.existsSync(fromDir)) continue;
|
||||||
|
for (const name of fs.readdirSync(fromDir)) {
|
||||||
|
const p = path.join(fromDir, name);
|
||||||
|
if (!fs.statSync(p).isFile()) continue;
|
||||||
|
const ext = path.extname(name).toLowerCase();
|
||||||
|
if (!ALLOWED_EXT.has(ext)) continue;
|
||||||
|
total += fs.statSync(p).size;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return total;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Свободные байты на томе, где лежит tmpRoot; при ошибке — «достаточно». */
|
||||||
|
function freeBytesOnVolume(tmpRoot) {
|
||||||
|
try {
|
||||||
|
const s = fs.statfsSync(tmpRoot);
|
||||||
|
const bavail = typeof s.bavail === 'bigint' ? Number(s.bavail) : s.bavail;
|
||||||
|
const bsize = typeof s.bsize === 'bigint' ? Number(s.bsize) : s.bsize;
|
||||||
|
if (!Number.isFinite(bavail) || !Number.isFinite(bsize)) return Number.MAX_SAFE_INTEGER;
|
||||||
|
return bavail * bsize;
|
||||||
|
} catch {
|
||||||
|
return Number.MAX_SAFE_INTEGER;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertFeedDiskHeadroom(tmpRoot, artifactBytes) {
|
||||||
|
if (process.env.DND_FEED_SKIP_DISK_CHECK?.trim() === '1') return;
|
||||||
|
const avail = freeBytesOnVolume(tmpRoot);
|
||||||
|
const minBytes = Math.max(2_000_000_000, Math.round(artifactBytes * 2.5) + 1_000_000_000);
|
||||||
|
if (avail < minBytes) {
|
||||||
|
throw new Error(
|
||||||
|
`[sync-update-feed] мало места на томе «${tmpRoot}»: свободно ~${(avail / 1e9).toFixed(2)} GiB, ` +
|
||||||
|
`нужно примерно ≥ ${(minBytes / 1e9).toFixed(2)} GiB (артефакты ~${(artifactBytes / 1e9).toFixed(2)} GiB + shallow clone/pack + git add). ` +
|
||||||
|
`Освободите диск на раннере, увеличьте том или задайте DND_FEED_TMP_ROOT на другой диск. Либо DND_FEED_SKIP_DISK_CHECK=1 (не рекомендуется).`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function tryGitGcPrune(work) {
|
||||||
|
try {
|
||||||
|
execFileSync('git', ['gc', '--prune=now'], { cwd: work, stdio: 'ignore' });
|
||||||
|
} catch {
|
||||||
|
/* после оборванного fetch часть pack/tmp остаётся — gc освобождает; игнорируем сбой gc */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function mustEnv(name) {
|
||||||
|
const v = process.env[name]?.trim();
|
||||||
|
if (!v) throw new Error(`Missing env ${name}`);
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
function optionalDir(name) {
|
||||||
|
const v = process.env[name]?.trim();
|
||||||
|
return v && v.length > 0 ? v : '';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Куда класть временный клон: workspace раннера предпочтительнее, чем /tmp (место под AppImage). */
|
||||||
|
function feedTempRoot() {
|
||||||
|
const a =
|
||||||
|
process.env.DND_FEED_TMP_ROOT?.trim() ||
|
||||||
|
process.env.GITHUB_WORKSPACE?.trim() ||
|
||||||
|
process.env.GITEA_WORKSPACE?.trim() ||
|
||||||
|
process.env.TMPDIR?.trim() ||
|
||||||
|
os.tmpdir();
|
||||||
|
return a;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Перенос (rename) без дублирования байтов на одном томе; иначе copy + unlink исходника (освобождение места). */
|
||||||
|
function moveOrCopyArtifactFile(src, dest) {
|
||||||
|
if (fs.existsSync(dest)) {
|
||||||
|
fs.unlinkSync(dest);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
fs.renameSync(src, dest);
|
||||||
|
return;
|
||||||
|
} catch (e) {
|
||||||
|
const code = /** @type {NodeJS.ErrnoException} */ (e).code;
|
||||||
|
if (code !== 'EXDEV' && code !== 'EINVAL') throw e;
|
||||||
|
}
|
||||||
|
fs.copyFileSync(src, dest);
|
||||||
|
fs.unlinkSync(src);
|
||||||
|
}
|
||||||
|
|
||||||
|
function moveOrCopyFlatReleaseFiles(fromDir, toDir) {
|
||||||
|
if (!fromDir || !fs.existsSync(fromDir)) {
|
||||||
|
console.warn(`[sync-update-feed] skip missing dir: ${fromDir || '(empty)'}`);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
let n = 0;
|
||||||
|
for (const name of fs.readdirSync(fromDir)) {
|
||||||
|
const src = path.join(fromDir, name);
|
||||||
|
if (!fs.statSync(src).isFile()) continue;
|
||||||
|
const ext = path.extname(name).toLowerCase();
|
||||||
|
if (!ALLOWED_EXT.has(ext)) continue;
|
||||||
|
moveOrCopyArtifactFile(src, path.join(toDir, name));
|
||||||
|
n += 1;
|
||||||
|
}
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
function runGit(args, cwd) {
|
||||||
|
execFileSync('git', args, { cwd, stdio: 'inherit' });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Большие AppImage + exe в одном push: без этого Git по умолчанию может оборвать HTTPS (postBuffer / stall). */
|
||||||
|
function configureGitHttpForLargePush(cwd) {
|
||||||
|
// 2 GiB — достаточно для пачки артефактов; на старых Git при необходимости поднять на сервере лимиты nginx/Gitea.
|
||||||
|
runGit(['config', 'http.version', 'HTTP/1.1'], cwd);
|
||||||
|
runGit(['config', 'http.postBuffer', '2147483648'], cwd);
|
||||||
|
runGit(['config', 'http.lowSpeedLimit', '0'], cwd);
|
||||||
|
runGit(['config', 'http.lowSpeedTime', '0'], cwd);
|
||||||
|
}
|
||||||
|
|
||||||
|
function sleepSyncSeconds(seconds) {
|
||||||
|
try {
|
||||||
|
execFileSync('sleep', [String(seconds)], { stdio: 'ignore' });
|
||||||
|
} catch {
|
||||||
|
const end = Date.now() + seconds * 1000;
|
||||||
|
while (Date.now() < end) {
|
||||||
|
/* fallback без утилиты sleep */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function feedSquashSingleCommitEnabled() {
|
||||||
|
return process.env.DND_UPDATES_SQUASH_HISTORY?.trim() === '1';
|
||||||
|
}
|
||||||
|
|
||||||
|
function hadOriginUpdatesRemoteRef(work) {
|
||||||
|
try {
|
||||||
|
execFileSync('git', ['show-ref', '--verify', '--quiet', 'refs/remotes/origin/updates'], {
|
||||||
|
cwd: work,
|
||||||
|
stdio: 'ignore',
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function sanitizeRefPart(s) {
|
||||||
|
return s
|
||||||
|
.replace(/[^0-9A-Za-z._-]+/gu, '-')
|
||||||
|
.replace(/^-+|-+$/gu, '')
|
||||||
|
.slice(0, 80);
|
||||||
|
}
|
||||||
|
|
||||||
|
function pushWithRetries(work, args, label) {
|
||||||
|
const retries = Math.max(1, Math.min(5, Number.parseInt(process.env.DND_GIT_PUSH_RETRIES || '3', 10) || 3));
|
||||||
|
let lastError;
|
||||||
|
for (let attempt = 1; attempt <= retries; attempt += 1) {
|
||||||
|
try {
|
||||||
|
console.log(`[sync-update-feed] ${label} (attempt ${attempt}/${retries})`);
|
||||||
|
execFileSync('git', args, { cwd: work, stdio: 'inherit' });
|
||||||
|
return;
|
||||||
|
} catch (err) {
|
||||||
|
lastError = err;
|
||||||
|
console.warn(`[sync-update-feed] ${label} failed (attempt ${attempt}/${retries})`);
|
||||||
|
if (attempt < retries) {
|
||||||
|
sleepSyncSeconds(20);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw lastError;
|
||||||
|
}
|
||||||
|
|
||||||
|
function listFeedFiles(work) {
|
||||||
|
return fs
|
||||||
|
.readdirSync(work)
|
||||||
|
.filter((name) => name !== '.git' && fs.statSync(path.join(work, name)).isFile())
|
||||||
|
.sort((a, b) => a.localeCompare(b));
|
||||||
|
}
|
||||||
|
|
||||||
|
function gitAddFiles(work, files) {
|
||||||
|
if (files.length === 0) return;
|
||||||
|
runGit(['add', '--', ...files], work);
|
||||||
|
}
|
||||||
|
|
||||||
|
function commitStagedIfAny(work, message) {
|
||||||
|
try {
|
||||||
|
execFileSync('git', ['diff', '--cached', '--quiet'], { cwd: work, stdio: 'ignore' });
|
||||||
|
return false;
|
||||||
|
} catch {
|
||||||
|
runGit(['commit', '-m', message], work);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* История старых релизов удаляется, но загрузка идёт маленькими pack'ами:
|
||||||
|
* временная ветка получает small files + каждый большой файл отдельным push,
|
||||||
|
* а `updates` передвигается на готовый коммит только в конце.
|
||||||
|
*/
|
||||||
|
function publishSquashedUpdatesBranchStreamed(work, message, tag) {
|
||||||
|
const tempBranch = `updates-upload-${sanitizeRefPart(tag || 'ci')}-${String(Date.now())}`;
|
||||||
|
const files = listFeedFiles(work);
|
||||||
|
const largeFileBytes = Math.max(
|
||||||
|
8_000_000,
|
||||||
|
Math.min(
|
||||||
|
256_000_000,
|
||||||
|
Number.parseInt(process.env.DND_FEED_LARGE_FILE_BYTES || '64000000', 10) || 64_000_000,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const smallFiles = [];
|
||||||
|
const largeFiles = [];
|
||||||
|
for (const file of files) {
|
||||||
|
const size = fs.statSync(path.join(work, file)).size;
|
||||||
|
if (size >= largeFileBytes) {
|
||||||
|
largeFiles.push(file);
|
||||||
|
} else {
|
||||||
|
smallFiles.push(file);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.warn(
|
||||||
|
`[sync-update-feed] DND_UPDATES_SQUASH_HISTORY=1: переписываем только UPDATES_REPO/updates; ` +
|
||||||
|
`push дробится через временную ветку ${tempBranch} (${smallFiles.length} small, ${largeFiles.length} large)`,
|
||||||
|
);
|
||||||
|
|
||||||
|
runGit(['checkout', '--orphan', 'dnd-feed-upload-tmp'], work);
|
||||||
|
execFileSync('git', ['rm', '-r', '--cached', '--ignore-unmatch', '.'], { cwd: work, stdio: 'inherit' });
|
||||||
|
|
||||||
|
let pushedTemp = false;
|
||||||
|
gitAddFiles(work, smallFiles);
|
||||||
|
if (commitStagedIfAny(work, `${message} (metadata)`)) {
|
||||||
|
pushWithRetries(
|
||||||
|
work,
|
||||||
|
['push', '--force', '-u', 'origin', `HEAD:refs/heads/${tempBranch}`],
|
||||||
|
`push temp feed branch ${tempBranch}`,
|
||||||
|
);
|
||||||
|
pushedTemp = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const file of largeFiles) {
|
||||||
|
gitAddFiles(work, [file]);
|
||||||
|
if (commitStagedIfAny(work, `${message}: ${file}`)) {
|
||||||
|
pushWithRetries(
|
||||||
|
work,
|
||||||
|
['push', ...(pushedTemp ? [] : ['--force', '-u']), 'origin', `HEAD:refs/heads/${tempBranch}`],
|
||||||
|
`push temp feed object ${file}`,
|
||||||
|
);
|
||||||
|
pushedTemp = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!pushedTemp) {
|
||||||
|
throw new Error('[sync-update-feed] no feed files staged for streamed squash push');
|
||||||
|
}
|
||||||
|
|
||||||
|
const updateArgs = hadOriginUpdatesRemoteRef(work)
|
||||||
|
? ['push', '--force-with-lease', '-u', 'origin', 'HEAD:updates']
|
||||||
|
: ['push', '-u', 'origin', 'HEAD:updates'];
|
||||||
|
pushWithRetries(work, updateArgs, 'publish complete feed branch updates');
|
||||||
|
|
||||||
|
try {
|
||||||
|
execFileSync('git', ['push', 'origin', `:refs/heads/${tempBranch}`], { cwd: work, stdio: 'inherit' });
|
||||||
|
} catch {
|
||||||
|
console.warn(`[sync-update-feed] temp branch cleanup failed: ${tempBranch}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function mergeOriginUpdates(work) {
|
||||||
|
const fetchRetries = Math.max(
|
||||||
|
1,
|
||||||
|
Math.min(8, Number.parseInt(process.env.DND_GIT_FETCH_RETRIES || '6', 10) || 6),
|
||||||
|
);
|
||||||
|
let fetchOk = false;
|
||||||
|
/** @type {Error | undefined} */
|
||||||
|
let lastFetchErr;
|
||||||
|
for (let i = 0; i < fetchRetries; i += 1) {
|
||||||
|
const r = spawnSync('git', ['fetch', 'origin', 'updates'], {
|
||||||
|
cwd: work,
|
||||||
|
encoding: 'utf8',
|
||||||
|
maxBuffer: 64 * 1024 * 1024,
|
||||||
|
});
|
||||||
|
if (r.status === 0) {
|
||||||
|
fetchOk = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
const errText = `${r.stderr || ''}\n${r.stdout || ''}`;
|
||||||
|
if (GIT_FETCH_MISSING_UPDATES_REF_RE.test(errText)) {
|
||||||
|
console.warn('[sync-update-feed] ветки updates нет на remote — пропуск merge (первый push feed)');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
lastFetchErr = new Error(errText.trim() || `git fetch exited with status ${String(r.status)}`);
|
||||||
|
console.warn(`[sync-update-feed] git fetch failed (attempt ${i + 1}/${fetchRetries})`);
|
||||||
|
if (r.stderr?.trim()) {
|
||||||
|
console.warn(r.stderr.trim());
|
||||||
|
}
|
||||||
|
tryGitGcPrune(work);
|
||||||
|
if (i < fetchRetries - 1) {
|
||||||
|
sleepSyncSeconds(18);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!fetchOk) {
|
||||||
|
throw lastFetchErr ?? new Error('git fetch origin updates failed');
|
||||||
|
}
|
||||||
|
runGit(['merge', '--no-edit', 'origin/updates'], work);
|
||||||
|
}
|
||||||
|
|
||||||
|
function pushUpdatesBranch(work) {
|
||||||
|
const retries = Math.max(1, Math.min(5, Number.parseInt(process.env.DND_GIT_PUSH_RETRIES || '3', 10) || 3));
|
||||||
|
let lastError;
|
||||||
|
for (let attempt = 1; attempt <= retries; attempt += 1) {
|
||||||
|
try {
|
||||||
|
console.log(`[sync-update-feed] merge origin/updates before push (attempt ${attempt}/${retries})`);
|
||||||
|
mergeOriginUpdates(work);
|
||||||
|
runGit(['push', '-u', 'origin', 'updates'], work);
|
||||||
|
return;
|
||||||
|
} catch (err) {
|
||||||
|
lastError = err;
|
||||||
|
console.warn(`[sync-update-feed] merge/push failed (attempt ${attempt}/${retries})`);
|
||||||
|
if (attempt < retries) {
|
||||||
|
sleepSyncSeconds(20);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw lastError;
|
||||||
|
}
|
||||||
|
|
||||||
|
function main() {
|
||||||
|
const server = mustEnv('DND_UPDATES_SERVER').replace(/\/+$/u, '');
|
||||||
|
const updatesRepo = mustEnv('UPDATES_REPO');
|
||||||
|
const token = mustEnv('DND_UPDATES_PUSH_TOKEN');
|
||||||
|
const winDir = optionalDir('ARTIFACT_WIN');
|
||||||
|
const macDir = optionalDir('ARTIFACT_MAC');
|
||||||
|
const linuxDir = optionalDir('ARTIFACT_LINUX');
|
||||||
|
|
||||||
|
const u = new URL(server);
|
||||||
|
const host = u.host;
|
||||||
|
const cloneUrl = `https://oauth2:${encodeURIComponent(token)}@${host}/${updatesRepo}.git`;
|
||||||
|
|
||||||
|
const tmpRoot = feedTempRoot();
|
||||||
|
fs.mkdirSync(tmpRoot, { recursive: true });
|
||||||
|
assertFeedDiskHeadroom(tmpRoot, estimateArtifactBytes(winDir, macDir, linuxDir));
|
||||||
|
const tmp = fs.mkdtempSync(path.join(tmpRoot, 'dnd-feed-'));
|
||||||
|
const work = path.join(tmp, 'repo');
|
||||||
|
|
||||||
|
const squash = feedSquashSingleCommitEnabled();
|
||||||
|
const cloneDepth = squash
|
||||||
|
? Math.max(1, Math.min(200, Number.parseInt(process.env.DND_UPDATES_CLONE_DEPTH || '8', 10) || 8))
|
||||||
|
: Math.max(2, Math.min(200, Number.parseInt(process.env.DND_UPDATES_CLONE_DEPTH || '40', 10) || 40));
|
||||||
|
|
||||||
|
const gh = gitHttpInlineFlags();
|
||||||
|
try {
|
||||||
|
execFileSync('git', [...gh, 'clone', `--depth=${String(cloneDepth)}`, '-b', 'updates', cloneUrl, work], {
|
||||||
|
stdio: 'inherit',
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
execFileSync('git', [...gh, 'clone', `--depth=${String(cloneDepth)}`, cloneUrl, work], {
|
||||||
|
stdio: 'inherit',
|
||||||
|
});
|
||||||
|
runGit(['checkout', '-B', 'updates'], work);
|
||||||
|
}
|
||||||
|
|
||||||
|
runGit(['config', 'user.email', 'ci@gitea-actions.local'], work);
|
||||||
|
runGit(['config', 'user.name', 'gitea-actions'], work);
|
||||||
|
configureGitHttpForLargePush(work);
|
||||||
|
|
||||||
|
mergeOriginUpdates(work);
|
||||||
|
|
||||||
|
const artifactDirs = [...new Set([winDir, macDir, linuxDir].filter(Boolean))];
|
||||||
|
let copied = 0;
|
||||||
|
for (const d of artifactDirs) {
|
||||||
|
copied += moveOrCopyFlatReleaseFiles(d, work);
|
||||||
|
}
|
||||||
|
if (copied === 0) {
|
||||||
|
throw new Error(
|
||||||
|
'[sync-update-feed] no release files copied (check ARTIFACT_WIN / ARTIFACT_MAC / ARTIFACT_LINUX)',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const tag = process.env.GIT_COMMIT_TAG?.trim() || 'ci';
|
||||||
|
runGit(['add', '-A'], work);
|
||||||
|
const st = execFileSync('git', ['status', '--porcelain'], { cwd: work }).toString().trim();
|
||||||
|
if (st) {
|
||||||
|
const msg = `update feed ${tag}`;
|
||||||
|
if (squash) {
|
||||||
|
publishSquashedUpdatesBranchStreamed(work, msg, tag);
|
||||||
|
} else {
|
||||||
|
runGit(['commit', '-m', msg], work);
|
||||||
|
pushUpdatesBranch(work);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.warn('[sync-update-feed] nothing to commit (identical artifacts?)');
|
||||||
|
}
|
||||||
|
|
||||||
|
fs.rmSync(tmp, { recursive: true, force: true });
|
||||||
|
console.log(`[sync-update-feed] done (${String(copied)} file(s) into feed repo)`);
|
||||||
|
}
|
||||||
|
|
||||||
|
main();
|
||||||
Reference in New Issue
Block a user