2 Commits

Author SHA1 Message Date
Ivan Fontosh 1fbaaa6e77 feat(scene): video map editor parity and help updates
Enable scene editor, overlays, effects, and darkness on video scenes; brighten GM trap markers; document snap, NPC types, materials, and control controls in RU/EN help.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-07 08:23:08 +08:00
Ivan Fontosh 8d5a68c71e fix(pack): lazy-load sharp and verify unpacked natives
Avoid crashing Electron at startup when sharp is corrupt, and fail pack if asarUnpack natives look truncated.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-07 07:47:36 +08:00
23 changed files with 811 additions and 103 deletions
+3 -1
View File
@@ -267,7 +267,9 @@ function emitScenePlayerTokensSessionState(): void {
function syncSceneDarknessForProject(project: Project): void { function syncSceneDarknessForProject(project: Project): void {
const cacheKey = project.currentGraphNodeId ?? project.currentSceneId ?? null; const cacheKey = project.currentGraphNodeId ?? project.currentSceneId ?? null;
const scene = project.currentSceneId ? project.scenes[project.currentSceneId] : undefined; const scene = project.currentSceneId ? project.scenes[project.currentSceneId] : undefined;
const enabled = Boolean(scene?.darkenScene) && scene?.previewAssetType === 'image'; const enabled =
Boolean(scene?.darkenScene) &&
(scene?.previewAssetType === 'image' || scene?.previewAssetType === 'video');
sceneDarknessStore.switchScene(cacheKey, enabled); sceneDarknessStore.switchScene(cacheKey, enabled);
} }
+9 -1
View File
@@ -2,7 +2,7 @@
* Visually lossless re-encode for imported raster images (same pixel dimensions). * Visually lossless re-encode for imported raster images (same pixel dimensions).
* Node-only; shared by the main app and ../project-converter (monorepo sibling). * Node-only; shared by the main app and ../project-converter (monorepo sibling).
*/ */
import sharp from 'sharp'; import { getSharp } from './sharpRuntime.mjs';
/** @typedef {import('node:buffer').Buffer} Buffer */ /** @typedef {import('node:buffer').Buffer} Buffer */
@@ -102,6 +102,7 @@ function makePassthrough(buf, meta) {
* @param {number} h0 * @param {number} h0
*/ */
async function sameDimensionsOrThrow(outBuf, w0, h0) { async function sameDimensionsOrThrow(outBuf, w0, h0) {
const sharp = getSharp();
const m = await sharp(outBuf).metadata(); const m = await sharp(outBuf).metadata();
if ((m.width ?? 0) !== w0 || (m.height ?? 0) !== h0) { if ((m.width ?? 0) !== w0 || (m.height ?? 0) !== h0) {
const err = new Error('encode changed dimensions'); const err = new Error('encode changed dimensions');
@@ -120,6 +121,13 @@ export async function optimizeImageBufferVisuallyLossless(src) {
return makePassthrough(input, { width: 0, height: 0, format: 'png' }); return makePassthrough(input, { width: 0, height: 0, format: 'png' });
} }
let sharp;
try {
sharp = getSharp();
} catch {
return makePassthrough(input, null);
}
let meta0; let meta0;
try { try {
meta0 = await sharp(input, { failOn: 'error', unlimited: true }).metadata(); meta0 = await sharp(input, { failOn: 'error', unlimited: true }).metadata();
+3 -1
View File
@@ -5,7 +5,8 @@ import path from 'node:path';
import { promisify } from 'node:util'; import { promisify } from 'node:util';
import ffmpegStatic from 'ffmpeg-static'; import ffmpegStatic from 'ffmpeg-static';
import sharp from 'sharp';
import { getSharp } from './sharpRuntime.mjs';
const execFileAsync = promisify(execFile); const execFileAsync = promisify(execFile);
@@ -21,6 +22,7 @@ export async function generateScenePreviewThumbnailBytes(
kind: 'image' | 'video', kind: 'image' | 'video',
): Promise<Buffer | null> { ): Promise<Buffer | null> {
try { try {
const sharp = getSharp();
if (kind === 'image') { if (kind === 'image') {
return await sharp(source) return await sharp(source)
.rotate() .rotate()
+71
View File
@@ -0,0 +1,71 @@
/**
* Lazy `sharp` load so a corrupt/missing native install does not crash Electron at import time.
* Call only from image-processing paths; errors are recoverable for the rest of the app.
*
* Note: main is bundled to CJS (esbuild). `import.meta.url` is empty there — prefer `__filename`.
*/
import { createRequire } from 'node:module';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
/**
* @returns {string}
*/
function requireBaseFilename() {
// CJS bundle / Electron main
if (typeof __filename === 'string' && __filename.length > 0) {
return __filename;
}
// Direct ESM (unit tests)
const metaUrl = import.meta.url;
if (typeof metaUrl === 'string' && metaUrl.startsWith('file:')) {
return fileURLToPath(metaUrl);
}
return path.join(process.cwd(), 'package.json');
}
const require = createRequire(requireBaseFilename());
/** @type {typeof import('sharp') | null} */
let cached = null;
/** @type {Error | null} */
let loadError = null;
/**
* @param {unknown} err
* @returns {Error}
*/
export function sharpLoadFailure(err) {
const detail = err instanceof Error ? err.message : String(err);
return new Error(
[
'Не удалось загрузить модуль обработки изображений (sharp).',
'Переустановите приложение полностью (удалите и поставьте заново)',
'или исключите папку установки из проверки антивируса.',
detail ? `Детали: ${detail}` : '',
]
.filter(Boolean)
.join(' '),
);
}
/**
* @returns {typeof import('sharp')}
*/
export function getSharp() {
if (cached) return cached;
if (loadError) throw loadError;
try {
cached = require('sharp');
return cached;
} catch (err) {
loadError = sharpLoadFailure(err);
throw loadError;
}
}
/** Reset cache (tests only). */
export function __resetSharpRuntimeForTests() {
cached = null;
loadError = null;
}
+20
View File
@@ -0,0 +1,20 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
__resetSharpRuntimeForTests,
getSharp,
sharpLoadFailure,
} from './sharpRuntime.mjs';
void test('getSharp: loads sharp when install is healthy', () => {
__resetSharpRuntimeForTests();
const sharp = getSharp();
assert.equal(typeof sharp, 'function');
});
void test('sharpLoadFailure: includes reinstall hint', () => {
const err = sharpLoadFailure(new Error('SyntaxError: Unexpected end of input'));
assert.match(err.message, /переустановите/i);
assert.match(err.message, /SyntaxError/);
});
+23 -33
View File
@@ -373,8 +373,7 @@ export function ControlApp() {
const currentHistoryIdx = currentGraphNodeId != null ? history.lastIndexOf(currentGraphNodeId) : -1; const currentHistoryIdx = currentGraphNodeId != null ? history.lastIndexOf(currentGraphNodeId) : -1;
const currentScene = const currentScene =
project && session?.currentSceneId ? project.scenes[session.currentSceneId] : undefined; project && session?.currentSceneId ? project.scenes[session.currentSceneId] : undefined;
const isVideoPreviewScene = currentScene?.previewAssetType === 'video'; const isDarkenScene = Boolean(currentScene?.darkenScene);
const isDarkenScene = Boolean(currentScene?.darkenScene) && !isVideoPreviewScene;
const snapNormActive = useCallback( const snapNormActive = useCallback(
(nx: number, ny: number) => { (nx: number, ny: number) => {
@@ -868,7 +867,7 @@ export function ControlApp() {
useEffect(() => { useEffect(() => {
const frame = previewFrameRef.current; const frame = previewFrameRef.current;
if (!frame || isVideoPreviewScene) return; if (!frame) return;
const onWheel = (e: WheelEvent) => { const onWheel = (e: WheelEvent) => {
e.preventDefault(); e.preventDefault();
const host = previewHostRef.current; const host = previewHostRef.current;
@@ -892,7 +891,7 @@ export function ControlApp() {
}; };
frame.addEventListener('wheel', onWheel, { passive: false }); frame.addEventListener('wheel', onWheel, { passive: false });
return () => frame.removeEventListener('wheel', onWheel); return () => frame.removeEventListener('wheel', onWheel);
}, [isVideoPreviewScene]); }, []);
useEffect(() => { useEffect(() => {
return () => { return () => {
@@ -1256,11 +1255,6 @@ export function ControlApp() {
} }
async function commitStroke(): Promise<void> { async function commitStroke(): Promise<void> {
if (isVideoPreviewScene) {
brushRef.current = null;
clearDraftFromPixi();
return;
}
if (!fxState) return; if (!fxState) return;
const b = brushRef.current; const b = brushRef.current;
if (!b) return; if (!b) return;
@@ -1608,8 +1602,7 @@ export function ControlApp() {
</Button> </Button>
</div> </div>
<div className={styles.spacer12} /> <div className={styles.spacer12} />
{!isVideoPreviewScene ? ( <>
<>
<div className={styles.sectionLabel}>{t('control.effects')}</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}>
@@ -1815,7 +1808,6 @@ export function ControlApp() {
</div> </div>
<div className={styles.spacer12} /> <div className={styles.spacer12} />
</> </>
) : null}
<div className={styles.storyWrap}> <div className={styles.storyWrap}>
<div className={styles.sectionLabel}>{t('control.storyLine')}</div> <div className={styles.sectionLabel}>{t('control.storyLine')}</div>
<div className={styles.spacer10} /> <div className={styles.spacer10} />
@@ -1960,14 +1952,11 @@ export function ControlApp() {
</div> </div>
</div> </div>
<div className={styles.spacer10} /> <div className={styles.spacer10} />
{isVideoPreviewScene ? <div className={styles.videoHint}>{t('control.videoBrushHint')}</div> : null}
<div className={styles.spacer10} /> <div className={styles.spacer10} />
<div <div
ref={previewFrameRef} ref={previewFrameRef}
className={styles.previewFrame} className={styles.previewFrame}
title={ title="Колесо — зум; перетаскивание СКМ/ПКМ или Space+ЛКМ — пан"
isVideoPreviewScene ? undefined : 'Колесо — зум; перетаскивание СКМ/ПКМ или Space+ЛКМ — пан'
}
> >
<div ref={previewHostRef} className={styles.previewHost}> <div ref={previewHostRef} className={styles.previewHost}>
<ControlScenePreview <ControlScenePreview
@@ -1977,8 +1966,7 @@ export function ControlApp() {
onContentRectChange={setPreviewContentRect} onContentRectChange={setPreviewContentRect}
/> />
</div> </div>
{!isVideoPreviewScene ? ( <>
<>
<SceneGridOverlay grid={currentScene?.grid} viewport={previewContentRect} /> <SceneGridOverlay grid={currentScene?.grid} viewport={previewContentRect} />
<PixiEffectsOverlay <PixiEffectsOverlay
ref={effectsOverlayRef} ref={effectsOverlayRef}
@@ -2188,17 +2176,20 @@ export function ControlApp() {
ny: snapped.ny, ny: snapped.ny,
}); });
}} }}
onContextMenu={ {...(markersInteractive
markersInteractive ? {
? (e, placement) => { onContextMenu: (
e: React.MouseEvent,
placement: { id: string },
) => {
setNpcSessionCtxMenu({ setNpcSessionCtxMenu({
x: e.clientX, x: e.clientX,
y: e.clientY, y: e.clientY,
placementId: String(placement.id), placementId: String(placement.id),
}); });
} },
: undefined }
} : {})}
/> />
) : null} ) : null}
{USERS_BRANCH_FEATURES_ENABLED && previewContentRect ? ( {USERS_BRANCH_FEATURES_ENABLED && previewContentRect ? (
@@ -2280,6 +2271,13 @@ export function ControlApp() {
/> />
) : null} ) : null}
</> </>
{previewContentRect && currentScene?.darkenScene ? (
<SceneDarknessOverlay
state={sdState}
overlayAlpha={0.5}
viewport={previewContentRect}
style={{ zIndex: 30 }}
/>
) : null} ) : null}
{(() => { {(() => {
const project = session?.project; const project = session?.project;
@@ -2322,7 +2320,7 @@ export function ControlApp() {
const showMaterial = materialItems.length > 0; const showMaterial = materialItems.length > 0;
const showNpcs = npcItems.length > 0; const showNpcs = npcItems.length > 0;
const screenRect = presentationScreenRect; const screenRect = presentationScreenRect;
const showGuide = Boolean(screenRect) && !isVideoPreviewScene; const showGuide = Boolean(screenRect);
if (!showMaterial && !showNpcs && !showGuide) return null; if (!showMaterial && !showNpcs && !showGuide) return null;
const closes = [ const closes = [
...(showMaterial ...(showMaterial
@@ -2357,14 +2355,6 @@ export function ControlApp() {
}; };
return ( return (
<> <>
{previewContentRect && currentScene?.darkenScene ? (
<SceneDarknessOverlay
state={sdState}
overlayAlpha={0.5}
viewport={previewContentRect}
style={{ zIndex: 30 }}
/>
) : null}
<SceneOverlayHost <SceneOverlayHost
active={showMaterial || showNpcs} active={showMaterial || showNpcs}
viewport={screenRect} viewport={screenRect}
@@ -25,6 +25,8 @@
display: grid; display: grid;
gap: 8px; gap: 8px;
pointer-events: auto; pointer-events: auto;
/* Above brush / traps layers so transport stays usable on video scenes. */
z-index: 50;
} }
.scrub { .scrub {
+7 -7
View File
@@ -4,6 +4,7 @@ import { computeTimeSec } from '../../main/video/videoPlaybackStore';
import type { SessionState } from '../../shared/ipc/contracts'; import type { SessionState } from '../../shared/ipc/contracts';
import type { SceneViewCamera } from '../../shared/types'; import type { SceneViewCamera } from '../../shared/types';
import { useEditorI18n } from '../editor/i18n/EditorI18nContext'; import { useEditorI18n } from '../editor/i18n/EditorI18nContext';
import { ContainedVideo } from '../shared/ContainedVideo';
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';
@@ -106,20 +107,19 @@ export function ControlScenePreview({ session, videoRef, viewCamera = null, onCo
onContentRectChange={onContentRectChange} onContentRectChange={onContentRectChange}
/> />
) : url && isVideo ? ( ) : url && isVideo ? (
<video <ContainedVideo
ref={(el) => { url={url}
(videoRef as unknown as { current: HTMLVideoElement | null }).current = el; videoRef={videoRef}
}}
className={styles.video}
src={url}
playsInline playsInline
loop={Boolean(scene?.settings?.loopVideo)} loop={Boolean(scene?.settings?.loopVideo)}
preload="auto" preload="auto"
viewCamera={viewCamera}
onContentRectChange={onContentRectChange}
onTimeUpdate={() => setTick((x) => x + 1)} onTimeUpdate={() => setTick((x) => x + 1)}
onLoadedMetadata={() => setTick((x) => x + 1)} onLoadedMetadata={() => setTick((x) => x + 1)}
> >
<track kind="captions" srcLang="ru" label={t('control.previewTrackLabel')} /> <track kind="captions" srcLang="ru" label={t('control.previewTrackLabel')} />
</video> </ContainedVideo>
) : ( ) : (
<div className={styles.placeholder} /> <div className={styles.placeholder} />
)} )}
@@ -58,7 +58,7 @@ void test('ControlApp: эффект «взрыв» + ловушка исполь
const appSrc = readControlApp(); const appSrc = readControlApp();
const sfxSrc = fs.readFileSync(path.join(here, 'explosionSfx.ts'), 'utf8'); const sfxSrc = fs.readFileSync(path.join(here, 'explosionSfx.ts'), 'utf8');
assert.ok(appSrc.includes("title={t('control.explosion')}")); assert.ok(appSrc.includes("title={t('control.explosion')}"));
assert.ok(appSrc.includes("tool: 'explosion'")); assert.ok(appSrc.includes("selectEffectTool('explosion')"));
assert.ok(appSrc.includes("type: 'explosion'")); assert.ok(appSrc.includes("type: 'explosion'"));
assert.ok(appSrc.includes('getExplosionEffectLifeMs')); assert.ok(appSrc.includes('getExplosionEffectLifeMs'));
assert.ok(appSrc.includes('playExplosionEffectSound')); assert.ok(appSrc.includes('playExplosionEffectSound'));
+4
View File
@@ -2755,6 +2755,10 @@ function SceneInspector({
> >
{t('scene.rotate')} {t('scene.rotate')}
</Button> </Button>
</>
) : null}
{previewAssetId && (previewAssetType === 'image' || previewAssetType === 'video') ? (
<>
<div className={styles.spacer6} /> <div className={styles.spacer6} />
<label className={styles.checkboxLabel}> <label className={styles.checkboxLabel}>
<input <input
+20 -20
View File
@@ -180,23 +180,23 @@ export const EDITOR_MESSAGES: Record<EditorLocale, Record<string, string>> = {
'help.section.sceneProps.title': 'Свойства сцены', 'help.section.sceneProps.title': 'Свойства сцены',
'help.section.sceneProps.body': 'help.section.sceneProps.body':
'Выберите сцену в списке слева — справа откроются её свойства.\n\n«Название сцены» — для мастера. «Описание» — заметки мастера с форматированием: рядом с подписью нажмите карандаш, откроется редактор (жирный, курсив, заголовки, списки, ссылки). Под подписью видно фрагмент текста или «описание отсутствует», если поле пустое. Во время сессии описание открывается с пульта в отдельном окне (см. «Пульт управления»), а не в блоке «Сюжетная линия».\n\nЕсли у сцены на карте есть карточка с синей меткой «ПОБОЧНАЯ», появится поле «Название побочной линии».\n\nКартинка или видео для игроков:\n\n1) В «Превью сцены» нажмите «Загрузить» или «Изменить».\n\n2) Выберите файл (PNG, JPG, WebP, GIF и др.).\n\n3) Для картинки можно «Повернуть» (шаг 90°). «Очистить» — убрать превью.\n\n4) Для картинки можно включить «Затемнить сцену»: при показе игроки сначала увидят карту в полной темноте, а вы снимете её с пульта «Кистью Открытия» (см. «Эффекты»).\n\n5) Для картинки доступна кнопка «Редактор сцены» — сетка, ловушки и неигровые токены на карте (см. «Редактор сцены», «Генератор сетки», «Ловушки», «Неигровые токены»).\n\nДля видео включите «Автостарт», если ролик должен сам начаться на экране игроков. На видео-сценах эффекты кистью и редактор сцены недоступны.\n\n«Аудио сцены» — музыка и звуки этого эпизода. «Загрузить» добавляет файлы. У каждого трека: «Авто» (играть при входе в сцену) и «Цикл». Корзина удаляет трек.\n\nСвязи между сценами задаются на карте, а не здесь — см. «Граф сцен».', 'Выберите сцену в списке слева — справа откроются её свойства.\n\n«Название сцены» — для мастера. «Описание» — заметки мастера с форматированием: рядом с подписью нажмите карандаш, откроется редактор (жирный, курсив, заголовки, списки, ссылки). Под подписью видно фрагмент текста или «описание отсутствует», если поле пустое. Во время сессии описание открывается с пульта в отдельном окне (см. «Пульт управления»), а не в блоке «Сюжетная линия».\n\nЕсли у сцены на карте есть карточка с синей меткой «ПОБОЧНАЯ», появится поле «Название побочной линии».\n\nКартинка или видео для игроков:\n\n1) В «Превью сцены» нажмите «Загрузить» или «Изменить».\n\n2) Выберите файл (PNG, JPG, WebP, GIF, видео и др.).\n\n3) Для картинки можно «Повернуть» (шаг 90°). «Очистить» — убрать превью.\n\n4) Для картинки и видео можно включить «Затемнить сцену»: при показе игроки сначала увидят кадр в полной темноте, а вы снимете её с пульта «Кистью Открытия» (см. «Эффекты»).\n\n5) Кнопка «Редактор сцены» доступна и для картинки, и для видео — сетка, ловушки и неигровые токены поверх превью (см. «Редактор сцены», «Генератор сетки», «Ловушки», «Неигровые токены»).\n\nДля видео включите «Автостарт», если ролик должен сам начаться на экране игроков, и при необходимости «Цикл».\n\n«Аудио сцены» — музыка и звуки этого эпизода. «Загрузить» добавляет файлы. У каждого трека: «Авто» (играть при входе в сцену) и «Цикл». Корзина удаляет трек.\n\nСвязи между сценами задаются на карте, а не здесь — см. «Граф сцен».',
'help.section.sceneEditor.title': 'Редактор сцены', 'help.section.sceneEditor.title': 'Редактор сцены',
'help.section.sceneEditor.body': 'help.section.sceneEditor.body':
'«Редактор сцены» — отдельное окно для подготовки карты: сетка боя, ловушки, неигровые токены и круглые токены НПС. Доступен только для сцен с изображением (не с видео).\n\nОткрыть:\n\n1) Выберите сцену в списке слева.\n\n2) В «Свойствах сцены» загрузите картинку, если её ещё нет.\n\n3) Нажмите «Редактор сцены».\n\nСлева — аккордеоны «Сетка», «Неигровые токены», «НПС» и «Ловушки»; справа — карта сцены. Перетащите НПС на карту, чтобы добавить его круглый токен.\n\nНавигация по карте: колесо мыши — зум; средняя кнопка мыши или Space+ЛКМ — сдвиг вида. Delete / Backspace убирает выделенный маркер на карте.\n\nПод аккордеонами кнопка «Очистить сцену» убирает с текущей карты все ловушки и токены (пул токенов приложения не трогает).\n\nПодробнее: разделы «Генератор сетки», «Ловушки» и «Неигровые токены».', '«Редактор сцены» — отдельное окно для подготовки карты: сетка боя, ловушки, неигровые токены и круглые токены НПС. Работает для сцен с изображением и с видео (оверлеи поверх ролика).\n\nОткрыть:\n\n1) Выберите сцену в списке слева.\n\n2) В «Свойствах сцены» загрузите картинку или видео, если превью ещё нет.\n\n3) Нажмите «Редактор сцены».\n\nСлева — аккордеоны «Сетка», «Неигровые токены», «НПС» и «Ловушки»; справа — карта сцены. Перетащите НПС на карту, чтобы добавить его круглый токен.\n\nНавигация по карте: колесо мыши — зум; средняя кнопка мыши или Space+ЛКМ — сдвиг вида. Delete / Backspace убирает выделенный маркер на карте.\n\nПод аккордеонами кнопка «Очистить сцену» убирает с текущей карты все ловушки и токены (пул токенов приложения не трогает).\n\nПодробнее: разделы «Генератор сетки», «Ловушки» и «Неигровые токены».',
'help.section.grid.title': 'Генератор сетки', 'help.section.grid.title': 'Генератор сетки',
'help.section.grid.body': 'help.section.grid.body':
'Генератор сетки накладывает на картинку сцены боевую сетку — квадратную или гексагональную. Сетка помогает ориентироваться по клеткам во время боя и видна и вам на пульте, и игрокам на презентации.\n\nНастроить:\n\n1) Откройте «Редактор сцены» для сцены с изображением (см. «Редактор сцены»).\n\n2) Раскройте аккордеон «Сетка» слева.\n\n3) Включите «Наложить сетку» — линии появятся поверх карты.\n\n4) «Тип» — «Квадратная» или «Гексогональная».\n\n5) «Цвет» — оттенок линий (удобно подобрать контраст к карте).\n\n6) «Размер» — ползунок ячейки: чем больше значение, тем крупнее клетки.\n\nПока сетка выключена, тип, цвет и размер недоступны для изменения, но запомненные значения сохраняются и вернутся при повторном включении.\n\nНастройки сетки хранятся в проекте вместе со сценой. На видео-сценах генератор недоступен — только на картинках. Сетка рисуется под маркерами ловушек и токенов и не мешает их расставлять.', 'Генератор сетки накладывает на превью сцены (картинку или видео) боевую сетку — квадратную или гексагональную. Сетка помогает ориентироваться по клеткам во время боя и видна и вам на пульте, и игрокам на презентации.\n\nНастроить:\n\n1) Откройте «Редактор сцены» (см. «Редактор сцены»).\n\n2) Раскройте аккордеон «Сетка» слева.\n\n3) Включите «Наложить сетку» — линии появятся поверх карты.\n\n4) «Тип» — «Квадратная» или «Гексогональная».\n\n5) «Цвет» — оттенок линий (удобно подобрать контраст к карте).\n\n6) «Размер» — ползунок ячейки: чем больше значение, тем крупнее клетки.\n\nПока сетка выключена, тип, цвет и размер недоступны для изменения, но запомненные значения сохраняются и вернутся при повторном включении.\n\nНастройки сетки хранятся в проекте вместе со сценой. Сетка рисуется под маркерами ловушек и токенов и не мешает их расставлять.\n\nВо время сессии на пульте можно включить «Привязка токенов к сетке»: при перетаскивании неигровые токены, токены НПС и игроков «прилипают» к клеткам (квадрат или гекс — по типу сетки). Если сетка выключена, галочка не действует.',
'help.section.traps.title': 'Ловушки', 'help.section.traps.title': 'Ловушки',
'help.section.traps.body': 'help.section.traps.body':
'Ловушки — маркеры на карте сцены для скрытых угроз и сюрпризов. Расстановка хранится в проекте вместе со сценой; во время игры вы решаете, когда их показать игрокам.\n\nВ редакторе сцены:\n\n1) Откройте «Редактор сцены» для сцены с картинкой (см. «Редактор сцены»).\n\n2) Раскройте аккордеон «Ловушки» слева.\n\n3) Перетащите тип из палитры на нужное место карты.\n\n4) Перетащите маркер, чтобы сдвинуть его; потяните за уголок выделенного маркера — изменить размер.\n\n5) Delete / Backspace — убрать выделенную ловушку. «Очистить сцену» снимает все маркеры сразу.\n\nТипы: Мимик, Взрыв, Яд, Пропасть, Стрела, Лазер и Метка (универсальный маркер без особого эффекта).\n\nВо время сессии:\n\n1) На пульте в «Предпросмотр экрана» видны все ловушки текущей сцены. Пока они скрыты от игроков, маркеры у вас слегка приглушены.\n\n2) На презентации маркеры появляются только после проявления или срабатывания.\n\n3) Правый клик по маркеру на пульте:\n• «Проявить» — показать игрокам без срабатывания.\n• «Активировать» — проявить и запустить эффект: у Мимика, Пропасти, Стрелы и Лазера — анимация и звук; у Яда и Взрыва — как соответствующие эффекты с пульта (облако яда / взрыв); у Метки — короткая вспышка.\n• «Обезвредить» — показать как обезвреженную.\n\nСостояние ловушек (проявлены / сработали / обезврежены) сбрасывается при новом запуске сессии. Сами маркеры на карте остаются.', 'Ловушки — маркеры на карте сцены для скрытых угроз и сюрпризов. Расстановка хранится в проекте вместе со сценой; во время игры вы решаете, когда их показать игрокам.\n\nВ редакторе сцены:\n\n1) Откройте «Редактор сцены» для сцены с картинкой или видео (см. «Редактор сцены»).\n\n2) Раскройте аккордеон «Ловушки» слева.\n\n3) Перетащите тип из палитры на нужное место карты.\n\n4) Перетащите маркер, чтобы сдвинуть его; потяните за уголок выделенного маркера — изменить размер.\n\n5) Delete / Backspace — убрать выделенную ловушку. «Очистить сцену» снимает все маркеры сразу.\n\nТипы: Мимик, Взрыв, Яд, Пропасть, Стрела, Лазер и Метка (универсальный маркер без особого эффекта).\n\nВо время сессии:\n\n1) На пульте в «Предпросмотр экрана» видны все ловушки текущей сцены. Пока они скрыты от игроков, у вас маркеры остаются хорошо читаемыми (пунктирная рамка), чтобы их было удобно найти на карте.\n\n2) На презентации маркеры появляются только после проявления или срабатывания.\n\n3) Правый клик по маркеру на пульте:\n• «Проявить» — показать игрокам без срабатывания.\n• «Активировать» — проявить и запустить эффект: у Мимика, Пропасти, Стрелы и Лазера — анимация и звук; у Яда и Взрыва — как соответствующие эффекты с пульта (облако яда / взрыв); у Метки — короткая вспышка.\n• «Обезвредить» — показать как обезвреженную.\n\nСостояние ловушек (проявлены / сработали / обезврежены) сбрасывается при новом запуске сессии. Сами маркеры на карте остаются.',
'help.section.tokens.title': 'Неигровые токены', 'help.section.tokens.title': 'Неигровые токены',
'help.section.tokens.body': 'help.section.tokens.body':
'Неигровые токены — картинки существ, предметов и маркеров, которые вы ставите на карту сцены. Библиотека токенов хранится в приложении на этом компьютере (не внутри файла проекта). На сцене сохраняется только расстановка: какой токен, где стоит, размер и поворот.\n\nВ редакторе сцены:\n\n1) Откройте «Редактор сцены» для сцены с картинкой (см. «Редактор сцены»).\n\n2) Раскройте «Неигровые токены».\n\n3) «Добавить» — задайте уникальное название и изображение (кнопка выбора или перетаскивание файла).\n\n4) В поиске можно быстро найти токен по имени.\n\n5) Меню «⋮» у плитки — «Изменить» или «Удалить» (с подтверждением). Удаление из пула также убирает этот токен с текущей сцены.\n\n6) Перетащите плитку на карту, чтобы поставить токен. Выделите маркер: перетаскивание — сдвиг, уголок — размер, ручка поворота — угол. Delete / Backspace или ПКМ по маркеру — убрать с карты. «Очистить сцену» снимает все токены и ловушки со сцены.\n\nВо время сессии:\n\n1) На пульте в «Предпросмотр экрана» токены видны сразу (в отличие от ловушек их не нужно проявлять).\n\n2) Перетаскивайте токены левой кнопкой — новая позиция запоминается до конца текущей сессии, в том числе если вы возвращаетесь к сцене через «Сюжетную линию». При новом «Запустить» позиции снова берутся из редактора.\n\n3) На экране презентации токены только отображаются: клики и перетаскивание для игроков недоступны.\n\nПри экспорте и импорте сюжетных линий нужные файлы токенов упаковываются вместе с линией, чтобы на другом компьютере расстановка не «теряла» картинки.', 'Неигровые токены — картинки существ, предметов и маркеров, которые вы ставите на карту сцены. Библиотека токенов хранится в приложении на этом компьютере (не внутри файла проекта). На сцене сохраняется только расстановка: какой токен, где стоит, размер и поворот.\n\nВ редакторе сцены:\n\n1) Откройте «Редактор сцены» для сцены с картинкой или видео (см. «Редактор сцены»).\n\n2) Раскройте «Неигровые токены».\n\n3) «Добавить» — задайте уникальное название и изображение (кнопка выбора или перетаскивание файла).\n\n4) В поиске можно быстро найти токен по имени.\n\n5) Меню «⋮» у плитки — «Изменить» или «Удалить» (с подтверждением). Удаление из пула также убирает этот токен с текущей сцены.\n\n6) Перетащите плитку на карту, чтобы поставить токен. Выделите маркер: перетаскивание — сдвиг, уголок — размер, ручка поворота — угол. Delete / Backspace или ПКМ по маркеру — убрать с карты. «Очистить сцену» снимает все токены и ловушки со сцены.\n\nВо время сессии:\n\n1) На пульте в «Предпросмотр экрана» токены видны сразу (в отличие от ловушек их не нужно проявлять).\n\n2) Перетаскивайте токены левой кнопкой — новая позиция запоминается до конца текущей сессии, в том числе если вы возвращаетесь к сцене через «Сюжетную линию». При новом «Запустить» позиции снова берутся из редактора.\n\n3) Если на сцене включена сетка, на пульте можно отметить «Привязка токенов к сетке» — при перетаскивании токены встают по клеткам (см. «Генератор сетки»).\n\n4) На экране презентации токены только отображаются: клики и перетаскивание для игроков недоступны.\n\nПри экспорте и импорте сюжетных линий нужные файлы токенов упаковываются вместе с линией, чтобы на другом компьютере расстановка не «теряла» картинки.',
'help.section.campaignAudio.title': 'Аудио игры', 'help.section.campaignAudio.title': 'Аудио игры',
'help.section.campaignAudio.body': 'help.section.campaignAudio.body':
@@ -204,14 +204,14 @@ export const EDITOR_MESSAGES: Record<EditorLocale, Record<string, string>> = {
'help.section.materials.title': 'Материалы', 'help.section.materials.title': 'Материалы',
'help.section.materials.body': 'help.section.materials.body':
'Материалы — изображения кампании (карты, записки, чертежи), которые можно показать игрокам поверх сцены во время игры. Они общие для проекта и не привязаны к одной сцене.\n\nВ редакторе:\n\n1) В блоке «Свойства игры» нажмите «Материалы».\n\n2) «Добавить» — укажите уникальное название и изображение (PNG, JPG или WebP): кнопка выбора или перетаскивание файла.\n\n3) В списке можно искать, менять порядок перетаскиванием, править или удалять через меню «⋮» (перед удалением будет подтверждение).\n\n4) Под большим превью — «Повернуть»: поворот на 90° (учитывается и в плитке, и при показе на экране).\n\nВо время сессии:\n\n1) На пульте в «Инструменты» нажмите кнопку материалов (иконка карты сокровищ) — откроется отдельное окно со списком.\n\n2) Клик по плитке показывает материал поверх сцены на пульте и на презентации; повторный клик по той же плитке скрывает его.\n\n3) На предпросмотре пульта материал можно перетаскивать и менять размер за углы; крестик закрывает показ.\n\n4) В окне материалов лупы «+» / «−» — инструменты масштаба: выберите лупу, затем кликните по материалу в предпросмотре пульта.\n\nПри смене сцены показ материала сбрасывается. Описание сцены и эффекты поля с материалами не связаны.', 'Материалы — изображения кампании (карты, записки, чертежи), которые можно показать игрокам поверх сцены во время игры. Они общие для проекта и не привязаны к одной сцене.\n\nВ редакторе:\n\n1) В блоке «Свойства игры» нажмите «Материалы».\n\n2) «Добавить» — укажите уникальное название и изображение (PNG, JPG или WebP): кнопка выбора или перетаскивание файла.\n\n3) В списке можно искать, менять порядок перетаскиванием, править или удалять через меню «⋮» (перед удалением будет подтверждение).\n\n4) Под большим превью — «Повернуть»: поворот на 90° (учитывается и в плитке, и при показе на экране).\n\n5) Блок «Легенда» у выбранного материала: можно включить легенду, разместить нумерованные маркеры на картинке и подписать пункты списка. При показе на пульте и презентации легенда идёт вместе с материалом.\n\nВо время сессии:\n\n1) На пульте в «Инструменты» нажмите кнопку материалов (иконка карты сокровищ) — откроется отдельное окно со списком.\n\n2) Клик по плитке показывает материал поверх сцены на пульте и на презентации; повторный клик по той же плитке скрывает его. Можно открыть несколько материалов сразу — каждый кликом по своей плитке.\n\n3) На предпросмотре пульта материал можно перетаскивать, менять размер за углы и поворачивать; крестик закрывает показ этого материала (остальные остаются).\n\n4) В окне материалов лупы «+» / «−» — инструменты масштаба: выберите лупу, затем кликните по материалу в предпросмотре пульта.\n\nПри смене сцены показ материалов сбрасывается. Описание сцены и эффекты поля с материалами не связаны.',
'help.section.players.title': 'Игроки', 'help.section.players.title': 'Игроки',
'help.section.players.body': 'help.section.players.body':
'Раздел «Игроки» в шапке хранит локальную библиотеку живых игроков на этом компьютере (не внутри файла проекта).\n\n1) Откройте «Игроки» в шапке.\n\n2) «Добавить игрока» — имя и изображение обязательны. Пока идёт сохранение, видно окно с прогрессом.\n\n3) Справа — превью игрового токена: круг с цветной рамкой, аватар внутри (перетащите мышью, чтобы отцентровать; колесо мыши — увеличить/уменьшить), имя на тёмной подложке и выбор цвета рамки.\n\n4) Команды — плоские группы без вложенности: создайте команду, перетащите игрока в неё или в «Без команды».\n\nКампанийных НПС на сцену ставят отдельно: в «Редактор сцены» аккордеон «НПС» — плитки персонажей проекта, на карте они выглядят как такой же круглый токен.', 'Раздел «Игроки» в шапке хранит локальную библиотеку живых игроков на этом компьютере (не внутри файла проекта).\n\n1) Откройте «Игроки» в шапке.\n\n2) «Добавить игрока» — имя и изображение обязательны. Пока идёт сохранение, видно окно с прогрессом.\n\n3) Справа — превью игрового токена: круг с цветной рамкой, аватар внутри (перетащите мышью, чтобы отцентровать; колесо мыши — увеличить/уменьшить), имя на тёмной подложке и выбор цвета рамки.\n\n4) Команды — плоские группы без вложенности: создайте команду, перетащите игрока в неё или в «Без команды».\n\nКампанийных НПС на сцену ставят отдельно: в «Редактор сцены» аккордеон «НПС» — плитки персонажей проекта, на карте они выглядят как такой же круглый токен.\n\nВо время сессии размер круглых токенов игроков и НПС на пульте можно менять ползунком «Размеры игр. токенов» (см. «Пульт управления»).',
'help.section.npcs.title': 'НПС', 'help.section.npcs.title': 'НПС',
'help.section.npcs.body': 'help.section.npcs.body':
'НПС — персонажи кампании с аватаром, описанием и однонаправленными связями между собой. Они общие для проекта.\n\nВ редакторе:\n\n1) В блоке «Свойства игры» нажмите «НПС» — откроется отдельное окно редактора персонажей.\n\n2) «Добавить» — укажите уникальное имя и обязательный аватар (PNG, JPG или WebP): кнопка выбора или перетаскивание файла. При необходимости сразу заполните описание.\n\n3) Слева — список персонажей: поиск, порядок перетаскиванием; меню «⋮» — только удаление (с подтверждением; все связи с этим персонажем тоже удаляются).\n\n4) В центре — граф связей: протяните стрелку от одного персонажа к другому и укажите обязательное название связи.\n\n5) Справа — карточка выбранного персонажа: настройте круглый токен, цвет рамки и положение аватара (перетаскивание и колесо мыши для масштаба), а также имя, описание и отношения.\n\n6) В «Редакторе сцены» раскройте «НПС» и перетащите персонажа на карту. Круглый токен можно двигать и менять его размер; во время сессии он доступен на пульте и только отображается в презентации.', 'НПС — персонажи кампании с аватаром, описанием и однонаправленными связями между собой. Они общие для проекта.\n\nВ редакторе:\n\n1) В блоке «Свойства игры» нажмите «НПС» — откроется отдельное окно редактора персонажей.\n\n2) «Добавить» — укажите уникальное имя и обязательный аватар (PNG, JPG или WebP): кнопка выбора или перетаскивание файла. При необходимости сразу заполните описание.\n\n3) Слева — список персонажей: поиск, порядок перетаскиванием; меню «⋮» — только удаление (с подтверждением; все связи с этим персонажем тоже удаляются). Персонажей можно объединять в группы (и подгруппы): создайте группу и перетащите НПС в неё или оставьте «Без группы». На графе связей доступен фильтр по группе.\n\n4) В центре — граф связей: протяните стрелку от одного персонажа к другому и укажите обязательное название связи.\n\n5) Справа — карточка выбранного персонажа: настройте круглый токен, цвет рамки, положение аватара (перетаскивание и колесо мыши для масштаба), имя, описание, группу и отношения. Поле «Тип» задаёт отношение: враждебный, нейтральный или дружественный — от этого зависит цвет кольца токена на карте.\n\n6) В «Редакторе сцены» раскройте «НПС» и перетащите персонажа на карту. Круглый токен можно двигать и менять его размер.\n\nВо время сессии на пульте токен НПС можно двигать; правый клик по маркеру:\n• если токен неактивен — «Сделать активным»;\n• если активен — «Открыть информацию» (карточка НПС), смена типа (враждебный / нейтральный / дружественный) и «Сделать неактивным».\nНа презентации токены только отображаются. Подробнее о пульте — в разделе «Пульт управления».',
'help.section.session.title': 'Запуск сессии', 'help.section.session.title': 'Запуск сессии',
'help.section.session.body': 'help.section.session.body':
@@ -219,7 +219,7 @@ export const EDITOR_MESSAGES: Record<EditorLocale, Record<string, string>> = {
'help.section.controlPanel.title': 'Пульт управления', 'help.section.controlPanel.title': 'Пульт управления',
'help.section.controlPanel.body': 'help.section.controlPanel.body':
'Пульт — ваш стол во время игры. Игроки смотрят на презентацию, вы управляете всем отсюда.\n\nСлева сверху — «Инструменты», затем эффекты и ход сюжета; справа — мини-копия экрана игроков, варианты переходов и музыка.\n\nВ «Инструменты» кнопка с книгой открывает отдельное окно с оформленным описанием текущей сцены. Если описания нет, кнопка неактивна — при наведении подсказка «Описание отсутствует». Кнопка материалов (иконка карты) открывает окно со списком материалов кампании — подробнее в разделе «Материалы». Кнопка НПС (цветная иконка человека) открывает окно персонажей — см. раздел «НПС».\n\n«Предпросмотр экрана» показывает то же, что видят игроки. На сценах с картинкой здесь же рисуют эффекты — они сразу появляются на большом экране. Если на сцене расставлены ловушки, они видны на предпросмотре: правый клик по маркеру — проявить, активировать или обезвредить (см. «Ловушки»). Неигровые токены тоже видны на предпросмотре и их можно двигать до конца сессии (см. «Неигровые токены»).\n\n«Сюжетная линия» — цепочка пройденных эпизодов. Текущая сцена помечена «ТЕКУЩАЯ СЦЕНА». Клик по прошлому шагу переносит партию к тому месту на карте и добавляет новый шаг в историю.\n\n«Выключить демонстрацию» — закончить показ и вернуться в редактор.', 'Пульт — ваш стол во время игры. Игроки смотрят на презентацию, вы управляете всем отсюда.\n\nСлева сверху — «Инструменты», затем эффекты и ход сюжета; справа — мини-копия экрана игроков, варианты переходов и музыка.\n\nВ «Инструменты» кнопка с книгой открывает отдельное окно с оформленным описанием текущей сцены. Если описания нет, кнопка неактивна — при наведении подсказка «Описание отсутствует». Кнопка материалов (иконка карты) открывает окно со списком материалов кампании — подробнее в разделе «Материалы». Кнопка НПС (цветная иконка человека) открывает окно персонажей — см. раздел «НПС».\n\n«Предпросмотр экрана» показывает то же, что видят игроки. Здесь же рисуют эффекты — они сразу появляются на большом экране (и на картинке, и на видео). Если на сцене расставлены ловушки, они видны на предпросмотре: правый клик по маркеру — проявить, активировать или обезвредить (см. «Ловушки»). Неигровые токены и токены НПС тоже видны на предпросмотре и их можно двигать до конца сессии; ПКМ по токену НПС — активировать / открыть информацию / сменить тип / сделать неактивным (см. «НПС»). На видео-сценах внизу превью остаются кнопки воспроизведения и полоса перемотки.\n\nНад превью:\n• «Привязка токенов к сетке» — если на сцене включена сетка, перетаскиваемые токены (неигровые, НПС, игроки) встают по клеткам;\n• «Размеры игр. токенов» — общий масштаб круглых токенов игроков и НПС на предпросмотре и презентации;\n• «Показать игроков» / «Скрыть игроков» — после запуска с игроками.\n\n«Сюжетная линия» — цепочка пройденных эпизодов. Текущая сцена помечена «ТЕКУЩАЯ СЦЕНА». Клик по прошлому шагу переносит партию к тому месту на карте и добавляет новый шаг в историю.\n\n«Выключить демонстрацию» — закончить показ и вернуться в редактор.',
'help.section.transitions.title': 'Переходы между сценами', 'help.section.transitions.title': 'Переходы между сценами',
'help.section.transitions.body': 'help.section.transitions.body':
@@ -231,7 +231,7 @@ export const EDITOR_MESSAGES: Record<EditorLocale, Record<string, string>> = {
'help.section.effects.title': 'Эффекты поля и действий', 'help.section.effects.title': 'Эффекты поля и действий',
'help.section.effects.body': 'help.section.effects.body':
'Эффекты работают на сценах с картинкой, не на видео. Рисуйте в «Предпросмотр экрана» — игроки увидят то же на презентации.\n\nВыберите инструмент слева:\n• Эффекты поля (туман, дождь, огонь, вода) — зажмите левую кнопку и ведите по карте.\n• Эффекты действий (молния, луч света, заморозка, тьма, облако яда, взрыв) — короткий клик или штрих; у некоторых есть звук.\n\nЕсли у сцены в свойствах включено «Затемнить сцену», появится блок «Управление затемнением» с «Кистью Открытия» 🔦 и «Кистью Закрытия» ⬛. «Кисть Открытия» снимает тьму на обоих экранах сразу; «Кисть Закрытия» снова накрывает уже открытые участки. У игроков нераскрытое остаётся чёрным, у вас на пульте — полузатемнённым. Состояние сохраняется, пока идёт показ и вы снова попадаете на ту же карточку сцены на карте. Это не то же самое, что эффект «Тьма» 🌑 в блоке действий.\n\nЛастик 🧹 — для эффектов поля (туман, дождь, огонь, вода) водите кистью, как «Кистью Открытия» для затемнения: стирается только пройденный участок. Эффекты действий (молния, луч и т.д.) убираются целиком при клике или проведении по ним. «Очистить эффекты» — снять всё сразу.\n\n«Радиус кисти» под панелью — чем больше число, тем шире мазок.', 'Эффекты работают на сценах с картинкой и с видео. Рисуйте в «Предпросмотр экрана» — игроки увидят то же на презентации.\n\nВыберите инструмент слева:\n• Эффекты поля (туман, дождь, огонь, вода) — зажмите левую кнопку и ведите по карте.\n• Эффекты действий (молния, луч света, заморозка, тьма, облако яда, взрыв) — короткий клик или штрих; у некоторых есть звук.\n\nЕсли у сцены в свойствах включено «Затемнить сцену», появится блок «Управление затемнением» с «Кистью Открытия» 🔦 и «Кистью Закрытия» ⬛. «Кисть Открытия» снимает тьму на обоих экранах сразу; «Кисть Закрытия» снова накрывает уже открытые участки. У игроков нераскрытое остаётся чёрным, у вас на пульте — полузатемнённым. Состояние сохраняется, пока идёт показ и вы снова попадаете на ту же карточку сцены на карте. Это не то же самое, что эффект «Тьма» 🌑 в блоке действий.\n\nЛастик 🧹 — для эффектов поля (туман, дождь, огонь, вода) водите кистью, как «Кистью Открытия» для затемнения: стирается только пройденный участок. Эффекты действий (молния, луч и т.д.) убираются целиком при клике или проведении по ним. «Очистить эффекты» — снять всё сразу.\n\n«Радиус кисти» под панелью — чем больше число, тем шире мазок.',
'help.section.presentation.title': 'Экран презентации', 'help.section.presentation.title': 'Экран презентации',
'help.section.presentation.body': 'help.section.presentation.body':
@@ -800,23 +800,23 @@ export const EDITOR_MESSAGES: Record<EditorLocale, Record<string, string>> = {
'help.section.sceneProps.title': 'Scene properties', 'help.section.sceneProps.title': 'Scene properties',
'help.section.sceneProps.body': 'help.section.sceneProps.body':
'Select a scene in the left list — its properties open on the right.\n\nScene title is for the GM. Description is GM notes with formatting: click the pencil next to the label to open the editor (bold, italic, headings, lists, links). Below the label you see a text preview, or “no description” when empty. During a session, open the description from the control panel in a separate window (see Control panel) — it is not shown inside the Storyline list.\n\nIf the scene has a graph card with a blue SIDE badge, a Side storyline title field appears.\n\nImage or video for players:\n\n1) Under Scene preview, click Upload or Change.\n\n2) Pick a file (PNG, JPG, WebP, GIF, etc.).\n\n3) For images, use Rotate (90° steps). Clear removes the preview.\n\n4) For images, enable Darken scene so players start in full darkness and you reveal the map with the Opening brush on the control panel (see Effects).\n\n5) For images, Scene editor opens the battle grid, traps, and non-player tokens on the map (see Scene editor, Grid generator, Traps, and Non-player tokens).\n\nFor video, enable Autostart if the clip should start on its own on the player screen. Brush effects and the scene editor are not available on video scenes.\n\nScene audio — music and sounds for this episode. Upload adds files. Per track: Auto (play when entering the scene) and Loop. The trash icon removes a track.\n\nLinks between scenes are drawn on the map, not here — see Scene graph.', 'Select a scene in the left list — its properties open on the right.\n\nScene title is for the GM. Description is GM notes with formatting: click the pencil next to the label to open the editor (bold, italic, headings, lists, links). Below the label you see a text preview, or “no description” when empty. During a session, open the description from the control panel in a separate window (see Control panel) — it is not shown inside the Storyline list.\n\nIf the scene has a graph card with a blue SIDE badge, a Side storyline title field appears.\n\nImage or video for players:\n\n1) Under Scene preview, click Upload or Change.\n\n2) Pick a file (PNG, JPG, WebP, GIF, video, etc.).\n\n3) For images, use Rotate (90° steps). Clear removes the preview.\n\n4) For images and video, enable Darken scene so players start in full darkness and you reveal the frame with the Opening brush on the control panel (see Effects).\n\n5) Scene editor works for both images and video — battle grid, traps, and non-player tokens over the preview (see Scene editor, Grid generator, Traps, and Non-player tokens).\n\nFor video, enable Autostart if the clip should start on its own on the player screen, and Loop if needed.\n\nScene audio — music and sounds for this episode. Upload adds files. Per track: Auto (play when entering the scene) and Loop. The trash icon removes a track.\n\nLinks between scenes are drawn on the map, not here — see Scene graph.',
'help.section.sceneEditor.title': 'Scene editor', 'help.section.sceneEditor.title': 'Scene editor',
'help.section.sceneEditor.body': 'help.section.sceneEditor.body':
'Scene editor is a separate window for preparing the map: battle grid, traps, non-player tokens, and circular NPC tokens. It is available only for image scenes (not video).\n\nOpen it:\n\n1) Select a scene in the left list.\n\n2) In Scene properties, upload an image if the scene has none yet.\n\n3) Click Scene editor.\n\nOn the left are the Grid, Non-player tokens, NPCs, and Traps accordions; on the right is the scene map. Drag an NPC onto the map to add its circular token.\n\nMap navigation: mouse wheel zooms; middle mouse button or Space+left-drag pans the view. Delete / Backspace removes the selected marker on the map.\n\nUnder the accordions, Clear scene removes every trap and token from the current map (it does not delete tokens from the app library).\n\nFor details, see Grid generator, Traps, and Non-player tokens.', 'Scene editor is a separate window for preparing the map: battle grid, traps, non-player tokens, and circular NPC tokens. It works for image and video scenes (overlays sit on top of the clip).\n\nOpen it:\n\n1) Select a scene in the left list.\n\n2) In Scene properties, upload an image or video if the scene has none yet.\n\n3) Click Scene editor.\n\nOn the left are the Grid, Non-player tokens, NPCs, and Traps accordions; on the right is the scene map. Drag an NPC onto the map to add its circular token.\n\nMap navigation: mouse wheel zooms; middle mouse button or Space+left-drag pans the view. Delete / Backspace removes the selected marker on the map.\n\nUnder the accordions, Clear scene removes every trap and token from the current map (it does not delete tokens from the app library).\n\nFor details, see Grid generator, Traps, and Non-player tokens.',
'help.section.grid.title': 'Grid generator', 'help.section.grid.title': 'Grid generator',
'help.section.grid.body': 'help.section.grid.body':
'The grid generator overlays a battle grid on the scene image — square or hexagonal. It helps track cells in combat and is visible both on your control panel and on the players presentation.\n\nSet it up:\n\n1) Open Scene editor for an image scene (see Scene editor).\n\n2) Expand the Grid accordion on the left.\n\n3) Enable Overlay grid — lines appear over the map.\n\n4) Type — Square or Hexagonal.\n\n5) Color — line tint (pick contrast that suits the map).\n\n6) Size — cell size slider: higher values mean larger cells.\n\nWhile the grid is off, type, color, and size stay disabled, but the saved values return when you turn it back on.\n\nGrid settings are stored with the scene in the project. The generator is not available on video scenes — only on images. The grid draws under trap and token markers and does not block placing them.', 'The grid generator overlays a battle grid on the scene preview (image or video) — square or hexagonal. It helps track cells in combat and is visible both on your control panel and on the players presentation.\n\nSet it up:\n\n1) Open Scene editor (see Scene editor).\n\n2) Expand the Grid accordion on the left.\n\n3) Enable Overlay grid — lines appear over the map.\n\n4) Type — Square or Hexagonal.\n\n5) Color — line tint (pick contrast that suits the map).\n\n6) Size — cell size slider: higher values mean larger cells.\n\nWhile the grid is off, type, color, and size stay disabled, but the saved values return when you turn it back on.\n\nGrid settings are stored with the scene in the project. The grid draws under trap and token markers and does not block placing them.\n\nDuring a session you can enable Snap tokens to grid on the control panel: dragging non-player tokens, NPC tokens, and player tokens snaps them to cells (square or hex, matching the grid type). If the grid is off, the checkbox has no effect.',
'help.section.traps.title': 'Traps', 'help.section.traps.title': 'Traps',
'help.section.traps.body': 'help.section.traps.body':
'Traps are markers on the scene map for hidden threats and surprises. Placement is stored with the scene in the project; during play you decide when players see them.\n\nIn the scene editor:\n\n1) Open Scene editor for an image scene (see Scene editor).\n\n2) Expand the Traps accordion on the left.\n\n3) Drag a type from the palette onto the map.\n\n4) Drag a marker to move it; drag the corner handle of the selected marker to resize.\n\n5) Delete / Backspace removes the selected trap. Clear scene removes all markers at once.\n\nTypes: Mimic, Explosion, Poison, Pit, Arrow, Laser, and Marker (a generic marker without a special effect).\n\nDuring a session:\n\n1) On the control panel Screen preview you see every trap on the current scene. While still hidden from players, markers look slightly muted on your side.\n\n2) On presentation, markers appear only after reveal or activation.\n\n3) Right-click a marker on the control panel:\n• Reveal — show it to players without triggering.\n• Activate — reveal and play the effect: Mimic, Pit, Arrow, and Laser play animation and sound; Poison and Explosion use the matching control-panel effects (poison cloud / explosion); Marker shows a short flash.\n• Disarm — show it as disarmed.\n\nTrap runtime state (revealed / triggered / disarmed) resets when you start a new session. Markers placed on the map remain.', 'Traps are markers on the scene map for hidden threats and surprises. Placement is stored with the scene in the project; during play you decide when players see them.\n\nIn the scene editor:\n\n1) Open Scene editor for an image or video scene (see Scene editor).\n\n2) Expand the Traps accordion on the left.\n\n3) Drag a type from the palette onto the map.\n\n4) Drag a marker to move it; drag the corner handle of the selected marker to resize.\n\n5) Delete / Backspace removes the selected trap. Clear scene removes all markers at once.\n\nTypes: Mimic, Explosion, Poison, Pit, Arrow, Laser, and Marker (a generic marker without a special effect).\n\nDuring a session:\n\n1) On the control panel Screen preview you see every trap on the current scene. While still hidden from players, markers stay clearly readable on your side (dashed outline) so you can find them on the map.\n\n2) On presentation, markers appear only after reveal or activation.\n\n3) Right-click a marker on the control panel:\n• Reveal — show it to players without triggering.\n• Activate — reveal and play the effect: Mimic, Pit, Arrow, and Laser play animation and sound; Poison and Explosion use the matching control-panel effects (poison cloud / explosion); Marker shows a short flash.\n• Disarm — show it as disarmed.\n\nTrap runtime state (revealed / triggered / disarmed) resets when you start a new session. Markers placed on the map remain.',
'help.section.tokens.title': 'Non-player tokens', 'help.section.tokens.title': 'Non-player tokens',
'help.section.tokens.body': 'help.section.tokens.body':
'Non-player tokens are images of creatures, props, and markers you place on the scene map. The token library lives in the app on this computer (not inside the project file). The scene only stores placements: which token, where it stands, size, and rotation.\n\nIn the scene editor:\n\n1) Open Scene editor for an image scene (see Scene editor).\n\n2) Expand Non-player tokens.\n\n3) Add — enter a unique name and an image (choose file or drop one).\n\n4) Use search to find a token by name.\n\n5) The ⋮ menu on a tile opens Edit or Delete (with confirmation). Deleting from the library also removes that token from the current scene.\n\n6) Drag a tile onto the map to place it. Select a marker: drag to move, corner handle to resize, rotate handle to turn. Delete / Backspace or right-click the marker removes it from the map. Clear scene removes all tokens and traps from the scene.\n\nDuring a session:\n\n1) On the control panel Screen preview, tokens are visible right away (unlike traps, they do not need revealing).\n\n2) Drag tokens with the left button — the new position is kept until the current session ends, including when you return to the scene via Storyline. A new Run resets positions to what you set in the editor.\n\n3) On the presentation screen tokens are display-only: players cannot click or drag them.\n\nWhen you export or import storylines, the needed token files are packed with the line so placements keep their images on another computer.', 'Non-player tokens are images of creatures, props, and markers you place on the scene map. The token library lives in the app on this computer (not inside the project file). The scene only stores placements: which token, where it stands, size, and rotation.\n\nIn the scene editor:\n\n1) Open Scene editor for an image or video scene (see Scene editor).\n\n2) Expand Non-player tokens.\n\n3) Add — enter a unique name and an image (choose file or drop one).\n\n4) Use search to find a token by name.\n\n5) The ⋮ menu on a tile opens Edit or Delete (with confirmation). Deleting from the library also removes that token from the current scene.\n\n6) Drag a tile onto the map to place it. Select a marker: drag to move, corner handle to resize, rotate handle to turn. Delete / Backspace or right-click the marker removes it from the map. Clear scene removes all tokens and traps from the scene.\n\nDuring a session:\n\n1) On the control panel Screen preview, tokens are visible right away (unlike traps, they do not need revealing).\n\n2) Drag tokens with the left button — the new position is kept until the current session ends, including when you return to the scene via Storyline. A new Run resets positions to what you set in the editor.\n\n3) If the scene has a grid, enable Snap tokens to grid on the control panel so dragged tokens snap to cells (see Grid generator).\n\n4) On the presentation screen tokens are display-only: players cannot click or drag them.\n\nWhen you export or import storylines, the needed token files are packed with the line so placements keep their images on another computer.',
'help.section.campaignAudio.title': 'Game audio', 'help.section.campaignAudio.title': 'Game audio',
'help.section.campaignAudio.body': 'help.section.campaignAudio.body':
@@ -824,14 +824,14 @@ export const EDITOR_MESSAGES: Record<EditorLocale, Record<string, string>> = {
'help.section.materials.title': 'Materials', 'help.section.materials.title': 'Materials',
'help.section.materials.body': 'help.section.materials.body':
'Materials are campaign images (maps, notes, sketches) you can show players on top of the scene during play. They belong to the project and are not tied to one scene.\n\nIn the editor:\n\n1) Under Game properties, click Materials.\n\n2) Add — enter a unique name and an image (PNG, JPG, or WebP) via Choose image or by dropping a file.\n\n3) In the list you can search, reorder by drag-and-drop, and edit or delete via the ⋮ menu (delete asks for confirmation).\n\n4) Under the large preview, Rotate turns the image by 90° (applied in the tile and when shown on screen).\n\nDuring a session:\n\n1) On the control panel under Tools, click the materials button (treasure-map icon) to open a separate window with the list.\n\n2) Click a tile to show the material over the scene on the control preview and presentation; click the same tile again to hide it.\n\n3) On the control preview you can drag the material and resize it from the corners; the × button closes the overlay.\n\n4) In the materials window, the + / magnifiers are zoom tools: pick one, then click the material on the control preview.\n\nChanging scenes clears the material overlay. Scene description and field effects are separate from materials.', 'Materials are campaign images (maps, notes, sketches) you can show players on top of the scene during play. They belong to the project and are not tied to one scene.\n\nIn the editor:\n\n1) Under Game properties, click Materials.\n\n2) Add — enter a unique name and an image (PNG, JPG, or WebP) via Choose image or by dropping a file.\n\n3) In the list you can search, reorder by drag-and-drop, and edit or delete via the ⋮ menu (delete asks for confirmation).\n\n4) Under the large preview, Rotate turns the image by 90° (applied in the tile and when shown on screen).\n\n5) The Legend block for the selected material: enable the legend, place numbered markers on the image, and label the list items. When shown on the control panel and presentation, the legend travels with the material.\n\nDuring a session:\n\n1) On the control panel under Tools, click the materials button (treasure-map icon) to open a separate window with the list.\n\n2) Click a tile to show the material over the scene on the control preview and presentation; click the same tile again to hide it. You can show several materials at once — one click per tile.\n\n3) On the control preview you can drag the material, resize it from the corners, and rotate it; the × button closes that material (others stay open).\n\n4) In the materials window, the + / magnifiers are zoom tools: pick one, then click the material on the control preview.\n\nChanging scenes clears material overlays. Scene description and field effects are separate from materials.',
'help.section.players.title': 'Players', 'help.section.players.title': 'Players',
'help.section.players.body': 'help.section.players.body':
'The Players item in the header stores a local library of live players on this computer (not inside the project file).\n\n1) Open Players in the header.\n\n2) Add player — name and image are required. A progress dialog appears while saving.\n\n3) On the right — player token preview: a circle with a colored ring, avatar inside (drag to recenter; mouse wheel to zoom), name on a dark plate, and a ring color picker.\n\n4) Teams are flat groups with no nesting: create a team and drag a player into it or into No team.\n\nCampaign NPCs are placed separately: in Scene editor open the NPCs accordion and drag project characters onto the map — they appear as the same circular token.', 'The Players item in the header stores a local library of live players on this computer (not inside the project file).\n\n1) Open Players in the header.\n\n2) Add player — name and image are required. A progress dialog appears while saving.\n\n3) On the right — player token preview: a circle with a colored ring, avatar inside (drag to recenter; mouse wheel to zoom), name on a dark plate, and a ring color picker.\n\n4) Teams are flat groups with no nesting: create a team and drag a player into it or into No team.\n\nCampaign NPCs are placed separately: in Scene editor open the NPCs accordion and drag project characters onto the map — they appear as the same circular token.\n\nDuring a session you can change the size of circular player and NPC tokens with the Play token size slider on the control panel (see Control panel).',
'help.section.npcs.title': 'NPCs', 'help.section.npcs.title': 'NPCs',
'help.section.npcs.body': 'help.section.npcs.body':
'NPCs are campaign characters with an avatar, description, and one-way relations between them. They belong to the project.\n\nIn the NPC editor, select a character and use the right inspector to configure their circular token: ring color, avatar position (drag), and zoom (mouse wheel) can be adjusted directly in the preview. Name, description, group, and relations remain available there as well.\n\nIn Scene editor, expand NPCs and drag a character onto the map. The circular marker can be moved and resized. During a session it remains movable on the control preview and is read-only on presentation.', 'NPCs are campaign characters with an avatar, description, and one-way relations between them. They belong to the project.\n\nIn the editor:\n\n1) Under Game properties, click NPCs to open the character editor window.\n\n2) Add — enter a unique name and a required avatar (PNG, JPG, or WebP) via Choose image or by dropping a file. Fill in the description if needed.\n\n3) On the left — character list: search, reorder by drag-and-drop; the ⋮ menu only deletes (with confirmation; relations to that character are removed too). Characters can be organized into groups (and subgroups): create a group and drag NPCs into it, or leave them Ungrouped. The relation graph has a group filter.\n\n4) In the center — relation graph: drag an arrow from one character to another and enter a required relation title.\n\n5) On the right — selected character card: circular token, ring color, avatar position (drag and mouse wheel to zoom), name, description, group, and relations. Type sets disposition: hostile, neutral, or friendly — it controls the ring color on the map.\n\n6) In Scene editor, expand NPCs and drag a character onto the map. The circular marker can be moved and resized.\n\nDuring a session on the control panel you can move NPC tokens; right-click a marker:\n• if inactive — Make active;\n• if active — Open information (NPC card), change type (hostile / neutral / friendly), and Make inactive.\nOn presentation tokens are display-only. See Control panel for more.',
'help.section.session.title': 'Starting a session', 'help.section.session.title': 'Starting a session',
'help.section.session.body': 'help.section.session.body':
@@ -839,7 +839,7 @@ export const EDITOR_MESSAGES: Record<EditorLocale, Record<string, string>> = {
'help.section.controlPanel.title': 'Control panel', 'help.section.controlPanel.title': 'Control panel',
'help.section.controlPanel.body': 'help.section.controlPanel.body':
'The control panel is your desk during play. Players watch presentation; you run everything from here.\n\nTop-left: Tools, then effects and storyline. On the right: a mini copy of the player screen, branch options, and music.\n\nUnder Tools, the book button opens a separate window with the current scenes formatted description. If there is no description, the button is disabled — the tooltip reads “No description”. The materials button (map icon) opens a window with the campaign materials list — see the Materials section for details. The NPCs button (colored person icon) opens the characters window — see the NPCs section.\n\nScreen preview shows what players see. On image scenes, paint effects here — they appear on the big screen right away. If the scene has traps, they appear on the preview: right-click a marker to reveal, activate, or disarm (see Traps). Non-player tokens are also visible on the preview and can be moved until the session ends (see Non-player tokens).\n\nStoryline lists episodes you have visited. The current scene is marked CURRENT SCENE. Click an earlier step to move the party back to that spot and add a new history entry.\n\nStop presentation ends the show and unlocks the editor.', 'The control panel is your desk during play. Players watch presentation; you run everything from here.\n\nTop-left: Tools, then effects and storyline. On the right: a mini copy of the player screen, branch options, and music.\n\nUnder Tools, the book button opens a separate window with the current scenes formatted description. If there is no description, the button is disabled — the tooltip reads “No description”. The materials button (map icon) opens a window with the campaign materials list — see the Materials section for details. The NPCs button (colored person icon) opens the characters window — see the NPCs section.\n\nScreen preview shows what players see. Paint effects here — they appear on the big screen right away for both image and video scenes. If the scene has traps, they appear on the preview: right-click a marker to reveal, activate, or disarm (see Traps). Non-player tokens and NPC tokens are also visible on the preview and can be moved until the session ends; right-click an NPC token to activate / open information / change type / make inactive (see NPCs). On video scenes, transport controls and the scrub bar stay at the bottom of the preview.\n\nAbove the preview:\n• Snap tokens to grid — when the scene grid is on, dragged tokens (non-player, NPC, players) snap to cells;\n• Play token size — shared scale for circular player and NPC tokens on the preview and presentation;\n• Show players / Hide players — after Run with players.\n\nStoryline lists episodes you have visited. The current scene is marked CURRENT SCENE. Click an earlier step to move the party back to that spot and add a new history entry.\n\nStop presentation ends the show and unlocks the editor.',
'help.section.transitions.title': 'Scene transitions', 'help.section.transitions.title': 'Scene transitions',
'help.section.transitions.body': 'help.section.transitions.body':
@@ -851,7 +851,7 @@ export const EDITOR_MESSAGES: Record<EditorLocale, Record<string, string>> = {
'help.section.effects.title': 'Field and action effects', 'help.section.effects.title': 'Field and action effects',
'help.section.effects.body': 'help.section.effects.body':
'Effects work on image scenes, not video. Paint in Screen preview — players see the same on presentation.\n\nPick a tool on the left:\n• Field effects (fog, rain, fire, water) — hold the left button and brush on the map.\n• Action effects (lightning, sunbeam, freeze, darkness, poison cloud, explosion) — click or short stroke; some include sound.\n\nIf Darken scene is enabled in scene properties, a Darkness control section appears with the Opening brush 🔦 and Closing brush ⬛. Opening brush clears darkness on both screens at once; Closing brush covers revealed areas again. Unrevealed areas stay fully black for players and half-dark on your preview. The state is remembered while the show runs and you return to the same graph card. This is not the same as the Darkness 🌑 action effect.\n\nEraser 🧹 — for field effects (fog, rain, fire, water), brush like the Opening brush for darkness: only the stroke area is erased. Action effects (lightning, sunbeam, etc.) are removed whole when you click or drag over them. Clear effects removes everything at once.\n\nBrush radius under the panel — higher values mean a wider stroke.', 'Effects work on image and video scenes. Paint in Screen preview — players see the same on presentation.\n\nPick a tool on the left:\n• Field effects (fog, rain, fire, water) — hold the left button and brush on the map.\n• Action effects (lightning, sunbeam, freeze, darkness, poison cloud, explosion) — click or short stroke; some include sound.\n\nIf Darken scene is enabled in scene properties, a Darkness control section appears with the Opening brush 🔦 and Closing brush ⬛. Opening brush clears darkness on both screens at once; Closing brush covers revealed areas again. Unrevealed areas stay fully black for players and half-dark on your preview. The state is remembered while the show runs and you return to the same graph card. This is not the same as the Darkness 🌑 action effect.\n\nEraser 🧹 — for field effects (fog, rain, fire, water), brush like the Opening brush for darkness: only the stroke area is erased. Action effects (lightning, sunbeam, etc.) are removed whole when you click or drag over them. Clear effects removes everything at once.\n\nBrush radius under the panel — higher values mean a wider stroke.',
'help.section.presentation.title': 'Presentation screen', 'help.section.presentation.title': 'Presentation screen',
'help.section.presentation.body': 'help.section.presentation.body':
+24 -9
View File
@@ -50,6 +50,7 @@ import { useEditorI18n } from '../editor/i18n/EditorI18nContext';
import { getDndApi } from '../shared/dndApi'; import { getDndApi } from '../shared/dndApi';
import { EllipsisText } from '../shared/ui/EllipsisText'; import { EllipsisText } from '../shared/ui/EllipsisText';
import ellipsisStyles from '../shared/ui/ellipsisText.module.css'; import ellipsisStyles from '../shared/ui/ellipsisText.module.css';
import { ContainedVideo } from '../shared/ContainedVideo';
import { SceneGridOverlay } from '../shared/grid/SceneGridOverlay'; import { SceneGridOverlay } from '../shared/grid/SceneGridOverlay';
import { PlayerTokenView } from '../shared/playerToken/PlayerTokenView'; import { PlayerTokenView } from '../shared/playerToken/PlayerTokenView';
import { RotatedImage } from '../shared/RotatedImage'; import { RotatedImage } from '../shared/RotatedImage';
@@ -521,6 +522,8 @@ export function SceneEditorApp() {
const editingToken = const editingToken =
tokenModal?.mode === 'edit' ? (appTokens.find((t) => t.id === tokenModal.tokenId) ?? null) : null; tokenModal?.mode === 'edit' ? (appTokens.find((t) => t.id === tokenModal.tokenId) ?? null) : null;
const isImage = scene?.previewAssetType === 'image' && Boolean(url); const isImage = scene?.previewAssetType === 'image' && Boolean(url);
const isVideo = scene?.previewAssetType === 'video' && Boolean(url);
const hasMapMedia = isImage || isVideo;
return ( return (
<div className={styles.page}> <div className={styles.page}>
@@ -703,8 +706,8 @@ export function SceneEditorApp() {
</aside> </aside>
<div className={styles.stage}> <div className={styles.stage}>
{!isImage ? ( {!hasMapMedia ? (
<div className={styles.empty}>Нужно изображение сцены</div> <div className={styles.empty}>Нужно изображение или видео сцены</div>
) : ( ) : (
<div <div
ref={hostRef} ref={hostRef}
@@ -808,13 +811,25 @@ export function SceneEditorApp() {
dragRef.current = null; dragRef.current = null;
}} }}
> >
<RotatedImage {isImage ? (
url={url!} <RotatedImage
rotationDeg={rot} url={url!}
mode="contain" rotationDeg={rot}
viewCamera={viewCamera} mode="contain"
onContentRectChange={setContentRect} viewCamera={viewCamera}
/> onContentRectChange={setContentRect}
/>
) : (
<ContainedVideo
url={url!}
muted
playsInline
loop
preload="metadata"
viewCamera={viewCamera}
onContentRectChange={setContentRect}
/>
)}
<SceneGridOverlay grid={localGrid} viewport={contentRect} /> <SceneGridOverlay grid={localGrid} viewport={contentRect} />
{contentRect {contentRect
? localTokens.map((tok) => { ? localTokens.map((tok) => {
@@ -0,0 +1,16 @@
.root {
width: 100%;
height: 100%;
position: relative;
overflow: hidden;
}
.video {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
transform-origin: center;
display: block;
background: #000;
}
+158
View File
@@ -0,0 +1,158 @@
import React, { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { containMediaRect } from '../../shared/types/containMediaRect';
import { DEFAULT_SCENE_VIEW_CAMERA, type SceneViewCamera } from '../../shared/types/sceneView';
import styles from './ContainedVideo.module.css';
export type ContainedVideoProps = {
url: string;
/** Зум/пан как у RotatedImage в mode=contain. */
viewCamera?: SceneViewCamera | null;
onContentRectChange?: ((rect: { x: number; y: number; w: number; h: number }) => void) | undefined;
videoRef?: React.Ref<HTMLVideoElement | null>;
loop?: boolean;
muted?: boolean;
playsInline?: boolean;
preload?: React.VideoHTMLAttributes<HTMLVideoElement>['preload'];
className?: string;
style?: React.CSSProperties;
onTimeUpdate?: React.VideoHTMLAttributes<HTMLVideoElement>['onTimeUpdate'];
onLoadedMetadata?: React.VideoHTMLAttributes<HTMLVideoElement>['onLoadedMetadata'];
onError?: React.VideoHTMLAttributes<HTMLVideoElement>['onError'];
children?: React.ReactNode;
};
function useElementSize<T extends HTMLElement>() {
const ref = useRef<T | null>(null);
const [size, setSize] = useState<{ w: number; h: number }>({ w: 0, h: 0 });
useEffect(() => {
const el = ref.current;
if (!el) return;
const readLayoutSize = () => {
setSize({ w: el.clientWidth, h: el.clientHeight });
};
const ro = new ResizeObserver(() => {
readLayoutSize();
});
ro.observe(el);
readLayoutSize();
return () => ro.disconnect();
}, []);
return [ref, size] as const;
}
function assignRef<T>(ref: React.Ref<T> | undefined, value: T): void {
if (!ref) return;
if (typeof ref === 'function') {
ref(value);
return;
}
(ref as React.MutableRefObject<T>).current = value;
}
/**
* Video laid out like RotatedImage(mode=contain): reports the visible content rect
* so grid / traps / tokens / effects align with the letterboxed frame.
*/
export function ContainedVideo({
url,
viewCamera = null,
onContentRectChange,
videoRef,
loop = false,
muted = false,
playsInline = true,
preload = 'auto',
className,
style,
onTimeUpdate,
onLoadedMetadata,
onError,
children,
}: ContainedVideoProps) {
const [hostRef, size] = useElementSize<HTMLDivElement>();
const [mediaSize, setMediaSize] = useState<{ w: number; h: number } | null>(null);
const elRef = useRef<HTMLVideoElement | null>(null);
const cam = viewCamera ?? DEFAULT_SCENE_VIEW_CAMERA;
const viewScale = Math.max(1, cam.scale);
const viewOx = cam.ox;
const viewOy = cam.oy;
const syncMediaSize = (el: HTMLVideoElement) => {
const w0 = el.videoWidth || 0;
const h0 = el.videoHeight || 0;
if (w0 <= 0 || h0 <= 0) return;
setMediaSize((prev) => (prev && prev.w === w0 && prev.h === h0 ? prev : { w: w0, h: h0 }));
};
useLayoutEffect(() => {
const el = elRef.current;
if (!el) return;
if (el.readyState >= 1) syncMediaSize(el);
}, [url]);
const contentRect = useMemo(() => {
if (!mediaSize) return null;
return containMediaRect({
hostW: size.w,
hostH: size.h,
mediaW: mediaSize.w,
mediaH: mediaSize.h,
scale: viewScale,
ox: viewOx,
oy: viewOy,
});
}, [mediaSize, size.h, size.w, viewOx, viewOy, viewScale]);
useEffect(() => {
if (!onContentRectChange || !contentRect) return;
onContentRectChange(contentRect);
}, [contentRect, onContentRectChange]);
const w = contentRect?.w;
const h = contentRect?.h;
const leftPx = contentRect ? contentRect.x + contentRect.w / 2 : undefined;
const topPx = contentRect ? contentRect.y + contentRect.h / 2 : undefined;
return (
<div
ref={hostRef}
className={[styles.root, className].filter(Boolean).join(' ')}
style={style}
>
<video
ref={(el) => {
elRef.current = el;
assignRef(videoRef, el);
}}
className={styles.video}
src={url}
loop={loop}
muted={muted}
playsInline={playsInline}
preload={preload}
draggable={false}
onTimeUpdate={onTimeUpdate}
onLoadedMetadata={(e) => {
syncMediaSize(e.currentTarget);
onLoadedMetadata?.(e);
}}
onError={onError}
style={{
width: w ?? '100%',
height: h ?? '100%',
left: leftPx !== undefined ? `${String(leftPx)}px` : '50%',
top: topPx !== undefined ? `${String(topPx)}px` : '50%',
objectFit: mediaSize ? undefined : 'contain',
transform: 'translate(-50%, -50%)',
}}
>
{children}
</video>
</div>
);
}
+31 -20
View File
@@ -29,6 +29,7 @@ import { useSceneTokensSession } from './tokens/useSceneTokensSession';
import { SceneTrapsOverlay } from './traps/SceneTrapsOverlay'; import { SceneTrapsOverlay } from './traps/SceneTrapsOverlay';
import { useSceneTrapsState } from './traps/useSceneTrapsState'; import { useSceneTrapsState } from './traps/useSceneTrapsState';
import styles from './PresentationView.module.css'; import styles from './PresentationView.module.css';
import { ContainedVideo } from './ContainedVideo';
import { RotatedImage } from './RotatedImage'; import { RotatedImage } from './RotatedImage';
import { useAssetUrl } from './useAssetImageUrl'; import { useAssetUrl } from './useAssetImageUrl';
import { useVideoPlaybackState } from './video/useVideoPlaybackState'; import { useVideoPlaybackState } from './video/useVideoPlaybackState';
@@ -171,26 +172,29 @@ export function PresentationView({
/> />
</div> </div>
) : originalUrl && scene?.previewAssetType === 'video' ? ( ) : originalUrl && scene?.previewAssetType === 'video' ? (
<video <div className={styles.fill}>
ref={videoElRef} <ContainedVideo
className={styles.video} url={originalUrl}
src={originalUrl} videoRef={videoElRef}
muted muted
playsInline playsInline
loop={Boolean(scene?.settings?.loopVideo)} loop={Boolean(scene?.settings?.loopVideo)}
preload="auto" preload="auto"
onError={() => { viewCamera={sceneView}
// noop: status surfaced in control app; keep presentation clean onContentRectChange={setContentRect}
}} onError={() => {
/> // noop: status surfaced in control app; keep presentation clean
}}
/>
</div>
) : ( ) : (
<div className={styles.placeholderBg} /> <div className={styles.placeholderBg} />
)} )}
{scene?.previewAssetType === 'image' ? ( {scene?.previewAssetType === 'image' || scene?.previewAssetType === 'video' ? (
<SceneGridOverlay grid={scene.grid} viewport={contentRect} /> <SceneGridOverlay grid={scene.grid} viewport={contentRect} />
) : null} ) : null}
<div className={styles.vignette} /> <div className={styles.vignette} />
{scene?.previewAssetType === 'image' && contentRect ? ( {(scene?.previewAssetType === 'image' || scene?.previewAssetType === 'video') && contentRect ? (
<SceneTokensOverlay <SceneTokensOverlay
placements={scene.tokens ?? []} placements={scene.tokens ?? []}
library={appTokens} library={appTokens}
@@ -198,7 +202,9 @@ export function PresentationView({
viewport={contentRect} viewport={contentRect}
/> />
) : null} ) : null}
{USERS_BRANCH_FEATURES_ENABLED && scene?.previewAssetType === 'image' && contentRect ? ( {USERS_BRANCH_FEATURES_ENABLED &&
(scene?.previewAssetType === 'image' || scene?.previewAssetType === 'video') &&
contentRect ? (
<SceneNpcTokensOverlay <SceneNpcTokensOverlay
placements={scene.npcTokens ?? []} placements={scene.npcTokens ?? []}
library={project?.npcs ?? []} library={project?.npcs ?? []}
@@ -207,7 +213,9 @@ export function PresentationView({
grid={scene.grid} grid={scene.grid}
/> />
) : null} ) : null}
{USERS_BRANCH_FEATURES_ENABLED && scene?.previewAssetType === 'image' && contentRect ? ( {USERS_BRANCH_FEATURES_ENABLED &&
(scene?.previewAssetType === 'image' || scene?.previewAssetType === 'video') &&
contentRect ? (
<ScenePlayerTokensOverlay <ScenePlayerTokensOverlay
library={appPlayers} library={appPlayers}
session={scenePlayerTokensSession} session={scenePlayerTokensSession}
@@ -216,7 +224,7 @@ export function PresentationView({
grid={scene.grid} grid={scene.grid}
/> />
) : null} ) : null}
{scene?.previewAssetType === 'image' && contentRect ? ( {(scene?.previewAssetType === 'image' || scene?.previewAssetType === 'video') && contentRect ? (
<SceneTrapsOverlay <SceneTrapsOverlay
traps={scene.traps ?? []} traps={scene.traps ?? []}
session={sceneTraps} session={sceneTraps}
@@ -224,7 +232,7 @@ export function PresentationView({
mode="presentation" mode="presentation"
/> />
) : null} ) : null}
{showEffects && scene?.previewAssetType !== 'video' ? ( {showEffects && (scene?.previewAssetType === 'image' || scene?.previewAssetType === 'video') ? (
<PixiEffectsOverlay <PixiEffectsOverlay
state={fxState} state={fxState}
style={{ zIndex: 6 }} style={{ zIndex: 6 }}
@@ -235,10 +243,13 @@ export function PresentationView({
} }
/> />
) : null} ) : null}
{showEffects && scene?.previewAssetType !== 'video' ? ( {showEffects && (scene?.previewAssetType === 'image' || scene?.previewAssetType === 'video') ? (
<ExplosionVideoOverlay state={fxState} viewport={contentRect} /> <ExplosionVideoOverlay state={fxState} viewport={contentRect} />
) : null} ) : null}
{showEffects && scene?.previewAssetType === 'image' && scene.darkenScene && contentRect ? ( {showEffects &&
(scene?.previewAssetType === 'image' || scene?.previewAssetType === 'video') &&
scene.darkenScene &&
contentRect ? (
<SceneDarknessOverlay state={sdState} overlayAlpha={1} viewport={contentRect} style={{ zIndex: 30 }} /> <SceneDarknessOverlay state={sdState} overlayAlpha={1} viewport={contentRect} style={{ zIndex: 30 }} />
) : null} ) : null}
<SceneOverlayHost active={activeMaterialItems.length > 0 || activeNpcItems.length > 0}> <SceneOverlayHost active={activeMaterialItems.length > 0 || activeNpcItems.length > 0}>
@@ -11,13 +11,15 @@
position: absolute; position: absolute;
transform: translate(-50%, -50%); transform: translate(-50%, -50%);
border-radius: 50%; border-radius: 50%;
border: 2px solid rgba(255, 255, 255, 0.5); border: 2px solid rgba(255, 255, 255, 0.72);
background: rgba(0, 0, 0, 0.5); background: rgba(12, 14, 20, 0.62);
display: grid; display: grid;
place-items: center; place-items: center;
pointer-events: auto; pointer-events: auto;
cursor: context-menu; cursor: context-menu;
box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.35); box-shadow:
0 0 0 1px rgba(0, 0, 0, 0.45),
0 0 10px rgba(0, 0, 0, 0.35);
} }
.trapActive { .trapActive {
@@ -30,12 +32,18 @@
.trapDisarmed { .trapDisarmed {
border-color: #9ca3af; border-color: #9ca3af;
filter: grayscale(0.7); filter: grayscale(0.7);
opacity: 0.75; opacity: 0.8;
} }
.trapGmHidden { .trapGmHidden {
opacity: 0.55; /* Hidden from players, but still readable for the GM on control preview. */
opacity: 0.88;
border-style: dashed; border-style: dashed;
border-color: rgba(255, 230, 160, 0.85);
background: rgba(28, 24, 12, 0.72);
box-shadow:
0 0 0 1px rgba(0, 0, 0, 0.4),
0 0 12px rgba(255, 200, 80, 0.22);
} }
.trapNonInteractive { .trapNonInteractive {
@@ -0,0 +1,48 @@
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));
const rendererRoot = path.resolve(here, '..');
void test('video scenes share map overlays / effects with image scenes', () => {
const control = fs.readFileSync(path.join(rendererRoot, 'control/ControlApp.tsx'), 'utf8');
const presentation = fs.readFileSync(path.join(rendererRoot, 'shared/PresentationView.tsx'), 'utf8');
const sceneEditor = fs.readFileSync(path.join(rendererRoot, 'sceneEditor/SceneEditorApp.tsx'), 'utf8');
const editor = fs.readFileSync(path.join(rendererRoot, 'editor/EditorApp.tsx'), 'utf8');
const main = fs.readFileSync(path.join(rendererRoot, '../main/index.ts'), 'utf8');
assert.equal(control.includes('isVideoPreviewScene'), false);
assert.ok(fs.readFileSync(path.join(rendererRoot, 'control/ControlScenePreview.tsx'), 'utf8').includes('ContainedVideo'));
assert.ok(presentation.includes('ContainedVideo'));
assert.ok(presentation.includes("previewAssetType === 'video'"));
assert.ok(presentation.includes('SceneTrapsOverlay'));
assert.ok(presentation.includes('PixiEffectsOverlay'));
assert.ok(presentation.includes('SceneDarknessOverlay'));
assert.ok(sceneEditor.includes('ContainedVideo'));
assert.ok(sceneEditor.includes('hasMapMedia'));
assert.ok(sceneEditor.includes('Нужно изображение или видео сцены'));
assert.ok(editor.includes("previewAssetType === 'image' || previewAssetType === 'video'"));
assert.ok(editor.includes('windows.openSceneEditor'));
assert.ok(main.includes("scene?.previewAssetType === 'video'"));
assert.ok(main.includes('syncSceneDarknessForProject'));
assert.match(
main,
/darkenScene[\s\S]{0,120}previewAssetType === 'image'[\s\S]{0,80}previewAssetType === 'video'/,
);
});
void test('control traps: GM-hidden markers stay relatively bright', () => {
const css = fs.readFileSync(
path.join(rendererRoot, 'shared/traps/SceneTrapsOverlay.module.css'),
'utf8',
);
assert.ok(css.includes('.trapGmHidden'));
assert.doesNotMatch(css, /\.trapGmHidden\s*\{[^}]*opacity:\s*0\.[0-6]/);
});
+45
View File
@@ -0,0 +1,45 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { containMediaRect } from './containMediaRect';
void test('containMediaRect: letterboxes 16:9 into square host', () => {
const r = containMediaRect({
hostW: 400,
hostH: 400,
mediaW: 1920,
mediaH: 1080,
scale: 1,
ox: 0.5,
oy: 0.5,
});
assert.ok(r);
assert.ok(Math.abs(r!.w - 400) < 0.01);
assert.ok(Math.abs(r!.h - (400 * 1080) / 1920) < 0.01);
assert.ok(Math.abs(r!.x - 0) < 0.01);
assert.ok(r!.y > 0);
});
void test('containMediaRect: zoom grows rect around ox/oy', () => {
const base = containMediaRect({
hostW: 800,
hostH: 450,
mediaW: 800,
mediaH: 450,
scale: 1,
ox: 0.5,
oy: 0.5,
});
const zoomed = containMediaRect({
hostW: 800,
hostH: 450,
mediaW: 800,
mediaH: 450,
scale: 2,
ox: 0.5,
oy: 0.5,
});
assert.ok(base && zoomed);
assert.ok(zoomed!.w > base!.w);
assert.ok(zoomed!.x < base!.x);
});
+26
View File
@@ -0,0 +1,26 @@
/**
* Pure layout math shared by ContainedVideo / RotatedImage contain-mode.
* Kept free of DOM so unit tests can lock overlay alignment for video scenes.
*/
export function containMediaRect(args: {
hostW: number;
hostH: number;
mediaW: number;
mediaH: number;
scale: number;
ox: number;
oy: number;
}): { x: number; y: number; w: number; h: number } | null {
const { hostW, hostH, mediaW, mediaH, scale, ox, oy } = args;
if (hostW <= 1 || hostH <= 1 || mediaW <= 0 || mediaH <= 0) return null;
const fit = Math.min(hostW / mediaW, hostH / mediaH);
const s = fit * Math.max(1, scale);
const w = mediaW * s;
const h = mediaH * s;
return {
x: hostW / 2 - ox * w,
y: hostH / 2 - oy * h,
w,
h,
};
}
+5 -5
View File
@@ -10,15 +10,15 @@
"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/renderer/shared/ui/secondaryWindows.stability.test.ts app/renderer/npcs/tiptapEditorSafe.test.ts app/renderer/editor/state/projectState.race.test.ts app/renderer/editor/fileDrop.test.ts app/shared/graph/sceneListOrder.test.ts app/renderer/editor/graph/sceneCardById.test.ts app/renderer/editor/i18n/editorMessages.locale.test.ts app/renderer/editor/help/helpLinkify.test.ts app/renderer/editor/sceneDescriptionHtml.test.ts app/shared/graph/storylineExportImport.test.ts app/shared/foundry/foundryGraph.test.ts app/shared/ipc/contracts.mediaRemoval.test.ts app/shared/effectEraserHitTest.test.ts app/shared/fieldEffectEraser.test.ts app/renderer/control/controlApp.effectsPanel.test.ts app/renderer/control/controlApp.audioPerf.networkRegression.test.ts app/renderer/control/controlApp.brushPerf.networkRegression.test.ts app/renderer/shared/useAssetImageUrl.cache.test.ts app/main/sessionIpc.phase6.networkRegression.test.ts app/renderer/shared/sceneOverlay/sceneOverlayHost.test.ts app/renderer/shared/effects/PxiEffectsOverlay.pointer.test.ts app/renderer/shared/traps/trapActivation.test.ts app/main/windows/createWindows.editorClose.test.ts app/main/safeConsole.test.ts app/main/windows/bootWindow.test.ts app/main/effects/effectsStore.test.ts app/main/effects/sceneDarknessStore.test.ts app/main/sceneTraps/sceneTrapsStore.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 app/main/license/machineFingerprint.test.ts app/shared/types/appPlayers.test.ts app/shared/types/npcDisposition.test.ts app/shared/types/sceneGrid.test.ts app/shared/types/sceneGridSnap.test.ts app/main/tokens/tokenGridSnapSessionStore.test.ts app/shared/players/playerTeams.test.ts app/shared/players/launchPlayersSelection.test.ts app/main/players/playersStore.test.ts app/main/players/sceneNpcTokensSessionStore.test.ts app/main/players/scenePlayerTokensSessionStore.test.ts app/shared/ipc/contracts.players.test.ts && node --test scripts/build-env.test.mjs scripts/obfuscate-main.test.mjs scripts/release-mac-prep.test.mjs scripts/release-native-prep.test.mjs", "test": "tsx --test app/renderer/shared/ui/controls.tooltip.test.ts app/renderer/shared/ui/secondaryWindows.stability.test.ts app/renderer/npcs/tiptapEditorSafe.test.ts app/renderer/editor/state/projectState.race.test.ts app/renderer/editor/fileDrop.test.ts app/shared/graph/sceneListOrder.test.ts app/renderer/editor/graph/sceneCardById.test.ts app/renderer/editor/i18n/editorMessages.locale.test.ts app/renderer/editor/help/helpLinkify.test.ts app/renderer/editor/sceneDescriptionHtml.test.ts app/shared/graph/storylineExportImport.test.ts app/shared/foundry/foundryGraph.test.ts app/shared/ipc/contracts.mediaRemoval.test.ts app/shared/effectEraserHitTest.test.ts app/shared/fieldEffectEraser.test.ts app/renderer/control/controlApp.effectsPanel.test.ts app/renderer/control/controlApp.audioPerf.networkRegression.test.ts app/renderer/control/controlApp.brushPerf.networkRegression.test.ts app/renderer/shared/useAssetImageUrl.cache.test.ts app/main/sessionIpc.phase6.networkRegression.test.ts app/renderer/shared/sceneOverlay/sceneOverlayHost.test.ts app/renderer/shared/effects/PxiEffectsOverlay.pointer.test.ts app/renderer/shared/traps/trapActivation.test.ts app/renderer/shared/videoSceneMapParity.test.ts app/main/windows/createWindows.editorClose.test.ts app/main/safeConsole.test.ts app/main/windows/bootWindow.test.ts app/main/effects/effectsStore.test.ts app/main/effects/sceneDarknessStore.test.ts app/main/sceneTraps/sceneTrapsStore.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 app/main/license/machineFingerprint.test.ts app/shared/types/appPlayers.test.ts app/shared/types/npcDisposition.test.ts app/shared/types/sceneGrid.test.ts app/shared/types/sceneGridSnap.test.ts app/main/tokens/tokenGridSnapSessionStore.test.ts app/shared/players/playerTeams.test.ts app/shared/players/launchPlayersSelection.test.ts app/main/players/playersStore.test.ts app/main/players/sceneNpcTokensSessionStore.test.ts app/main/players/scenePlayerTokensSessionStore.test.ts app/shared/ipc/contracts.players.test.ts app/shared/types/containMediaRect.test.ts && node --test scripts/build-env.test.mjs scripts/obfuscate-main.test.mjs scripts/release-mac-prep.test.mjs scripts/release-native-prep.test.mjs scripts/verify-packaged-sharp.test.mjs app/main/project/sharpRuntime.test.mjs",
"format": "prettier . --check", "format": "prettier . --check",
"format:write": "prettier . --write", "format:write": "prettier . --write",
"postinstall": "patch-package", "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 && node scripts/verify-packaged-sharp.mjs",
"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 && node scripts/verify-packaged-sharp.mjs",
"pack:mac": "npm run build && node scripts/release-mac-prep.mjs && electron-builder --mac", "pack:mac": "npm run build && node scripts/release-mac-prep.mjs && electron-builder --mac && node scripts/verify-packaged-sharp.mjs",
"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 && node scripts/verify-packaged-sharp.mjs",
"pack:linux": "node scripts/release-linux-pack.mjs", "pack:linux": "node scripts/release-linux-pack.mjs",
"release": "powershell -ExecutionPolicy Bypass -File scripts/ttrpg-release/release.ps1", "release": "powershell -ExecutionPolicy Bypass -File scripts/ttrpg-release/release.ps1",
"release:all": "powershell -ExecutionPolicy Bypass -File scripts/ttrpg-release/release-all.ps1", "release:all": "powershell -ExecutionPolicy Bypass -File scripts/ttrpg-release/release-all.ps1",
+1
View File
@@ -71,3 +71,4 @@ run('npm', ['run', 'build']);
ensureReleaseNativeDeps(projectRoot, 'linux'); ensureReleaseNativeDeps(projectRoot, 'linux');
run('electron-builder', ['--linux']); run('electron-builder', ['--linux']);
normalizeLinuxReleaseNames(); normalizeLinuxReleaseNames();
run('node', [path.join(projectRoot, 'scripts', 'verify-packaged-sharp.mjs')]);
+192
View File
@@ -0,0 +1,192 @@
/**
* After electron-builder: fail the pack if sharp / @img look missing or truncated
* in release unpacked dirs. Catches AV quarantine and incomplete asarUnpack before shipping.
*/
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
/**
* @param {string} startDir
* @returns {string | null}
*/
function findAsarUnpackedNodeModules(startDir) {
const direct = path.join(startDir, 'resources', 'app.asar.unpacked', 'node_modules');
if (fs.existsSync(direct)) return direct;
// macOS: *.app/Contents/Resources/app.asar.unpacked/node_modules
if (!fs.existsSync(startDir)) return null;
for (const name of fs.readdirSync(startDir)) {
if (!name.endsWith('.app')) continue;
const macNm = path.join(
startDir,
name,
'Contents',
'Resources',
'app.asar.unpacked',
'node_modules',
);
if (fs.existsSync(macNm)) return macNm;
}
return null;
}
/**
* @param {string} filePath
* @param {number} minBytes
*/
function assertJsLooksIntact(filePath, minBytes) {
if (!fs.existsSync(filePath)) {
throw new Error(`[verify-packaged-sharp] missing: ${filePath}`);
}
const st = fs.statSync(filePath);
if (st.size < minBytes) {
throw new Error(
`[verify-packaged-sharp] truncated (${st.size} B < ${minBytes}): ${filePath}`,
);
}
const head = fs.readFileSync(filePath, { encoding: 'utf8', flag: 'r' }).slice(0, 120);
const trimmed = head.trimStart();
const ok =
trimmed.startsWith("'use strict'") ||
trimmed.startsWith('"use strict"') ||
head.includes('require(') ||
head.includes('module.exports');
if (!ok) {
throw new Error(
`[verify-packaged-sharp] sharp entry does not look like JS (corrupt?): ${filePath}`,
);
}
}
/**
* @param {string} dir
*/
function assertHasNativeBinary(dir) {
if (!fs.existsSync(dir)) {
throw new Error(`[verify-packaged-sharp] missing native package dir: ${dir}`);
}
const stack = [dir];
while (stack.length) {
const cur = stack.pop();
if (!cur) break;
for (const name of fs.readdirSync(cur)) {
const p = path.join(cur, name);
const st = fs.statSync(p);
if (st.isDirectory()) {
stack.push(p);
continue;
}
if (
name.endsWith('.node') ||
name.endsWith('.dll') ||
name.endsWith('.dylib') ||
/\.so(\.|$)/u.test(name)
) {
if (st.size < 50_000) {
throw new Error(
`[verify-packaged-sharp] native binary too small (${st.size} B): ${p}`,
);
}
return;
}
}
}
throw new Error(`[verify-packaged-sharp] no .node/.dll/.so under ${dir}`);
}
/**
* @param {{ label: string; unpackedRoot: string; imgDirs: string[] }} probe
*/
export function verifyUnpackedSharp(probe) {
const unpackedNm =
findAsarUnpackedNodeModules(probe.unpackedRoot) ??
path.join(probe.unpackedRoot, 'resources', 'app.asar.unpacked', 'node_modules');
const sharpIndex = path.join(unpackedNm, 'sharp', 'lib', 'index.js');
// Real sharp/lib/index.js is typically several KB; empty/AV-quarantined files fail here.
assertJsLooksIntact(sharpIndex, 32);
for (const img of probe.imgDirs) {
assertHasNativeBinary(path.join(unpackedNm, '@img', img));
}
}
/** @type {{ label: string; unpackedRoot: string; imgDirs: string[] }[]} */
const PROBES = [
{
label: 'win-unpacked',
unpackedRoot: path.join(root, 'release', 'win-unpacked'),
imgDirs: ['sharp-win32-x64'],
},
{
label: 'mac-arm64',
unpackedRoot: path.join(root, 'release', 'mac-arm64'),
imgDirs: ['sharp-darwin-arm64'],
},
{
label: 'mac',
unpackedRoot: path.join(root, 'release', 'mac'),
imgDirs: ['sharp-darwin-x64', 'sharp-darwin-arm64'],
},
{
label: 'linux-unpacked',
unpackedRoot: path.join(root, 'release', 'linux-unpacked'),
imgDirs: ['sharp-linux-x64', 'sharp-linux-arm64'],
},
];
/**
* Verify every existing unpacked release dir. At least one must exist.
* For multi-arch probes, require at least one listed @img package that is present.
*/
export function verifyPackagedSharpRelease(releaseRoot = root) {
const probes = PROBES.map((p) => ({
...p,
unpackedRoot: path.join(
releaseRoot,
path.relative(root, p.unpackedRoot),
),
}));
const existing = probes.filter((p) => fs.existsSync(p.unpackedRoot));
if (existing.length === 0) {
throw new Error(
'[verify-packaged-sharp] no release unpacked dir found — run electron-builder first',
);
}
for (const probe of existing) {
const nm = findAsarUnpackedNodeModules(probe.unpackedRoot);
if (!nm) {
throw new Error(
`[verify-packaged-sharp] app.asar.unpacked/node_modules missing under ${probe.unpackedRoot}`,
);
}
const presentImg = probe.imgDirs.filter((d) =>
fs.existsSync(path.join(nm, '@img', d)),
);
if (presentImg.length === 0) {
throw new Error(
`[verify-packaged-sharp] none of @img/{${probe.imgDirs.join(',')}} under ${nm}`,
);
}
verifyUnpackedSharp({ ...probe, imgDirs: presentImg });
console.log(`[verify-packaged-sharp] OK: ${probe.label}`);
}
}
function main() {
verifyPackagedSharpRelease();
}
const entry = process.argv[1] ? pathToFileURL(path.resolve(process.argv[1])).href : '';
if (import.meta.url === entry) {
try {
main();
} catch (err) {
console.error(err instanceof Error ? err.message : err);
process.exit(1);
}
}
+89
View File
@@ -0,0 +1,89 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import test from 'node:test';
import { verifyUnpackedSharp } from './verify-packaged-sharp.mjs';
void test('verifyUnpackedSharp: accepts intact layout', () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'dnd-sharp-verify-'));
try {
const nm = path.join(root, 'resources', 'app.asar.unpacked', 'node_modules');
const sharpLib = path.join(nm, 'sharp', 'lib');
fs.mkdirSync(sharpLib, { recursive: true });
fs.writeFileSync(
path.join(sharpLib, 'index.js'),
"'use strict';\nmodule.exports = require('./constructor');\n",
'utf8',
);
const imgDir = path.join(nm, '@img', 'sharp-win32-x64');
fs.mkdirSync(imgDir, { recursive: true });
fs.writeFileSync(path.join(imgDir, 'sharp.node'), Buffer.alloc(60_000, 1));
verifyUnpackedSharp({
label: 'fixture',
unpackedRoot: root,
imgDirs: ['sharp-win32-x64'],
});
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
});
void test('verifyUnpackedSharp: rejects truncated sharp index', () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'dnd-sharp-verify-'));
try {
const nm = path.join(root, 'resources', 'app.asar.unpacked', 'node_modules');
const sharpLib = path.join(nm, 'sharp', 'lib');
fs.mkdirSync(sharpLib, { recursive: true });
fs.writeFileSync(path.join(sharpLib, 'index.js'), 'x', 'utf8');
const imgDir = path.join(nm, '@img', 'sharp-win32-x64');
fs.mkdirSync(imgDir, { recursive: true });
fs.writeFileSync(path.join(imgDir, 'sharp.node'), Buffer.alloc(60_000, 1));
assert.throws(
() =>
verifyUnpackedSharp({
label: 'fixture',
unpackedRoot: root,
imgDirs: ['sharp-win32-x64'],
}),
/truncated|corrupt/i,
);
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
});
void test('verifyUnpackedSharp: accepts mac .app layout', () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'dnd-sharp-verify-mac-'));
try {
const nm = path.join(
root,
'TTRPGPlayer.app',
'Contents',
'Resources',
'app.asar.unpacked',
'node_modules',
);
const sharpLib = path.join(nm, 'sharp', 'lib');
fs.mkdirSync(sharpLib, { recursive: true });
fs.writeFileSync(
path.join(sharpLib, 'index.js'),
"'use strict';\nmodule.exports = {};\n",
'utf8',
);
const imgDir = path.join(nm, '@img', 'sharp-darwin-arm64');
fs.mkdirSync(imgDir, { recursive: true });
fs.writeFileSync(path.join(imgDir, 'sharp.node'), Buffer.alloc(60_000, 1));
verifyUnpackedSharp({
label: 'mac-fixture',
unpackedRoot: root,
imgDirs: ['sharp-darwin-arm64'],
});
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
});