14 Commits

Author SHA1 Message Date
Ivan Fontosh 1ab6ffd593 feat(tokens): animated paths for scene and NPC tokens
Add path editor window, session playback on control/presentation, and RMB controls. Fix live pose clock so motion no longer freezes after ~250ms.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-14 08:48:41 +08:00
Ivan Fontosh 46bec1a86a feat(scene): keep map tokens with preview rotation
When previewRotationDeg changes, remap non-player, NPC and trap
markers (plus live session token overrides) so they stay on the art.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-11 12:29:20 +08:00
Ivan Fontosh 7362a36fe5 feat(scene): rotate video previews like images
Reuse previewRotationDeg for video scenes across editor, control,
presentation and overlays via ContainedVideo layout parity.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-11 12:17:57 +08:00
Ivan Fontosh 1d94c95cc8 fix(release): upload Linux AppImage under feed x64 name
Prevent stale TTRPGPlayer-x64.AppImage on the updates host when
electron-builder leaves an x86_64 alias beside an older x64 file.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-08 18:47:20 +08:00
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
Ivan Fontosh 4456eb0277 feat(control): grid snap, NPC context actions, and overlay dim fix
Re-enable users-branch UI, snap session tokens to square/hex grid from the control preview, refine inactive/open-info NPC menus, block marker actions while an effect brush is active, and dim materials/NPC overlays only when they are open.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-06 13:48:59 +08:00
     Фонтош Иван Сергеевич e53d1ea934 chore: bump version to 1.0.28
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-04 10:19:41 +08:00
Ivan Fontosh cbb6edc378 chore(release): gate users-branch features for hotfix
Add USERS_BRANCH_FEATURES_ENABLED (off by default) to hide Players library, session tokens, and related UI while keeping the preview import fix. Restore primary Run button when the flag is off.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-04 10:15:28 +08:00
Ivan Fontosh 4e6f7321b8 fix(project): race-safe batch scene preview import and close
Serialize updateProject and preview finalize, drain before pack/close, buffer zip entries, and abort finalize cleanly when leaving the project to avoid ENOENT on multi-image drops.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-04 09:44:45 +08:00
Ivan Fontosh f75444a5dd Merge branch 'users' into main
Players library, circular NPC tokens, disposition types; keep main overlay/release fixes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-04 08:03:22 +08:00
Ivan Fontosh 0f01950cc1 feat(effects): add Closing brush as inverse of Opening brush
Allow covering revealed darkness again during darkened scene sessions.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-30 17:21:40 +08:00
Ivan Fontosh cc50e64e21 feat(players): NPC disposition types and launch-with-players session tokens
Add Hostile/Neutral/Friendly ring types with session-only inactive overrides on control, plus launch-with-players flow and live player tokens on the map.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-30 17:11:01 +08:00
Ivan Fontosh 101f595bac feat(players): app Players library and circular NPC tokens on scenes
Add userData players/teams, scene npcTokens with hex-inscribed sizing, session scale synced to presentation, and Playwright e2e coverage.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-30 13:38:35 +08:00
124 changed files with 11082 additions and 577 deletions
+3
View File
@@ -17,3 +17,6 @@ Thumbs.db
.vscode/*
!.vscode/extensions.json
*.tsbuildinfo
test-results/
playwright-report/
e2e/fixtures/sample.png
+5
View File
@@ -387,6 +387,7 @@ export async function buildProjectFromFoundryDocuments(
darkenScene: false,
traps: [],
tokens: [],
npcTokens: [],
grid: { enabled: false, type: 'square', sizeN: 0.06, color: '#ffffff' },
media: { videos: [], audios: audioRefs },
settings: {
@@ -446,6 +447,10 @@ export async function buildProjectFromFoundryDocuments(
x: 80 + (npcIndex % 4) * 220,
y: 80 + Math.floor(npcIndex / 4) * 200,
groupId,
ringColor: '#c9a227',
disposition: 'neutral',
imageOffset: { x: 0, y: 0 },
imageScale: 1,
});
npcIndex += 1;
}
+365 -37
View File
@@ -8,6 +8,7 @@ import { installStdoutEpipeGuards } from './safeConsole';
installStdoutEpipeGuards();
import { openDialogFilterLabel } from '../shared/appBranding';
import { USERS_BRANCH_FEATURES_ENABLED } from '../shared/features/usersBranchFeatures';
import { ipcChannels, type ScenePreviewImportEvent, type SessionState } from '../shared/ipc/contracts';
import {
PROJECT_ZIP_OPEN_DIALOG_FILTER,
@@ -18,6 +19,11 @@ import {
stripProjectZipExtension,
} from '../shared/project/projectZipExtension';
import type { Project } from '../shared/types';
import { asNpcId } from '../shared/types/ids';
import {
asPreviewRotationDeg,
previewRotationStepsCw,
} from '../shared/types/scenePreviewRotation';
import { EffectsStore, effectsDefaultTool } from './effects/effectsStore';
import { SceneDarknessStore } from './effects/sceneDarknessStore';
@@ -29,7 +35,11 @@ import { NpcsOverlayStore } from './npcs/npcsOverlayStore';
import { ZipProjectStore } from './project/zipStore';
import { SceneViewStore } from './sceneView/sceneViewStore';
import { registerDndAssetProtocol } from './protocol/dndAssetProtocol';
import { PlayersStore } from './players/playersStore';
import { SceneNpcTokensSessionStore } from './players/sceneNpcTokensSessionStore';
import { ScenePlayerTokensSessionStore } from './players/scenePlayerTokensSessionStore';
import { SceneTokensSessionStore } from './tokens/sceneTokensSessionStore';
import { TokenGridSnapSessionStore } from './tokens/tokenGridSnapSessionStore';
import { TokensStore } from './tokens/tokensStore';
import { installAutoUpdater } from './update/installAutoUpdater';
import { getAppSemanticVersion, getOptionalBuildNumber } from './versionInfo';
@@ -49,17 +59,20 @@ import {
focusEditorWindow,
getPresentationContentSize,
getSceneDescriptionContent,
getTokenPathEditorTarget,
isMultiWindowOpen,
markAppQuitting,
openMaterialsWindow,
openMultiWindow,
openNpcsEditorWindow,
openSceneEditorWindow,
openTokenPathEditorWindow,
openNpcsWindow,
openSceneDescriptionWindow,
closeMaterialsWindow,
closeNpcsEditorWindow,
closeSceneEditorWindow,
closeTokenPathEditorWindow,
closeNpcsWindow,
sendToAppWindows,
syncAllWindowChromeTitles,
@@ -67,6 +80,9 @@ import {
waitForEditorWindowReady,
warmNpcsEditorWindow,
} from './windows/createWindows';
import { TokenPathSessionStore } from './tokens/tokenPathSessionStore';
import { tokenPathTotalLength } from '../shared/types/tokenPath';
import type { TokenPathTargetKind } from '../shared/types/tokenPathSession';
function emitZipProgress(evt: {
kind: 'import' | 'export';
@@ -88,21 +104,13 @@ function emitScenePreviewImportProgress(evt: ScenePreviewImportEvent): void {
}
}
function emitMaterialUpsertProgress(evt: {
percent: number;
stage: string;
detail?: string;
}): void {
function emitMaterialUpsertProgress(evt: { percent: number; stage: string; detail?: string }): void {
for (const win of BrowserWindow.getAllWindows()) {
win.webContents.send(ipcChannels.project.materialUpsertProgress, evt);
}
}
function emitNpcUpsertProgress(evt: {
percent: number;
stage: string;
detail?: string;
}): void {
function emitNpcUpsertProgress(evt: { percent: number; stage: string; detail?: string }): void {
for (const win of BrowserWindow.getAllWindows()) {
win.webContents.send(ipcChannels.project.npcUpsertProgress, evt);
}
@@ -158,7 +166,58 @@ const videoStore = new VideoPlaybackStore();
const materialsOverlayStore = new MaterialsOverlayStore();
const npcsOverlayStore = new NpcsOverlayStore();
const sceneTokensSessionStore = new SceneTokensSessionStore();
const tokenPathSessionStore = new TokenPathSessionStore();
const sceneNpcTokensSessionStore = new SceneNpcTokensSessionStore();
const scenePlayerTokensSessionStore = new ScenePlayerTokensSessionStore();
const tokenGridSnapSessionStore = new TokenGridSnapSessionStore();
let tokensStore: TokensStore | null = null;
let playersStore: PlayersStore | null = null;
function emitTokenPathSessionState(): void {
const state = tokenPathSessionStore.getState();
for (const win of BrowserWindow.getAllWindows()) {
win.webContents.send(ipcChannels.tokenPathSession.stateChanged, { state });
}
}
function seedTokenPathPlaybackForProject(project: Project | null): void {
tokenPathSessionStore.reset();
if (!project?.currentSceneId) {
emitTokenPathSessionState();
return;
}
const scene = project.scenes[project.currentSceneId];
if (!scene) {
emitTokenPathSessionState();
return;
}
const now = Date.now();
const seedOne = (kind: TokenPathTargetKind, placementId: string, path: NonNullable<(typeof scene.tokens)[number]['path']>) => {
const pathLength = tokenPathTotalLength(path);
if (pathLength <= 1e-9) return;
tokenPathSessionStore.dispatch({
kind: 'seedPlayback',
entry: {
kind,
placementId,
phase: path.startMode === 'delayed' ? 'delay' : 'moving',
baseDist: 0,
direction: 1,
rejoinDist: null,
durationSec: path.durationSec,
pathLength,
segmentStartedAtMs: now,
},
});
};
for (const t of scene.tokens ?? []) {
if (t.path && t.path.points.length >= 2) seedOne('token', String(t.id), t.path);
}
for (const t of scene.npcTokens ?? []) {
if (t.path && t.path.points.length >= 2) seedOne('npcToken', String(t.id), t.path);
}
emitTokenPathSessionState();
}
function emitEffectsState(): void {
const state = effectsStore.getState();
@@ -227,10 +286,47 @@ function emitSceneTokensSessionState(): void {
}
}
function emitTokenGridSnapState(): void {
const { enabled } = tokenGridSnapSessionStore.getState();
for (const win of BrowserWindow.getAllWindows()) {
win.webContents.send(ipcChannels.tokenGridSnap.stateChanged, { enabled });
}
}
function emitPlayersState(): void {
const players = playersStore?.listPlayers() ?? [];
const teams = playersStore?.listTeams() ?? [];
for (const win of BrowserWindow.getAllWindows()) {
win.webContents.send(ipcChannels.players.stateChanged, { players, teams });
}
}
function emitPlayerUpsertProgress(p: { percent: number; stage: string; detail?: string }): void {
for (const win of BrowserWindow.getAllWindows()) {
win.webContents.send(ipcChannels.players.upsertProgress, p);
}
}
function emitSceneNpcTokensSessionState(): void {
const state = sceneNpcTokensSessionStore.getState();
for (const win of BrowserWindow.getAllWindows()) {
win.webContents.send(ipcChannels.sceneNpcTokensSession.stateChanged, { state });
}
}
function emitScenePlayerTokensSessionState(): void {
const state = scenePlayerTokensSessionStore.getState();
for (const win of BrowserWindow.getAllWindows()) {
win.webContents.send(ipcChannels.scenePlayerTokensSession.stateChanged, { state });
}
}
function syncSceneDarknessForProject(project: Project): void {
const cacheKey = project.currentGraphNodeId ?? project.currentSceneId ?? null;
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);
}
@@ -376,11 +472,15 @@ async function main() {
const licenseService = new LicenseService(app.getPath('userData'));
tokensStore = new TokensStore(app.getPath('userData'));
await tokensStore.ensureLoaded();
if (USERS_BRANCH_FEATURES_ENABLED) {
playersStore = new PlayersStore(app.getPath('userData'));
await playersStore.ensureLoaded();
}
setLicenseAssert(() => {
licenseService.assertForIpc();
});
installAppMenuForSession();
registerDndAssetProtocol(projectStore, tokensStore);
registerDndAssetProtocol(projectStore, tokensStore, playersStore);
registerHandler(ipcChannels.app.quit, () => {
markAppQuitting();
app.quit();
@@ -395,25 +495,43 @@ async function main() {
registerHandler(ipcChannels.license.setToken, async ({ token }) => licenseService.setToken(token));
registerHandler(ipcChannels.license.clearToken, () => licenseService.clearToken());
registerHandler(ipcChannels.license.acceptEula, ({ version }) => licenseService.acceptEula(version));
registerHandler(ipcChannels.windows.openMultiWindow, () => {
registerHandler(ipcChannels.windows.openMultiWindow, (req) => {
sceneDarknessStore.resetSession();
sceneTrapsStore.resetSession();
sceneTokensSessionStore.reset();
tokenPathSessionStore.reset();
sceneNpcTokensSessionStore.reset();
scenePlayerTokensSessionStore.reset();
tokenGridSnapSessionStore.reset();
if (USERS_BRANCH_FEATURES_ENABLED) {
const playerIds = Array.isArray(req?.playerIds) ? req.playerIds.map(String).filter(Boolean) : [];
if (playerIds.length > 0) {
scenePlayerTokensSessionStore.dispatch({ kind: 'setSelection', playerIds });
}
}
effectsStore.dispatch({ kind: 'tool.set', tool: effectsDefaultTool() });
openMultiWindow();
const project = projectStore.getOpenProject();
if (project) {
syncSceneDarknessForProject(project);
syncSceneTrapsForProject(project);
seedTokenPathPlaybackForProject(project);
} else {
emitTokenPathSessionState();
}
emitSceneDarknessState();
emitSceneTrapsState();
emitSceneTokensSessionState();
emitSceneNpcTokensSessionState();
emitScenePlayerTokensSessionState();
emitTokenGridSnapState();
emitEffectsState();
return { ok: true };
});
registerHandler(ipcChannels.windows.closeMultiWindow, () => {
closeMultiWindow();
tokenGridSnapSessionStore.reset();
emitTokenGridSnapState();
return { ok: true };
});
registerHandler(ipcChannels.windows.syncChromeTitles, ({ localeTag }) => {
@@ -466,8 +584,22 @@ async function main() {
closeSceneEditorWindow();
return { ok: true };
});
registerHandler(ipcChannels.windows.openNpcs, () => {
registerHandler(ipcChannels.windows.openTokenPathEditor, ({ kind, placementId }) => {
openTokenPathEditorWindow(kind, placementId);
return { ok: true };
});
registerHandler(ipcChannels.windows.closeTokenPathEditor, () => {
closeTokenPathEditorWindow();
return { ok: true };
});
registerHandler(ipcChannels.windows.getTokenPathEditorTarget, () => getTokenPathEditorTarget());
registerHandler(ipcChannels.windows.openNpcs, (req) => {
openNpcsWindow();
const npcId = req?.npcId ? asNpcId(String(req.npcId)) : null;
if (npcId) {
npcsOverlayStore.dispatch({ kind: 'show', npcId });
emitNpcsOverlayState();
}
return { ok: true };
});
registerHandler(ipcChannels.windows.closeNpcs, () => {
@@ -513,8 +645,12 @@ async function main() {
const project = await projectStore.openProjectById(projectId);
sceneViewStore.reset();
sceneTokensSessionStore.reset();
sceneNpcTokensSessionStore.reset();
scenePlayerTokensSessionStore.reset();
emitSceneViewState();
emitSceneTokensSessionState();
emitSceneNpcTokensSessionState();
emitScenePlayerTokensSessionState();
emitSessionState();
warmNpcsEditorWindow();
return { project };
@@ -529,6 +665,9 @@ async function main() {
sceneTrapsStore.resetSession();
sceneViewStore.reset();
sceneTokensSessionStore.reset();
sceneNpcTokensSessionStore.reset();
scenePlayerTokensSessionStore.reset();
tokenGridSnapSessionStore.reset();
emitEffectsState();
emitMaterialsOverlayState();
emitNpcsOverlayState();
@@ -536,6 +675,9 @@ async function main() {
emitSceneTrapsState();
emitSceneViewState();
emitSceneTokensSessionState();
emitSceneNpcTokensSessionState();
emitScenePlayerTokensSessionState();
emitTokenGridSnapState();
emitSessionState();
return { ok: true };
});
@@ -552,6 +694,7 @@ async function main() {
materialsOverlayStore.clear();
npcsOverlayStore.clear();
sceneViewStore.reset();
scenePlayerTokensSessionStore.clearPlacements();
// Token moves persist for the whole play session (reset only on project open/close).
const project = projectStore.getOpenProject();
if (project) {
@@ -565,6 +708,8 @@ async function main() {
emitSceneTrapsState();
emitSceneViewState();
emitSceneTokensSessionState();
emitScenePlayerTokensSessionState();
seedTokenPathPlaybackForProject(project);
emitSessionState();
return { currentSceneId: projectStore.getOpenProject()?.currentSceneId ?? null };
});
@@ -581,6 +726,7 @@ async function main() {
materialsOverlayStore.clear();
npcsOverlayStore.clear();
sceneViewStore.reset();
scenePlayerTokensSessionStore.clearPlacements();
// Token moves persist for the whole play session (reset only on project open/close).
const project = projectStore.getOpenProject();
if (project) {
@@ -594,6 +740,8 @@ async function main() {
emitSceneTrapsState();
emitSceneViewState();
emitSceneTokensSessionState();
emitScenePlayerTokensSessionState();
seedTokenPathPlaybackForProject(project);
emitSessionState();
const p = projectStore.getOpenProject();
return {
@@ -602,6 +750,7 @@ async function main() {
};
});
registerHandler(ipcChannels.project.updateScene, async ({ sceneId, patch }) => {
const before = projectStore.getOpenProject()?.scenes[sceneId];
const next = await projectStore.updateScene(sceneId, patch);
const project = projectStore.getOpenProject();
if (project?.currentSceneId === sceneId && patch.darkenScene !== undefined) {
@@ -612,6 +761,29 @@ async function main() {
syncSceneTrapsForProject(project);
emitSceneTrapsState();
}
if (
project?.currentSceneId === sceneId &&
patch.previewRotationDeg !== undefined &&
before
) {
const steps = previewRotationStepsCw(
asPreviewRotationDeg(before.previewRotationDeg),
asPreviewRotationDeg(patch.previewRotationDeg),
);
if (steps !== 0) {
sceneTokensSessionStore.rotateMapCwSteps(steps);
sceneNpcTokensSessionStore.rotateMapCwSteps(steps);
scenePlayerTokensSessionStore.rotateMapCwSteps(steps);
emitSceneTokensSessionState();
emitSceneNpcTokensSessionState();
emitScenePlayerTokensSessionState();
}
}
if (project && project.currentSceneId === sceneId && patch.previewRotationDeg !== undefined) {
// Trap ids stay the same; runtime statuses remain valid after coordinate remap in project.
syncSceneTrapsForProject(project);
emitSceneTrapsState();
}
emitSessionState();
return { scene: next };
});
@@ -671,7 +843,9 @@ async function main() {
emitSessionState();
return { project };
});
registerHandler(ipcChannels.project.upsertMaterial, async ({ materialId, name, filePath: pathFromDrop }) => {
registerHandler(
ipcChannels.project.upsertMaterial,
async ({ materialId, name, filePath: pathFromDrop }) => {
let filePath = pathFromDrop;
if (!filePath && !materialId) {
const { canceled, filePaths } = await dialog.showOpenDialog({
@@ -700,7 +874,8 @@ async function main() {
emitMaterialsOverlayState();
emitSessionState();
return { project };
});
},
);
registerHandler(ipcChannels.project.deleteMaterial, async ({ materialId }) => {
const project = await projectStore.deleteMaterial(materialId);
syncMaterialsOverlayWithProject(project);
@@ -737,14 +912,13 @@ async function main() {
const filePath = filePaths[0]!;
const buf = await fs.readFile(filePath);
const ext = path.extname(filePath).toLowerCase();
const mime =
ext === '.png' ? 'image/png' : ext === '.webp' ? 'image/webp' : 'image/jpeg';
const mime = ext === '.png' ? 'image/png' : ext === '.webp' ? 'image/webp' : 'image/jpeg';
const previewDataUrl = `data:${mime};base64,${buf.toString('base64')}`;
return { canceled: false as const, filePath, previewDataUrl };
});
registerHandler(
ipcChannels.project.upsertNpc,
async ({ npcId, name, description, filePath: pathFromDrop, groupId }) => {
async ({ npcId, name, description, filePath: pathFromDrop, groupId, ringColor, disposition, imageOffset }) => {
let filePath = pathFromDrop;
if (!filePath && !npcId) {
const { canceled, filePaths } = await dialog.showOpenDialog({
@@ -768,6 +942,9 @@ async function main() {
...(typeof description === 'string' ? { description } : {}),
...(filePath ? { filePath } : {}),
...(groupId !== undefined ? { groupId } : {}),
...(ringColor !== undefined ? { ringColor } : {}),
...(disposition !== undefined ? { disposition } : {}),
...(imageOffset !== undefined ? { imageOffset } : {}),
},
(p) => emitNpcUpsertProgress(p),
);
@@ -779,11 +956,15 @@ async function main() {
);
registerHandler(
ipcChannels.project.updateNpcFields,
async ({ npcId, name, description, groupId }) => {
async ({ npcId, name, description, groupId, ringColor, disposition, imageOffset, imageScale }) => {
const project = await projectStore.updateNpcFields(npcId, {
...(typeof name === 'string' ? { name } : {}),
...(typeof description === 'string' ? { description } : {}),
...(groupId !== undefined ? { groupId } : {}),
...(ringColor !== undefined ? { ringColor } : {}),
...(disposition !== undefined ? { disposition } : {}),
...(imageOffset !== undefined ? { imageOffset } : {}),
...(imageScale !== undefined ? { imageScale } : {}),
});
emitSessionState();
return { project };
@@ -820,8 +1001,7 @@ async function main() {
const filePath = filePaths[0]!;
const buf = await fs.readFile(filePath);
const ext = path.extname(filePath).toLowerCase();
const mime =
ext === '.png' ? 'image/png' : ext === '.webp' ? 'image/webp' : 'image/jpeg';
const mime = ext === '.png' ? 'image/png' : ext === '.webp' ? 'image/webp' : 'image/jpeg';
const previewDataUrl = `data:${mime};base64,${buf.toString('base64')}`;
return { canceled: false as const, filePath, previewDataUrl };
});
@@ -843,9 +1023,7 @@ async function main() {
emitSessionState();
return { project };
});
registerHandler(
ipcChannels.project.upsertNpcGroup,
async ({ groupId, name, color, parentId }) => {
registerHandler(ipcChannels.project.upsertNpcGroup, async ({ groupId, name, color, parentId }) => {
const project = await projectStore.upsertNpcGroup({
...(groupId ? { groupId } : {}),
name,
@@ -854,8 +1032,7 @@ async function main() {
});
emitSessionState();
return { project };
},
);
});
registerHandler(ipcChannels.project.deleteNpcGroup, async ({ groupId }) => {
const project = await projectStore.deleteNpcGroup(groupId);
syncNpcsOverlayWithProject(project);
@@ -901,13 +1078,14 @@ async function main() {
const finalized = await projectStore.finalizeScenePreviewImport(sceneId, result.assetId);
if (finalized.changed) {
emitSessionState();
}
// Always clear optimizing UI — including abort on project close (changed: false).
emitScenePreviewImportProgress({
sceneId,
assetId: result.assetId,
phase: 'done',
project: finalized.project,
...(finalized.changed && finalized.project ? { project: finalized.project } : {}),
});
}
} catch (e) {
emitScenePreviewImportProgress({
sceneId,
@@ -1029,9 +1207,12 @@ async function main() {
registerHandler(ipcChannels.project.peekImportZipPath, async ({ filePath, labels, targetHasMainStart }) => {
return projectStore.peekImportFromZipPath(filePath, labels, targetHasMainStart);
});
registerHandler(ipcChannels.project.peekImportFromProject, async ({ sourceProjectId, labels, targetHasMainStart }) => {
registerHandler(
ipcChannels.project.peekImportFromProject,
async ({ sourceProjectId, labels, targetHasMainStart }) => {
return projectStore.peekImportFromProjectId(sourceProjectId, labels, targetHasMainStart);
});
},
);
registerHandler(
ipcChannels.project.mergeImportZip,
async ({ filePath, storylineSelections, sceneResolutions, npcResolutions }) => {
@@ -1130,7 +1311,8 @@ async function main() {
const project = await projectStore.importProjectFromFoundry(sourcePath, (p) => {
emitZipProgress({
kind: 'import',
stage: p.stage === 'unzip' ? 'unzip' : p.stage === 'zip' ? 'zip' : p.stage === 'done' ? 'done' : 'copy',
stage:
p.stage === 'unzip' ? 'unzip' : p.stage === 'zip' ? 'zip' : p.stage === 'done' ? 'done' : 'copy',
percent: p.percent,
...(p.detail ? { detail: p.detail } : null),
});
@@ -1143,7 +1325,9 @@ async function main() {
throw e;
}
});
registerHandler(ipcChannels.project.exportZip, async ({ projectId, storylineSelections, npcIds, labels }) => {
registerHandler(
ipcChannels.project.exportZip,
async ({ projectId, storylineSelections, npcIds, labels }) => {
const list = await projectStore.listProjects();
const entry = list.find((p) => p.id === projectId);
if (!entry) {
@@ -1189,7 +1373,8 @@ async function main() {
emitZipProgress({ kind: 'export', stage: 'error', percent: 0, detail });
throw err;
}
});
},
);
registerHandler(ipcChannels.project.deleteProject, async ({ projectId }) => {
await projectStore.deleteProjectById(projectId);
emitSessionState();
@@ -1240,7 +1425,11 @@ async function main() {
return { tokens: tokensStore!.list() };
});
registerHandler(ipcChannels.tokens.upsert, async ({ id, name, filePath }) => {
const token = await tokensStore!.upsert({ id, name, filePath });
const token = await tokensStore!.upsert({
name,
...(id !== undefined ? { id } : {}),
...(filePath !== undefined ? { filePath } : {}),
});
emitTokensState();
return { token };
});
@@ -1275,8 +1464,7 @@ async function main() {
const filePath = filePaths[0]!;
const buf = await fs.readFile(filePath);
const ext = path.extname(filePath).toLowerCase();
const mime =
ext === '.png' ? 'image/png' : ext === '.webp' ? 'image/webp' : 'image/jpeg';
const mime = ext === '.png' ? 'image/png' : ext === '.webp' ? 'image/webp' : 'image/jpeg';
const previewDataUrl = `data:${mime};base64,${buf.toString('base64')}`;
return { canceled: false as const, filePath, previewDataUrl };
});
@@ -1291,6 +1479,146 @@ async function main() {
emitSceneTokensSessionState();
return { ok: true };
});
registerHandler(ipcChannels.tokenPathSession.getState, () => {
return { state: tokenPathSessionStore.getState() };
});
registerHandler(ipcChannels.tokenPathSession.dispatch, ({ event }) => {
tokenPathSessionStore.dispatch(event);
emitTokenPathSessionState();
return { ok: true };
});
registerHandler(ipcChannels.tokenGridSnap.getState, () => tokenGridSnapSessionStore.getState());
registerHandler(ipcChannels.tokenGridSnap.setEnabled, ({ enabled }) => {
const next = tokenGridSnapSessionStore.setEnabled(enabled);
emitTokenGridSnapState();
return next;
});
registerHandler(ipcChannels.players.list, async () => {
if (!USERS_BRANCH_FEATURES_ENABLED || !playersStore) {
return { players: [], teams: [] };
}
await playersStore.ensureLoaded();
return { players: playersStore.listPlayers(), teams: playersStore.listTeams() };
});
registerHandler(
ipcChannels.players.upsert,
async ({ id, name, filePath, teamId, ringColor, imageOffset, imageScale }) => {
if (!USERS_BRANCH_FEATURES_ENABLED || !playersStore) {
throw new Error('Players library is disabled in this build');
}
const player = await playersStore.upsert(
{
name,
...(id !== undefined ? { id } : {}),
...(filePath !== undefined ? { filePath } : {}),
...(teamId !== undefined ? { teamId } : {}),
...(ringColor !== undefined ? { ringColor } : {}),
...(imageOffset !== undefined ? { imageOffset } : {}),
...(imageScale !== undefined ? { imageScale } : {}),
},
(p) => emitPlayerUpsertProgress(p),
);
emitPlayersState();
return { player };
},
);
registerHandler(ipcChannels.players.delete, async ({ id }) => {
if (!USERS_BRANCH_FEATURES_ENABLED || !playersStore) {
return { ok: true };
}
await playersStore.delete(id);
emitPlayersState();
return { ok: true };
});
registerHandler(ipcChannels.players.setOrder, async ({ playerIds }) => {
if (!USERS_BRANCH_FEATURES_ENABLED || !playersStore) {
return { players: [] };
}
const players = await playersStore.setPlayersOrder(playerIds);
emitPlayersState();
return { players };
});
registerHandler(ipcChannels.players.upsertTeam, async ({ id, name, color }) => {
if (!USERS_BRANCH_FEATURES_ENABLED || !playersStore) {
throw new Error('Players library is disabled in this build');
}
const team = await playersStore.upsertTeam({
name,
...(id !== undefined ? { id } : {}),
...(color !== undefined ? { color } : {}),
});
emitPlayersState();
return { team };
});
registerHandler(ipcChannels.players.deleteTeam, async ({ id }) => {
if (!USERS_BRANCH_FEATURES_ENABLED || !playersStore) {
return { ok: true };
}
await playersStore.deleteTeam(id);
emitPlayersState();
return { ok: true };
});
registerHandler(ipcChannels.players.setTeamsOrder, async ({ teamIds }) => {
if (!USERS_BRANCH_FEATURES_ENABLED || !playersStore) {
return { teams: [] };
}
const teams = await playersStore.setTeamsOrder(teamIds);
emitPlayersState();
return { teams };
});
registerHandler(ipcChannels.players.assignTeam, async ({ playerId, teamId }) => {
if (!USERS_BRANCH_FEATURES_ENABLED || !playersStore) {
throw new Error('Players library is disabled in this build');
}
const player = await playersStore.assignPlayerTeam(playerId, teamId);
emitPlayersState();
return { player };
});
registerHandler(ipcChannels.players.pickImage, async () => {
if (!USERS_BRANCH_FEATURES_ENABLED || !playersStore) {
return { canceled: true as const };
}
const { canceled, filePaths } = await dialog.showOpenDialog({
properties: ['openFile'],
filters: [
{
name: openDialogFilterLabel('images', app.getLocale()),
extensions: ['png', 'jpg', 'jpeg', 'webp'],
},
],
});
if (canceled || filePaths.length === 0) return { canceled: true as const };
const filePath = filePaths[0]!;
const buf = await fs.readFile(filePath);
const ext = path.extname(filePath).toLowerCase();
const mime = ext === '.png' ? 'image/png' : ext === '.webp' ? 'image/webp' : 'image/jpeg';
const previewDataUrl = `data:${mime};base64,${buf.toString('base64')}`;
return { canceled: false as const, filePath, previewDataUrl };
});
registerHandler(ipcChannels.players.imageUrl, ({ id }) => {
if (!USERS_BRANCH_FEATURES_ENABLED || !playersStore) {
return { url: null };
}
return { url: playersStore.getImageUrl(id) };
});
registerHandler(ipcChannels.sceneNpcTokensSession.getState, () => {
return { state: sceneNpcTokensSessionStore.getState() };
});
registerHandler(ipcChannels.sceneNpcTokensSession.dispatch, ({ event }) => {
sceneNpcTokensSessionStore.dispatch(event);
emitSceneNpcTokensSessionState();
return { ok: true };
});
registerHandler(ipcChannels.scenePlayerTokensSession.getState, () => {
return { state: scenePlayerTokensSessionStore.getState() };
});
registerHandler(ipcChannels.scenePlayerTokensSession.dispatch, ({ event }) => {
scenePlayerTokensSessionStore.dispatch(event);
emitScenePlayerTokensSessionState();
return { ok: true };
});
registerHandler(ipcChannels.video.getState, () => {
return { state: videoStore.getState() };
+70
View File
@@ -0,0 +1,70 @@
import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import test from 'node:test';
import { PlayersStore } from './playersStore';
import { asPlayerId } from '../../shared/types/ids';
async function withTempStore(run: (store: PlayersStore, root: string) => Promise<void>) {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'dnd-players-'));
const store = new PlayersStore(root);
try {
await run(store, root);
} finally {
await fs.rm(root, { recursive: true, force: true });
}
}
void test('PlayersStore upsert list delete and teams', async () => {
await withTempStore(async (store, root) => {
const png = path.join(root, 'sample.png');
// minimal 1x1 png
const buf = Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',
'base64',
);
await fs.writeFile(png, buf);
const progress: number[] = [];
const player = await store.upsert(
{ name: 'Ada', filePath: png, ringColor: '#112233', imageOffset: { x: 0.1, y: -0.1 } },
(p) => progress.push(p.percent),
);
assert.equal(player.name, 'Ada');
assert.equal(player.ringColor, '#112233');
assert.ok(progress.length > 0);
assert.equal(store.listPlayers().length, 1);
const team = await store.upsertTeam({ name: 'Party', color: '#abcdef' });
assert.equal(team.name, 'Party');
const assigned = await store.assignPlayerTeam(player.id, team.id);
assert.equal(assigned?.teamId, team.id);
await store.deleteTeam(team.id);
assert.equal(store.listTeams().length, 0);
assert.equal(store.getById(player.id)?.teamId, null);
await store.delete(player.id);
assert.equal(store.listPlayers().length, 0);
});
});
void test('PlayersStore persists across reload', async () => {
await withTempStore(async (store, root) => {
const png = path.join(root, 'sample.png');
await fs.writeFile(
png,
Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',
'base64',
),
);
const created = await store.upsert({ name: 'Bob', filePath: png });
const store2 = new PlayersStore(root);
await store2.ensureLoaded();
assert.equal(store2.listPlayers().length, 1);
assert.equal(store2.getById(asPlayerId(created.id))?.name, 'Bob');
});
});
+295
View File
@@ -0,0 +1,295 @@
import crypto from 'node:crypto';
import fs from 'node:fs/promises';
import path from 'node:path';
import {
assignPlayerToTeam,
createPlayerTeamDraft,
deletePlayerTeam,
normalizeAppPlayerTeams,
uniquePlayerTeamName,
} from '../../shared/players/playerTeams';
import type {
AppPlayer,
AppPlayerTeam,
PlayerId,
PlayerImageOffset,
PlayersUpsertProgressEvent,
PlayerTeamId,
} from '../../shared/types/appPlayers';
import {
clampPlayerImageOffset,
clampPlayerImageScale,
DEFAULT_PLAYER_IMAGE_OFFSET,
DEFAULT_PLAYER_IMAGE_SCALE,
DEFAULT_PLAYER_RING_COLOR,
normalizeAppPlayer,
} from '../../shared/types/appPlayers';
import { asPlayerId } from '../../shared/types/ids';
import { normalizeHexColor } from '../../shared/npcs/npcGroups';
import { optimizeImageBufferVisuallyLossless } from '../project/optimizeImageImport.lib.mjs';
type PlayersManifest = {
players: AppPlayer[];
teams: AppPlayerTeam[];
};
function mimeFromExt(ext: string): string {
const e = ext.toLowerCase();
if (e === '.png') return 'image/png';
if (e === '.jpg' || e === '.jpeg') return 'image/jpeg';
if (e === '.webp') return 'image/webp';
if (e === '.gif') return 'image/gif';
return 'application/octet-stream';
}
function safeFileBase(name: string): string {
const base = name.replace(/[^\w.\-]+/gu, '_').slice(0, 48);
return base || 'player';
}
function randomPlayerId(): PlayerId {
return asPlayerId(`player_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`);
}
export class PlayersStore {
private readonly rootDir: string;
private readonly filesDir: string;
private readonly manifestPath: string;
private players: AppPlayer[] = [];
private teams: AppPlayerTeam[] = [];
private loaded = false;
constructor(userData: string) {
this.rootDir = path.join(userData, 'players');
this.filesDir = path.join(this.rootDir, 'files');
this.manifestPath = path.join(this.rootDir, 'players.json');
}
async ensureLoaded(): Promise<void> {
if (this.loaded) return;
await fs.mkdir(this.filesDir, { recursive: true });
try {
const raw = await fs.readFile(this.manifestPath, 'utf8');
const parsed = JSON.parse(raw) as PlayersManifest;
this.teams = normalizeAppPlayerTeams(parsed.teams);
const teamIds = new Set(this.teams.map((t) => t.id));
this.players = (Array.isArray(parsed.players) ? parsed.players : [])
.map((p) => normalizeAppPlayer(p, teamIds))
.filter((p): p is AppPlayer => Boolean(p));
} catch {
this.players = [];
this.teams = [];
await this.persist();
}
this.loaded = true;
}
listPlayers(): AppPlayer[] {
return [...this.players];
}
listTeams(): AppPlayerTeam[] {
return [...this.teams];
}
getById(id: PlayerId): AppPlayer | null {
return this.players.find((p) => p.id === id) ?? null;
}
getImageReadInfo(id: PlayerId): { absPath: string; mime: string } | null {
const player = this.getById(id);
if (!player) return null;
const absPath = path.join(this.rootDir, player.imageRelPath);
return { absPath, mime: mimeFromExt(path.extname(player.imageRelPath)) };
}
getImageUrl(id: PlayerId): string | null {
if (!this.getImageReadInfo(id)) return null;
return `dnd://player?id=${encodeURIComponent(id)}`;
}
async upsert(
input: {
id?: PlayerId | null;
name: string;
filePath?: string | null;
teamId?: PlayerTeamId | null;
ringColor?: string;
imageOffset?: PlayerImageOffset;
imageScale?: number;
},
onProgress?: (p: PlayersUpsertProgressEvent) => void,
): Promise<AppPlayer> {
await this.ensureLoaded();
const name = input.name.trim();
if (!name) throw new Error('Player name is required');
const existing = input.id ? this.getById(input.id) : null;
if (input.id && !existing) throw new Error('Player not found');
if (!existing && !input.filePath) throw new Error('Player image is required');
const emit = (percent: number, stage: string, detail?: string) => {
onProgress?.({ percent, stage, ...(detail ? { detail } : {}) });
};
emit(5, 'prepare', 'Подготовка…');
let imageRelPath = existing?.imageRelPath ?? '';
let sha256 = existing?.sha256 ?? '';
const id = existing?.id ?? randomPlayerId();
if (input.filePath) {
emit(15, 'read', 'Чтение изображения…');
let buf = await fs.readFile(input.filePath);
emit(40, 'optimize', 'Оптимизация…');
try {
const opt = await optimizeImageBufferVisuallyLossless(buf);
if (opt.buffer && opt.buffer.length > 0) buf = Buffer.from(opt.buffer);
} catch {
/* keep original */
}
sha256 = crypto.createHash('sha256').update(buf).digest('hex');
const ext = path.extname(input.filePath) || '.png';
const fileName = `${id}_${safeFileBase(name)}${ext.toLowerCase()}`;
imageRelPath = path.join('files', fileName).replace(/\\/gu, '/');
const abs = path.join(this.rootDir, imageRelPath);
await fs.mkdir(path.dirname(abs), { recursive: true });
emit(75, 'write', 'Сохранение…');
await fs.writeFile(abs, buf);
if (existing && existing.imageRelPath !== imageRelPath) {
try {
await fs.unlink(path.join(this.rootDir, existing.imageRelPath));
} catch {
/* ignore */
}
}
}
const teamIds = new Set(this.teams.map((t) => t.id));
let teamId: PlayerTeamId | null =
input.teamId !== undefined ? input.teamId : (existing?.teamId ?? null);
if (teamId && !teamIds.has(teamId)) teamId = null;
const player: AppPlayer = {
id,
name,
imageRelPath,
sha256,
teamId,
ringColor: normalizeHexColor(
input.ringColor ?? existing?.ringColor,
DEFAULT_PLAYER_RING_COLOR,
),
imageOffset: clampPlayerImageOffset(
input.imageOffset ?? existing?.imageOffset ?? DEFAULT_PLAYER_IMAGE_OFFSET,
),
imageScale: clampPlayerImageScale(
input.imageScale ?? existing?.imageScale ?? DEFAULT_PLAYER_IMAGE_SCALE,
),
};
if (existing) {
this.players = this.players.map((p) => (p.id === player.id ? player : p));
} else {
this.players = [...this.players, player];
}
emit(95, 'persist', 'Запись…');
await this.persist();
emit(100, 'done', 'Готово');
return player;
}
async delete(id: PlayerId): Promise<void> {
await this.ensureLoaded();
const existing = this.getById(id);
if (!existing) return;
this.players = this.players.filter((p) => p.id !== id);
await this.persist();
try {
await fs.unlink(path.join(this.rootDir, existing.imageRelPath));
} catch {
/* ignore */
}
}
async setPlayersOrder(playerIds: PlayerId[]): Promise<AppPlayer[]> {
await this.ensureLoaded();
const byId = new Map(this.players.map((p) => [p.id, p]));
const next: AppPlayer[] = [];
for (const id of playerIds) {
const p = byId.get(id);
if (p) {
next.push(p);
byId.delete(id);
}
}
for (const p of byId.values()) next.push(p);
this.players = next;
await this.persist();
return this.listPlayers();
}
async upsertTeam(input: {
id?: PlayerTeamId | null;
name: string;
color?: string;
}): Promise<AppPlayerTeam> {
await this.ensureLoaded();
const existing = input.id ? this.teams.find((t) => t.id === input.id) : null;
if (input.id && !existing) throw new Error('Team not found');
if (existing) {
const team: AppPlayerTeam = {
id: existing.id,
name: uniquePlayerTeamName(input.name, this.teams, existing.id),
color: normalizeHexColor(input.color ?? existing.color, DEFAULT_PLAYER_RING_COLOR),
};
this.teams = this.teams.map((t) => (t.id === team.id ? team : t));
await this.persist();
return team;
}
const team = createPlayerTeamDraft(input.name, input.color, this.teams);
this.teams = [...this.teams, team];
await this.persist();
return team;
}
async deleteTeam(id: PlayerTeamId): Promise<void> {
await this.ensureLoaded();
const next = deletePlayerTeam(this.teams, this.players, id);
this.teams = next.teams;
this.players = next.players;
await this.persist();
}
async setTeamsOrder(teamIds: PlayerTeamId[]): Promise<AppPlayerTeam[]> {
await this.ensureLoaded();
const byId = new Map(this.teams.map((t) => [t.id, t]));
const next: AppPlayerTeam[] = [];
for (const id of teamIds) {
const t = byId.get(id);
if (t) {
next.push(t);
byId.delete(id);
}
}
for (const t of byId.values()) next.push(t);
this.teams = next;
await this.persist();
return this.listTeams();
}
async assignPlayerTeam(playerId: PlayerId, teamId: PlayerTeamId | null): Promise<AppPlayer | null> {
await this.ensureLoaded();
const teamIds = new Set(this.teams.map((t) => t.id as string));
this.players = assignPlayerToTeam(this.players, playerId, teamId, teamIds);
await this.persist();
return this.getById(playerId);
}
private async persist(): Promise<void> {
await fs.mkdir(this.rootDir, { recursive: true });
const payload: PlayersManifest = { players: this.players, teams: this.teams };
await fs.writeFile(this.manifestPath, `${JSON.stringify(payload, null, 2)}\n`, 'utf8');
}
}
@@ -0,0 +1,60 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { DEFAULT_NPC_TOKEN_SESSION_SCALE } from '../../shared/types/appPlayers';
import { SceneNpcTokensSessionStore } from './sceneNpcTokensSessionStore';
void test('SceneNpcTokensSessionStore move and reset', () => {
const store = new SceneNpcTokensSessionStore();
const s1 = store.dispatch({ kind: 'move', placementId: 'a', nx: 0.2, ny: 0.3 });
assert.equal(s1.byPlacementId.a?.nx, 0.2);
assert.equal(s1.revision, 2);
const s2 = store.dispatch({ kind: 'move', placementId: 'a', nx: 0.2, ny: 0.3 });
assert.equal(s2.revision, s1.revision); // no-op
const s3 = store.reset();
assert.deepEqual(s3.byPlacementId, {});
assert.equal(s3.scale, DEFAULT_NPC_TOKEN_SESSION_SCALE);
assert.ok(s3.revision > s1.revision);
});
void test('SceneNpcTokensSessionStore setScale', () => {
const store = new SceneNpcTokensSessionStore();
const s1 = store.dispatch({ kind: 'setScale', scale: 1.5 });
assert.equal(s1.scale, 1.5);
store.dispatch({ kind: 'move', placementId: 'a', nx: 0.1, ny: 0.2 });
const s2 = store.dispatch({ kind: 'setScale', scale: 0.1 });
assert.equal(s2.scale, 0.4); // clamped min
assert.ok(s2.byPlacementId.a);
const s3 = store.reset();
assert.equal(s3.scale, DEFAULT_NPC_TOKEN_SESSION_SCALE);
assert.deepEqual(s3.byPlacementId, {});
});
void test('SceneNpcTokensSessionStore setDisposition without inventing position', () => {
const store = new SceneNpcTokensSessionStore();
const s1 = store.dispatch({
kind: 'setDisposition',
placementId: 'a',
disposition: 'hostile',
});
assert.equal(s1.byPlacementId.a?.disposition, 'hostile');
assert.equal(s1.byPlacementId.a?.nx, undefined);
assert.equal(s1.byPlacementId.a?.ny, undefined);
const s2 = store.dispatch({ kind: 'move', placementId: 'a', nx: 0.4, ny: 0.6 });
assert.equal(s2.byPlacementId.a?.nx, 0.4);
assert.equal(s2.byPlacementId.a?.disposition, 'hostile');
});
void test('SceneNpcTokensSessionStore setInactive is session flag', () => {
const store = new SceneNpcTokensSessionStore();
const s1 = store.dispatch({ kind: 'setInactive', placementId: 'a', inactive: true });
assert.equal(s1.byPlacementId.a?.inactive, true);
const s2 = store.dispatch({ kind: 'setInactive', placementId: 'a', inactive: false });
assert.deepEqual(s2.byPlacementId, {});
store.dispatch({ kind: 'move', placementId: 'a', nx: 0.2, ny: 0.3 });
store.dispatch({ kind: 'setInactive', placementId: 'a', inactive: true });
const s3 = store.dispatch({ kind: 'setInactive', placementId: 'a', inactive: false });
assert.equal(s3.byPlacementId.a?.nx, 0.2);
assert.equal(s3.byPlacementId.a?.inactive, undefined);
});
@@ -0,0 +1,182 @@
import {
clampNpcTokenSessionScale,
DEFAULT_NPC_TOKEN_SESSION_SCALE,
type SceneNpcTokensSessionEvent,
type SceneNpcTokensSessionPlacement,
type SceneNpcTokensSessionState,
} from '../../shared/types/appPlayers';
import { normalizeNpcDisposition } from '../../shared/types/npcDisposition';
import { rotateMapNormPointByCwSteps } from '../../shared/types/scenePreviewRotation';
function emptyState(revision = 1): SceneNpcTokensSessionState {
return {
revision,
byPlacementId: {},
scale: DEFAULT_NPC_TOKEN_SESSION_SCALE,
};
}
function isEmptyPlacement(p: SceneNpcTokensSessionPlacement): boolean {
return p.nx === undefined && p.ny === undefined && !p.disposition && !p.inactive;
}
function withMove(
prev: SceneNpcTokensSessionPlacement | undefined,
nx: number,
ny: number,
): SceneNpcTokensSessionPlacement {
return {
nx,
ny,
...(prev?.disposition ? { disposition: prev.disposition } : {}),
...(prev?.inactive ? { inactive: true } : {}),
};
}
function withoutPlacement(
state: SceneNpcTokensSessionState,
placementId: string,
): SceneNpcTokensSessionState {
if (!(placementId in state.byPlacementId)) return state;
const { [placementId]: _removed, ...rest } = state.byPlacementId;
return {
revision: state.revision + 1,
byPlacementId: rest,
scale: state.scale,
};
}
export class SceneNpcTokensSessionStore {
private state: SceneNpcTokensSessionState = emptyState();
getState(): SceneNpcTokensSessionState {
return this.state;
}
reset(): SceneNpcTokensSessionState {
if (
Object.keys(this.state.byPlacementId).length === 0 &&
this.state.scale === DEFAULT_NPC_TOKEN_SESSION_SCALE
) {
return this.state;
}
this.state = emptyState(this.state.revision + 1);
return this.state;
}
/** Rotate session position overrides with the scene preview (CSS rotate steps). */
rotateMapCwSteps(steps: number): SceneNpcTokensSessionState {
const n = ((steps % 4) + 4) % 4;
if (n === 0) return this.state;
const ids = Object.keys(this.state.byPlacementId);
if (ids.length === 0) return this.state;
let changed = false;
const byPlacementId: SceneNpcTokensSessionState['byPlacementId'] = {};
for (const id of ids) {
const prev = this.state.byPlacementId[id];
if (!prev) continue;
if (typeof prev.nx === 'number' && typeof prev.ny === 'number') {
const p = rotateMapNormPointByCwSteps(prev.nx, prev.ny, n);
byPlacementId[id] = { ...prev, nx: p.nx, ny: p.ny };
changed = true;
} else {
byPlacementId[id] = prev;
}
}
if (!changed) return this.state;
this.state = {
revision: this.state.revision + 1,
byPlacementId,
scale: this.state.scale,
};
return this.state;
}
dispatch(event: SceneNpcTokensSessionEvent): SceneNpcTokensSessionState {
switch (event.kind) {
case 'clear':
return this.reset();
case 'setScale': {
const scale = clampNpcTokenSessionScale(event.scale);
if (this.state.scale === scale) return this.state;
this.state = {
...this.state,
revision: this.state.revision + 1,
scale,
};
return this.state;
}
case 'move': {
const placementId = String(event.placementId ?? '');
if (!placementId) return this.state;
const nx = Math.max(0, Math.min(1, event.nx));
const ny = Math.max(0, Math.min(1, event.ny));
if (!Number.isFinite(nx) || !Number.isFinite(ny)) return this.state;
const prev = this.state.byPlacementId[placementId];
if (prev && prev.nx === nx && prev.ny === ny) return this.state;
this.state = {
revision: this.state.revision + 1,
byPlacementId: {
...this.state.byPlacementId,
[placementId]: withMove(prev, nx, ny),
},
scale: this.state.scale,
};
return this.state;
}
case 'setDisposition': {
const placementId = String(event.placementId ?? '');
if (!placementId) return this.state;
const disposition = normalizeNpcDisposition(event.disposition);
const prev = this.state.byPlacementId[placementId];
if (prev?.disposition === disposition) return this.state;
const next: SceneNpcTokensSessionPlacement = {
...(prev?.nx !== undefined ? { nx: prev.nx } : {}),
...(prev?.ny !== undefined ? { ny: prev.ny } : {}),
disposition,
...(prev?.inactive ? { inactive: true } : {}),
};
this.state = {
revision: this.state.revision + 1,
byPlacementId: {
...this.state.byPlacementId,
[placementId]: next,
},
scale: this.state.scale,
};
return this.state;
}
case 'setInactive': {
const placementId = String(event.placementId ?? '');
if (!placementId) return this.state;
const inactive = Boolean(event.inactive);
const prev = this.state.byPlacementId[placementId];
if (Boolean(prev?.inactive) === inactive) return this.state;
const next: SceneNpcTokensSessionPlacement = {
...(prev?.nx !== undefined ? { nx: prev.nx } : {}),
...(prev?.ny !== undefined ? { ny: prev.ny } : {}),
...(prev?.disposition ? { disposition: prev.disposition } : {}),
...(inactive ? { inactive: true } : {}),
};
if (isEmptyPlacement(next)) {
this.state = withoutPlacement(this.state, placementId);
return this.state;
}
this.state = {
revision: this.state.revision + 1,
byPlacementId: {
...this.state.byPlacementId,
[placementId]: next,
},
scale: this.state.scale,
};
return this.state;
}
default: {
const _exhaustive: never = event;
void _exhaustive;
return this.state;
}
}
}
}
@@ -0,0 +1,49 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { ScenePlayerTokensSessionStore } from './scenePlayerTokensSessionStore';
void test('ScenePlayerTokensSessionStore selection and show/hide', () => {
const store = new ScenePlayerTokensSessionStore();
store.dispatch({ kind: 'setSelection', playerIds: ['a', 'b', 'a'] });
assert.deepEqual(store.getState().selectedPlayerIds, ['a', 'b']);
assert.equal(store.getState().visible, false);
store.dispatch({ kind: 'show', sizeN: 0.08 });
assert.equal(store.getState().visible, true);
assert.equal(Object.keys(store.getState().byPlayerId).length, 2);
assert.ok(store.getState().byPlayerId.a);
assert.equal(store.getState().byPlayerId.a?.ny, 0.88);
store.dispatch({ kind: 'setVisible', visible: false });
assert.equal(store.getState().visible, false);
assert.ok(store.getState().byPlayerId.a);
store.dispatch({ kind: 'clearPlacements' });
assert.equal(store.getState().visible, false);
assert.deepEqual(store.getState().byPlayerId, {});
assert.deepEqual(store.getState().selectedPlayerIds, ['a', 'b']);
});
void test('ScenePlayerTokensSessionStore move and reset', () => {
const store = new ScenePlayerTokensSessionStore();
store.dispatch({ kind: 'setSelection', playerIds: ['p1'] });
store.dispatch({ kind: 'show', sizeN: 0.1 });
const s1 = store.dispatch({ kind: 'move', playerId: 'p1', nx: 0.3, ny: 0.4 });
assert.equal(s1.byPlayerId.p1?.nx, 0.3);
assert.equal(s1.byPlayerId.p1?.ny, 0.4);
const s2 = store.reset();
assert.deepEqual(s2.selectedPlayerIds, []);
assert.equal(s2.visible, false);
assert.deepEqual(s2.byPlayerId, {});
});
void test('ScenePlayerTokensSessionStore rotateMapCwSteps', () => {
const store = new ScenePlayerTokensSessionStore();
store.dispatch({ kind: 'setSelection', playerIds: ['p1'] });
store.dispatch({ kind: 'show', sizeN: 0.1 });
store.dispatch({ kind: 'move', playerId: 'p1', nx: 0.2, ny: 0.1 });
const s = store.rotateMapCwSteps(1);
assert.equal(s.byPlayerId.p1?.nx, 0.9);
assert.equal(s.byPlayerId.p1?.ny, 0.2);
});
@@ -0,0 +1,165 @@
import {
clampSceneNpcTokenSizeN,
DEFAULT_SCENE_NPC_TOKEN_SIZE_N,
layoutPlayerTokensBottom,
type ScenePlayerTokensSessionEvent,
type ScenePlayerTokensSessionState,
} from '../../shared/types/appPlayers';
import { rotateMapNormPointByCwSteps } from '../../shared/types/scenePreviewRotation';
function emptyState(revision = 1): ScenePlayerTokensSessionState {
return {
revision,
selectedPlayerIds: [],
visible: false,
byPlayerId: {},
};
}
function normalizePlayerIds(raw: readonly string[]): string[] {
const seen = new Set<string>();
const out: string[] = [];
for (const id of raw) {
const s = String(id ?? '').trim();
if (!s || seen.has(s)) continue;
seen.add(s);
out.push(s);
}
return out;
}
export class ScenePlayerTokensSessionStore {
private state: ScenePlayerTokensSessionState = emptyState();
getState(): ScenePlayerTokensSessionState {
return this.state;
}
reset(): ScenePlayerTokensSessionState {
if (
this.state.selectedPlayerIds.length === 0 &&
!this.state.visible &&
Object.keys(this.state.byPlayerId).length === 0
) {
return this.state;
}
this.state = emptyState(this.state.revision + 1);
return this.state;
}
/** Смена сцены: спрятать токены, сбросить позиции; выбор игроков сохранить. */
clearPlacements(): ScenePlayerTokensSessionState {
if (!this.state.visible && Object.keys(this.state.byPlayerId).length === 0) {
return this.state;
}
this.state = {
...this.state,
revision: this.state.revision + 1,
visible: false,
byPlayerId: {},
};
return this.state;
}
/** Rotate live player tokens with the scene preview (CSS rotate steps). */
rotateMapCwSteps(steps: number): ScenePlayerTokensSessionState {
const n = ((steps % 4) + 4) % 4;
if (n === 0) return this.state;
const ids = Object.keys(this.state.byPlayerId);
if (ids.length === 0) return this.state;
const byPlayerId: ScenePlayerTokensSessionState['byPlayerId'] = {};
for (const id of ids) {
const prev = this.state.byPlayerId[id];
if (!prev) continue;
const p = rotateMapNormPointByCwSteps(prev.nx, prev.ny, n);
byPlayerId[id] = { ...prev, nx: p.nx, ny: p.ny };
}
this.state = {
...this.state,
revision: this.state.revision + 1,
byPlayerId,
};
return this.state;
}
dispatch(event: ScenePlayerTokensSessionEvent): ScenePlayerTokensSessionState {
switch (event.kind) {
case 'clear':
return this.reset();
case 'clearPlacements':
return this.clearPlacements();
case 'setSelection': {
const selectedPlayerIds = normalizePlayerIds(event.playerIds);
const same =
selectedPlayerIds.length === this.state.selectedPlayerIds.length &&
selectedPlayerIds.every((id, i) => id === this.state.selectedPlayerIds[i]);
if (same) return this.state;
this.state = {
revision: this.state.revision + 1,
selectedPlayerIds,
visible: false,
byPlayerId: {},
};
return this.state;
}
case 'setVisible': {
const visible = Boolean(event.visible);
if (this.state.visible === visible) return this.state;
if (visible && this.state.selectedPlayerIds.length === 0) return this.state;
this.state = { ...this.state, revision: this.state.revision + 1, visible };
return this.state;
}
case 'show': {
if (this.state.selectedPlayerIds.length === 0) return this.state;
const sizeN = clampSceneNpcTokenSizeN(event.sizeN);
const byPlayerId =
Object.keys(this.state.byPlayerId).length > 0
? this.state.byPlayerId
: layoutPlayerTokensBottom(this.state.selectedPlayerIds, sizeN);
if (this.state.visible && byPlayerId === this.state.byPlayerId) return this.state;
this.state = {
...this.state,
revision: this.state.revision + 1,
visible: true,
byPlayerId,
};
return this.state;
}
case 'seedBottom': {
if (this.state.selectedPlayerIds.length === 0) return this.state;
if (Object.keys(this.state.byPlayerId).length > 0) return this.state;
const sizeN = clampSceneNpcTokenSizeN(event.sizeN);
this.state = {
...this.state,
revision: this.state.revision + 1,
byPlayerId: layoutPlayerTokensBottom(this.state.selectedPlayerIds, sizeN),
};
return this.state;
}
case 'move': {
const playerId = String(event.playerId ?? '');
if (!playerId || !this.state.selectedPlayerIds.includes(playerId)) return this.state;
const nx = Math.max(0, Math.min(1, event.nx));
const ny = Math.max(0, Math.min(1, event.ny));
if (!Number.isFinite(nx) || !Number.isFinite(ny)) return this.state;
const prev = this.state.byPlayerId[playerId];
if (prev && prev.nx === nx && prev.ny === ny) return this.state;
const sizeN = clampSceneNpcTokenSizeN(prev?.sizeN ?? DEFAULT_SCENE_NPC_TOKEN_SIZE_N);
this.state = {
...this.state,
revision: this.state.revision + 1,
byPlayerId: {
...this.state.byPlayerId,
[playerId]: { nx, ny, sizeN },
},
};
return this.state;
}
default: {
const _exhaustive: never = event;
void _exhaustive;
return this.state;
}
}
}
}
+9 -1
View File
@@ -2,7 +2,7 @@
* Visually lossless re-encode for imported raster images (same pixel dimensions).
* Node-only; shared by the main app and ../project-converter (monorepo sibling).
*/
import sharp from 'sharp';
import { getSharp } from './sharpRuntime.mjs';
/** @typedef {import('node:buffer').Buffer} Buffer */
@@ -102,6 +102,7 @@ function makePassthrough(buf, meta) {
* @param {number} h0
*/
async function sameDimensionsOrThrow(outBuf, w0, h0) {
const sharp = getSharp();
const m = await sharp(outBuf).metadata();
if ((m.width ?? 0) !== w0 || (m.height ?? 0) !== h0) {
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' });
}
let sharp;
try {
sharp = getSharp();
} catch {
return makePassthrough(input, null);
}
let meta0;
try {
meta0 = await sharp(input, { failOn: 'error', unlimited: true }).metadata();
@@ -33,3 +33,19 @@ void test('generateScenePreviewThumbnailBytes: image scales to max edge', async
await fs.rm(tmp, { recursive: true, force: true });
});
void test('generateScenePreviewThumbnailBytes: accepts image Buffer', async () => {
const png = await sharp({
create: {
width: 120,
height: 80,
channels: 3,
background: { r: 10, g: 20, b: 30 },
},
})
.png()
.toBuffer();
const buf = await generateScenePreviewThumbnailBytes(png, 'image');
assert.ok(buf !== null);
assert.ok(buf.length > 0);
});
+9 -3
View File
@@ -5,7 +5,8 @@ import path from 'node:path';
import { promisify } from 'node:util';
import ffmpegStatic from 'ffmpeg-static';
import sharp from 'sharp';
import { getSharp } from './sharpRuntime.mjs';
const execFileAsync = promisify(execFile);
@@ -14,14 +15,16 @@ export const SCENE_PREVIEW_THUMB_MAX_PX = 320;
/**
* Builds a small WebP still for graph/list previews. Returns null if generation fails (import still succeeds).
* For images, prefer a Buffer so callers are not racy with reconcileAssetFiles unlinking paths.
*/
export async function generateScenePreviewThumbnailBytes(
sourceAbsPath: string,
source: string | Buffer,
kind: 'image' | 'video',
): Promise<Buffer | null> {
try {
const sharp = getSharp();
if (kind === 'image') {
return await sharp(sourceAbsPath)
return await sharp(source)
.rotate()
.resize(SCENE_PREVIEW_THUMB_MAX_PX, SCENE_PREVIEW_THUMB_MAX_PX, {
fit: 'inside',
@@ -31,6 +34,9 @@ export async function generateScenePreviewThumbnailBytes(
.toBuffer();
}
const sourceAbsPath = typeof source === 'string' ? source : null;
if (!sourceAbsPath) return null;
const ffmpegPath = ffmpegStatic;
if (!ffmpegPath) return null;
+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/);
});
@@ -50,6 +50,17 @@ void test('zipStore: pack and open operations are serialized', () => {
assert.match(src, /enqueueProjectSwitch/);
});
void test('zipStore: project updates and preview finalize are serialized', () => {
const src = fs.readFileSync(path.join(here, 'zipStore.ts'), 'utf8');
assert.match(src, /private projectUpdateChain: Promise<unknown>/);
assert.match(src, /private previewFinalizeChain: Promise<unknown>/);
assert.match(src, /enqueueProjectUpdate/);
assert.match(src, /enqueuePreviewFinalize/);
assert.match(src, /finalizeScenePreviewImportInner/);
assert.match(src, /drainProjectMutations/);
assert.match(src, /addBuffer/);
});
void test('zipStore: closeOpenProject is serialized with open on projectSwitchChain', () => {
const src = fs.readFileSync(path.join(here, 'zipStore.ts'), 'utf8');
assert.match(src, /async closeOpenProject\(\): Promise<void> \{[\s\S]*enqueueProjectSwitch/);
+299 -66
View File
@@ -53,9 +53,35 @@ import type {
import { PROJECT_SCHEMA_VERSION } from '../../shared/types';
import { normalizeMaterialLegend } from '../../shared/types/materialLegend';
import { normalizeSceneToken, type SceneToken } from '../../shared/types/appTokens';
import {
clampPlayerImageOffset,
clampPlayerImageScale,
DEFAULT_PLAYER_RING_COLOR,
normalizeSceneNpcToken,
type SceneNpcToken,
} from '../../shared/types/appPlayers';
import {
DEFAULT_NPC_DISPOSITION,
normalizeNpcDisposition,
npcDispositionRingColor,
type NpcDisposition,
} from '../../shared/types/npcDisposition';
import { DEFAULT_SCENE_GRID, normalizeSceneGrid } from '../../shared/types/sceneGrid';
import {
asPreviewRotationDeg,
previewRotationStepsCw,
rotateMapMarkersByCwSteps,
rotateSceneTokensByCwSteps,
} from '../../shared/types/scenePreviewRotation';
import { normalizeSceneTrap } from '../../shared/types/sceneTraps';
import type { AssetId, GraphNodeId, MaterialId, NpcGroupId, NpcId, NpcRelationId } from '../../shared/types/ids';
import type {
AssetId,
GraphNodeId,
MaterialId,
NpcGroupId,
NpcId,
NpcRelationId,
} from '../../shared/types/ids';
import {
asAssetId,
asGraphNodeId,
@@ -110,12 +136,44 @@ export class ZipProjectStore {
private projectSession = 0;
/** Serializes project.json writes — parallel renames caused ENOENT on Windows. */
private projectWriteChain: Promise<void> = Promise.resolve();
/**
* Serializes project mutations (mutator + reconcileAssetFiles).
* Parallel updateProject during batch scene-preview import caused lost updates and
* reconcileAssetFiles deleting preview files still referenced after a stale write (ENOENT).
*/
private projectUpdateChain: Promise<unknown> = Promise.resolve();
/** Serializes background preview optimize/thumb — avoids parallel sharp + orphan races. */
private previewFinalizeChain: Promise<unknown> = Promise.resolve();
/** Serializes zip pack operations — parallel yazl/yauzl caused «unexpected number of bytes». */
private packChain: Promise<void> = Promise.resolve();
/** Serializes open/close/unzip — concurrent IPC caused ghost open projects and deadlocks. */
private projectSwitchChain: Promise<void> = Promise.resolve();
private saveDebounceTimer: ReturnType<typeof setTimeout> | null = null;
private enqueueProjectUpdate<T>(fn: () => Promise<T>): Promise<T> {
const task = this.projectUpdateChain.then(() => fn());
this.projectUpdateChain = task.then(
() => undefined,
() => undefined,
);
return task;
}
private enqueuePreviewFinalize<T>(fn: () => Promise<T>): Promise<T> {
const task = this.previewFinalizeChain.then(() => fn());
this.previewFinalizeChain = task.then(
() => undefined,
() => undefined,
);
return task;
}
/** Wait until preview optimize/thumb and project mutators finish (before pack/close). */
private async drainProjectMutations(): Promise<void> {
await this.previewFinalizeChain;
await this.projectUpdateChain;
}
private enqueuePack(cacheDir: string, zipPath: string): Promise<void> {
const next = this.packChain.then(async () => {
await this.packZipFromCache(cacheDir, zipPath);
@@ -143,6 +201,8 @@ export class ZipProjectStore {
clearTimeout(this.saveDebounceTimer);
this.saveDebounceTimer = null;
}
// Finish preview finalizers before flush/pack — otherwise yazl ENOENT on deleted assets.
await this.drainProjectMutations();
if (this.saveQueued) {
this.saveQueued = false;
await this.flushSave();
@@ -152,6 +212,7 @@ export class ZipProjectStore {
}
await this.packChain;
await this.projectWriteChain;
await this.drainProjectMutations();
}
async ensureRoots(): Promise<void> {
@@ -437,32 +498,68 @@ export class ZipProjectStore {
sceneId: SceneId,
assetId: AssetId,
): Promise<{ project: Project; changed: boolean }> {
return this.enqueuePreviewFinalize(() => this.finalizeScenePreviewImportInner(sceneId, assetId));
}
private async finalizeScenePreviewImportInner(
sceneId: SceneId,
assetId: AssetId,
): Promise<{ project: Project; changed: boolean }> {
const sessionAtStart = this.projectSession;
const open = this.openProject;
if (!open) throw new Error('No open project');
const sceneAtStart = open.project.scenes[sceneId];
if (!open) {
// Queued finalize after close — nothing to apply.
return { project: undefined as unknown as Project, changed: false };
}
const projectAtStart = open.project;
const sceneAtStart = projectAtStart.scenes[sceneId];
if (sceneAtStart?.previewAssetId !== assetId) {
return { project: open.project, changed: false };
return { project: projectAtStart, changed: false };
}
const sourceAsset = open.project.assets[assetId];
const sourceAsset = projectAtStart.assets[assetId];
if (!sourceAsset || (sourceAsset.type !== 'image' && sourceAsset.type !== 'video')) {
return { project: open.project, changed: false };
return { project: projectAtStart, changed: false };
}
const cacheDir = open.cacheDir;
const stillOpen = () =>
this.openProject !== null &&
this.projectSession === sessionAtStart &&
this.openProject.cacheDir === cacheDir;
const generatedRelPaths: string[] = [];
let finalAsset = sourceAsset;
let finalAssetId = assetId;
let finalAbs = path.join(open.cacheDir, sourceAsset.relPath);
let finalAbs = path.join(cacheDir, sourceAsset.relPath);
/** Image bytes kept in memory so thumb/optimize do not re-open a path that reconcile may unlink. */
let imageBytes: Buffer | null = null;
if (sourceAsset.type === 'image') {
const input = await fs.readFile(finalAbs);
const opt = await optimizeImageBufferVisuallyLossless(input);
try {
imageBytes = await fs.readFile(finalAbs);
} catch (e) {
const err = e as NodeJS.ErrnoException;
if (err?.code === 'ENOENT') {
const latest = this.getOpenProject();
return { project: latest ?? projectAtStart, changed: false };
}
throw e;
}
if (!stillOpen()) {
return { project: this.getOpenProject() ?? projectAtStart, changed: false };
}
const opt = await optimizeImageBufferVisuallyLossless(imageBytes);
if (!stillOpen()) {
return { project: this.getOpenProject() ?? projectAtStart, changed: false };
}
if (!opt.passthrough) {
finalAssetId = asAssetId(this.randomId());
const optimizedName = `${path.parse(sourceAsset.originalName).name}.${opt.ext}`;
const safeOptimizedName = sanitizeFileName(optimizedName);
const optimizedRelPath = `assets/${finalAssetId}_${safeOptimizedName}`;
finalAbs = path.join(open.cacheDir, optimizedRelPath);
finalAbs = path.join(cacheDir, optimizedRelPath);
const optimizedBuffer = Buffer.from(opt.buffer);
imageBytes = optimizedBuffer;
await fs.writeFile(finalAbs, optimizedBuffer);
generatedRelPaths.push(optimizedRelPath);
const optimizedAsset = buildMediaAsset(
@@ -480,14 +577,26 @@ export class ZipProjectStore {
}
}
if (!stillOpen()) {
await Promise.all(
generatedRelPaths.map((relPath) =>
fs.unlink(path.join(cacheDir, relPath)).catch(() => undefined),
),
);
return { project: this.getOpenProject() ?? projectAtStart, changed: false };
}
const thumbKind = finalAsset.type === 'image' ? 'image' : 'video';
const thumbBytes = await generateScenePreviewThumbnailBytes(finalAbs, thumbKind);
const thumbBytes =
thumbKind === 'image' && imageBytes
? await generateScenePreviewThumbnailBytes(imageBytes, 'image')
: await generateScenePreviewThumbnailBytes(finalAbs, thumbKind);
let thumbAsset: MediaAsset | null = null;
let thumbId: AssetId | null = null;
if (thumbBytes !== null && thumbBytes.length > 0) {
thumbId = asAssetId(this.randomId());
const thumbRelPath = `assets/${thumbId}_preview_thumb.webp`;
const thumbAbs = path.join(open.cacheDir, thumbRelPath);
const thumbAbs = path.join(cacheDir, thumbRelPath);
await fs.writeFile(thumbAbs, thumbBytes);
generatedRelPaths.push(thumbRelPath);
const thumbOrigName = `${path.parse(finalAsset.originalName).name}_preview_thumb.webp`;
@@ -501,12 +610,27 @@ export class ZipProjectStore {
);
}
if (!stillOpen()) {
await Promise.all(
generatedRelPaths.map((relPath) =>
fs.unlink(path.join(cacheDir, relPath)).catch(() => undefined),
),
);
return { project: this.getOpenProject() ?? projectAtStart, changed: false };
}
let applied = false;
try {
await this.updateProject((p) => {
const scene = p.scenes[sceneId];
if (scene?.previewAssetId !== assetId) {
return p;
}
applied = true;
const assets: Record<AssetId, MediaAsset> = { ...p.assets, [finalAssetId]: finalAsset };
if (finalAssetId !== assetId) {
delete assets[assetId];
}
if (thumbAsset !== null && thumbId !== null) {
assets[thumbId] = thumbAsset;
}
@@ -525,22 +649,28 @@ export class ZipProjectStore {
},
};
});
} catch (e) {
if (!stillOpen() || (e instanceof Error && e.message === 'No open project')) {
await Promise.all(
generatedRelPaths.map((relPath) =>
fs.unlink(path.join(cacheDir, relPath)).catch(() => undefined),
),
);
return { project: this.getOpenProject() ?? projectAtStart, changed: false };
}
throw e;
}
const latest = this.getOpenProject();
if (!latest) throw new Error('No open project');
const latestScene = latest.scenes[sceneId];
const applied =
latestScene?.previewAssetId === finalAssetId &&
(thumbId === null || latestScene.previewThumbAssetId === thumbId);
if (!applied) {
await Promise.all(
generatedRelPaths.map((relPath) =>
fs.unlink(path.join(open.cacheDir, relPath)).catch(() => undefined),
fs.unlink(path.join(cacheDir, relPath)).catch(() => undefined),
),
);
}
return { project: latest, changed: applied };
return { project: latest ?? projectAtStart, changed: applied };
}
async clearScenePreview(sceneId: SceneId): Promise<Project> {
@@ -581,6 +711,7 @@ export class ZipProjectStore {
}
async updateProject(mutator: (draft: Project) => Project): Promise<Project> {
return this.enqueueProjectUpdate(async () => {
const open = this.openProject;
if (!open) throw new Error('No open project');
const prev = open.project;
@@ -590,6 +721,7 @@ export class ZipProjectStore {
await this.writeCacheProject(open.cacheDir, next);
this.queueSave();
return next;
});
}
async updateScene(sceneId: SceneId, patch: ScenePatch): Promise<Scene> {
@@ -614,6 +746,7 @@ export class ZipProjectStore {
darkenScene: false,
traps: [],
tokens: [],
npcTokens: [],
grid: { ...DEFAULT_SCENE_GRID },
} satisfies Scene);
@@ -621,6 +754,7 @@ export class ZipProjectStore {
...base,
traps: base.traps ?? [],
tokens: base.tokens ?? [],
npcTokens: base.npcTokens ?? [],
grid: base.grid ?? { ...DEFAULT_SCENE_GRID },
...(patch.title !== undefined ? { title: patch.title } : null),
...(patch.description !== undefined ? { description: patch.description } : null),
@@ -636,9 +770,7 @@ export class ZipProjectStore {
...(patch.darkenScene !== undefined ? { darkenScene: patch.darkenScene } : null),
...(patch.traps !== undefined
? {
traps: patch.traps
.map((t) => normalizeSceneTrap(t))
.filter((t): t is SceneTrap => Boolean(t)),
traps: patch.traps.map((t) => normalizeSceneTrap(t)).filter((t): t is SceneTrap => Boolean(t)),
}
: null),
...(patch.tokens !== undefined
@@ -648,12 +780,37 @@ export class ZipProjectStore {
.filter((t): t is SceneToken => Boolean(t)),
}
: null),
...(patch.npcTokens !== undefined
? {
npcTokens: patch.npcTokens
.map((t) => normalizeSceneNpcToken(t))
.filter((t): t is SceneNpcToken => Boolean(t)),
}
: null),
...(patch.grid !== undefined ? { grid: normalizeSceneGrid(patch.grid) } : null),
...(patch.settings ? { settings: { ...base.settings, ...patch.settings } } : null),
...(patch.media ? { media: { ...base.media, ...patch.media } } : null),
...(patch.layout ? { layout: { ...base.layout, ...patch.layout } } : null),
};
// Keep map markers glued to the art when previewRotationDeg changes (image/video).
if (patch.previewRotationDeg !== undefined) {
const fromRot = asPreviewRotationDeg(base.previewRotationDeg);
const toRot = asPreviewRotationDeg(patch.previewRotationDeg);
const steps = previewRotationStepsCw(fromRot, toRot);
if (steps !== 0) {
if (patch.tokens === undefined) {
next.tokens = rotateSceneTokensByCwSteps(base.tokens ?? [], steps);
}
if (patch.npcTokens === undefined) {
next.npcTokens = rotateMapMarkersByCwSteps(base.npcTokens ?? [], steps);
}
if (patch.traps === undefined) {
next.traps = rotateMapMarkersByCwSteps(base.traps ?? [], steps);
}
}
}
await this.updateProject((p) => {
const scenes = { ...p.scenes, [sceneId]: next };
const sceneListOrder =
@@ -798,7 +955,10 @@ export class ZipProjectStore {
const node = open.project.sceneGraphNodes.find((n) => n.id === graphNodeId);
if (!node) throw new Error('Graph node not found');
const enabling = !node.isSideStoryStart;
if (enabling && !canSetSideStoryStart(open.project.sceneGraphNodes, open.project.sceneGraphEdges, graphNodeId)) {
if (
enabling &&
!canSetSideStoryStart(open.project.sceneGraphNodes, open.project.sceneGraphEdges, graphNodeId)
) {
return open.project;
}
await this.updateProject((p) => {
@@ -1158,16 +1318,11 @@ export class ZipProjectStore {
return latest;
}
async setMaterialRotation(
materialId: MaterialId,
rotationDeg: 0 | 90 | 180 | 270,
): Promise<Project> {
async setMaterialRotation(materialId: MaterialId, rotationDeg: 0 | 90 | 180 | 270): Promise<Project> {
const open = this.openProject;
if (!open) throw new Error('No open project');
await this.updateProject((p) => {
const materials = (p.materials ?? []).map((m) =>
m.id === materialId ? { ...m, rotationDeg } : m,
);
const materials = (p.materials ?? []).map((m) => (m.id === materialId ? { ...m, rotationDeg } : m));
return { ...p, materials };
});
const latest = this.getOpenProject();
@@ -1243,6 +1398,10 @@ export class ZipProjectStore {
description?: string;
filePath?: string;
groupId?: NpcGroupId | null;
ringColor?: string;
disposition?: NpcDisposition;
imageOffset?: { x: number; y: number };
imageScale?: number;
},
onProgress?: (p: { percent: number; stage: string; detail?: string }) => void,
): Promise<Project> {
@@ -1300,7 +1459,10 @@ export class ZipProjectStore {
if (stagedAsset) assets[stagedAsset.id] = stagedAsset;
const groupIds = new Set((p.npcGroups ?? []).map((g) => g.id));
const resolveGroup = (raw: NpcGroupId | null | undefined, prev: NpcGroupId | null): NpcGroupId | null => {
const resolveGroup = (
raw: NpcGroupId | null | undefined,
prev: NpcGroupId | null,
): NpcGroupId | null => {
if (raw === undefined) return prev;
if (raw === null) return null;
return groupIds.has(raw) ? raw : null;
@@ -1314,13 +1476,28 @@ export class ZipProjectStore {
...prev,
name,
avatarAssetId: nextAssetId ?? prev.avatarAssetId,
description:
typeof input.description === 'string' ? input.description : prev.description,
description: typeof input.description === 'string' ? input.description : prev.description,
groupId: resolveGroup(input.groupId, prev.groupId),
...(input.ringColor !== undefined
? { ringColor: normalizeHexColor(input.ringColor, DEFAULT_PLAYER_RING_COLOR) }
: {}),
...(input.disposition !== undefined
? {
disposition: normalizeNpcDisposition(input.disposition),
ringColor: npcDispositionRingColor(normalizeNpcDisposition(input.disposition)),
}
: {}),
...(input.imageOffset !== undefined
? { imageOffset: clampPlayerImageOffset(input.imageOffset) }
: {}),
...(input.imageScale !== undefined
? { imageScale: clampPlayerImageScale(input.imageScale) }
: {}),
};
} else {
if (!nextAssetId) throw new Error('NPC avatar is required');
const count = npcs.length;
const disposition = normalizeNpcDisposition(input.disposition ?? DEFAULT_NPC_DISPOSITION);
npcs.push({
id: asNpcId(`npc_${this.randomId()}`),
name,
@@ -1329,6 +1506,10 @@ export class ZipProjectStore {
x: 80 + (count % 4) * 220,
y: 80 + Math.floor(count / 4) * 200,
groupId: resolveGroup(input.groupId, null),
disposition,
ringColor: npcDispositionRingColor(disposition),
imageOffset: clampPlayerImageOffset(input.imageOffset),
imageScale: clampPlayerImageScale(input.imageScale),
});
}
return { ...p, assets, npcs };
@@ -1346,20 +1527,19 @@ export class ZipProjectStore {
name?: string;
description?: string;
groupId?: NpcGroupId | null;
ringColor?: string;
disposition?: NpcDisposition;
imageOffset?: { x: number; y: number };
imageScale?: number;
},
): Promise<Project> {
const open = this.openProject;
if (!open) throw new Error('No open project');
const name =
typeof patch.name === 'string' ? patch.name.trim() : undefined;
const name = typeof patch.name === 'string' ? patch.name.trim() : undefined;
if (name !== undefined) {
if (name.length < 1) throw new Error('NPC name is required');
const nameKey = name.toLowerCase();
if (
(open.project.npcs ?? []).some(
(n) => n.id !== npcId && n.name.trim().toLowerCase() === nameKey,
)
) {
if ((open.project.npcs ?? []).some((n) => n.id !== npcId && n.name.trim().toLowerCase() === nameKey)) {
throw new Error('NPC name already exists');
}
}
@@ -1369,14 +1549,30 @@ export class ZipProjectStore {
if (n.id !== npcId) return n;
let groupId = n.groupId;
if (patch.groupId !== undefined) {
groupId =
patch.groupId === null ? null : groupIds.has(patch.groupId) ? patch.groupId : null;
groupId = patch.groupId === null ? null : groupIds.has(patch.groupId) ? patch.groupId : null;
}
const disposition =
patch.disposition !== undefined
? normalizeNpcDisposition(patch.disposition)
: normalizeNpcDisposition(n.disposition);
return {
...n,
...(name !== undefined ? { name } : {}),
...(typeof patch.description === 'string' ? { description: patch.description } : {}),
groupId,
disposition,
ringColor:
patch.disposition !== undefined
? npcDispositionRingColor(disposition)
: patch.ringColor !== undefined
? normalizeHexColor(patch.ringColor, DEFAULT_PLAYER_RING_COLOR)
: n.ringColor || npcDispositionRingColor(disposition),
...(patch.imageOffset !== undefined
? { imageOffset: clampPlayerImageOffset(patch.imageOffset) }
: {}),
...(patch.imageScale !== undefined
? { imageScale: clampPlayerImageScale(patch.imageScale) }
: {}),
};
});
return { ...p, npcs };
@@ -1401,13 +1597,25 @@ export class ZipProjectStore {
async deleteNpc(npcId: NpcId): Promise<Project> {
const open = this.openProject;
if (!open) throw new Error('No open project');
await this.updateProject((p) => ({
await this.updateProject((p) => {
const scenes: Record<SceneId, Scene> = { ...p.scenes };
for (const sid of Object.keys(scenes) as SceneId[]) {
const sc = scenes[sid];
if (!sc) continue;
const npcTokens = (sc.npcTokens ?? []).filter((t) => t.npcId !== npcId);
if (npcTokens.length !== (sc.npcTokens ?? []).length) {
scenes[sid] = { ...sc, npcTokens };
}
}
return {
...p,
scenes,
npcs: (p.npcs ?? []).filter((n) => n.id !== npcId),
npcRelations: (p.npcRelations ?? []).filter(
(r) => r.sourceNpcId !== npcId && r.targetNpcId !== npcId,
),
}));
};
});
const latest = this.getOpenProject();
if (!latest) throw new Error('No open project');
return latest;
@@ -1462,10 +1670,7 @@ export class ZipProjectStore {
}
const nameKey = name.toLowerCase();
const siblingConflict = groups.some(
(g) =>
g.id !== editingId &&
g.parentId === parentId &&
g.name.trim().toLowerCase() === nameKey,
(g) => g.id !== editingId && g.parentId === parentId && g.name.trim().toLowerCase() === nameKey,
);
if (siblingConflict) throw new Error('Group name already exists');
@@ -1498,9 +1703,7 @@ export class ZipProjectStore {
const nextGroups = groups
.filter((g) => g.id !== groupId)
.map((g) => (g.parentId === groupId ? { ...g, parentId: parentOfDeleted } : g));
const npcs = (p.npcs ?? []).map((n) =>
n.groupId === groupId ? { ...n, groupId: null } : n,
);
const npcs = (p.npcs ?? []).map((n) => (n.groupId === groupId ? { ...n, groupId: null } : n));
return { ...p, npcGroups: nextGroups, npcs };
});
const latest = this.getOpenProject();
@@ -1541,10 +1744,7 @@ export class ZipProjectStore {
if (label.length < 1) throw new Error('Relation label is required');
if (input.sourceNpcId === input.targetNpcId) throw new Error('Cannot relate NPC to itself');
const npcs = open.project.npcs ?? [];
if (
!npcs.some((n) => n.id === input.sourceNpcId) ||
!npcs.some((n) => n.id === input.targetNpcId)
) {
if (!npcs.some((n) => n.id === input.sourceNpcId) || !npcs.some((n) => n.id === input.targetNpcId)) {
throw new Error('NPC not found');
}
await this.updateProject((p) => {
@@ -1583,14 +1783,18 @@ export class ZipProjectStore {
async saveNow(): Promise<void> {
const open = this.openProject;
if (!open) return;
// Let background preview finalizers finish before packing cache → zip.
await this.drainProjectMutations();
await this.projectWriteChain;
await this.enqueuePack(open.cacheDir, open.zipPath);
}
async closeOpenProject(): Promise<void> {
return this.enqueueProjectSwitch(async () => {
// Invalidate in-flight finalize early; then wait for queue to settle.
this.projectSession += 1;
if (!this.openProject) return;
await this.drainProjectMutations();
await this.saveNow();
await this.drainSavePipeline();
this.saveQueued = false;
@@ -2089,16 +2293,14 @@ export class ZipProjectStore {
sourceForMerge = remapProjectSceneTokenIds(source, remap);
}
const offsetX = computeGraphImportOffsetX(this.openProject.project);
const { project: merged, report, assetCopies } = mergeStorylinesIntoProject(
this.openProject.project,
sourceForMerge,
selections,
sceneResolutions,
{
const {
project: merged,
report,
assetCopies,
} = mergeStorylinesIntoProject(this.openProject.project, sourceForMerge, selections, sceneResolutions, {
graphOffsetX: offsetX,
...(npcResolutions ? { npcResolutions } : {}),
},
);
});
const targetCache = this.openProject.cacheDir;
await fs.mkdir(path.join(targetCache, 'assets'), { recursive: true });
@@ -2307,6 +2509,10 @@ function normalizeScene(s: Scene): Scene {
const tokens = (Array.isArray(rawTokens) ? rawTokens : [])
.map((t) => normalizeSceneToken(t))
.filter((t): t is SceneToken => Boolean(t));
const rawNpcTokens = (s as unknown as { npcTokens?: unknown[] }).npcTokens;
const npcTokens = (Array.isArray(rawNpcTokens) ? rawNpcTokens : [])
.map((t) => normalizeSceneNpcToken(t))
.filter((t): t is SceneNpcToken => Boolean(t));
const grid = normalizeSceneGrid((s as unknown as { grid?: unknown }).grid);
const rawAudios = Array.isArray(raw.audios) ? raw.audios : [];
@@ -2338,6 +2544,7 @@ function normalizeScene(s: Scene): Scene {
darkenScene,
traps,
tokens,
npcTokens,
grid,
layout: layoutIn ?? { x: 0, y: 0 },
media: {
@@ -2429,6 +2636,8 @@ function normalizeProject(p: Project): Project {
x?: number;
y?: number;
groupId?: string | null;
ringColor?: string;
imageOffset?: unknown;
};
if (!obj.id || !obj.avatarAssetId || typeof obj.name !== 'string') return null;
const name = obj.name.trim();
@@ -2444,6 +2653,12 @@ function normalizeProject(p: Project): Project {
x,
y,
groupId: resolveNpcGroupId(obj.groupId, groupIdSet),
disposition: normalizeNpcDisposition((obj as { disposition?: unknown }).disposition),
ringColor: npcDispositionRingColor(
normalizeNpcDisposition((obj as { disposition?: unknown }).disposition),
),
imageOffset: clampPlayerImageOffset(obj.imageOffset),
imageScale: clampPlayerImageScale((obj as { imageScale?: unknown }).imageScale),
};
})
.filter((x): x is ProjectNpc => Boolean(x));
@@ -2481,6 +2696,15 @@ function normalizeProject(p: Project): Project {
if (a && a.length > 0) return a;
return '0.0.0';
})();
const scenesPruned: Record<SceneId, Scene> = {};
for (const sid of Object.keys(scenes) as SceneId[]) {
const sc = scenes[sid];
if (!sc) continue;
scenesPruned[sid] = {
...sc,
npcTokens: (sc.npcTokens ?? []).filter((t) => npcIdSet.has(t.npcId)),
};
}
return {
...p,
meta: {
@@ -2491,7 +2715,7 @@ function normalizeProject(p: Project): Project {
createdWithAppVersion,
schemaVersion: PROJECT_SCHEMA_VERSION,
},
scenes,
scenes: scenesPruned,
campaignAudios,
materials,
npcs,
@@ -2501,7 +2725,7 @@ function normalizeProject(p: Project): Project {
sceneGraphEdges,
currentGraphNodeId,
sceneListOrder: reconcileSceneListOrder(
scenes,
scenesPruned,
(p as { sceneListOrder?: SceneId[] }).sceneListOrder,
),
};
@@ -2662,7 +2886,16 @@ async function zipDir(srcDir: string, outZipPath: string): Promise<void> {
const all = await listFilesRecursive(srcDir);
for (const abs of all) {
const rel = path.relative(srcDir, abs).replace(/\\/gu, '/');
zipfile.addFile(abs, rel, zipOptionsForRelativeEntry(rel));
// Bufferize: yazl.addFile opens lazily and can ENOENT if reconcile unlinks mid-pack.
let buf: Buffer;
try {
buf = await fs.readFile(abs);
} catch (e) {
const err = e as NodeJS.ErrnoException;
if (err?.code === 'ENOENT') continue;
throw e;
}
zipfile.addBuffer(buf, rel, zipOptionsForRelativeEntry(rel));
}
await fs.mkdir(path.dirname(outZipPath), { recursive: true });
const out = fssync.createWriteStream(outZipPath);
+6 -2
View File
@@ -2,7 +2,8 @@ import fs from 'node:fs/promises';
import { session } from 'electron';
import { asAssetId, asTokenId } from '../../shared/types/ids';
import { asAssetId, asPlayerId, asTokenId } from '../../shared/types/ids';
import type { PlayersStore } from '../players/playersStore';
import type { ZipProjectStore } from '../project/zipStore';
import type { TokensStore } from '../tokens/tokensStore';
@@ -75,11 +76,12 @@ async function serveFile(info: ReadInfo, request: Request): Promise<Response> {
}
/**
* Обслуживает `dnd://asset?...` и `dnd://token?...`.
* Обслуживает `dnd://asset?...`, `dnd://token?...` и `dnd://player?...`.
*/
export function registerDndAssetProtocol(
projectStore: ZipProjectStore,
tokensStore: TokensStore,
playersStore: PlayersStore | null,
): void {
session.defaultSession.protocol.handle('dnd', async (request) => {
const url = new URL(request.url);
@@ -92,6 +94,8 @@ export function registerDndAssetProtocol(
info = projectStore.getAssetReadInfo(asAssetId(id));
} else if (url.hostname === 'token') {
info = tokensStore.getImageReadInfo(asTokenId(id));
} else if (url.hostname === 'player') {
info = playersStore?.getImageReadInfo(asPlayerId(id)) ?? null;
}
if (!info) {
return new Response(null, { status: 404 });
@@ -1,4 +1,5 @@
import type { SceneTokensSessionEvent, SceneTokensSessionState } from '../../shared/types';
import { rotateMapNormPointByCwSteps } from '../../shared/types/scenePreviewRotation';
function emptyState(): SceneTokensSessionState {
return {
@@ -23,6 +24,26 @@ export class SceneTokensSessionStore {
return this.state;
}
/** Rotate session position overrides with the scene preview (CSS rotate steps). */
rotateMapCwSteps(steps: number): SceneTokensSessionState {
const n = ((steps % 4) + 4) % 4;
if (n === 0) return this.state;
const ids = Object.keys(this.state.byPlacementId);
if (ids.length === 0) return this.state;
const byPlacementId: SceneTokensSessionState['byPlacementId'] = {};
for (const id of ids) {
const prev = this.state.byPlacementId[id];
if (!prev) continue;
const next = rotateMapNormPointByCwSteps(prev.nx, prev.ny, n);
byPlacementId[id] = { nx: next.nx, ny: next.ny };
}
this.state = {
revision: this.state.revision + 1,
byPlacementId,
};
return this.state;
}
dispatch(event: SceneTokensSessionEvent): SceneTokensSessionState {
switch (event.kind) {
case 'clear':
@@ -0,0 +1,12 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { TokenGridSnapSessionStore } from './tokenGridSnapSessionStore';
void test('TokenGridSnapSessionStore: set and reset', () => {
const store = new TokenGridSnapSessionStore();
assert.equal(store.getState().enabled, false);
assert.equal(store.setEnabled(true).enabled, true);
assert.equal(store.getState().enabled, true);
assert.equal(store.reset().enabled, false);
});
@@ -0,0 +1,21 @@
export type TokenGridSnapSessionState = {
enabled: boolean;
};
export class TokenGridSnapSessionStore {
private enabled = false;
getState(): TokenGridSnapSessionState {
return { enabled: this.enabled };
}
setEnabled(enabled: boolean): TokenGridSnapSessionState {
this.enabled = Boolean(enabled);
return this.getState();
}
reset(): TokenGridSnapSessionState {
this.enabled = false;
return this.getState();
}
}
+171
View File
@@ -0,0 +1,171 @@
import {
emptyTokenPathSessionState,
tokenPathKey,
type TokenPathPlaybackEntry,
type TokenPathSessionEvent,
type TokenPathSessionState,
type TokenPathTargetRef,
} from '../../shared/types/tokenPathSession';
function bump(
state: TokenPathSessionState,
patch: Partial<Omit<TokenPathSessionState, 'revision' | 'serverNowMs'>>,
): TokenPathSessionState {
return {
...state,
...patch,
revision: state.revision + 1,
serverNowMs: Date.now(),
};
}
export class TokenPathSessionStore {
private state: TokenPathSessionState = emptyTokenPathSessionState();
getState(): TokenPathSessionState {
return this.state;
}
/** Refresh clock without logical change (optional heartbeat). */
touchClock(): TokenPathSessionState {
this.state = { ...this.state, serverNowMs: Date.now() };
return this.state;
}
reset(): TokenPathSessionState {
if (
Object.keys(this.state.playback).length === 0 &&
Object.keys(this.state.presentationVisible).length === 0
) {
return this.state;
}
this.state = emptyTokenPathSessionState(this.state.revision + 1);
return this.state;
}
dispatch(event: TokenPathSessionEvent): TokenPathSessionState {
switch (event.kind) {
case 'clear':
return this.reset();
case 'showPresentation': {
const key = tokenPathKey(event.target.kind, event.target.placementId);
if (this.state.presentationVisible[key]) return this.state;
this.state = bump(this.state, {
presentationVisible: { ...this.state.presentationVisible, [key]: true },
});
return this.state;
}
case 'hidePresentation': {
const key = tokenPathKey(event.target.kind, event.target.placementId);
if (!this.state.presentationVisible[key]) return this.state;
const { [key]: _removed, ...rest } = this.state.presentationVisible;
this.state = bump(this.state, { presentationVisible: rest });
return this.state;
}
case 'stop': {
const key = tokenPathKey(event.target.kind, event.target.placementId);
const prev = this.state.playback[key];
if (!prev || prev.phase === 'stopped') return this.state;
const atDist =
typeof event.atDist === 'number' && Number.isFinite(event.atDist)
? Math.max(0, event.atDist)
: prev.baseDist;
this.state = bump(this.state, {
playback: {
...this.state.playback,
[key]: {
...prev,
phase: 'stopped',
baseDist: atDist,
rejoinDist: null,
segmentStartedAtMs: Date.now(),
},
},
});
return this.state;
}
case 'resume': {
const key = tokenPathKey(event.target.kind, event.target.placementId);
const prev = this.state.playback[key];
if (!prev) return this.state;
if (prev.phase !== 'stopped' && prev.phase !== 'done') return this.state;
const entry: TokenPathPlaybackEntry = {
...prev,
phase: 'moving',
segmentStartedAtMs: Date.now(),
// Jump to nearest-ahead on path, then continue (v1: no off-path lerp).
baseDist: Math.max(0, event.fromDist),
rejoinDist: null,
direction: 1,
};
this.state = bump(this.state, {
playback: { ...this.state.playback, [key]: entry },
});
return this.state;
}
case 'resetToStart': {
const key = tokenPathKey(event.target.kind, event.target.placementId);
const prev = this.state.playback[key];
const entry: TokenPathPlaybackEntry = {
kind: event.target.kind,
placementId: event.target.placementId,
phase: 'moving',
segmentStartedAtMs: Date.now(),
baseDist: 0,
direction: 1,
rejoinDist: null,
durationSec: prev?.durationSec ?? 8,
pathLength: prev?.pathLength ?? 1,
};
this.state = bump(this.state, {
playback: { ...this.state.playback, [key]: entry },
});
return this.state;
}
case 'seedPlayback': {
const e = event.entry;
const key = tokenPathKey(e.kind, e.placementId);
const entry: TokenPathPlaybackEntry = {
kind: e.kind,
placementId: e.placementId,
phase: e.phase,
segmentStartedAtMs: e.segmentStartedAtMs ?? Date.now(),
baseDist: e.baseDist,
direction: e.direction,
rejoinDist: e.rejoinDist,
durationSec: e.durationSec,
pathLength: e.pathLength,
};
this.state = bump(this.state, {
playback: { ...this.state.playback, [key]: entry },
});
return this.state;
}
case 'markDone': {
const key = tokenPathKey(event.target.kind, event.target.placementId);
const prev = this.state.playback[key];
if (!prev || prev.phase === 'done') return this.state;
this.state = bump(this.state, {
playback: {
...this.state.playback,
[key]: {
...prev,
phase: 'done',
baseDist: prev.pathLength,
rejoinDist: null,
segmentStartedAtMs: Date.now(),
},
},
});
return this.state;
}
default: {
const _exhaustive: never = event;
void _exhaustive;
return this.state;
}
}
}
}
export type { TokenPathTargetRef };
+3 -8
View File
@@ -92,11 +92,7 @@ export class TokensStore {
return path.join(this.rootDir, relPath);
}
async upsert(input: {
id?: TokenId | null;
name: string;
filePath?: string | null;
}): Promise<AppToken> {
async upsert(input: { id?: TokenId | null; name: string; filePath?: string | null }): Promise<AppToken> {
await this.ensureLoaded();
const name = input.name.trim();
if (!name) throw new Error('Token name is required');
@@ -166,8 +162,7 @@ export class TokensStore {
}): Promise<{ token: AppToken; remappedFrom: TokenId }> {
await this.ensureLoaded();
let buf = await fs.readFile(input.absFilePath);
const sha256 =
input.sha256 ?? crypto.createHash('sha256').update(buf).digest('hex');
const sha256 = input.sha256 ?? crypto.createHash('sha256').update(buf).digest('hex');
const existingByHash = this.findBySha256(sha256);
if (existingByHash) {
return { token: existingByHash, remappedFrom: input.preferredId };
@@ -262,7 +257,7 @@ export class TokensStore {
preferredId: asTokenId(t.id),
name: typeof t.name === 'string' ? t.name : 'Token',
absFilePath: abs,
sha256: typeof t.sha256 === 'string' ? t.sha256 : undefined,
...(typeof t.sha256 === 'string' ? { sha256: t.sha256 } : {}),
});
remap.set(remappedFrom, token.id);
}
+80
View File
@@ -18,6 +18,7 @@ export type WindowKind =
| 'materials'
| 'npcsEditor'
| 'sceneEditor'
| 'tokenPathEditor'
| 'npcs';
/** Окна, которые реально слушают session.stateChanged (редактор синхронизируется через invoke). */
@@ -28,6 +29,7 @@ export const SESSION_STATE_WINDOW_KINDS: readonly WindowKind[] = [
'npcs',
'npcsEditor',
'sceneEditor',
'tokenPathEditor',
] as const;
const windows = new Map<WindowKind, BrowserWindow>();
@@ -209,6 +211,8 @@ function pageNameForKind(kind: WindowKind): string {
return 'npcsEditor.html';
case 'sceneEditor':
return 'sceneEditor.html';
case 'tokenPathEditor':
return 'tokenPathEditor.html';
case 'npcs':
return 'npcs.html';
}
@@ -280,6 +284,7 @@ function windowSizeForKind(kind: WindowKind): { width: number; height: number }
if (kind === 'materials') return { width: MATERIALS_WINDOW_WIDTH, height: MATERIALS_WINDOW_HEIGHT };
if (kind === 'npcsEditor') return { width: NPCS_EDITOR_WINDOW_WIDTH, height: NPCS_EDITOR_WINDOW_HEIGHT };
if (kind === 'sceneEditor') return { width: 1280, height: 800 };
if (kind === 'tokenPathEditor') return { width: 1100, height: 760 };
if (kind === 'npcs') return { width: NPCS_WINDOW_WIDTH, height: NPCS_WINDOW_HEIGHT };
return { width: 1280, height: 800 };
}
@@ -323,6 +328,14 @@ function createWindow(kind: WindowKind, opts?: CreateWindowOpts): BrowserWindow
minHeight: 600,
}
: {}),
...(kind === 'tokenPathEditor'
? {
width: 1100,
height: 760,
minWidth: 900,
minHeight: 560,
}
: {}),
...(kind === 'npcs'
? {
width: NPCS_WINDOW_WIDTH,
@@ -361,6 +374,7 @@ function createWindow(kind: WindowKind, opts?: CreateWindowOpts): BrowserWindow
kind === 'materials' ||
kind === 'npcsEditor' ||
kind === 'sceneEditor' ||
kind === 'tokenPathEditor' ||
kind === 'npcs'
) {
win.setMenuBarVisibility(false);
@@ -408,6 +422,11 @@ function createWindow(kind: WindowKind, opts?: CreateWindowOpts): BrowserWindow
});
}
win.on('closed', () => windows.delete(kind));
if (kind === 'sceneEditor') {
win.on('closed', () => {
closeTokenPathEditorWindow();
});
}
win.on('closed', () => {
if (kind !== 'presentation' && kind !== 'control') return;
const open = windows.has('presentation') || windows.has('control');
@@ -535,12 +554,73 @@ export function closeNpcsEditorWindow(): void {
}
export function closeSceneEditorWindow(): void {
closeTokenPathEditorWindow();
const win = windows.get('sceneEditor');
if (win && !win.isDestroyed()) {
win.close();
}
}
export function closeTokenPathEditorWindow(): void {
const win = windows.get('tokenPathEditor');
if (win && !win.isDestroyed()) {
win.close();
}
}
let pendingTokenPathEditorTarget: { kind: 'token' | 'npcToken'; placementId: string } | null = null;
export function getTokenPathEditorTarget(): { kind: 'token' | 'npcToken'; placementId: string } | null {
return pendingTokenPathEditorTarget;
}
function broadcastTokenPathEditorTarget(): void {
const win = windows.get('tokenPathEditor');
if (!win || win.isDestroyed() || win.webContents.isDestroyed()) return;
try {
win.webContents.send(ipcChannels.windows.tokenPathEditorTargetChanged, pendingTokenPathEditorTarget);
} catch {
/* ignore */
}
}
/** Одно окно пути: смена токена = фокус + targetChanged, без второго окна. */
export function openTokenPathEditorWindow(kind: 'token' | 'npcToken', placementId: string): void {
pendingTokenPathEditorTarget = { kind, placementId };
const existing = windows.get('tokenPathEditor');
if (existing && !existing.isDestroyed()) {
if (existing.isMinimized()) existing.restore();
existing.show();
existing.focus();
existing.moveTop();
broadcastTokenPathEditorTarget();
return;
}
const parent = windows.get('sceneEditor') ?? windows.get('editor');
const win = createWindow('tokenPathEditor', parent ? { parent } : undefined);
const { width, height } = win.getBounds();
const display = screen.getDisplayMatching(parent?.getBounds() ?? win.getBounds());
const { x, y, width: dw, height: dh } = display.workArea;
win.setBounds({
x: Math.round(x + Math.max(0, (dw - width) / 2)),
y: Math.round(y + Math.max(0, (dh - height) / 2)),
width,
height,
});
win.webContents.once('did-finish-load', () => {
if (!win.isDestroyed()) {
win.show();
win.focus();
win.moveTop();
broadcastTokenPathEditorTarget();
}
});
win.on('closed', () => {
pendingTokenPathEditorTarget = null;
});
}
export function closeNpcsWindow(): void {
const win = windows.get('npcs');
if (win && !win.isDestroyed()) {
@@ -303,9 +303,45 @@
.previewActions {
display: flex;
align-items: center;
gap: 10px;
}
.npcTokenScale {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
}
.snapToGrid {
display: flex;
align-items: center;
gap: 6px;
min-width: 0;
cursor: pointer;
user-select: none;
}
.snapToGridLabel {
color: var(--text2);
font-size: var(--text-xs);
font-weight: 700;
white-space: nowrap;
}
.npcTokenScaleLabel {
color: var(--text2);
font-size: var(--text-xs);
font-weight: 700;
white-space: nowrap;
}
.npcTokenScaleRange {
width: min(140px, 22vw);
accent-color: var(--color-accent, #c9a227);
}
.videoHint {
color: var(--text2);
font-size: var(--text-xs);
@@ -579,3 +615,43 @@
.audioScrubDefault {
cursor: default;
}
.ctxMenuBackdrop {
position: fixed;
inset: 0;
z-index: 40;
border: none;
padding: 0;
margin: 0;
background: transparent;
cursor: default;
}
.ctxMenu {
position: fixed;
z-index: 41;
min-width: 200px;
padding: 6px;
border-radius: 8px;
border: 1px solid var(--stroke, #2a2f3a);
background: var(--color-surface-menu, #1a1e28);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.45);
display: grid;
gap: 2px;
}
.ctxItem {
text-align: left;
padding: 8px 10px;
border-radius: 6px;
border: none;
background: transparent;
color: var(--text1, #e8eaef);
font-size: 13px;
cursor: pointer;
width: 100%;
}
.ctxItem:hover {
background: rgba(255, 255, 255, 0.06);
}
File diff suppressed because it is too large Load Diff
@@ -25,6 +25,8 @@
display: grid;
gap: 8px;
pointer-events: auto;
/* Above brush / traps layers so transport stays usable on video scenes. */
z-index: 50;
}
.scrub {
+8 -7
View File
@@ -4,6 +4,7 @@ import { computeTimeSec } from '../../main/video/videoPlaybackStore';
import type { SessionState } from '../../shared/ipc/contracts';
import type { SceneViewCamera } from '../../shared/types';
import { useEditorI18n } from '../editor/i18n/EditorI18nContext';
import { ContainedVideo } from '../shared/ContainedVideo';
import { RotatedImage } from '../shared/RotatedImage';
import { useAssetUrl } from '../shared/useAssetImageUrl';
import { useVideoPlaybackState } from '../shared/video/useVideoPlaybackState';
@@ -106,20 +107,20 @@ export function ControlScenePreview({ session, videoRef, viewCamera = null, onCo
onContentRectChange={onContentRectChange}
/>
) : url && isVideo ? (
<video
ref={(el) => {
(videoRef as unknown as { current: HTMLVideoElement | null }).current = el;
}}
className={styles.video}
src={url}
<ContainedVideo
url={url}
rotationDeg={rot}
videoRef={videoRef}
playsInline
loop={Boolean(scene?.settings?.loopVideo)}
preload="auto"
viewCamera={viewCamera}
onContentRectChange={onContentRectChange}
onTimeUpdate={() => setTick((x) => x + 1)}
onLoadedMetadata={() => setTick((x) => x + 1)}
>
<track kind="captions" srcLang="ru" label={t('control.previewTrackLabel')} />
</video>
</ContainedVideo>
) : (
<div className={styles.placeholder} />
)}
@@ -58,7 +58,7 @@ void test('ControlApp: эффект «взрыв» + ловушка исполь
const appSrc = readControlApp();
const sfxSrc = fs.readFileSync(path.join(here, 'explosionSfx.ts'), 'utf8');
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('getExplosionEffectLifeMs'));
assert.ok(appSrc.includes('playExplosionEffectSound'));
@@ -116,6 +116,18 @@ void test('ControlApp: эффекты в пульте, иконки с тулт
assert.ok(fx !== -1 && story !== -1 && fx < story, 'Блок эффектов должен быть выше сюжетной линии');
});
void test('ControlApp: чекбокс привязки токенов к сетке', () => {
const src = readControlApp();
const css = readControlAppCss();
assert.ok(src.includes('useTokenGridSnapSession'));
assert.ok(src.includes('snapNormToGridCell'));
assert.ok(src.includes('data-testid="token-grid-snap"'));
assert.ok(src.includes("t('control.snapTokensToGrid')"));
assert.ok(src.includes('snapAllTokensToGrid'));
assert.ok(src.includes('snapNorm={snapNormActive}'));
assert.ok(css.includes('.snapToGrid'));
});
void test('ControlApp: сюжетная линия — колонка сверху вниз и фон как у карточек ветвления', () => {
const src = readControlApp();
const css = readControlAppCss();
+62
View File
@@ -59,6 +59,68 @@
gap: 10px;
}
.splitRun {
display: inline-flex;
align-items: stretch;
height: 34px;
border-radius: var(--radius-sm);
border: 1px solid var(--accent-border);
background: var(--accent-fill-solid);
overflow: hidden;
}
.splitRun:disabled,
.splitRun[aria-disabled='true'] {
opacity: 0.45;
pointer-events: none;
}
.splitRunMain,
.splitRunChevron {
border: 0;
background: transparent;
color: rgba(255, 255, 255, 0.95);
cursor: pointer;
font: inherit;
font-weight: 600;
}
.splitRunMain {
padding: 0 14px;
}
.splitRunMain:hover:not(:disabled),
.splitRunChevron:hover:not(:disabled) {
background: color-mix(in srgb, var(--accent-fill-solid) 72%, white);
}
.splitRunMain:active:not(:disabled),
.splitRunChevron:active:not(:disabled),
.splitRunChevronOpen {
background: color-mix(in srgb, var(--accent-fill-solid) 78%, black);
}
.splitRunDivider {
width: 1px;
align-self: stretch;
background: rgba(0, 0, 0, 0.28);
flex: 0 0 auto;
}
.splitRunChevron {
width: 32px;
display: inline-flex;
align-items: center;
justify-content: center;
padding: 0;
}
.splitRunChevronSvg {
width: 12px;
height: 12px;
display: block;
}
.editorSidebar {
height: 100%;
min-height: 0;
+185 -46
View File
@@ -2,6 +2,7 @@ import React, { startTransition, useCallback, useEffect, useMemo, useRef, useSta
import { createPortal } from 'react-dom';
import { moveSceneInListOrder, reconcileSceneListOrder } from '../../shared/graph/sceneListOrder';
import { USERS_BRANCH_FEATURES_ENABLED } from '../../shared/features/usersBranchFeatures';
import type {
NpcImportResolution,
SceneImportResolution,
@@ -28,6 +29,7 @@ import type {
SceneId,
} from '../../shared/types';
import { AppLogo } from '../shared/branding/AppLogo';
import { ContainedVideo } from '../shared/ContainedVideo';
import { getDndApi } from '../shared/dndApi';
import { RotatedImage } from '../shared/RotatedImage';
import { Button, Input } from '../shared/ui/controls';
@@ -55,6 +57,8 @@ import type { HelpSectionId } from './help/helpSections';
import { useEditorI18n } from './i18n/EditorI18nContext';
import { EulaModal, LicenseAboutModal, LicenseTokenModal } from './license/EditorLicenseModals';
import { MaterialEditModal, MaterialsManagerModal } from './MaterialsModals';
import { PlayersManagerModal } from './PlayersModals';
import { LaunchPlayersModal } from './LaunchPlayersModal';
import { isSceneDescriptionEmpty, sanitizeSceneDescriptionHtml } from './sceneDescriptionHtml';
import { SceneDescriptionModal } from './SceneDescriptionModal';
import type { ProjectNoticeCode } from './state/projectState';
@@ -134,9 +138,9 @@ export function EditorApp() {
const [importConflictsOpen, setImportConflictsOpen] = useState(false);
const [importConflicts, setImportConflicts] = useState<ReturnType<typeof computeImportConflicts>>([]);
const [importNpcConflictsOpen, setImportNpcConflictsOpen] = useState(false);
const [importNpcConflicts, setImportNpcConflicts] = useState<
ReturnType<typeof computeNpcImportConflicts>
>([]);
const [importNpcConflicts, setImportNpcConflicts] = useState<ReturnType<typeof computeNpcImportConflicts>>(
[],
);
const [pendingImportSelections, setPendingImportSelections] = useState<StorylineSelection[]>([]);
const [pendingSceneResolutions, setPendingSceneResolutions] = useState<SceneImportResolution[]>([]);
const [importReportOpen, setImportReportOpen] = useState(false);
@@ -154,6 +158,11 @@ export function EditorApp() {
const licenseActive = licenseSnap?.active === true;
const [appNotice, setAppNotice] = useState<{ title?: string; message: string } | null>(null);
const [materialsManagerOpen, setMaterialsManagerOpen] = useState(false);
const [playersManagerOpen, setPlayersManagerOpen] = useState(false);
const [launchPlayersOpen, setLaunchPlayersOpen] = useState(false);
const [runMenuOpen, setRunMenuOpen] = useState(false);
const [runMenuPos, setRunMenuPos] = useState<{ left: number; top: number } | null>(null);
const runSplitRef = useRef<HTMLDivElement | null>(null);
const [materialEdit, setMaterialEdit] = useState<ProjectMaterial | null | 'new'>(null);
const onProjectNotice = useCallback(
(code: ProjectNoticeCode) => {
@@ -351,13 +360,17 @@ export function EditorApp() {
const runHelpTooltip = !licenseActive ? t('top.afterLicense') : t('top.setStartScene');
const launchFromGraphNode = useCallback(
(graphNodeId: GraphNodeId) => {
(graphNodeId: GraphNodeId, playerIds?: string[]) => {
if (!licenseActive || launching) return;
setLaunching(true);
setRunMenuOpen(false);
setLaunchPlayersOpen(false);
void (async () => {
try {
await getDndApi().invoke(ipcChannels.project.setCurrentGraphNode, { graphNodeId });
await getDndApi().invoke(ipcChannels.windows.openMultiWindow, {});
await getDndApi().invoke(ipcChannels.windows.openMultiWindow, {
...(playerIds && playerIds.length > 0 ? { playerIds } : {}),
});
} catch {
setLaunching(false);
}
@@ -461,6 +474,23 @@ export function EditorApp() {
return () => window.removeEventListener('mousedown', onDown);
}, [aboutMenuOpen]);
useEffect(() => {
if (!runMenuOpen) return;
const r = runSplitRef.current?.getBoundingClientRect() ?? null;
queueMicrotask(() => {
if (r) setRunMenuPos({ left: r.right, top: r.bottom + 8 });
else setRunMenuPos(null);
});
const onDown = (e: MouseEvent) => {
const t = e.target as HTMLElement | null;
if (!t) return;
if (t.closest('[data-runmenu-root="1"]')) return;
setRunMenuOpen(false);
};
window.addEventListener('mousedown', onDown);
return () => window.removeEventListener('mousedown', onDown);
}, [runMenuOpen]);
useEffect(() => {
let off: (() => void) | null = null;
void (async () => {
@@ -546,12 +576,7 @@ export function EditorApp() {
sceneResolutions,
npcResolutions,
)
: await actions.mergeImportZip(
importPeek.filePath!,
selections,
sceneResolutions,
npcResolutions,
);
: await actions.mergeImportZip(importPeek.filePath!, selections, sceneResolutions, npcResolutions);
setImportReport(report);
setImportReportOpen(true);
clearImportFlow();
@@ -571,12 +596,7 @@ export function EditorApp() {
setImportNpcConflictsOpen(true);
return;
}
const npcResolutions = buildNpcResolutionsForImport(
state.project,
importPeek.sourceProject,
[],
[],
);
const npcResolutions = buildNpcResolutionsForImport(state.project, importPeek.sourceProject, [], []);
void runStorylineMerge(selections, sceneResolutions, npcResolutions);
},
[importPeek, runStorylineMerge, state.project],
@@ -724,9 +744,7 @@ export function EditorApp() {
{t('scenes.batchProgress')
.replace('{current}', String(state.sceneBatchImport.current))
.replace('{total}', String(state.sceneBatchImport.total))}
{state.sceneBatchImport.fileName
? `: ${state.sceneBatchImport.fileName}`
: ''}
{state.sceneBatchImport.fileName ? `: ${state.sceneBatchImport.fileName}` : ''}
</div>
<div>
{Math.round(
@@ -825,6 +843,25 @@ export function EditorApp() {
{t('top.file')}
</button>
) : null}
{USERS_BRANCH_FEATURES_ENABLED ? (
<button
type="button"
data-testid="players-header-btn"
className={styles.fileMenuTrigger}
disabled={!licenseActive}
title={!licenseActive ? t('top.afterLicense') : undefined}
onClick={() => {
if (!licenseActive) return;
setProjectMenuOpen(false);
setSettingsMenuOpen(false);
setAboutMenuOpen(false);
setFileMenuOpen(false);
setPlayersManagerOpen(true);
}}
>
{t('top.players')}
</button>
) : null}
</div>
<div className={styles.flex1} />
{appVersionText ? (
@@ -835,9 +872,61 @@ export function EditorApp() {
<div className={styles.headerActions}>
{state.project ? (
<>
{USERS_BRANCH_FEATURES_ENABLED ? (
<div
ref={runSplitRef}
className={styles.splitRun}
data-runmenu-root="1"
aria-disabled={runDisabled || launching ? true : undefined}
>
<button
type="button"
className={styles.splitRunMain}
disabled={runDisabled || launching}
data-testid="run-main-btn"
onClick={() => {
if (!licenseActive || !graphStartGraphNodeId || launching) return;
launchFromGraphNode(graphStartGraphNodeId);
}}
>
{t('top.run')}
</button>
<span className={styles.splitRunDivider} aria-hidden />
<button
type="button"
className={[
styles.splitRunChevron,
runMenuOpen ? styles.splitRunChevronOpen : '',
]
.filter(Boolean)
.join(' ')}
disabled={runDisabled || launching}
aria-label={t('top.runMenuAria')}
aria-haspopup="menu"
aria-expanded={runMenuOpen}
data-testid="run-menu-btn"
onClick={() => {
if (runDisabled || launching) return;
setRunMenuOpen((v) => !v);
}}
>
<svg className={styles.splitRunChevronSvg} viewBox="0 0 12 12" aria-hidden>
<path
d="M2.5 4.25 L6 7.75 L9.5 4.25"
fill="none"
stroke="currentColor"
strokeWidth="1.6"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</button>
</div>
) : (
<Button
variant="primary"
disabled={runDisabled || launching}
data-testid="run-main-btn"
onClick={() => {
if (!licenseActive || !graphStartGraphNodeId || launching) return;
launchFromGraphNode(graphStartGraphNodeId);
@@ -845,6 +934,7 @@ export function EditorApp() {
>
{t('top.run')}
</Button>
)}
{runDisabled ? (
<Button
variant="ghost"
@@ -900,9 +990,7 @@ export function EditorApp() {
scene={s}
reorderEnabled={sceneListReorderEnabled}
listDragActive={draggingListSceneId !== null}
dropPlace={
sceneListDrop?.targetId === s.id ? sceneListDrop.place : null
}
dropPlace={sceneListDrop?.targetId === s.id ? sceneListDrop.place : null}
isDragging={draggingListSceneId === s.id}
onSelect={() => {
setSelectedGraphNodeId(null);
@@ -925,9 +1013,7 @@ export function EditorApp() {
return;
}
setSceneListDrop((cur) =>
cur?.targetId === targetId && cur.place === place
? cur
: { targetId, place },
cur?.targetId === targetId && cur.place === place ? cur : { targetId, place },
);
}}
onDropListReorder={(draggedId, targetId, place) => {
@@ -1552,6 +1638,43 @@ export function EditorApp() {
}}
/>
<CheckUpdatesModal open={checkUpdatesOpen} onClose={() => setCheckUpdatesOpen(false)} />
{USERS_BRANCH_FEATURES_ENABLED ? (
<>
<PlayersManagerModal open={playersManagerOpen} onClose={() => setPlayersManagerOpen(false)} />
<LaunchPlayersModal
open={launchPlayersOpen}
onClose={() => setLaunchPlayersOpen(false)}
onConfirm={(playerIds) => {
if (!graphStartGraphNodeId) return;
launchFromGraphNode(graphStartGraphNodeId, playerIds);
}}
/>
</>
) : null}
{USERS_BRANCH_FEATURES_ENABLED && runMenuOpen && runMenuPos
? createPortal(
<div
data-runmenu-root="1"
className={styles.fileMenu}
style={{ left: runMenuPos.left, top: runMenuPos.top, transform: 'translateX(-100%)' }}
role="menu"
>
<button
type="button"
className={styles.fileMenuItem}
role="menuitem"
data-testid="run-with-players-item"
onClick={() => {
setRunMenuOpen(false);
setLaunchPlayersOpen(true);
}}
>
{t('top.runWithPlayers')}
</button>
</div>,
document.body,
)
: null}
<MaterialsManagerModal
open={materialsManagerOpen}
materials={state.project?.materials ?? []}
@@ -2379,9 +2502,7 @@ function CampaignInspector({
onDragOver={audioDrop.onDragOver}
onDrop={audioDrop.onDrop}
>
{audioDrop.dragOver ? (
<div className={styles.dropHintOverlay}>{t('drop.hintAudio')}</div>
) : null}
{audioDrop.dragOver ? <div className={styles.dropHintOverlay}>{t('drop.hintAudio')}</div> : null}
{mediaAssets.filter((a) => a.type === 'audio').length === 0 ? (
<div className={styles.audioDropEmpty}>
<div className={[styles.muted, styles.spanSm].join(' ')}>{t('campaign.noFiles')}</div>
@@ -2548,10 +2669,7 @@ function SceneInspector({
{sideStoryStartNodes.map((gn) => (
<div key={gn.id}>
<div className={styles.labelSm}>{t('scene.sideStoryLineTitle')}</div>
<Input
value={gn.sideStoryLineTitle}
onChange={(v) => onSideStoryLineTitleChange(gn.id, v)}
/>
<Input value={gn.sideStoryLineTitle} onChange={(v) => onSideStoryLineTitleChange(gn.id, v)} />
<div className={styles.spacer8} />
</div>
))}
@@ -2567,9 +2685,7 @@ function SceneInspector({
onDragOver={previewDrop.onDragOver}
onDrop={previewDrop.onDrop}
>
{previewDrop.dragOver ? (
<div className={styles.dropHintOverlay}>{t('drop.hintPreview')}</div>
) : null}
{previewDrop.dragOver ? <div className={styles.dropHintOverlay}>{t('drop.hintPreview')}</div> : null}
{previewUrl && previewAssetType === 'image' ? (
<div className={styles.previewFill}>
<RotatedImage
@@ -2581,14 +2697,16 @@ function SceneInspector({
</div>
) : previewUrl && previewAssetType === 'video' ? (
<div className={styles.previewFill}>
<video
src={previewUrl}
<ContainedVideo
url={previewUrl}
rotationDeg={previewRotationDeg}
mode="cover"
muted
playsInline
autoPlay={previewVideoAutostart}
loop={previewVideoLoop}
preload="metadata"
className={styles.videoCover}
style={{ width: '100%', height: '100%' }}
/>
</div>
) : (
@@ -2629,7 +2747,7 @@ function SceneInspector({
</label>
</div>
) : null}
{previewAssetId && previewAssetType === 'image' ? (
{previewAssetId && (previewAssetType === 'image' || previewAssetType === 'video') ? (
<>
<div className={styles.spacer6} />
<Button
@@ -2640,6 +2758,10 @@ function SceneInspector({
>
{t('scene.rotate')}
</Button>
</>
) : null}
{previewAssetId && (previewAssetType === 'image' || previewAssetType === 'video') ? (
<>
<div className={styles.spacer6} />
<label className={styles.checkboxLabel}>
<input
@@ -2668,9 +2790,7 @@ function SceneInspector({
onDragOver={sceneAudioDrop.onDragOver}
onDrop={sceneAudioDrop.onDrop}
>
{sceneAudioDrop.dragOver ? (
<div className={styles.dropHintOverlay}>{t('drop.hintAudio')}</div>
) : null}
{sceneAudioDrop.dragOver ? <div className={styles.dropHintOverlay}>{t('drop.hintAudio')}</div> : null}
{mediaAssets.filter((a) => a.type === 'audio').length === 0 ? (
<div className={styles.audioDropEmpty}>
<div className={[styles.muted, styles.spanSm].join(' ')}>{t('campaign.noFiles')}</div>
@@ -2872,6 +2992,7 @@ function SceneListCard({
</div>
) : previewUrl && scene.previewAssetType === 'video' ? (
<div className={styles.sceneThumbInner}>
{scene.previewRotationDeg === 0 ? (
<video
src={previewUrl}
muted
@@ -2889,6 +3010,26 @@ function SceneListCard({
}
}}
/>
) : (
<ContainedVideo
url={previewUrl}
rotationDeg={scene.previewRotationDeg}
mode="cover"
muted
playsInline
preload="metadata"
style={{ width: '100%', height: '100%' }}
onLoadedData={(e) => {
const v = e.currentTarget;
try {
v.currentTime = 0;
v.pause();
} catch {
// ignore
}
}}
/>
)}
</div>
) : (
<div className={styles.sceneThumbEmptyInner} aria-hidden />
@@ -2983,9 +3124,7 @@ function SceneListCard({
</button>
</div>
<div className={styles.fieldGrid}>
<div className={styles.muted}>
{t('confirmDeleteScene.body', { name: scene.title })}
</div>
<div className={styles.muted}>{t('confirmDeleteScene.body', { name: scene.title })}</div>
</div>
<div className={styles.modalFooter}>
<Button onClick={() => setPendingDelete(false)}>{t('common.cancel')}</Button>
@@ -0,0 +1,63 @@
.dialog {
width: min(440px, calc(100vw - 48px));
}
.hint {
margin: 0 0 12px;
color: var(--text2);
font-size: var(--text-sm);
line-height: 1.4;
}
.section {
display: grid;
gap: 8px;
margin-bottom: 14px;
}
.sectionTitle {
font-size: 11px;
font-weight: 700;
color: var(--text2);
text-transform: uppercase;
letter-spacing: 0.04em;
}
.list {
display: grid;
gap: 4px;
max-height: 220px;
overflow: auto;
padding: 8px;
border: 1px solid var(--stroke);
border-radius: var(--radius-sm);
background: var(--color-overlay-dark-3);
}
.row {
display: flex;
align-items: center;
gap: 8px;
padding: 6px 8px;
border-radius: 6px;
cursor: pointer;
color: var(--text);
font-size: var(--text-sm);
}
.row:hover {
background: var(--accent-fill-soft);
}
.teamDot {
width: 10px;
height: 10px;
border-radius: 50%;
flex: 0 0 auto;
}
.empty {
padding: 10px 8px;
color: var(--text2);
font-size: var(--text-sm);
}
+165
View File
@@ -0,0 +1,165 @@
import React, { useEffect, useMemo, useState } from 'react';
import { createPortal } from 'react-dom';
import type { AppPlayer, AppPlayerTeam, PlayerId, PlayerTeamId } from '../../shared/types';
import { resolveLaunchPlayerIds } from '../../shared/players/resolveLaunchPlayerIds';
import { useAppPlayers } from '../shared/playerToken/useAppPlayers';
import { Button } from '../shared/ui/controls';
import styles from './EditorApp.module.css';
import { useEditorI18n } from './i18n/EditorI18nContext';
import launchStyles from './LaunchPlayersModal.module.css';
export { resolveLaunchPlayerIds } from '../../shared/players/resolveLaunchPlayerIds';
export function LaunchPlayersModal({
open,
onClose,
onConfirm,
}: {
open: boolean;
onClose: () => void;
onConfirm: (playerIds: string[]) => void;
}) {
const { t } = useEditorI18n();
const { players, teams } = useAppPlayers();
const [selectedPlayers, setSelectedPlayers] = useState<Set<string>>(() => new Set());
const [selectedTeams, setSelectedTeams] = useState<Set<string>>(() => new Set());
useEffect(() => {
if (!open) return;
setSelectedPlayers(new Set());
setSelectedTeams(new Set());
}, [open]);
const resolvedIds = useMemo(
() => resolveLaunchPlayerIds(players, selectedPlayers, selectedTeams),
[players, selectedPlayers, selectedTeams],
);
const standalonePlayers = useMemo(
() =>
players.filter((p) => !(p.teamId && selectedTeams.has(String(p.teamId)))),
[players, selectedTeams],
);
if (!open) return null;
const togglePlayer = (id: PlayerId) => {
setSelectedPlayers((prev) => {
const next = new Set(prev);
const key = String(id);
if (next.has(key)) next.delete(key);
else next.add(key);
return next;
});
};
const toggleTeam = (id: PlayerTeamId) => {
const key = String(id);
setSelectedTeams((prev) => {
const next = new Set(prev);
if (next.has(key)) next.delete(key);
else next.add(key);
return next;
});
// Участники выбранной команды не показываются в «Игроки» — снимаем их индивидуальный выбор.
setSelectedPlayers((prev) => {
if (prev.size === 0) return prev;
const next = new Set(prev);
let changed = false;
for (const p of players) {
if (String(p.teamId) !== key) continue;
if (next.delete(String(p.id))) changed = true;
}
return changed ? next : prev;
});
};
return createPortal(
<>
<div className={styles.modalBackdrop} aria-hidden onClick={onClose} />
<div
className={[styles.modalDialog, launchStyles.dialog].join(' ')}
role="dialog"
aria-modal="true"
data-testid="launch-players-modal"
>
<div className={styles.modalHeader}>
<div className={styles.modalTitle}>{t('top.runWithPlayersTitle')}</div>
<button
type="button"
aria-label={t('common.close')}
onClick={onClose}
className={styles.modalClose}
>
×
</button>
</div>
<div>
<p className={launchStyles.hint}>{t('top.runWithPlayersHint')}</p>
{teams.length > 0 ? (
<section className={launchStyles.section}>
<div className={launchStyles.sectionTitle}>{t('top.runWithPlayersTeams')}</div>
<div className={launchStyles.list}>
{teams.map((team: AppPlayerTeam) => {
const count = players.filter((p) => p.teamId === team.id).length;
return (
<label key={team.id} className={launchStyles.row}>
<input
type="checkbox"
checked={selectedTeams.has(String(team.id))}
onChange={() => toggleTeam(team.id)}
data-testid={`launch-team-${team.id}`}
/>
<span className={launchStyles.teamDot} style={{ background: team.color }} />
<span>
{team.name} ({count})
</span>
</label>
);
})}
</div>
</section>
) : null}
{standalonePlayers.length > 0 ? (
<section className={launchStyles.section}>
<div className={launchStyles.sectionTitle}>{t('top.runWithPlayersPlayers')}</div>
<div className={launchStyles.list}>
{standalonePlayers.map((player: AppPlayer) => (
<label key={player.id} className={launchStyles.row}>
<input
type="checkbox"
checked={selectedPlayers.has(String(player.id))}
onChange={() => togglePlayer(player.id)}
data-testid={`launch-player-${player.id}`}
/>
<span>{player.name}</span>
</label>
))}
</div>
</section>
) : players.length === 0 ? (
<section className={launchStyles.section}>
<div className={launchStyles.empty}>{t('top.runWithPlayersEmpty')}</div>
</section>
) : null}
</div>
<div className={styles.modalFooter}>
<Button variant="ghost" onClick={onClose}>
{t('common.cancel')}
</Button>
<Button
variant="primary"
disabled={resolvedIds.length === 0}
data-testid="launch-players-confirm"
onClick={() => onConfirm(resolvedIds)}
>
{t('top.runWithPlayersConfirm')}
</Button>
</div>
</div>
</>,
document.body,
);
}
@@ -0,0 +1,243 @@
.dialog {
width: min(1080px, calc(100vw - 48px));
max-width: 1080px;
}
.body {
display: grid;
grid-template-columns: 330px minmax(0, 1fr);
gap: 16px;
min-height: 560px;
max-height: min(78vh, 760px);
}
.sidebar,
.editor {
min-height: 0;
}
.sidebar {
display: flex;
flex-direction: column;
gap: 8px;
}
.sidebarActions {
display: flex;
gap: 8px;
}
.sidebarActions > * {
flex: 1 1 0;
min-width: 0;
}
.sidebarActions button {
width: 100%;
}
.teamForm {
display: grid;
gap: 8px;
padding: 10px;
border: 1px solid var(--stroke);
border-radius: 10px;
background: var(--color-overlay-dark-3);
}
.teamFormField {
display: grid;
gap: 4px;
color: var(--text2);
font-size: 11px;
font-weight: 700;
}
.teamFormField input[type='color'] {
width: 100%;
height: 34px;
padding: 0;
border: 1px solid var(--stroke);
border-radius: 8px;
background: transparent;
}
.teamFormActions {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.teamFormActions > * {
flex: 1 1 0;
min-width: 0;
}
.teamFormActions button {
width: 100%;
}
.list {
display: grid;
gap: 10px;
overflow: auto;
padding-right: 3px;
}
.team {
border: 1px solid var(--stroke);
border-radius: 10px;
background: var(--color-overlay-dark-2);
overflow: visible;
}
.teamHeader {
display: grid;
grid-template-columns: auto minmax(0, 1fr) auto;
align-items: center;
gap: 7px;
min-height: 34px;
padding: 4px 8px;
border-bottom: 1px solid var(--stroke);
}
.teamDot {
width: 11px;
height: 11px;
border-radius: 50%;
}
.teamName {
overflow: hidden;
font-size: 12px;
font-weight: 800;
text-overflow: ellipsis;
white-space: nowrap;
}
.teamMenu {
position: relative;
}
.teamMenu summary {
cursor: pointer;
list-style: none;
padding: 4px 7px;
}
.teamMenuPopup {
position: absolute;
z-index: 10;
top: 100%;
right: 0;
min-width: 130px;
padding: 5px;
border: 1px solid var(--stroke);
border-radius: 8px;
background: var(--bg1, #1a1d24);
box-shadow: 0 10px 24px rgb(0 0 0 / 45%);
}
.teamMenuPopup button {
width: 100%;
padding: 7px 9px;
border: 0;
border-radius: 5px;
background: transparent;
color: inherit;
text-align: left;
cursor: pointer;
}
.teamMenuPopup button:hover {
background: rgb(255 255 255 / 8%);
}
.teamBody {
display: grid;
gap: 5px;
min-height: 28px;
padding: 6px;
}
.playerRow {
display: grid;
grid-template-columns: 48px minmax(0, 1fr);
align-items: center;
gap: 9px;
width: 100%;
padding: 5px;
border: 1px solid transparent;
border-radius: 8px;
background: transparent;
color: inherit;
text-align: left;
cursor: grab;
}
.playerRow:hover,
.playerRowSelected {
border-color: var(--color-accent, #c9a227);
background: rgb(255 255 255 / 5%);
}
.playerRow > span {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.dropTarget {
padding: 8px;
color: var(--text2);
font-size: 11px;
text-align: center;
}
.editor {
position: relative;
display: flex;
flex-direction: column;
align-items: center;
gap: 16px;
overflow: auto;
padding: 22px;
border: 1px solid var(--stroke);
border-radius: 12px;
background: var(--color-overlay-dark-3);
}
.editorDropOver {
border-color: var(--color-accent, #c9a227);
}
.field {
display: grid;
gap: 6px;
width: min(420px, 100%);
color: var(--text2);
font-size: 12px;
font-weight: 700;
}
.field input[type='color'] {
width: 100%;
height: 38px;
padding: 0;
border: 1px solid var(--stroke);
border-radius: 8px;
background: transparent;
}
.actions {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 8px;
}
@media (max-width: 760px) {
.body {
grid-template-columns: 1fr;
}
}
+665
View File
@@ -0,0 +1,665 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { createPortal, flushSync } from 'react-dom';
import { ipcChannels } from '../../shared/ipc/contracts';
import type { AppPlayer, AppPlayerTeam, PlayerId, PlayerTeamId } from '../../shared/types';
import {
DEFAULT_PLAYER_IMAGE_OFFSET,
DEFAULT_PLAYER_IMAGE_SCALE,
DEFAULT_PLAYER_RING_COLOR,
} from '../../shared/types/appPlayers';
import { getDndApi } from '../shared/dndApi';
import { PlayerTokenView } from '../shared/playerToken/PlayerTokenView';
import { useAppPlayers } from '../shared/playerToken/useAppPlayers';
import { usePlayerImageUrl } from '../shared/playerToken/usePlayerImageUrl';
import { Button, Input } from '../shared/ui/controls';
import styles from './EditorApp.module.css';
import {
filterMaterialImagePaths,
getDroppedFileEntries,
pickFirstMaterialImagePath,
useFileDropZone,
} from './fileDrop';
import { useEditorI18n } from './i18n/EditorI18nContext';
import playerStyles from './PlayersModals.module.css';
const PLAYER_DND_MIME = 'application/x-dnd-player-id';
function PlayerRow({
player,
selected,
onSelect,
}: {
player: AppPlayer;
selected: boolean;
onSelect: () => void;
}) {
const url = usePlayerImageUrl(player.id);
return (
<button
type="button"
data-testid={`player-row-${player.id}`}
className={[playerStyles.playerRow, selected ? playerStyles.playerRowSelected : '']
.filter(Boolean)
.join(' ')}
draggable
onDragStart={(e) => {
e.dataTransfer.setData(PLAYER_DND_MIME, player.id);
e.dataTransfer.effectAllowed = 'move';
}}
onClick={onSelect}
>
<PlayerTokenView
name={player.name}
imageUrl={url}
ringColor={player.ringColor}
imageOffset={player.imageOffset}
imageScale={player.imageScale}
sizePx={48}
hideName
/>
<span>{player.name}</span>
</button>
);
}
function TeamSection({
team,
players,
selectedId,
onSelect,
onAssign,
onEdit,
onDelete,
}: {
team: AppPlayerTeam | null;
players: AppPlayer[];
selectedId: PlayerId | null;
onSelect: (id: PlayerId) => void;
onAssign: (id: PlayerId, teamId: PlayerTeamId | null) => void;
onEdit?: () => void;
onDelete?: () => void;
}) {
const { t } = useEditorI18n();
return (
<section
className={playerStyles.team}
onDragOver={(e) => {
if (e.dataTransfer.types.includes(PLAYER_DND_MIME)) e.preventDefault();
}}
onDrop={(e) => {
e.preventDefault();
const id = e.dataTransfer.getData(PLAYER_DND_MIME);
if (id) onAssign(id as PlayerId, team?.id ?? null);
}}
>
<div className={playerStyles.teamHeader}>
{team ? <span className={playerStyles.teamDot} style={{ background: team.color }} /> : null}
<span className={playerStyles.teamName}>{team?.name ?? t('players.ungrouped')}</span>
{team ? (
<details className={playerStyles.teamMenu}>
<summary aria-label={t('players.teamMenu')}></summary>
<div className={playerStyles.teamMenuPopup}>
<button type="button" onClick={onEdit}>
{t('common.edit')}
</button>
<button type="button" onClick={onDelete}>
{t('common.delete')}
</button>
</div>
</details>
) : null}
</div>
<div className={playerStyles.teamBody}>
{players.map((player) => (
<PlayerRow
key={player.id}
player={player}
selected={player.id === selectedId}
onSelect={() => onSelect(player.id)}
/>
))}
{players.length === 0 ? <div className={playerStyles.dropTarget}>{t('players.dropHere')}</div> : null}
</div>
</section>
);
}
export function PlayersManagerModal({ open, onClose }: { open: boolean; onClose: () => void }) {
const { t } = useEditorI18n();
const api = getDndApi();
const { players, teams } = useAppPlayers();
const [query, setQuery] = useState('');
const [selectedId, setSelectedId] = useState<PlayerId | null>(null);
const [name, setName] = useState('');
const [ringColor, setRingColor] = useState(DEFAULT_PLAYER_RING_COLOR);
const [imageOffset, setImageOffset] = useState(DEFAULT_PLAYER_IMAGE_OFFSET);
const [imageScale, setImageScale] = useState(DEFAULT_PLAYER_IMAGE_SCALE);
const [filePath, setFilePath] = useState<string | null>(null);
const [previewUrl, setPreviewUrl] = useState<string | null>(null);
const [adding, setAdding] = useState(false);
const [saving, setSaving] = useState(false);
const [progress, setProgress] = useState({ percent: 0, detail: '' });
/** Electron не поддерживает window.prompt — форма команды в сайдбаре. */
const [teamForm, setTeamForm] = useState<{
id: PlayerTeamId | null;
name: string;
color: string;
} | null>(null);
const [pendingDeletePlayer, setPendingDeletePlayer] = useState<AppPlayer | null>(null);
const [pendingDeleteTeam, setPendingDeleteTeam] = useState<AppPlayerTeam | null>(null);
const appearanceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const selected = players.find((p) => p.id === selectedId) ?? null;
const selectedUrl = usePlayerImageUrl(selected?.id);
const resetModalState = useCallback(() => {
if (appearanceTimerRef.current) {
clearTimeout(appearanceTimerRef.current);
appearanceTimerRef.current = null;
}
setQuery('');
setSelectedId(null);
setName('');
setRingColor(DEFAULT_PLAYER_RING_COLOR);
setImageOffset({ ...DEFAULT_PLAYER_IMAGE_OFFSET });
setImageScale(DEFAULT_PLAYER_IMAGE_SCALE);
setFilePath(null);
setPreviewUrl((prev) => {
if (prev?.startsWith('blob:')) URL.revokeObjectURL(prev);
return null;
});
setAdding(false);
setSaving(false);
setProgress({ percent: 0, detail: '' });
setTeamForm(null);
setPendingDeletePlayer(null);
setPendingDeleteTeam(null);
}, []);
const handleClose = useCallback(() => {
if (saving) return;
resetModalState();
onClose();
}, [onClose, resetModalState, saving]);
useEffect(() => {
if (!open) return;
setSelectedId((current) =>
current && players.some((p) => p.id === current) ? current : (players[0]?.id ?? null),
);
}, [open, players]);
// Синхронизировать форму только при смене выбранного игрока — не при каждом
// players.stateChanged (иначе сбрасывается несохранённый zoom/pan).
useEffect(() => {
if (adding) return;
if (!selectedId) return;
const p = players.find((item) => item.id === selectedId);
if (!p) return;
setName(p.name);
setRingColor(p.ringColor);
setImageOffset(p.imageOffset);
setImageScale(p.imageScale ?? DEFAULT_PLAYER_IMAGE_SCALE);
setFilePath(null);
setPreviewUrl(null);
// eslint-disable-next-line react-hooks/exhaustive-deps -- только selectedId / adding
}, [adding, selectedId]);
useEffect(() => {
if (!open) return;
return api.on(ipcChannels.players.upsertProgress, (event) => {
setProgress({
percent: Math.max(0, Math.min(100, Math.round(event.percent))),
detail: event.detail?.trim() ?? t('players.savingWait'),
});
});
}, [api, open, t]);
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => {
if (e.key !== 'Escape' || saving) return;
if (pendingDeletePlayer) {
setPendingDeletePlayer(null);
return;
}
if (pendingDeleteTeam) {
setPendingDeleteTeam(null);
return;
}
if (teamForm) {
setTeamForm(null);
return;
}
handleClose();
};
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [handleClose, open, pendingDeletePlayer, pendingDeleteTeam, saving, teamForm]);
const filtered = useMemo(() => {
const q = query.trim().toLowerCase();
return q ? players.filter((p) => p.name.toLowerCase().includes(q)) : players;
}, [players, query]);
const beginAdd = () => {
setAdding(true);
setSelectedId(null);
setName('');
setRingColor(DEFAULT_PLAYER_RING_COLOR);
setImageOffset({ ...DEFAULT_PLAYER_IMAGE_OFFSET });
setImageScale(DEFAULT_PLAYER_IMAGE_SCALE);
setFilePath(null);
setPreviewUrl(null);
};
const setPreviewFromPathAndUrl = (path: string, url: string) => {
setFilePath(path);
setPreviewUrl((prev) => {
if (prev?.startsWith('blob:')) URL.revokeObjectURL(prev);
return url || null;
});
};
const pickImage = async () => {
const result = await api.invoke(ipcChannels.players.pickImage, {});
if (result.canceled) return;
setPreviewFromPathAndUrl(result.filePath, result.previewDataUrl);
};
const applyDroppedImage = (path: string, previewFromFile: string) => {
if (!adding && !selected) beginAdd();
setPreviewFromPathAndUrl(path, previewFromFile);
};
const drop = useFileDropZone({
disabled: saving,
filterPaths: filterMaterialImagePaths,
onDropPaths: (paths) => {
const picked = pickFirstMaterialImagePath(paths);
if (!picked) return;
applyDroppedImage(picked, '');
},
});
const appearanceLatestRef = useRef({
selected,
adding,
saving,
ringColor,
imageOffset,
imageScale,
});
appearanceLatestRef.current = { selected, adding, saving, ringColor, imageOffset, imageScale };
const persistAppearance = (patch: {
ringColor?: string;
imageOffset?: typeof imageOffset;
imageScale?: number;
}) => {
const snap = appearanceLatestRef.current;
if (!snap.selected || snap.adding || snap.saving) return;
const payload = {
id: snap.selected.id,
teamId: snap.selected.teamId,
name: snap.selected.name,
ringColor: patch.ringColor ?? snap.ringColor,
imageOffset: patch.imageOffset ?? snap.imageOffset,
imageScale: patch.imageScale ?? snap.imageScale,
};
if (appearanceTimerRef.current) clearTimeout(appearanceTimerRef.current);
appearanceTimerRef.current = setTimeout(() => {
appearanceTimerRef.current = null;
void api.invoke(ipcChannels.players.upsert, payload);
}, 180);
};
useEffect(() => {
return () => {
if (appearanceTimerRef.current) clearTimeout(appearanceTimerRef.current);
};
}, []);
const save = async () => {
const trimmed = name.trim();
if (!trimmed || (selected === null && filePath === null)) return;
if (appearanceTimerRef.current) {
clearTimeout(appearanceTimerRef.current);
appearanceTimerRef.current = null;
}
flushSync(() => {
setSaving(true);
setProgress({ percent: 0, detail: t('players.savingWait') });
});
try {
const result = await api.invoke(ipcChannels.players.upsert, {
...(selected ? { id: selected.id, teamId: selected.teamId } : {}),
name: trimmed,
...(filePath ? { filePath } : {}),
ringColor,
imageOffset,
imageScale,
});
setAdding(false);
setSelectedId(result.player.id);
} finally {
setSaving(false);
}
};
if (!open) return null;
const activeUrl = previewUrl ?? selectedUrl;
return createPortal(
<>
<div className={styles.modalBackdrop} aria-hidden />
<div
role="dialog"
aria-modal="true"
data-testid="players-modal"
className={[styles.modalDialog, playerStyles.dialog].join(' ')}
>
<div className={styles.modalHeader}>
<div className={styles.modalTitle}>{t('players.managerTitle')}</div>
<button
type="button"
aria-label={t('common.close')}
onClick={handleClose}
className={styles.modalClose}
disabled={saving}
>
×
</button>
</div>
<div className={playerStyles.body}>
<aside className={playerStyles.sidebar}>
<Input value={query} onChange={setQuery} placeholder={t('players.search')} />
<div className={playerStyles.sidebarActions}>
<Button variant="primary" data-testid="players-add" onClick={beginAdd}>
{t('players.add')}
</Button>
<Button
data-testid="players-add-team"
onClick={() =>
setTeamForm({
id: null,
name: '',
color: DEFAULT_PLAYER_RING_COLOR,
})
}
>
{t('players.addTeam')}
</Button>
</div>
{teamForm ? (
<div className={playerStyles.teamForm} data-testid="players-team-form">
<label className={playerStyles.teamFormField}>
<span>{t('players.teamName')}</span>
<Input
value={teamForm.name}
onChange={(v) => setTeamForm((prev) => (prev ? { ...prev, name: v } : prev))}
placeholder={t('players.teamName')}
autoFocus
/>
</label>
<label className={playerStyles.teamFormField}>
<span>{t('players.teamColor')}</span>
<input
type="color"
value={teamForm.color}
onChange={(e) =>
setTeamForm((prev) =>
prev ? { ...prev, color: e.currentTarget.value } : prev,
)
}
/>
</label>
<div className={playerStyles.teamFormActions}>
<Button
variant="primary"
disabled={!teamForm.name.trim()}
onClick={() => {
const trimmed = teamForm.name.trim();
if (!trimmed) return;
void api
.invoke(ipcChannels.players.upsertTeam, {
...(teamForm.id ? { id: teamForm.id } : {}),
name: trimmed,
color: teamForm.color,
})
.then(() => setTeamForm(null));
}}
>
{t('common.save')}
</Button>
<Button onClick={() => setTeamForm(null)}>{t('common.cancel')}</Button>
</div>
</div>
) : null}
<div className={playerStyles.list}>
{teams.map((team) => (
<TeamSection
key={team.id}
team={team}
players={filtered.filter((p) => p.teamId === team.id)}
selectedId={selectedId}
onSelect={(id) => {
setAdding(false);
setSelectedId(id);
}}
onAssign={(playerId, teamId) =>
void api.invoke(ipcChannels.players.assignTeam, { playerId, teamId })
}
onEdit={() =>
setTeamForm({
id: team.id,
name: team.name,
color: team.color,
})
}
onDelete={() => setPendingDeleteTeam(team)}
/>
))}
<TeamSection
team={null}
players={filtered.filter((p) => p.teamId === null)}
selectedId={selectedId}
onSelect={(id) => {
setAdding(false);
setSelectedId(id);
}}
onAssign={(playerId, teamId) =>
void api.invoke(ipcChannels.players.assignTeam, { playerId, teamId })
}
/>
</div>
</aside>
<main
className={[playerStyles.editor, drop.dragOver ? playerStyles.editorDropOver : '']
.filter(Boolean)
.join(' ')}
onDragEnter={drop.onDragEnter}
onDragLeave={drop.onDragLeave}
onDragOver={drop.onDragOver}
onDrop={(e) => {
drop.onDrop(e);
const entries = getDroppedFileEntries(e);
const files = e.dataTransfer?.files;
for (let i = 0; i < entries.length; i += 1) {
const entry = entries[i]!;
if (!pickFirstMaterialImagePath([entry.path])) continue;
const file = files?.[i];
applyDroppedImage(entry.path, file ? URL.createObjectURL(file) : '');
return;
}
}}
>
{drop.dragOver ? <div className={styles.dropHintOverlay}>{t('players.dropHint')}</div> : null}
{adding || selected ? (
<>
<PlayerTokenView
data-testid="player-token-preview"
name={name}
imageUrl={activeUrl}
ringColor={ringColor}
imageOffset={imageOffset}
imageScale={imageScale}
panEnabled
onImageOffsetChange={(next) => {
setImageOffset(next);
persistAppearance({ imageOffset: next });
}}
onImageScaleChange={(next) => {
setImageScale(next);
persistAppearance({ imageScale: next });
}}
sizePx={220}
/>
<label className={playerStyles.field}>
<span>{t('players.name')}</span>
<Input value={name} onChange={setName} placeholder={t('players.namePlaceholder')} />
</label>
<label className={playerStyles.field}>
<span>{t('players.ringColor')}</span>
<input
type="color"
value={ringColor}
onChange={(e) => {
const next = e.currentTarget.value;
setRingColor(next);
persistAppearance({ ringColor: next });
}}
/>
</label>
<div className={playerStyles.actions}>
<Button data-testid="players-choose-image" onClick={() => void pickImage()}>
{t('players.chooseImage')}
</Button>
<Button
variant="primary"
data-testid="players-save"
disabled={!name.trim() || (!selected && !filePath) || saving}
onClick={() => void save()}
>
{saving ? t('common.saving') : t('common.save')}
</Button>
{selected ? (
<Button onClick={() => setPendingDeletePlayer(selected)}>{t('common.delete')}</Button>
) : null}
</div>
</>
) : (
<div className={styles.muted}>{t('players.selectPrompt')}</div>
)}
</main>
</div>
</div>
{pendingDeletePlayer
? createPortal(
<>
<button
type="button"
aria-label={t('common.close')}
className={styles.modalBackdrop}
onClick={() => setPendingDeletePlayer(null)}
/>
<div
role="dialog"
aria-modal="true"
data-testid="players-delete-confirm"
className={styles.modalDialog}
>
<div className={styles.modalHeader}>
<div className={styles.modalTitle}>{t('players.deleteTitle')}</div>
<button
type="button"
aria-label={t('common.close')}
className={styles.modalClose}
onClick={() => setPendingDeletePlayer(null)}
>
×
</button>
</div>
<div className={styles.muted}>
{t('players.deleteConfirm', { name: pendingDeletePlayer.name })}
</div>
<div className={styles.modalFooter}>
<Button onClick={() => setPendingDeletePlayer(null)}>{t('common.cancel')}</Button>
<Button
variant="primary"
onClick={() => {
const id = pendingDeletePlayer.id;
setPendingDeletePlayer(null);
void api.invoke(ipcChannels.players.delete, { id });
}}
>
{t('common.delete')}
</Button>
</div>
</div>
</>,
document.body,
)
: null}
{pendingDeleteTeam
? createPortal(
<>
<button
type="button"
aria-label={t('common.close')}
className={styles.modalBackdrop}
onClick={() => setPendingDeleteTeam(null)}
/>
<div role="dialog" aria-modal="true" className={styles.modalDialog}>
<div className={styles.modalHeader}>
<div className={styles.modalTitle}>{t('players.deleteTeamTitle')}</div>
<button
type="button"
aria-label={t('common.close')}
className={styles.modalClose}
onClick={() => setPendingDeleteTeam(null)}
>
×
</button>
</div>
<div className={styles.muted}>
{t('players.deleteTeamConfirm', { name: pendingDeleteTeam.name })}
</div>
<div className={styles.modalFooter}>
<Button onClick={() => setPendingDeleteTeam(null)}>{t('common.cancel')}</Button>
<Button
variant="primary"
onClick={() => {
const id = pendingDeleteTeam.id;
setPendingDeleteTeam(null);
void api.invoke(ipcChannels.players.deleteTeam, { id });
}}
>
{t('common.delete')}
</Button>
</div>
</div>
</>,
document.body,
)
: null}
{saving ? (
<div className={styles.progressOverlay} role="dialog" aria-busy data-testid="players-save-progress">
<div className={styles.progressModal}>
<div className={styles.progressTitle}>{t('players.savingTitle')}</div>
<div className={styles.previewSpinner} aria-hidden />
<div className={styles.progressBar}>
<div className={styles.progressFill} style={{ width: `${String(progress.percent)}%` }} />
</div>
<div className={styles.progressMeta}>
<div>{progress.detail}</div>
<div>{progress.percent}%</div>
</div>
</div>
</div>
) : null}
</>,
document.body,
);
}
@@ -170,21 +170,21 @@ export function SceneDescriptionModal({ initialHtml, onClose, onSave }: SceneDes
<div className={modalStyles.toolbarGroup}>
<ToolButton
title={t('scene.descriptionBold')}
active={toolbarState.bold}
active={toolbarState?.bold ?? false}
onClick={() => editor.chain().focus().toggleBold().run()}
>
<strong>B</strong>
</ToolButton>
<ToolButton
title={t('scene.descriptionItalic')}
active={toolbarState.italic}
active={toolbarState?.italic ?? false}
onClick={() => editor.chain().focus().toggleItalic().run()}
>
<em>I</em>
</ToolButton>
<ToolButton
title={t('scene.descriptionUnderline')}
active={toolbarState.underline}
active={toolbarState?.underline ?? false}
onClick={() => editor.chain().focus().toggleUnderline().run()}
>
<span style={{ textDecoration: 'underline' }}>U</span>
@@ -194,21 +194,21 @@ export function SceneDescriptionModal({ initialHtml, onClose, onSave }: SceneDes
<div className={modalStyles.toolbarGroup}>
<ToolButton
title={t('scene.descriptionHeading2')}
active={toolbarState.h2}
active={toolbarState?.h2 ?? false}
onClick={() => editor.chain().focus().toggleHeading({ level: 2 }).run()}
>
H2
</ToolButton>
<ToolButton
title={t('scene.descriptionHeading3')}
active={toolbarState.h3}
active={toolbarState?.h3 ?? false}
onClick={() => editor.chain().focus().toggleHeading({ level: 3 }).run()}
>
H3
</ToolButton>
<ToolButton
title={t('scene.descriptionQuote')}
active={toolbarState.blockquote}
active={toolbarState?.blockquote ?? false}
onClick={() => editor.chain().focus().toggleBlockquote().run()}
>
<ToolbarIcon path="M6 17h3l2-4V7H5v6h3zm8 0h3l2-4V7h-6v6h3z" />
@@ -218,14 +218,14 @@ export function SceneDescriptionModal({ initialHtml, onClose, onSave }: SceneDes
<div className={modalStyles.toolbarGroup}>
<ToolButton
title={t('scene.descriptionBulletList')}
active={toolbarState.bulletList}
active={toolbarState?.bulletList ?? false}
onClick={() => editor.chain().focus().toggleBulletList().run()}
>
<ToolbarIcon path="M4 6h2v2H4V6zm0 5h2v2H4v-2zm0 5h2v2H4v-2zm4-10h12v2H8V6zm0 5h12v2H8v-2zm0 5h12v2H8v-2z" />
</ToolButton>
<ToolButton
title={t('scene.descriptionOrderedList')}
active={toolbarState.orderedList}
active={toolbarState?.orderedList ?? false}
onClick={() => editor.chain().focus().toggleOrderedList().run()}
>
<ToolbarIcon path="M2 17h2v.5H3v1h1v.5H2v1h3v-4H2v1zm1-9h1V4H2v1h1v3zm-1 3h1.8L2 13.1V14h3v-1H3.2L5 10.9V10H2v1zm5-6v2h14V5H7zm0 14h14v-2H7v2zm0-6h14v-2H7v2z" />
+24
View File
@@ -26,6 +26,7 @@ import {
isSideStoryEdge,
} from '../../../shared/graph/sceneGraphLineage';
import type { AssetId, GraphNodeId, SceneGraphEdge, SceneGraphNode, SceneId } from '../../../shared/types';
import { ContainedVideo } from '../../shared/ContainedVideo';
import { RotatedImage } from '../../shared/RotatedImage';
import { EllipsisText } from '../../shared/ui/EllipsisText';
import ellipsisStyles from '../../shared/ui/ellipsisText.module.css';
@@ -260,6 +261,8 @@ function SceneCardNode({ data }: NodeProps<SceneCardData>) {
)}
</div>
) : previewUrl && data.previewAssetType === 'video' ? (
<div className={styles.previewFill}>
{data.previewRotationDeg === 0 ? (
<video
src={previewUrl}
muted
@@ -276,6 +279,27 @@ function SceneCardNode({ data }: NodeProps<SceneCardData>) {
}
}}
/>
) : (
<ContainedVideo
url={previewUrl}
rotationDeg={data.previewRotationDeg}
mode="cover"
muted
playsInline
preload="metadata"
style={{ width: '100%', height: '100%' }}
onLoadedData={(e) => {
const v = e.currentTarget;
try {
v.currentTime = 0;
v.pause();
} catch {
// ignore
}
}}
/>
)}
</div>
) : (
<div className={styles.previewPlaceholder} aria-hidden />
)}
+2 -2
View File
@@ -18,6 +18,7 @@ const RU_TITLES: Record<HelpSectionId, string> = {
tokens: 'Неигровые токены',
campaignAudio: 'Аудио игры',
materials: 'Материалы',
players: 'Игроки',
npcs: 'НПС',
session: 'Запуск сессии',
controlPanel: 'Пульт управления',
@@ -31,8 +32,7 @@ const RU_TITLES: Record<HelpSectionId, string> = {
void test('findHelpLinkRanges: «Ловушки» и алиас «Эффекты»', () => {
const catalog = buildHelpLinkCatalog((id) => RU_TITLES[id]);
const text =
'см. «Ловушки» и кистью (см. «Эффекты»). Также разделы «Генератор сетки», «Неигровые токены».';
const text = 'см. «Ловушки» и кистью (см. «Эффекты»). Также разделы «Генератор сетки», «Неигровые токены».';
const ranges = findHelpLinkRanges(text, catalog);
assert.deepEqual(
ranges.map((r) => r.id),
+1
View File
@@ -9,6 +9,7 @@ export const HELP_SECTION_LINK_ALIASES: Partial<Record<HelpSectionId, readonly s
presentation: ['Презентация', 'Presentation'],
grid: ['Сетка', 'Grid'],
controlPanel: ['Пульт'],
players: ['Игроки', 'Players'],
};
export type HelpLinkCatalogEntry = {
+9 -2
View File
@@ -1,5 +1,7 @@
/** Порядок разделов в окне «Инструкция». */
export const HELP_SECTION_IDS = [
import { USERS_BRANCH_FEATURES_ENABLED } from '../../../shared/features/usersBranchFeatures';
const HELP_SECTION_IDS_ALL = [
'overview',
'license',
'projects',
@@ -13,6 +15,7 @@ export const HELP_SECTION_IDS = [
'tokens',
'campaignAudio',
'materials',
'players',
'npcs',
'session',
'controlPanel',
@@ -24,7 +27,11 @@ export const HELP_SECTION_IDS = [
'settings',
] as const;
export type HelpSectionId = (typeof HELP_SECTION_IDS)[number];
export type HelpSectionId = (typeof HELP_SECTION_IDS_ALL)[number];
export const HELP_SECTION_IDS: readonly HelpSectionId[] = USERS_BRANCH_FEATURES_ENABLED
? HELP_SECTION_IDS_ALL
: HELP_SECTION_IDS_ALL.filter((id) => id !== 'players');
export function helpSectionTitleKey(id: HelpSectionId): string {
return `help.section.${id}.title`;
+127 -25
View File
@@ -110,9 +110,18 @@ export const EDITOR_MESSAGES: Record<EditorLocale, Record<string, string>> = {
'top.settings': 'Настройки',
'top.project': 'Проект',
'top.file': 'Файл',
'top.players': 'Игроки',
'top.backToProjects': 'К списку проектов',
'top.appVersion': 'Версия приложения',
'top.run': 'Запустить',
'top.runMenuAria': 'Дополнительные варианты запуска',
'top.runWithPlayers': 'Запустить с игроками',
'top.runWithPlayersTitle': 'Запуск с игроками',
'top.runWithPlayersHint': 'Выберите игроков и/или команды. Выбор сохранится на время сессии.',
'top.runWithPlayersTeams': 'Команды',
'top.runWithPlayersPlayers': 'Игроки',
'top.runWithPlayersEmpty': 'Нет игроков в библиотеке.',
'top.runWithPlayersConfirm': 'Запустить',
'top.launching': 'Запуск…',
'top.afterLicense': 'Доступно после активации лицензии',
'top.setStartScene': 'Назначьте начальную сцену на графе (ПКМ по узлу)',
@@ -171,23 +180,23 @@ export const EDITOR_MESSAGES: Record<EditorLocale, Record<string, string>> = {
'help.section.sceneProps.title': 'Свойства сцены',
'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.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.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.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.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.body':
@@ -195,19 +204,22 @@ export const EDITOR_MESSAGES: Record<EditorLocale, Record<string, string>> = {
'help.section.materials.title': 'Материалы',
'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.body':
'Раздел «Игроки» в шапке хранит локальную библиотеку живых игроков на этом компьютере (не внутри файла проекта).\n\n1) Откройте «Игроки» в шапке.\n\n2) «Добавить игрока» — имя и изображение обязательны. Пока идёт сохранение, видно окно с прогрессом.\n\n3) Справа — превью игрового токена: круг с цветной рамкой, аватар внутри (перетащите мышью, чтобы отцентровать; колесо мыши — увеличить/уменьшить), имя на тёмной подложке и выбор цвета рамки.\n\n4) Команды — плоские группы без вложенности: создайте команду, перетащите игрока в неё или в «Без команды».\n\nКампанийных НПС на сцену ставят отдельно: в «Редактор сцены» аккордеон «НПС» — плитки персонажей проекта, на карте они выглядят как такой же круглый токен.\n\nВо время сессии размер круглых токенов игроков и НПС на пульте можно менять ползунком «Размеры игр. токенов» (см. «Пульт управления»).',
'help.section.npcs.title': 'НПС',
'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) Справа — список персонажей; клик по плитке показывает аватар поверх сцены на пульте и на презентации; повторный клик по той же плитке скрывает его. Слева — описание и исходящие отношения выбранного персонажа (их видите только вы).\n\n3) На предпросмотре пульта аватар можно перетаскивать и менять размер за углы; крестик закрывает показ.\n\n4) В окне НПС лупы «+» / «−» — инструменты масштаба: выберите лупу, затем кликните по аватару в предпросмотре пульта.\n\nПри смене сцены показ НПС сбрасывается. Игроки на презентации видят только аватар.',
'НПС — персонажи кампании с аватаром, описанием и однонаправленными связями между собой. Они общие для проекта.\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.body':
'Когда кампания готова, можно начать игру.\n\nОбычный запуск:\n\n1) На карте связей щёлкните правой кнопкой по карточке старта → «Начальная сцена».\n\n2) Нажмите «Запустить» в шапке редактора.\n\nБыстрый запуск с любой карточки: правый клик по нужной карточке на карте → «Запустить с этой сцены». Презентация и пульт откроются сразу с выбранного места.\n\nОткроются «Презентация» (для игроков) и «Пульт управления» (для вас). Редактор на время показа затемняется — так и должно быть.\n\nВернуться к подготовке:\n\n1) На пульте нажмите «Выключить демонстрацию» или «Завершить показ» (если дальше некуда переходить).\n\n2) Дождитесь закрытия обоих окон.\n\nОкно «Презентация» перенесите на второй монитор, проектор или ТВ и разверните на весь экран (F11). Игроки увидят только картинку, видео и эффекты — без ваших кнопок.',
'Когда кампания готова, можно начать игру.\n\nОбычный запуск:\n\n1) На карте связей щёлкните правой кнопкой по карточке старта → «Начальная сцена».\n\n2) Нажмите «Запустить» в шапке редактора (левая часть кнопки).\n\nЗапуск с игроками: стрелка справа на кнопке «Запустить» → «Запустить с игроками» — выберите игроков и/или команды. Выбор сохранится на время сессии; на пульте появится «Показать игроков» / «Скрыть игроков». При смене сцены токены игроков скрываются.\n\nБыстрый запуск с любой карточки: правый клик по нужной карточке на карте → «Запустить с этой сцены». Презентация и пульт откроются сразу с выбранного места.\n\nОткроются «Презентация» (для игроков) и «Пульт управления» (для вас). Редактор на время показа затемняется — так и должно быть.\n\nВернуться к подготовке:\n\n1) На пульте нажмите «Выключить» или «Завершить показ» (если дальше некуда переходить).\n\n2) Дождитесь закрытия обоих окон.\n\nОкно «Презентация» перенесите на второй монитор, проектор или ТВ и разверните на весь экран (F11). Игроки увидят только картинку, видео и эффекты — без ваших кнопок.',
'help.section.controlPanel.title': 'Пульт управления',
'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.body':
@@ -219,11 +231,11 @@ export const EDITOR_MESSAGES: Record<EditorLocale, Record<string, string>> = {
'help.section.effects.title': 'Эффекты поля и действий',
'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.body':
'«Презентация» — то, что видят игроки: картинка сцены (с учётом поворота из редактора) или видео по вашим настройкам.\n\nЭффекты с пульта накладываются поверх. Меню и кнопки мастера здесь не показываются — клики по карте, ловушкам и токенам для игроков недоступны.\n\nЕсли у сцены включено «Затемнить сцену», игроки сначала видят полностью чёрный экран. Мастер открывает карту «Кистью Открытия» и при необходимости снова закрывает участки «Кистью Закрытия» на пульте.\n\nПри смене сцены с пульта картинка обновляется сама. Перенесите окно на экран для игроков и при необходимости спрячьте панель задач.\n\nПустой или тёмный экран — скорее всего, у сцены нет превью. Добавьте картинку в свойствах сцены в редакторе.',
'«Презентация» — то, что видят игроки: картинка или видео сцены (с учётом поворота из редактора) по вашим настройкам.\n\nЭффекты с пульта накладываются поверх. Меню и кнопки мастера здесь не показываются — клики по карте, ловушкам и токенам для игроков недоступны.\n\nЕсли у сцены включено «Затемнить сцену», игроки сначала видят полностью чёрный экран. Мастер открывает карту «Кистью Открытия» и при необходимости снова закрывает участки «Кистью Закрытия» на пульте.\n\nПри смене сцены с пульта картинка обновляется сама. Перенесите окно на экран для игроков и при необходимости спрячьте панель задач.\n\nПустой или тёмный экран — скорее всего, у сцены нет превью. Добавьте картинку в свойствах сцены в редакторе.',
'help.section.importExport.title': 'Импорт и экспорт',
'help.section.importExport.body':
@@ -416,6 +428,28 @@ export const EDITOR_MESSAGES: Record<EditorLocale, Record<string, string>> = {
'materials.zoomOutHint': 'Кликните по материалу в предпросмотре пульта, чтобы уменьшить.',
'materials.zoomIdleHint': 'Выберите лупу, затем кликните по материалу в предпросмотре пульта.',
'players.managerTitle': 'Игроки',
'players.add': 'Добавить игрока',
'players.search': 'Поиск игроков…',
'players.selectPrompt': 'Выберите игрока или добавьте нового.',
'players.name': 'ИМЯ',
'players.namePlaceholder': 'Имя игрока…',
'players.ringColor': 'ЦВЕТ РАМКИ',
'players.chooseImage': 'Выбрать изображение',
'players.dropHint': 'Перетащите изображение (PNG, JPG, WebP)',
'players.savingTitle': 'Сохранение игрока',
'players.savingWait': 'Подождите…',
'players.ungrouped': 'Без команды',
'players.addTeam': 'Новая команда',
'players.teamName': 'Название команды',
'players.teamColor': 'Цвет команды',
'players.teamMenu': 'Меню команды',
'players.dropHere': 'Перетащите игрока сюда',
'players.deleteTitle': 'Удаление игрока',
'players.deleteConfirm': 'Вы уверены, что хотите удалить игрока «{name}»?',
'players.deleteTeamTitle': 'Удаление команды',
'players.deleteTeamConfirm': 'Вы уверены, что хотите удалить команду «{name}»? Игроки останутся без команды.',
'npcs.open': 'НПС',
'npcs.editorTitle': 'НПС',
'npcs.add': 'Добавить',
@@ -440,6 +474,17 @@ export const EDITOR_MESSAGES: Record<EditorLocale, Record<string, string>> = {
'npcs.avatarRequired': 'Выберите аватар.',
'npcs.chooseAvatar': 'Выбрать аватар',
'npcs.dropHint': 'Перетащите изображение (PNG, JPG, WebP)',
'npcs.disposition': 'ТИП',
'npcs.disposition.hostile': 'Враждебный',
'npcs.disposition.neutral': 'Нейтральный',
'npcs.disposition.friendly': 'Дружественный',
'npcs.makeHostile': 'Сделать враждебным',
'npcs.makeNeutral': 'Сделать нейтральным',
'npcs.makeFriendly': 'Сделать дружественным',
'npcs.inactive': 'Неактивен',
'npcs.makeActive': 'Сделать активным',
'npcs.openInfo': 'Открыть информацию',
'npcs.ringColor': 'ЦВЕТ РАМКИ ТОКЕНА',
'npcs.description': 'ОПИСАНИЕ',
'npcs.descriptionPlaceholder': 'Описание персонажа…',
'npcs.descriptionEmpty': 'Описание отсутствует',
@@ -578,7 +623,12 @@ export const EDITOR_MESSAGES: Record<EditorLocale, Record<string, string>> = {
'control.passed': 'Пройдено',
'control.noActiveScene': 'Нет активной сцены.',
'control.screenPreview': 'Предпросмотр экрана',
'control.stopPresentation': 'Выключить демонстрацию',
'control.npcTokenScale': 'Размеры игр. токенов',
'control.snapTokensToGrid': 'Привязка токенов к сетке',
'control.snapTokensToGridNoGrid': 'Сетка на текущей сцене выключена — привязка не применяется',
'control.stopPresentation': 'Выключить',
'control.showPlayers': 'Показать игроков',
'control.hidePlayers': 'Скрыть игроков',
'control.videoBrushHint':
'Видео-превью: кисть эффектов отключена (как на экране демонстрации — оверлей только для изображения).',
'control.branches': 'Варианты ветвления',
@@ -680,9 +730,18 @@ export const EDITOR_MESSAGES: Record<EditorLocale, Record<string, string>> = {
'top.settings': 'Settings',
'top.project': 'Project',
'top.file': 'File',
'top.players': 'Players',
'top.backToProjects': 'Back to projects',
'top.appVersion': 'App version',
'top.run': 'Run',
'top.runMenuAria': 'More launch options',
'top.runWithPlayers': 'Run with players',
'top.runWithPlayersTitle': 'Launch with players',
'top.runWithPlayersHint': 'Select players and/or teams. The selection is kept for this session.',
'top.runWithPlayersTeams': 'Teams',
'top.runWithPlayersPlayers': 'Players',
'top.runWithPlayersEmpty': 'No players in the library.',
'top.runWithPlayersConfirm': 'Launch',
'top.launching': 'Starting…',
'top.afterLicense': 'Available after license activation',
'top.setStartScene': 'Set a start scene on the graph (rightclick a node)',
@@ -741,23 +800,23 @@ export const EDITOR_MESSAGES: Record<EditorLocale, Record<string, string>> = {
'help.section.sceneProps.title': 'Scene properties',
'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 and video, 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.body':
'Scene editor is a separate window for preparing the map: battle grid, traps, and non-player 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, and Traps accordions; on the right is the scene map.\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.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.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.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 removes it from the map. Right-click opens a menu: Set movement / Delete / Reset to path start. 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.body':
@@ -765,19 +824,22 @@ export const EDITOR_MESSAGES: Record<EditorLocale, Record<string, string>> = {
'help.section.materials.title': 'Materials',
'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.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.\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.body':
'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 — a separate character editor window opens.\n\n2) Add — enter a unique name and a required avatar (PNG, JPG, or WebP) via Choose avatar or by dropping a file. You can fill in the description right away if you want.\n\n3) Left: character list with search and drag reorder; the ⋮ menu is delete only (with confirmation; all relations involving that character are removed too).\n\n4) Center: relationship graph — drag an arrow from one character to another and enter a required relation name. Relations are one-way (A → B and B → A are different). Multiple relations in the same direction are drawn as parallel curves. Click a relation or its label to select the source character and highlight their outgoing links.\n\n5) Right: the selected characters card — avatar, name, description (rich text), and a Relations list of outgoing links only (“name” + target name).\n\n6) Right-click a relation on the graph to Edit the name or Delete (with confirmation).\n\nDuring a session:\n\n1) On the control panel under Tools, next to materials, click the NPCs button (colored person icon) to open a separate window.\n\n2) Right: character list; click a tile to show the avatar over the scene on the control preview and presentation; click the same tile again to hide it. Left: description and outgoing relations for the selected character (visible only to you).\n\n3) On the control preview you can drag the avatar and resize it from the corners; the × button closes the overlay.\n\n4) In the NPCs window, the + / magnifiers are zoom tools: pick one, then click the avatar on the control preview.\n\nChanging scenes clears the NPC overlay. Players on presentation see only the avatar.',
'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.body':
'When your campaign is ready, you can start playing.\n\nStandard start:\n\n1) On the story map, right-click the starting card → Start scene.\n\n2) Click Run in the editor header.\n\nQuick start from any card: right-click the card on the map → Start from this scene. Presentation and the control panel open at that spot right away.\n\nPresentation (for players) and the Control panel (for you) open. The editor dims while the show runs — that is expected.\n\nReturn to prep:\n\n1) On the control panel, click Stop presentation or End presentation (when there is nowhere left to go).\n\n2) Wait until both windows close.\n\nMove the Presentation window to a second monitor, projector, or TV and go fullscreen (F11). Players see only the image, video, and effects — not your buttons.',
'When your campaign is ready, you can start playing.\n\nStandard start:\n\n1) On the story map, right-click the starting card → Start scene.\n\n2) Click Run in the editor header (left part of the button).\n\nRun with players: use the chevron on the right of Run → Run with players — pick players and/or teams. The selection lasts for the session; the control panel shows Show players / Hide players. Changing scenes hides player tokens.\n\nQuick start from any card: right-click the card on the map → Start from this scene. Presentation and the control panel open at that spot right away.\n\nPresentation (for players) and the Control panel (for you) open. The editor dims while the show runs — that is expected.\n\nReturn to prep:\n\n1) On the control panel, click Turn off or End presentation (when there is nowhere left to go).\n\n2) Wait until both windows close.\n\nMove the Presentation window to a second monitor, projector, or TV and go fullscreen (F11). Players see only the image, video, and effects — not your buttons.',
'help.section.controlPanel.title': 'Control panel',
'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.body':
@@ -789,11 +851,11 @@ export const EDITOR_MESSAGES: Record<EditorLocale, Record<string, string>> = {
'help.section.effects.title': 'Field and action effects',
'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.body':
'Presentation is what players see: the scene image (with rotation from the editor) or video according to your settings.\n\nEffects from the control panel draw on top. There are no GM menus or buttons here — players cannot click the map, traps, or tokens.\n\nIf Darken scene is enabled, players first see a fully black screen. The GM reveals the map with the Opening brush and can cover areas again with the Closing brush on the control panel.\n\nWhen you switch scenes from the control panel, the image updates automatically. Move the window to the display players watch and hide the taskbar if needed.\n\nA blank or dark screen usually means the scene has no preview — add one in scene properties in the editor.',
'Presentation is what players see: the scene image or video (with rotation from the editor) according to your settings.\n\nEffects from the control panel draw on top. There are no GM menus or buttons here — players cannot click the map, traps, or tokens.\n\nIf Darken scene is enabled, players first see a fully black screen. The GM reveals the map with the Opening brush and can cover areas again with the Closing brush on the control panel.\n\nWhen you switch scenes from the control panel, the image updates automatically. Move the window to the display players watch and hide the taskbar if needed.\n\nA blank or dark screen usually means the scene has no preview — add one in scene properties in the editor.',
'help.section.importExport.title': 'Import and export',
'help.section.importExport.body':
@@ -987,6 +1049,29 @@ export const EDITOR_MESSAGES: Record<EditorLocale, Record<string, string>> = {
'materials.zoomOutHint': 'Click the material on the control preview to zoom out.',
'materials.zoomIdleHint': 'Pick a magnifier, then click the material on the control preview.',
'players.managerTitle': 'Players',
'players.add': 'Add player',
'players.search': 'Search players…',
'players.selectPrompt': 'Select a player or add a new one.',
'players.name': 'NAME',
'players.namePlaceholder': 'Player name…',
'players.ringColor': 'RING COLOR',
'players.chooseImage': 'Choose image',
'players.dropHint': 'Drop an image (PNG, JPG, WebP)',
'players.savingTitle': 'Saving player',
'players.savingWait': 'Please wait…',
'players.ungrouped': 'No team',
'players.addTeam': 'New team',
'players.teamName': 'Team name',
'players.teamColor': 'Team color',
'players.teamMenu': 'Team menu',
'players.dropHere': 'Drop a player here',
'players.deleteTitle': 'Delete player',
'players.deleteConfirm': 'Are you sure you want to delete player “{name}”?',
'players.deleteTeamTitle': 'Delete team',
'players.deleteTeamConfirm':
'Are you sure you want to delete team “{name}”? Players will become ungrouped.',
'npcs.open': 'NPCs',
'npcs.editorTitle': 'NPCs',
'npcs.add': 'Add',
@@ -1011,13 +1096,25 @@ export const EDITOR_MESSAGES: Record<EditorLocale, Record<string, string>> = {
'npcs.avatarRequired': 'Choose an avatar.',
'npcs.chooseAvatar': 'Choose avatar',
'npcs.dropHint': 'Drop an image (PNG, JPG, WebP)',
'npcs.disposition': 'TYPE',
'npcs.disposition.hostile': 'Hostile',
'npcs.disposition.neutral': 'Neutral',
'npcs.disposition.friendly': 'Friendly',
'npcs.makeHostile': 'Make Hostile',
'npcs.makeNeutral': 'Make Neutral',
'npcs.makeFriendly': 'Make Friendly',
'npcs.inactive': 'Inactive',
'npcs.makeActive': 'Make Active',
'npcs.openInfo': 'Open information',
'npcs.ringColor': 'TOKEN RING COLOR',
'npcs.description': 'DESCRIPTION',
'npcs.descriptionPlaceholder': 'Character description…',
'npcs.descriptionEmpty': 'No description',
'npcs.relations': 'Relations',
'npcs.untitled': 'Untitled',
'npcs.deleteTitle': 'Delete NPC',
'npcs.deleteConfirm': 'Are you sure you want to delete NPC “{name}”? All of their relations will be removed.',
'npcs.deleteConfirm':
'Are you sure you want to delete NPC “{name}”? All of their relations will be removed.',
'npcs.relationCreateTitle': 'Relation name',
'npcs.relationEditTitle': 'Relation name',
'npcs.relationLabel': 'NAME',
@@ -1148,7 +1245,12 @@ export const EDITOR_MESSAGES: Record<EditorLocale, Record<string, string>> = {
'control.passed': 'Visited',
'control.noActiveScene': 'No active scene.',
'control.screenPreview': 'Screen preview',
'control.stopPresentation': 'Stop presentation',
'control.npcTokenScale': 'Play token size',
'control.snapTokensToGrid': 'Snap tokens to grid',
'control.snapTokensToGridNoGrid': 'Grid is off on this scene — snap has no effect',
'control.stopPresentation': 'Turn off',
'control.showPlayers': 'Show players',
'control.hidePlayers': 'Hide players',
'control.videoBrushHint':
'Video preview: effect brush is disabled (like on the presentation screen — overlay is for images only).',
'control.branches': 'Branch options',
+32 -15
View File
@@ -20,6 +20,7 @@ import type {
} from '../../../shared/types';
import { getDndApi } from '../../shared/dndApi';
import { invalidateAssetUrlCache } from '../../shared/useAssetImageUrl';
import { applyPreviewRotationToSceneMarkers } from '../../../shared/types/scenePreviewRotation';
type ProjectSummary = { id: ProjectId; name: string; updatedAt: string; fileName: string };
@@ -50,11 +51,7 @@ type Actions = {
importCampaignAudio: () => Promise<void>;
importCampaignAudioFromPaths: (filePaths: string[]) => Promise<void>;
updateCampaignAudios: (next: Project['campaignAudios']) => Promise<void>;
upsertMaterial: (input: {
materialId?: MaterialId;
name: string;
filePath?: string;
}) => Promise<void>;
upsertMaterial: (input: { materialId?: MaterialId; name: string; filePath?: string }) => Promise<void>;
deleteMaterial: (materialId: MaterialId) => Promise<void>;
setMaterialsOrder: (materialIds: MaterialId[]) => Promise<void>;
setMaterialRotation: (materialId: MaterialId, rotationDeg: 0 | 90 | 180 | 270) => Promise<void>;
@@ -104,7 +101,10 @@ type Actions = {
mode: 'folder' | 'archive',
) => Promise<{ canceled: true } | { canceled: false; sourcePath: string }>;
importFoundryProject: (sourcePath: string) => Promise<void>;
peekImportZip: (labels: StorylineLabels, targetHasMainStart: boolean) => Promise<
peekImportZip: (
labels: StorylineLabels,
targetHasMainStart: boolean,
) => Promise<
| { canceled: true }
| {
canceled: false;
@@ -355,6 +355,7 @@ export function useProjectState(licenseActive: boolean, opts?: ProjectStateOpts)
darkenScene: false,
traps: [],
tokens: [],
npcTokens: [],
grid: { enabled: false, type: 'square', sizeN: 0.06, color: '#ffffff' },
media: { videos: [], audios: [] },
settings: { autoplayVideo: false, autoplayAudio: true, loopVideo: true, loopAudio: true },
@@ -509,11 +510,7 @@ export function useProjectState(licenseActive: boolean, opts?: ProjectStateOpts)
await refreshProjects();
};
const upsertMaterial = async (input: {
materialId?: MaterialId;
name: string;
filePath?: string;
}) => {
const upsertMaterial = async (input: { materialId?: MaterialId; name: string; filePath?: string }) => {
const res = await api.invoke(ipcChannels.project.upsertMaterial, input);
setState((s) => ({ ...s, project: res.project }));
await refreshProjects();
@@ -531,10 +528,7 @@ export function useProjectState(licenseActive: boolean, opts?: ProjectStateOpts)
await refreshProjects();
};
const setMaterialRotation = async (
materialId: MaterialId,
rotationDeg: 0 | 90 | 180 | 270,
) => {
const setMaterialRotation = async (materialId: MaterialId, rotationDeg: 0 | 90 | 180 | 270) => {
const res = await api.invoke(ipcChannels.project.setMaterialRotation, {
materialId,
rotationDeg,
@@ -570,6 +564,9 @@ export function useProjectState(licenseActive: boolean, opts?: ProjectStateOpts)
previewRotationDeg?: 0 | 90 | 180 | 270;
darkenScene?: boolean;
traps?: import('../../../shared/types').SceneTrap[];
tokens?: import('../../../shared/types').SceneToken[];
npcTokens?: import('../../../shared/types').SceneNpcToken[];
grid?: import('../../../shared/types').SceneGrid;
settings?: Partial<Scene['settings']>;
media?: Partial<Scene['media']>;
layout?: { x: number; y: number };
@@ -598,11 +595,31 @@ export function useProjectState(licenseActive: boolean, opts?: ProjectStateOpts)
...(patch.darkenScene !== undefined ? { darkenScene: patch.darkenScene } : null),
...(patch.traps !== undefined ? { traps: patch.traps } : null),
...(patch.tokens !== undefined ? { tokens: patch.tokens } : null),
...(patch.npcTokens !== undefined ? { npcTokens: patch.npcTokens } : null),
...(patch.grid !== undefined ? { grid: patch.grid } : null),
...(patch.settings ? { settings: { ...scene.settings, ...patch.settings } } : null),
...(patch.media ? { media: { ...scene.media, ...patch.media } } : null),
layout: patch.layout ? { ...scene.layout, ...patch.layout } : scene.layout,
};
if (patch.previewRotationDeg !== undefined) {
const remapped = applyPreviewRotationToSceneMarkers(
{
previewRotationDeg: scene.previewRotationDeg ?? 0,
tokens: scene.tokens ?? [],
npcTokens: scene.npcTokens ?? [],
traps: scene.traps ?? [],
},
patch.previewRotationDeg,
{
tokensProvided: patch.tokens !== undefined,
npcTokensProvided: patch.npcTokens !== undefined,
trapsProvided: patch.traps !== undefined,
},
);
if (patch.tokens === undefined) next.tokens = remapped.tokens;
if (patch.npcTokens === undefined) next.npcTokens = remapped.npcTokens;
if (patch.traps === undefined) next.traps = remapped.traps;
}
const scenes = { ...p.scenes, [sceneId]: next };
const project: Project = { ...p, scenes };
return { ...s, project };
+1 -1
View File
@@ -302,7 +302,7 @@ function FilterToolbar({
return (
<Panel position="top-left">
<Select
className={styles.filterSelect}
{...(styles.filterSelect ? { className: styles.filterSelect } : {})}
ariaLabel={ui.graphFilter}
value={value}
onChange={(next) => onChange(next as GraphGroupFilter)}
+13 -4
View File
@@ -185,6 +185,15 @@ export function NpcsApp() {
() => activeIds.map((id) => npcs.find((n) => n.id === id)).filter((n): n is ProjectNpc => Boolean(n)),
[activeIds, npcs],
);
/** Описание: сфокусированный НПС (открытие информации / последний выбор), иначе все активные. */
const detailNpcs = useMemo(() => {
const focusId = overlay?.focusNpcId ?? null;
if (focusId) {
const focused = npcs.find((n) => n.id === focusId);
if (focused) return [focused];
}
return selectedNpcs;
}, [npcs, overlay?.focusNpcId, selectedNpcs]);
const filteredNpcs = useMemo(() => {
const q = query.trim().toLowerCase();
@@ -226,7 +235,7 @@ export function NpcsApp() {
const relationsByNpcId = useMemo(() => {
const map = new Map<NpcId, { id: string; text: string }[]>();
for (const npc of selectedNpcs) {
for (const npc of detailNpcs) {
const list = relations
.filter((r) => r.sourceNpcId === npc.id)
.map((r) => {
@@ -236,7 +245,7 @@ export function NpcsApp() {
map.set(npc.id, list);
}
return map;
}, [npcs, relations, selectedNpcs]);
}, [detailNpcs, npcs, relations]);
const onSelectTile = useCallback(
(id: NpcId) => {
@@ -304,8 +313,8 @@ export function NpcsApp() {
<div className={styles.body}>
<div className={styles.detail}>
{selectedNpcs.length > 0 ? (
selectedNpcs.map((npc) => {
{detailNpcs.length > 0 ? (
detailNpcs.map((npc) => {
const safeHtml = sanitizeSceneDescriptionHtml(npc.description);
const npcRelations = relationsByNpcId.get(npc.id) ?? [];
return (
@@ -189,6 +189,15 @@
margin-bottom: 8px;
}
.colorInput {
width: 100%;
height: 36px;
padding: 0;
border: 1px solid var(--stroke);
border-radius: 8px;
background: transparent;
}
.avatarPick {
display: grid;
gap: 10px;
+48
View File
@@ -14,8 +14,11 @@ import type {
import editorStyles from '../editor/EditorApp.module.css';
import { useEditorI18n } from '../editor/i18n/EditorI18nContext';
import { getDndApi } from '../shared/dndApi';
import { USERS_BRANCH_FEATURES_ENABLED } from '../../shared/features/usersBranchFeatures';
import { PlayerTokenView } from '../shared/playerToken/PlayerTokenView';
import { Button, Input, Select } from '../shared/ui/controls';
import { useAssetUrl } from '../shared/useAssetImageUrl';
import { npcDispositionRingColor } from '../../shared/types/npcDisposition';
import { NpcDescriptionField } from './NpcDescriptionField';
import { NpcEditModal } from './NpcEditModal';
@@ -735,11 +738,35 @@ export function NpcsEditorApp() {
<div>
<div className={styles.fieldLabel}>{t('npcs.avatar')}</div>
<div className={styles.avatarPick}>
{USERS_BRANCH_FEATURES_ENABLED ? (
<PlayerTokenView
name={selected.name}
imageUrl={selectedUrl}
ringColor={npcDispositionRingColor(selected.disposition ?? 'neutral')}
imageOffset={selected.imageOffset}
imageScale={selected.imageScale}
sizePx={140}
panEnabled
onImageOffsetChange={(imageOffset) => {
void api.invoke(ipcChannels.project.updateNpcFields, {
npcId: selected.id,
imageOffset,
});
}}
onImageScaleChange={(imageScale) => {
void api.invoke(ipcChannels.project.updateNpcFields, {
npcId: selected.id,
imageScale,
});
}}
/>
) : (
<div className={styles.avatarPreview}>
{selectedUrl ? (
<img className={styles.avatarPreviewImg} src={selectedUrl} alt="" />
) : null}
</div>
)}
<Button
disabled={avatarBusy}
onClick={() => {
@@ -764,6 +791,27 @@ export function NpcsEditorApp() {
</div>
</div>
{USERS_BRANCH_FEATURES_ENABLED ? (
<label>
<div className={styles.fieldLabel}>{t('npcs.disposition')}</div>
<Select
value={selected.disposition ?? 'neutral'}
ariaLabel={t('npcs.disposition')}
onChange={(next) => {
void api.invoke(ipcChannels.project.updateNpcFields, {
npcId: selected.id,
disposition: next as 'hostile' | 'neutral' | 'friendly',
});
}}
options={[
{ value: 'hostile', label: t('npcs.disposition.hostile') },
{ value: 'neutral', label: t('npcs.disposition.neutral') },
{ value: 'friendly', label: t('npcs.disposition.friendly') },
]}
/>
</label>
) : null}
<div>
<div className={styles.fieldLabel}>{t('npcs.name')}</div>
<Input
@@ -287,6 +287,34 @@
cursor: grabbing;
}
.npcTile {
display: grid;
justify-content: center;
overflow: hidden;
padding: 7px 4px;
border: 1px solid var(--stroke, #2a2f3a);
border-radius: 8px;
background: rgb(0 0 0 / 22%);
cursor: grab;
}
.sceneNpcToken {
position: absolute;
z-index: 2;
overflow: visible;
transform: translate(-50%, -50%);
cursor: move;
touch-action: none;
}
.sceneNpcToken > * {
pointer-events: none;
}
.sceneNpcToken .handle {
pointer-events: auto;
}
.tokenThumb {
aspect-ratio: 1;
border-radius: 6px;
@@ -452,3 +480,49 @@
.toolbar button {
font-size: 12px;
}
.ctxMenuBackdrop {
position: fixed;
inset: 0;
z-index: 40;
border: none;
padding: 0;
margin: 0;
background: transparent;
cursor: default;
}
.ctxMenu {
position: fixed;
z-index: 41;
min-width: 200px;
padding: 6px;
border-radius: 8px;
border: 1px solid var(--stroke, #2a2f3a);
background: var(--color-surface-menu, #1a1e28);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.45);
display: grid;
gap: 2px;
}
.ctxItem,
.ctxItemDanger {
text-align: left;
padding: 8px 10px;
border-radius: 6px;
border: none;
background: transparent;
color: var(--text1, #e8eaef);
font-size: 13px;
cursor: pointer;
width: 100%;
}
.ctxItemDanger {
color: var(--color-danger, #e57373);
}
.ctxItem:hover,
.ctxItemDanger:hover {
background: rgba(255, 255, 255, 0.06);
}
+526 -21
View File
@@ -2,7 +2,27 @@ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { createPortal } from 'react-dom';
import { ipcChannels, type SessionState } from '../../shared/ipc/contracts';
import type { SceneGrid, SceneToken, SceneTrap, SceneTrapType, TokenId } from '../../shared/types';
import type {
NpcDisposition,
NpcId,
ProjectNpc,
SceneGrid,
SceneNpcToken,
SceneToken,
SceneTrap,
SceneTrapType,
TokenId,
} from '../../shared/types';
import {
asSceneNpcTokenId,
clampSceneNpcTokenSizeN,
DEFAULT_SCENE_NPC_TOKEN_SIZE_N,
} from '../../shared/types/appPlayers';
import {
normalizeNpcDisposition,
npcDispositionRingColor,
otherNpcDispositions,
} from '../../shared/types/npcDisposition';
import {
asSceneTokenId,
asTokenId,
@@ -14,6 +34,7 @@ import {
DEFAULT_SCENE_GRID,
SCENE_GRID_SIZE_MAX,
SCENE_GRID_SIZE_MIN,
sceneGridTokenFitFactor,
sceneGridTypeLabelRu,
} from '../../shared/types/sceneGrid';
import {
@@ -23,22 +44,33 @@ import {
trapTypeLabelRu,
} from '../../shared/types/sceneTraps';
import { sceneViewPanBy, sceneViewZoomAt } from '../../shared/types/sceneView';
import { USERS_BRANCH_FEATURES_ENABLED } from '../../shared/features/usersBranchFeatures';
import editorStyles from '../editor/EditorApp.module.css';
import { useEditorI18n } from '../editor/i18n/EditorI18nContext';
import { getDndApi } from '../shared/dndApi';
import { EllipsisText } from '../shared/ui/EllipsisText';
import ellipsisStyles from '../shared/ui/ellipsisText.module.css';
import { ContainedVideo } from '../shared/ContainedVideo';
import { SceneGridOverlay } from '../shared/grid/SceneGridOverlay';
import { PlayerTokenView } from '../shared/playerToken/PlayerTokenView';
import { RotatedImage } from '../shared/RotatedImage';
import { TokenPathsOverlay } from '../shared/tokens/TokenPathsOverlay';
import { useAppTokens } from '../shared/tokens/useAppTokens';
import { TrapGlyph } from '../shared/traps/TrapGlyph';
import { Button, Input, Select } from '../shared/ui/controls';
import { useAssetUrl } from '../shared/useAssetImageUrl';
import { sampleTokenPathAtDistance } from '../../shared/types/tokenPath';
import { SceneTokenMarker } from './SceneTokenMarker';
import styles from './SceneEditorApp.module.css';
import { SceneTokenMarker } from './SceneTokenMarker';
import { TokenEditModal } from './TokenEditModal';
import { TOKEN_DND_MIME, TokenTile } from './TokenTile';
function dispositionMakeKey(d: NpcDisposition): string {
if (d === 'hostile') return 'npcs.makeHostile';
if (d === 'friendly') return 'npcs.makeFriendly';
return 'npcs.makeNeutral';
}
function isTypingTarget(el: EventTarget | null): boolean {
if (!(el instanceof HTMLElement)) return false;
const tag = el.tagName;
@@ -47,14 +79,37 @@ function isTypingTarget(el: EventTarget | null): boolean {
}
type LocalView = { scale: number; ox: number; oy: number };
type Selection = { kind: 'trap' | 'token'; id: string } | null;
type Selection = { kind: 'trap' | 'token' | 'npcToken'; id: string } | null;
type DragMode =
| { kind: 'pan'; lastX: number; lastY: number }
| { kind: 'moveTrap'; trapId: string; startNx: number; startNy: number; pointerNx: number; pointerNy: number }
| {
kind: 'moveTrap';
trapId: string;
startNx: number;
startNy: number;
pointerNx: number;
pointerNy: number;
}
| { kind: 'resizeTrap'; trapId: string; startSize: number; startDist: number }
| { kind: 'moveToken'; tokenId: string; startNx: number; startNy: number; pointerNx: number; pointerNy: number }
| {
kind: 'moveToken';
tokenId: string;
startNx: number;
startNy: number;
pointerNx: number;
pointerNy: number;
}
| { kind: 'resizeToken'; tokenId: string; startSize: number; startDist: number }
| {
kind: 'moveNpcToken';
tokenId: string;
startNx: number;
startNy: number;
pointerNx: number;
pointerNy: number;
}
| { kind: 'resizeNpcToken'; tokenId: string; startSize: number; startDist: number }
| {
kind: 'rotateToken';
tokenId: string;
@@ -80,27 +135,121 @@ function shortestAngleDelta(fromDeg: number, toDeg: number): number {
return d;
}
const SCENE_NPC_DND_MIME = 'application/x-dnd-scene-npc-id';
function SceneNpcMarker({
placement,
npc,
left,
top,
sizePx,
selected,
onSelect,
onContextMenu,
onMovePointerDown,
onResizePointerDown,
}: {
placement: SceneNpcToken;
npc: ProjectNpc;
left: number;
top: number;
sizePx: number;
selected: boolean;
onSelect: () => void;
onContextMenu: (e: React.MouseEvent) => void;
onMovePointerDown: (e: React.PointerEvent) => void;
onResizePointerDown: (e: React.PointerEvent) => void;
}) {
const imageUrl = useAssetUrl(npc.avatarAssetId);
const disposition = normalizeNpcDisposition(placement.disposition ?? npc.disposition);
return (
<div
data-testid={`scene-npc-token-${placement.id}`}
className={[styles.sceneNpcToken, selected ? styles.sceneTokenSelected : ''].filter(Boolean).join(' ')}
style={{ left, top, width: sizePx, height: sizePx }}
onContextMenu={(e) => {
e.preventDefault();
e.stopPropagation();
onContextMenu(e);
}}
onPointerDown={(e) => {
if (e.button !== 0) return;
onSelect();
onMovePointerDown(e);
}}
>
<PlayerTokenView
name={npc.name}
imageUrl={imageUrl}
ringColor={npcDispositionRingColor(disposition)}
imageOffset={npc.imageOffset}
imageScale={npc.imageScale}
sizePx={sizePx}
/>
{selected ? <div className={styles.handle} onPointerDown={onResizePointerDown} /> : null}
</div>
);
}
function NpcPaletteTile({ npc }: { npc: ProjectNpc }) {
const imageUrl = useAssetUrl(npc.avatarAssetId);
const disposition = normalizeNpcDisposition(npc.disposition);
return (
<div
className={styles.npcTile}
data-testid={`scene-npc-tile-${npc.id}`}
draggable
onDragStart={(e) => {
e.dataTransfer.setData(SCENE_NPC_DND_MIME, npc.id);
e.dataTransfer.effectAllowed = 'copy';
}}
title={npc.name}
>
<PlayerTokenView
name={npc.name}
imageUrl={imageUrl}
ringColor={npcDispositionRingColor(disposition)}
imageOffset={npc.imageOffset}
imageScale={npc.imageScale}
sizePx={70}
/>
</div>
);
}
export function SceneEditorApp() {
const api = getDndApi();
const { t } = useEditorI18n();
const appTokens = useAppTokens();
const [session, setSession] = useState<SessionState | null>(null);
const [trapsOpen, setTrapsOpen] = useState(false);
const [gridOpen, setGridOpen] = useState(false);
const [tokensOpen, setTokensOpen] = useState(false);
const [npcsOpen, setNpcsOpen] = useState(false);
const [tokenSearch, setTokenSearch] = useState('');
const [tokenModal, setTokenModal] = useState<{ mode: 'create' } | { mode: 'edit'; tokenId: TokenId } | null>(
null,
);
const [npcSearch, setNpcSearch] = useState('');
const [tokenModal, setTokenModal] = useState<
{ mode: 'create' } | { mode: 'edit'; tokenId: TokenId } | null
>(null);
const [pendingDeleteToken, setPendingDeleteToken] = useState<{ id: TokenId; name: string } | null>(null);
const [npcCtxMenu, setNpcCtxMenu] = useState<{
x: number;
y: number;
placementId: string;
} | null>(null);
const [tokenCtxMenu, setTokenCtxMenu] = useState<{
x: number;
y: number;
placementId: string;
} | null>(null);
const [selected, setSelected] = useState<Selection>(null);
const [view, setView] = useState<LocalView>({ scale: 1, ox: 0.5, oy: 0.5 });
const [contentRect, setContentRect] = useState<{ x: number; y: number; w: number; h: number } | null>(
null,
);
const [contentRect, setContentRect] = useState<{ x: number; y: number; w: number; h: number } | null>(null);
const hostRef = useRef<HTMLDivElement | null>(null);
const dragRef = useRef<DragMode>(null);
const saveTrapsTimerRef = useRef(0);
const saveTokensTimerRef = useRef(0);
const saveNpcTokensTimerRef = useRef(0);
const saveGridTimerRef = useRef(0);
const spaceDownRef = useRef(false);
@@ -111,15 +260,24 @@ export function SceneEditorApp() {
const rot = scene?.previewRotationDeg ?? 0;
const [localTraps, setLocalTraps] = useState<SceneTrap[]>([]);
const [localTokens, setLocalTokens] = useState<SceneToken[]>([]);
const [localNpcTokens, setLocalNpcTokens] = useState<SceneNpcToken[]>([]);
const [localGrid, setLocalGrid] = useState<SceneGrid>({ ...DEFAULT_SCENE_GRID });
const trapsRef = useRef<SceneTrap[]>([]);
const tokensRef = useRef<SceneToken[]>([]);
const npcTokensRef = useRef<SceneNpcToken[]>([]);
useEffect(() => {
trapsRef.current = localTraps;
tokensRef.current = localTokens;
npcTokensRef.current = localNpcTokens;
}, [localNpcTokens, localTokens, localTraps]);
useEffect(() => {
setLocalTraps(scene?.traps ?? []);
setLocalTokens((scene?.tokens ?? []).filter((t) => appTokens.some((a) => a.id === t.tokenId)));
setLocalNpcTokens(
(scene?.npcTokens ?? []).filter((t) => project?.npcs.some((npc) => npc.id === t.npcId)),
);
setLocalGrid(scene?.grid ?? { ...DEFAULT_SCENE_GRID });
setSelected(null);
setView({ scale: 1, ox: 0.5, oy: 0.5 });
@@ -136,6 +294,12 @@ export function SceneEditorApp() {
setLocalTokens((scene?.tokens ?? []).filter((t) => known.has(t.tokenId)));
}, [scene?.tokens, appTokens]);
useEffect(() => {
if (dragRef.current) return;
const known = new Set((project?.npcs ?? []).map((npc) => npc.id));
setLocalNpcTokens((scene?.npcTokens ?? []).filter((t) => known.has(t.npcId)));
}, [scene?.npcTokens, project?.npcs]);
useEffect(() => {
if (dragRef.current) return;
setLocalGrid(scene?.grid ?? { ...DEFAULT_SCENE_GRID });
@@ -176,6 +340,19 @@ export function SceneEditorApp() {
[api, sceneId],
);
const persistNpcTokens = useCallback(
(next: SceneNpcToken[]) => {
if (!sceneId) return;
setLocalNpcTokens(next);
npcTokensRef.current = next;
if (saveNpcTokensTimerRef.current) window.clearTimeout(saveNpcTokensTimerRef.current);
saveNpcTokensTimerRef.current = window.setTimeout(() => {
void api.invoke(ipcChannels.project.updateScene, { sceneId, patch: { npcTokens: next } });
}, 120);
},
[api, sceneId],
);
const persistGrid = useCallback(
(next: SceneGrid) => {
if (!sceneId) return;
@@ -196,8 +373,10 @@ export function SceneEditorApp() {
e.preventDefault();
if (selected.kind === 'trap') {
persistTraps(trapsRef.current.filter((t) => t.id !== selected.id));
} else {
} else if (selected.kind === 'token') {
persistTokens(tokensRef.current.filter((t) => t.id !== selected.id));
} else {
persistNpcTokens(npcTokensRef.current.filter((t) => t.id !== selected.id));
}
setSelected(null);
}
@@ -212,7 +391,7 @@ export function SceneEditorApp() {
window.removeEventListener('keydown', onKeyDown);
window.removeEventListener('keyup', onKeyUp);
};
}, [persistTraps, persistTokens, sceneId, selected]);
}, [persistNpcTokens, persistTraps, persistTokens, sceneId, selected]);
const hostToNorm = (clientX: number, clientY: number): { x: number; y: number } | null => {
const host = hostRef.current;
@@ -286,6 +465,24 @@ export function SceneEditorApp() {
persistTokens([...tokensRef.current, placement]);
};
const addNpcTokenAt = (npcId: NpcId, nx: number, ny: number) => {
const gridCellSize =
localGrid.enabled && Number.isFinite(localGrid.sizeN)
? clampSceneNpcTokenSizeN(localGrid.sizeN)
: DEFAULT_SCENE_NPC_TOKEN_SIZE_N;
const npc = project?.npcs.find((item) => item.id === npcId);
const placement: SceneNpcToken = {
id: asSceneNpcTokenId(randomId('snpc')),
npcId,
nx,
ny,
sizeN: gridCellSize,
disposition: normalizeNpcDisposition(npc?.disposition),
};
setSelected({ kind: 'npcToken', id: placement.id });
persistNpcTokens([...npcTokensRef.current, placement]);
};
const onStageDrop = (e: React.DragEvent) => {
e.preventDefault();
const p = hostToNorm(e.clientX, e.clientY);
@@ -295,6 +492,11 @@ export function SceneEditorApp() {
addTokenAt(asTokenId(tokenId), p.x, p.y);
return;
}
const npcId = e.dataTransfer.getData(SCENE_NPC_DND_MIME);
if (USERS_BRANCH_FEATURES_ENABLED && npcId) {
addNpcTokenAt(npcId as NpcId, p.x, p.y);
return;
}
const type = e.dataTransfer.getData('application/x-dnd-trap-type') as SceneTrapType;
if (!SCENE_TRAP_TYPES.includes(type)) return;
addTrapAt(type, p.x, p.y);
@@ -308,14 +510,27 @@ export function SceneEditorApp() {
persistTokens(tokensRef.current.map((t) => (t.id === id ? { ...t, ...patch } : t)));
};
const updateNpcToken = (id: string, patch: Partial<SceneNpcToken>) => {
persistNpcTokens(npcTokensRef.current.map((t) => (t.id === id ? { ...t, ...patch } : t)));
};
const filteredTokens = useMemo(() => {
const q = tokenSearch.trim().toLowerCase();
if (!q) return appTokens;
return appTokens.filter((t) => t.name.toLowerCase().includes(q));
}, [appTokens, tokenSearch]);
const editingToken = tokenModal?.mode === 'edit' ? appTokens.find((t) => t.id === tokenModal.tokenId) ?? null : null;
const filteredNpcs = useMemo(() => {
const q = npcSearch.trim().toLowerCase();
const npcs = project?.npcs ?? [];
return q ? npcs.filter((npc) => npc.name.toLowerCase().includes(q)) : npcs;
}, [npcSearch, project?.npcs]);
const editingToken =
tokenModal?.mode === 'edit' ? (appTokens.find((t) => t.id === tokenModal.tokenId) ?? null) : null;
const isImage = scene?.previewAssetType === 'image' && Boolean(url);
const isVideo = scene?.previewAssetType === 'video' && Boolean(url);
const hasMapMedia = isImage || isVideo;
return (
<div className={styles.page}>
@@ -396,6 +611,30 @@ export function SceneEditorApp() {
) : null}
</div>
{USERS_BRANCH_FEATURES_ENABLED ? (
<div className={styles.accordion} data-testid="scene-npc-accordion">
<button type="button" className={styles.accordionHead} onClick={() => setNpcsOpen((v) => !v)}>
НПС {npcsOpen ? '▾' : '▸'}
</button>
{npcsOpen ? (
<div className={styles.tokensPanel}>
<Input
value={npcSearch}
onChange={setNpcSearch}
placeholder="Поиск НПС…"
onKeyDown={(e) => e.stopPropagation()}
/>
<div className={styles.tokenGrid}>
{filteredNpcs.map((npc) => (
<NpcPaletteTile key={npc.id} npc={npc} />
))}
{filteredNpcs.length === 0 ? <div className={styles.hint}>Нет НПС</div> : null}
</div>
</div>
) : null}
</div>
) : null}
<div className={styles.accordion}>
<button type="button" className={styles.accordionHead} onClick={() => setTokensOpen((v) => !v)}>
Неигровые токены {tokensOpen ? '▾' : '▸'}
@@ -409,7 +648,6 @@ export function SceneEditorApp() {
value={tokenSearch}
onChange={setTokenSearch}
placeholder="Поиск…"
autoFocus={tokensOpen}
onKeyDown={(e) => e.stopPropagation()}
/>
<div className={styles.tokenGrid}>
@@ -457,10 +695,14 @@ export function SceneEditorApp() {
<div className={styles.clearSceneBtn}>
<Button
disabled={!sceneId || (localTraps.length === 0 && localTokens.length === 0)}
data-testid="scene-clear-btn"
disabled={
!sceneId || (localTraps.length === 0 && localTokens.length === 0 && localNpcTokens.length === 0)
}
onClick={() => {
persistTraps([]);
persistTokens([]);
persistNpcTokens([]);
setSelected(null);
}}
>
@@ -471,8 +713,8 @@ export function SceneEditorApp() {
</aside>
<div className={styles.stage}>
{!isImage ? (
<div className={styles.empty}>Нужно изображение сцены</div>
{!hasMapMedia ? (
<div className={styles.empty}>Нужно изображение или видео сцены</div>
) : (
<div
ref={hostRef}
@@ -543,6 +785,26 @@ export function SceneEditorApp() {
});
return;
}
if (d.kind === 'moveNpcToken') {
const p = hostToNorm(e.clientX, e.clientY);
if (!p) return;
updateNpcToken(d.tokenId, {
nx: Math.max(0, Math.min(1, d.startNx + (p.x - d.pointerNx))),
ny: Math.max(0, Math.min(1, d.startNy + (p.y - d.pointerNy))),
});
return;
}
if (d.kind === 'resizeNpcToken') {
const p = hostToNorm(e.clientX, e.clientY);
const tok = npcTokensRef.current.find((t) => t.id === d.tokenId);
if (!p || !tok) return;
const dist = Math.hypot(p.x - tok.nx, p.y - tok.ny);
const ratio = d.startDist > 1e-6 ? dist / d.startDist : 1;
updateNpcToken(d.tokenId, {
sizeN: clampSceneNpcTokenSizeN(d.startSize * ratio),
});
return;
}
if (d.kind === 'rotateToken') {
const ang = pointerAngleDeg(d.centerClientX, d.centerClientY, e.clientX, e.clientY);
const delta = shortestAngleDelta(d.startPointerAngle, ang);
@@ -556,6 +818,7 @@ export function SceneEditorApp() {
dragRef.current = null;
}}
>
{isImage ? (
<RotatedImage
url={url!}
rotationDeg={rot}
@@ -563,7 +826,25 @@ export function SceneEditorApp() {
viewCamera={viewCamera}
onContentRectChange={setContentRect}
/>
) : (
<ContainedVideo
url={url!}
rotationDeg={rot}
muted
playsInline
loop
preload="metadata"
viewCamera={viewCamera}
onContentRectChange={setContentRect}
/>
)}
<SceneGridOverlay grid={localGrid} viewport={contentRect} />
<TokenPathsOverlay
tokens={localTokens}
npcTokens={USERS_BRANCH_FEATURES_ENABLED ? localNpcTokens : []}
viewport={contentRect}
mode="always"
/>
{contentRect
? localTokens.map((tok) => {
const minDim = Math.min(contentRect.w, contentRect.h);
@@ -582,8 +863,8 @@ export function SceneEditorApp() {
onContextMenu={(e) => {
e.preventDefault();
e.stopPropagation();
persistTokens(tokensRef.current.filter((t) => t.id !== tok.id));
setSelected((cur) => (cur?.kind === 'token' && cur.id === tok.id ? null : cur));
setSelected({ kind: 'token', id: tok.id });
setTokenCtxMenu({ x: e.clientX, y: e.clientY, placementId: tok.id });
}}
onMovePointerDown={(e) => {
if (spaceDownRef.current) return;
@@ -635,6 +916,60 @@ export function SceneEditorApp() {
);
})
: null}
{USERS_BRANCH_FEATURES_ENABLED && contentRect
? localNpcTokens.map((tok) => {
const npc = project?.npcs.find((item) => item.id === tok.npcId);
if (!npc) return null;
const minDim = Math.min(contentRect.w, contentRect.h);
const sizePx = Math.max(16, tok.sizeN * sceneGridTokenFitFactor(localGrid) * minDim);
const left = contentRect.x + tok.nx * contentRect.w;
const top = contentRect.y + tok.ny * contentRect.h;
return (
<SceneNpcMarker
key={tok.id}
placement={tok}
npc={npc}
left={left}
top={top}
sizePx={sizePx}
selected={selected?.kind === 'npcToken' && selected.id === tok.id}
onSelect={() => setSelected({ kind: 'npcToken', id: tok.id })}
onContextMenu={(e) => {
setSelected({ kind: 'npcToken', id: tok.id });
setNpcCtxMenu({ x: e.clientX, y: e.clientY, placementId: tok.id });
}}
onMovePointerDown={(e) => {
if (spaceDownRef.current) return;
e.stopPropagation();
const p = hostToNorm(e.clientX, e.clientY);
if (!p) return;
(e.currentTarget as HTMLDivElement).setPointerCapture(e.pointerId);
dragRef.current = {
kind: 'moveNpcToken',
tokenId: tok.id,
startNx: tok.nx,
startNy: tok.ny,
pointerNx: p.x,
pointerNy: p.y,
};
}}
onResizePointerDown={(e) => {
e.stopPropagation();
e.preventDefault();
const p = hostToNorm(e.clientX, e.clientY);
if (!p) return;
(e.currentTarget as HTMLDivElement).setPointerCapture(e.pointerId);
dragRef.current = {
kind: 'resizeNpcToken',
tokenId: tok.id,
startSize: tok.sizeN,
startDist: Math.max(1e-4, Math.hypot(p.x - tok.nx, p.y - tok.ny)),
};
}}
/>
);
})
: null}
{contentRect
? localTraps.map((trap) => {
const minDim = Math.min(contentRect.w, contentRect.h);
@@ -645,7 +980,9 @@ export function SceneEditorApp() {
return (
<div
key={trap.id}
className={[styles.trap, isSelected ? styles.trapSelected : ''].filter(Boolean).join(' ')}
className={[styles.trap, isSelected ? styles.trapSelected : '']
.filter(Boolean)
.join(' ')}
style={{ left, top, width: sizePx, height: sizePx }}
onPointerDown={(e) => {
if (e.button !== 0 || spaceDownRef.current) return;
@@ -744,6 +1081,174 @@ export function SceneEditorApp() {
document.body,
)
: null}
{tokenCtxMenu
? createPortal(
<>
<button
type="button"
className={styles.ctxMenuBackdrop}
aria-label={t('common.close')}
onClick={() => setTokenCtxMenu(null)}
/>
<div
className={styles.ctxMenu}
style={{ left: tokenCtxMenu.x, top: tokenCtxMenu.y }}
role="menu"
>
<button
type="button"
className={styles.ctxItem}
role="menuitem"
onClick={() => {
const id = tokenCtxMenu.placementId;
setTokenCtxMenu(null);
void api
.invoke(ipcChannels.windows.openTokenPathEditor, {
kind: 'token',
placementId: id,
})
.catch((err) => console.error('[sceneEditor] openTokenPathEditor', err));
}}
>
Указать движение
</button>
{(() => {
const tok = localTokens.find((item) => item.id === tokenCtxMenu.placementId);
if (!tok?.path || tok.path.points.length < 2) return null;
return (
<button
type="button"
className={styles.ctxItem}
role="menuitem"
onClick={() => {
const sample = sampleTokenPathAtDistance(tok.path!, 0);
if (sample) {
updateToken(tok.id, {
nx: sample.nx,
ny: sample.ny,
...(tok.path?.facingMode === 'fixed'
? { rotationDeg: tok.path.fixedRotationDeg }
: { rotationDeg: sample.rotationDeg }),
});
}
setTokenCtxMenu(null);
}}
>
Сбросить на старт пути
</button>
);
})()}
<button
type="button"
className={styles.ctxItemDanger}
role="menuitem"
onClick={() => {
const id = tokenCtxMenu.placementId;
setTokenCtxMenu(null);
persistTokens(tokensRef.current.filter((item) => item.id !== id));
setSelected((current) =>
current?.kind === 'token' && current.id === id ? null : current,
);
}}
>
{t('common.delete')}
</button>
</div>
</>,
document.body,
)
: null}
{USERS_BRANCH_FEATURES_ENABLED && npcCtxMenu
? createPortal(
<>
<button
type="button"
className={styles.ctxMenuBackdrop}
aria-label={t('common.close')}
onClick={() => setNpcCtxMenu(null)}
/>
<div
className={styles.ctxMenu}
style={{ left: npcCtxMenu.x, top: npcCtxMenu.y }}
role="menu"
>
<button
type="button"
className={styles.ctxItem}
role="menuitem"
onClick={() => {
const id = npcCtxMenu.placementId;
setNpcCtxMenu(null);
void api
.invoke(ipcChannels.windows.openTokenPathEditor, {
kind: 'npcToken',
placementId: id,
})
.catch((err) => console.error('[sceneEditor] openTokenPathEditor', err));
}}
>
Указать движение
</button>
{(() => {
const tok = localNpcTokens.find((item) => item.id === npcCtxMenu.placementId);
if (!tok?.path || tok.path.points.length < 2) return null;
return (
<button
type="button"
className={styles.ctxItem}
role="menuitem"
onClick={() => {
const sample = sampleTokenPathAtDistance(tok.path!, 0);
if (sample) {
updateNpcToken(tok.id, { nx: sample.nx, ny: sample.ny });
}
setNpcCtxMenu(null);
}}
>
Сбросить на старт пути
</button>
);
})()}
<button
type="button"
className={styles.ctxItemDanger}
role="menuitem"
onClick={() => {
const id = npcCtxMenu.placementId;
setNpcCtxMenu(null);
persistNpcTokens(npcTokensRef.current.filter((item) => item.id !== id));
setSelected((current) => (current?.id === id ? null : current));
}}
>
{t('common.delete')}
</button>
{(() => {
const tok = localNpcTokens.find((item) => item.id === npcCtxMenu.placementId);
const npc = tok ? project?.npcs.find((item) => item.id === tok.npcId) : undefined;
if (!tok || !npc) return null;
const current = normalizeNpcDisposition(tok.disposition ?? npc.disposition);
return otherNpcDispositions(current).map((d) => (
<button
key={d}
type="button"
className={styles.ctxItem}
role="menuitem"
onClick={() => {
updateNpcToken(tok.id, { disposition: d });
setNpcCtxMenu(null);
}}
>
{t(dispositionMakeKey(d))}
</button>
));
})()}
</div>
</>,
document.body,
)
: null}
</div>
);
}
@@ -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;
}
+175
View File
@@ -0,0 +1,175 @@
import React, { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import {
containMediaLayout,
type MediaRotationDeg,
} 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;
/** Same 90° steps as scene image previewRotationDeg. */
rotationDeg?: MediaRotationDeg;
/** Default contain (map overlays). Cover for editor/graph thumbnails. */
mode?: 'contain' | 'cover';
/** Зум/пан как у 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;
autoPlay?: boolean;
preload?: React.VideoHTMLAttributes<HTMLVideoElement>['preload'];
className?: string;
style?: React.CSSProperties;
onTimeUpdate?: React.VideoHTMLAttributes<HTMLVideoElement>['onTimeUpdate'];
onLoadedMetadata?: React.VideoHTMLAttributes<HTMLVideoElement>['onLoadedMetadata'];
onLoadedData?: React.VideoHTMLAttributes<HTMLVideoElement>['onLoadedData'];
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: reports the visible content rect
* so grid / traps / tokens / effects align with the letterboxed (or cover) frame.
*/
export function ContainedVideo({
url,
rotationDeg = 0,
mode = 'contain',
viewCamera = null,
onContentRectChange,
videoRef,
loop = false,
muted = false,
playsInline = true,
autoPlay = false,
preload = 'auto',
className,
style,
onTimeUpdate,
onLoadedMetadata,
onLoadedData,
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 = mode === 'contain' ? Math.max(1, cam.scale) : 1;
const viewOx = mode === 'contain' ? cam.ox : 0.5;
const viewOy = mode === 'contain' ? cam.oy : 0.5;
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 layout = useMemo(() => {
if (!mediaSize) return null;
return containMediaLayout({
hostW: size.w,
hostH: size.h,
mediaW: mediaSize.w,
mediaH: mediaSize.h,
scale: viewScale,
ox: viewOx,
oy: viewOy,
rotationDeg,
mode,
});
}, [mediaSize, mode, rotationDeg, size.h, size.w, viewOx, viewOy, viewScale]);
const contentRect = layout?.contentRect ?? null;
useEffect(() => {
if (!onContentRectChange || !contentRect) return;
onContentRectChange(contentRect);
}, [contentRect, onContentRectChange]);
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}
autoPlay={autoPlay}
preload={preload}
draggable={false}
onTimeUpdate={onTimeUpdate}
onLoadedMetadata={(e) => {
syncMediaSize(e.currentTarget);
onLoadedMetadata?.(e);
}}
onLoadedData={onLoadedData}
onError={onError}
style={{
width: layout ? layout.elementW : '100%',
height: layout ? layout.elementH : '100%',
left: leftPx !== undefined ? `${String(leftPx)}px` : '50%',
top: topPx !== undefined ? `${String(topPx)}px` : '50%',
objectFit: mediaSize ? undefined : mode,
transform: `translate(-50%, -50%) rotate(${String(rotationDeg)}deg)`,
}}
>
{children}
</video>
</div>
);
}
+75 -10
View File
@@ -2,6 +2,7 @@ import React, { useEffect, useRef, useState } from 'react';
import { computeTimeSec } from '../../main/video/videoPlaybackStore';
import type { SessionState } from '../../shared/ipc/contracts';
import { USERS_BRANCH_FEATURES_ENABLED } from '../../shared/features/usersBranchFeatures';
import { ExplosionVideoOverlay } from './effects/ExplosionVideoOverlay';
import { PixiEffectsOverlay } from './effects/PxiEffectsOverlay';
@@ -15,17 +16,27 @@ import { MaterialOverlay } from './materials/MaterialOverlay';
import { useMaterialsOverlayState } from './materials/useMaterialsOverlayState';
import { NpcsSceneOverlay } from './npcs/NpcsSceneOverlay';
import { useNpcsOverlayState } from './npcs/useNpcsOverlayState';
import { SceneNpcTokensOverlay } from './playerToken/SceneNpcTokensOverlay';
import { ScenePlayerTokensOverlay } from './playerToken/ScenePlayerTokensOverlay';
import { useAppPlayers } from './playerToken/useAppPlayers';
import { useSceneNpcTokensSession } from './playerToken/useSceneNpcTokensSession';
import { useScenePlayerTokensSession } from './playerToken/useScenePlayerTokensSession';
import { SceneOverlayHost } from './sceneOverlay/SceneOverlayHost';
import { useSceneViewState } from './sceneView/useSceneViewState';
import { SceneTokensOverlay } from './tokens/SceneTokensOverlay';
import { TokenPathsOverlay } from './tokens/TokenPathsOverlay';
import { useAppTokens } from './tokens/useAppTokens';
import { useSceneTokensSession } from './tokens/useSceneTokensSession';
import { useTokenPathLivePoses } from './tokens/useTokenPathLivePoses';
import { useTokenPathSession } from './tokens/useTokenPathSession';
import { SceneTrapsOverlay } from './traps/SceneTrapsOverlay';
import { useSceneTrapsState } from './traps/useSceneTrapsState';
import styles from './PresentationView.module.css';
import { ContainedVideo } from './ContainedVideo';
import { RotatedImage } from './RotatedImage';
import { useAssetUrl } from './useAssetImageUrl';
import { useVideoPlaybackState } from './video/useVideoPlaybackState';
import { DEFAULT_NPC_TOKEN_SESSION_SCALE } from '../../shared/types/appPlayers';
export type PresentationViewProps = {
session: SessionState | null;
@@ -48,7 +59,12 @@ export function PresentationView({
const [materialsOverlay] = useMaterialsOverlayState();
const [npcsOverlay] = useNpcsOverlayState();
const appTokens = useAppTokens();
const appPlayersResult = useAppPlayers();
const appPlayers = USERS_BRANCH_FEATURES_ENABLED ? appPlayersResult.players : [];
const [sceneTokensSession] = useSceneTokensSession();
const [sceneNpcTokensSession] = useSceneNpcTokensSession();
const [scenePlayerTokensSession] = useScenePlayerTokensSession();
const [tokenPathSession, tokenPathApi] = useTokenPathSession();
const [vp] = useVideoPlaybackState();
const videoElRef = useRef<HTMLVideoElement | null>(null);
const [contentRect, setContentRect] = React.useState<{ x: number; y: number; w: number; h: number } | null>(
@@ -57,6 +73,15 @@ export function PresentationView({
const scene =
session?.project && session.currentSceneId ? session.project.scenes[session.currentSceneId] : undefined;
const project = session?.project;
const pathLivePoses = useTokenPathLivePoses({
tokens: scene?.tokens ?? [],
npcTokens: scene?.npcTokens ?? [],
pathSession: tokenPathSession,
enabled: Boolean(scene),
onMarkDone: (kind, placementId) => {
void tokenPathApi.dispatch({ kind: 'markDone', target: { kind, placementId } });
},
});
const activeMaterialItems =
project && (materialsOverlay?.activeMaterialIds?.length ?? 0) > 0
? (materialsOverlay?.activeMaterialIds ?? [])
@@ -160,34 +185,71 @@ export function PresentationView({
/>
</div>
) : originalUrl && scene?.previewAssetType === 'video' ? (
<video
ref={videoElRef}
className={styles.video}
src={originalUrl}
<div className={styles.fill}>
<ContainedVideo
url={originalUrl}
rotationDeg={rot}
videoRef={videoElRef}
muted
playsInline
loop={Boolean(scene?.settings?.loopVideo)}
preload="auto"
viewCamera={sceneView}
onContentRectChange={setContentRect}
onError={() => {
// noop: status surfaced in control app; keep presentation clean
}}
/>
</div>
) : (
<div className={styles.placeholderBg} />
)}
{scene?.previewAssetType === 'image' ? (
{scene?.previewAssetType === 'image' || scene?.previewAssetType === 'video' ? (
<SceneGridOverlay grid={scene.grid} viewport={contentRect} />
) : null}
<div className={styles.vignette} />
{scene?.previewAssetType === 'image' && contentRect ? (
{(scene?.previewAssetType === 'image' || scene?.previewAssetType === 'video') && contentRect ? (
<TokenPathsOverlay
tokens={scene.tokens ?? []}
npcTokens={USERS_BRANCH_FEATURES_ENABLED ? (scene.npcTokens ?? []) : []}
viewport={contentRect}
mode="presentation"
pathSession={tokenPathSession}
/>
) : null}
{(scene?.previewAssetType === 'image' || scene?.previewAssetType === 'video') && contentRect ? (
<SceneTokensOverlay
placements={scene.tokens ?? []}
library={appTokens}
session={sceneTokensSession}
viewport={contentRect}
poseOverrides={pathLivePoses.tokenPoses}
/>
) : null}
{scene?.previewAssetType === 'image' && contentRect ? (
{USERS_BRANCH_FEATURES_ENABLED &&
(scene?.previewAssetType === 'image' || scene?.previewAssetType === 'video') &&
contentRect ? (
<SceneNpcTokensOverlay
placements={scene.npcTokens ?? []}
library={project?.npcs ?? []}
session={sceneNpcTokensSession}
viewport={contentRect}
grid={scene.grid}
poseOverrides={pathLivePoses.npcPoses}
/>
) : null}
{USERS_BRANCH_FEATURES_ENABLED &&
(scene?.previewAssetType === 'image' || scene?.previewAssetType === 'video') &&
contentRect ? (
<ScenePlayerTokensOverlay
library={appPlayers}
session={scenePlayerTokensSession}
displayScale={sceneNpcTokensSession.scale ?? DEFAULT_NPC_TOKEN_SESSION_SCALE}
viewport={contentRect}
grid={scene.grid}
/>
) : null}
{(scene?.previewAssetType === 'image' || scene?.previewAssetType === 'video') && contentRect ? (
<SceneTrapsOverlay
traps={scene.traps ?? []}
session={sceneTraps}
@@ -195,7 +257,7 @@ export function PresentationView({
mode="presentation"
/>
) : null}
{showEffects && scene?.previewAssetType !== 'video' ? (
{showEffects && (scene?.previewAssetType === 'image' || scene?.previewAssetType === 'video') ? (
<PixiEffectsOverlay
state={fxState}
style={{ zIndex: 6 }}
@@ -206,10 +268,13 @@ export function PresentationView({
}
/>
) : null}
{showEffects && scene?.previewAssetType !== 'video' ? (
{showEffects && (scene?.previewAssetType === 'image' || scene?.previewAssetType === 'video') ? (
<ExplosionVideoOverlay state={fxState} viewport={contentRect} />
) : 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 }} />
) : null}
<SceneOverlayHost active={activeMaterialItems.length > 0 || activeNpcItems.length > 0}>
@@ -38,9 +38,11 @@
cursor: zoom-out;
}
/** Затемнение всего родителя (превью пульта / экран презентации); только при открытом материале/NPC. */
.dim {
position: absolute;
inset: 0;
z-index: 39;
background: rgba(0, 0, 0, 0.62);
pointer-events: none;
}
@@ -0,0 +1,63 @@
.root {
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
user-select: none;
}
.circle {
position: relative;
border-radius: 50%;
border: 4px solid #c9a227;
overflow: hidden;
background: #18181b;
box-shadow: 0 4px 18px rgba(0, 0, 0, 0.45);
flex-shrink: 0;
}
.circlePan {
cursor: grab;
touch-action: none;
}
.circlePan:active {
cursor: grabbing;
}
.avatar {
position: absolute;
left: 50%;
top: 50%;
width: 140%;
height: 140%;
object-fit: cover;
pointer-events: none;
}
.avatarEmpty {
position: absolute;
inset: 0;
background: repeating-linear-gradient(
-45deg,
#27272a,
#27272a 6px,
#3f3f46 6px,
#3f3f46 12px
);
}
.namePlate {
max-width: 100%;
padding: 4px 10px;
border-radius: 6px;
background: rgba(9, 9, 11, 0.88);
color: #fafafa;
font-size: 12px;
font-weight: 600;
line-height: 1.3;
text-align: center;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
@@ -0,0 +1,163 @@
import React, { useCallback, useEffect, useRef } from 'react';
import type { PlayerImageOffset } from '../../../shared/types/appPlayers';
import {
clampPlayerImageOffset,
clampPlayerImageScale,
DEFAULT_PLAYER_IMAGE_SCALE,
DEFAULT_PLAYER_RING_COLOR,
PLAYER_IMAGE_SCALE_STEP,
} from '../../../shared/types/appPlayers';
import styles from './PlayerTokenView.module.css';
export type PlayerTokenViewProps = {
name: string;
imageUrl: string | null;
ringColor?: string;
imageOffset?: PlayerImageOffset;
imageScale?: number;
/** Размер круга в px (для превью в модалке). На сцене задавайте через CSS width/height родителя. */
sizePx?: number;
/** Разрешить drag-pan аватара внутри круга и zoom колесом. */
panEnabled?: boolean;
onImageOffsetChange?: (offset: PlayerImageOffset) => void;
onImageScaleChange?: (scale: number) => void;
className?: string;
/** Без подписи имени (компактный маркер). */
hideName?: boolean;
/** Session «Неактивен»: серый фильтр аватара. */
inactive?: boolean;
'data-testid'?: string;
};
export function PlayerTokenView({
name,
imageUrl,
ringColor = DEFAULT_PLAYER_RING_COLOR,
imageOffset,
imageScale,
sizePx = 160,
panEnabled = false,
onImageOffsetChange,
onImageScaleChange,
className,
hideName = false,
inactive = false,
'data-testid': testId,
}: PlayerTokenViewProps) {
const offset = clampPlayerImageOffset(imageOffset);
const scale = clampPlayerImageScale(imageScale ?? DEFAULT_PLAYER_IMAGE_SCALE);
const circleRef = useRef<HTMLDivElement | null>(null);
const scaleRef = useRef(scale);
scaleRef.current = scale;
const onImageScaleChangeRef = useRef(onImageScaleChange);
onImageScaleChangeRef.current = onImageScaleChange;
const dragRef = useRef<{
pointerId: number;
startX: number;
startY: number;
origX: number;
origY: number;
} | null>(null);
const onPointerDown = useCallback(
(e: React.PointerEvent) => {
if (!panEnabled || !onImageOffsetChange) return;
e.preventDefault();
e.stopPropagation();
(e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);
dragRef.current = {
pointerId: e.pointerId,
startX: e.clientX,
startY: e.clientY,
origX: offset.x,
origY: offset.y,
};
},
[offset.x, offset.y, onImageOffsetChange, panEnabled],
);
const onPointerMove = useCallback(
(e: React.PointerEvent) => {
const d = dragRef.current;
if (!d || d.pointerId !== e.pointerId || !onImageOffsetChange) return;
const dx = (e.clientX - d.startX) / Math.max(1, sizePx);
const dy = (e.clientY - d.startY) / Math.max(1, sizePx);
onImageOffsetChange(clampPlayerImageOffset({ x: d.origX + dx, y: d.origY + dy }));
},
[onImageOffsetChange, sizePx],
);
const onPointerUp = useCallback((e: React.PointerEvent) => {
const d = dragRef.current;
if (!d || d.pointerId !== e.pointerId) return;
dragRef.current = null;
try {
(e.currentTarget as HTMLElement).releasePointerCapture(e.pointerId);
} catch {
/* ignore */
}
}, []);
useEffect(() => {
const el = circleRef.current;
if (!el || !panEnabled) return;
const onWheel = (e: WheelEvent) => {
const cb = onImageScaleChangeRef.current;
if (!cb) return;
e.preventDefault();
e.stopPropagation();
const direction = e.deltaY < 0 ? 1 : -1;
cb(clampPlayerImageScale(scaleRef.current + direction * PLAYER_IMAGE_SCALE_STEP));
};
el.addEventListener('wheel', onWheel, { passive: false });
return () => el.removeEventListener('wheel', onWheel);
}, [panEnabled]);
const rootClass = [styles.root, className ?? ''].filter(Boolean).join(' ');
const nameFontPx = Math.max(9, Math.min(13, Math.round(sizePx * 0.16)));
const nameGapPx = Math.max(2, Math.min(8, Math.round(sizePx * 0.06)));
return (
<div
className={rootClass}
style={{ width: sizePx, gap: hideName ? undefined : nameGapPx }}
data-testid={testId}
>
<div
ref={circleRef}
className={[styles.circle, panEnabled ? styles.circlePan : ''].filter(Boolean).join(' ')}
style={{
width: sizePx,
height: sizePx,
borderColor: inactive ? '#9ca3af' : ringColor,
}}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerUp}
onPointerCancel={onPointerUp}
>
{imageUrl ? (
<img
className={styles.avatar}
src={imageUrl}
alt=""
draggable={false}
style={{
transform: `translate(-50%, -50%) translate(${String(offset.x * 100)}%, ${String(offset.y * 100)}%) scale(${String(scale)})`,
...(inactive ? { filter: 'grayscale(1)', opacity: 0.85 } : {}),
}}
/>
) : (
<div className={styles.avatarEmpty} />
)}
</div>
{!hideName ? (
<div className={styles.namePlate} title={name} style={{ fontSize: nameFontPx }}>
{name || '—'}
</div>
) : null}
</div>
);
}
@@ -0,0 +1,27 @@
.layer {
position: absolute;
inset: 0;
z-index: 9;
pointer-events: none;
}
.token {
position: absolute;
overflow: visible;
transform: translate(-50%, -50%);
pointer-events: none;
touch-action: none;
}
.token > * {
pointer-events: none;
}
.editable {
pointer-events: auto;
cursor: grab;
}
.editable:active {
cursor: grabbing;
}
@@ -0,0 +1,233 @@
import React, { useRef, useState } from 'react';
import type {
NpcDisposition,
ProjectNpc,
SceneGrid,
SceneNpcToken,
SceneNpcTokensSessionState,
} from '../../../shared/types';
import { DEFAULT_NPC_TOKEN_SESSION_SCALE } from '../../../shared/types/appPlayers';
import {
normalizeNpcDisposition,
npcDispositionRingColor,
} from '../../../shared/types/npcDisposition';
import { sceneGridTokenFitFactor } from '../../../shared/types/sceneGrid';
import { useAssetUrl } from '../useAssetImageUrl';
import { PlayerTokenView } from './PlayerTokenView';
import { useLiveDragBroadcast } from './useLiveDragBroadcast';
import styles from './SceneNpcTokensOverlay.module.css';
type Viewport = { x: number; y: number; w: number; h: number };
export function resolveNpcTokenDisposition(
placement: SceneNpcToken,
npc: ProjectNpc,
sessionDisposition?: NpcDisposition,
): NpcDisposition {
if (sessionDisposition) return normalizeNpcDisposition(sessionDisposition);
return normalizeNpcDisposition(placement.disposition ?? npc.disposition);
}
function NpcSprite({
placement,
npc,
nx,
ny,
viewport,
editable,
dragEnabled,
displayScale,
gridFit,
disposition,
inactive,
onMove,
onContextMenu,
snapNorm,
}: {
placement: SceneNpcToken;
npc: ProjectNpc;
nx: number;
ny: number;
viewport: Viewport;
editable: boolean;
dragEnabled: boolean;
displayScale: number;
gridFit: number;
disposition: NpcDisposition;
inactive: boolean;
onMove?: (placementId: string, nx: number, ny: number) => void;
onContextMenu?: (e: React.MouseEvent, placement: SceneNpcToken) => void;
snapNorm?: (nx: number, ny: number) => { nx: number; ny: number };
}) {
const imageUrl = useAssetUrl(npc.avatarAssetId);
const [localPos, setLocalPos] = useState<{ nx: number; ny: number } | null>(null);
const dragRef = useRef<{
pointerId: number;
startNx: number;
startNy: number;
pointerNx: number;
pointerNy: number;
lastNx: number;
lastNy: number;
} | null>(null);
const { schedule, flush } = useLiveDragBroadcast(onMove, String(placement.id));
const pos = localPos ?? { nx, ny };
const minDim = Math.min(viewport.w, viewport.h);
const sizePx = Math.max(16, placement.sizeN * gridFit * displayScale * minDim);
const canDrag = editable && dragEnabled && onMove !== undefined;
const point = (e: React.PointerEvent) => {
const host = e.currentTarget.parentElement;
const rect = host?.getBoundingClientRect();
return {
x: Math.max(0, Math.min(1, (e.clientX - ((rect?.left ?? 0) + viewport.x)) / Math.max(1, viewport.w))),
y: Math.max(0, Math.min(1, (e.clientY - ((rect?.top ?? 0) + viewport.y)) / Math.max(1, viewport.h))),
};
};
const end = (e: React.PointerEvent<HTMLDivElement>) => {
const drag = dragRef.current;
if (drag?.pointerId !== e.pointerId) return;
dragRef.current = null;
flush(drag.lastNx, drag.lastNy);
setLocalPos(null);
};
return (
<div
className={[styles.token, canDrag ? styles.editable : ''].filter(Boolean).join(' ')}
data-testid={`session-npc-token-${placement.id}`}
style={{
left: viewport.x + pos.nx * viewport.w,
top: viewport.y + pos.ny * viewport.h,
width: sizePx,
height: sizePx,
pointerEvents: canDrag || onContextMenu ? 'auto' : undefined,
}}
onContextMenu={
onContextMenu
? (e) => {
e.preventDefault();
e.stopPropagation();
onContextMenu(e, placement);
}
: undefined
}
onPointerDown={
canDrag
? (e) => {
if (e.button !== 0) return;
e.preventDefault();
e.stopPropagation();
const p = point(e);
dragRef.current = {
pointerId: e.pointerId,
startNx: pos.nx,
startNy: pos.ny,
pointerNx: p.x,
pointerNy: p.y,
lastNx: pos.nx,
lastNy: pos.ny,
};
e.currentTarget.setPointerCapture(e.pointerId);
}
: undefined
}
onPointerMove={
canDrag
? (e) => {
const drag = dragRef.current;
if (drag?.pointerId !== e.pointerId) return;
const p = point(e);
const rawNx = Math.max(0, Math.min(1, drag.startNx + p.x - drag.pointerNx));
const rawNy = Math.max(0, Math.min(1, drag.startNy + p.y - drag.pointerNy));
const snapped = snapNorm ? snapNorm(rawNx, rawNy) : { nx: rawNx, ny: rawNy };
drag.lastNx = snapped.nx;
drag.lastNy = snapped.ny;
setLocalPos({ nx: drag.lastNx, ny: drag.lastNy });
schedule(drag.lastNx, drag.lastNy);
}
: undefined
}
onPointerUp={end}
onPointerCancel={end}
>
<PlayerTokenView
name={npc.name}
imageUrl={imageUrl}
ringColor={npcDispositionRingColor(disposition, inactive)}
imageOffset={npc.imageOffset}
imageScale={npc.imageScale}
sizePx={sizePx}
inactive={inactive}
/>
</div>
);
}
export function SceneNpcTokensOverlay({
placements,
library,
session,
viewport,
grid = null,
editable = false,
onMove,
onContextMenu,
snapNorm,
poseOverrides = null,
dragEnabledById = null,
}: {
placements: readonly SceneNpcToken[];
library: readonly ProjectNpc[];
session: SceneNpcTokensSessionState | null;
viewport: Viewport | null;
/** Для гекса — вписанный диаметр ячейки, не описанный. */
grid?: SceneGrid | null;
editable?: boolean;
onMove?: (placementId: string, nx: number, ny: number) => void;
onContextMenu?: (e: React.MouseEvent, placement: SceneNpcToken) => void;
snapNorm?: (nx: number, ny: number) => { nx: number; ny: number };
poseOverrides?: Record<string, { nx: number; ny: number }> | null;
dragEnabledById?: Record<string, boolean> | null;
}) {
if (!viewport) return null;
const byId = new Map(library.map((npc) => [npc.id, npc]));
const displayScale = session?.scale ?? DEFAULT_NPC_TOKEN_SESSION_SCALE;
const gridFit = sceneGridTokenFitFactor(grid);
return (
<div className={styles.layer}>
{placements.map((placement) => {
const npc = byId.get(placement.npcId);
if (!npc) return null;
const key = String(placement.id);
const pose = poseOverrides?.[key];
const override = session?.byPlacementId[key];
const disposition = resolveNpcTokenDisposition(placement, npc, override?.disposition);
const inactive = Boolean(override?.inactive);
const dragEnabled = dragEnabledById ? Boolean(dragEnabledById[key]) : true;
return (
<NpcSprite
key={placement.id}
placement={placement}
npc={npc}
nx={pose?.nx ?? override?.nx ?? placement.nx}
ny={pose?.ny ?? override?.ny ?? placement.ny}
viewport={viewport}
editable={editable}
dragEnabled={dragEnabled}
displayScale={displayScale}
gridFit={gridFit}
disposition={disposition}
inactive={inactive}
{...(onMove ? { onMove } : {})}
{...(onContextMenu ? { onContextMenu } : {})}
{...(snapNorm ? { snapNorm } : {})}
/>
);
})}
</div>
);
}
@@ -0,0 +1,182 @@
import React, { useRef, useState } from 'react';
import type {
AppPlayer,
SceneGrid,
ScenePlayerTokensSessionState,
} from '../../../shared/types';
import { DEFAULT_NPC_TOKEN_SESSION_SCALE } from '../../../shared/types/appPlayers';
import { sceneGridTokenFitFactor } from '../../../shared/types/sceneGrid';
import { usePlayerImageUrl } from './usePlayerImageUrl';
import { PlayerTokenView } from './PlayerTokenView';
import { useLiveDragBroadcast } from './useLiveDragBroadcast';
import styles from './SceneNpcTokensOverlay.module.css';
type Viewport = { x: number; y: number; w: number; h: number };
function PlayerSprite({
player,
nx,
ny,
sizeN,
viewport,
editable,
displayScale,
gridFit,
onMove,
snapNorm,
}: {
player: AppPlayer;
nx: number;
ny: number;
sizeN: number;
viewport: Viewport;
editable: boolean;
displayScale: number;
gridFit: number;
onMove?: (playerId: string, nx: number, ny: number) => void;
snapNorm?: (nx: number, ny: number) => { nx: number; ny: number };
}) {
const imageUrl = usePlayerImageUrl(player.id);
const [localPos, setLocalPos] = useState<{ nx: number; ny: number } | null>(null);
const dragRef = useRef<{
pointerId: number;
startNx: number;
startNy: number;
pointerNx: number;
pointerNy: number;
lastNx: number;
lastNy: number;
} | null>(null);
const { schedule, flush } = useLiveDragBroadcast(onMove, String(player.id));
const pos = localPos ?? { nx, ny };
const minDim = Math.min(viewport.w, viewport.h);
const sizePx = Math.max(16, sizeN * gridFit * displayScale * minDim);
const point = (e: React.PointerEvent) => {
const host = e.currentTarget.parentElement;
const rect = host?.getBoundingClientRect();
return {
x: Math.max(0, Math.min(1, (e.clientX - ((rect?.left ?? 0) + viewport.x)) / Math.max(1, viewport.w))),
y: Math.max(0, Math.min(1, (e.clientY - ((rect?.top ?? 0) + viewport.y)) / Math.max(1, viewport.h))),
};
};
const end = (e: React.PointerEvent<HTMLDivElement>) => {
const drag = dragRef.current;
if (drag?.pointerId !== e.pointerId) return;
dragRef.current = null;
flush(drag.lastNx, drag.lastNy);
setLocalPos(null);
};
return (
<div
className={[styles.token, editable ? styles.editable : ''].filter(Boolean).join(' ')}
data-testid={`session-player-token-${player.id}`}
style={{
left: viewport.x + pos.nx * viewport.w,
top: viewport.y + pos.ny * viewport.h,
width: sizePx,
height: sizePx,
}}
onPointerDown={
editable && onMove !== undefined
? (e) => {
if (e.button !== 0) return;
e.preventDefault();
e.stopPropagation();
const p = point(e);
dragRef.current = {
pointerId: e.pointerId,
startNx: pos.nx,
startNy: pos.ny,
pointerNx: p.x,
pointerNy: p.y,
lastNx: pos.nx,
lastNy: pos.ny,
};
e.currentTarget.setPointerCapture(e.pointerId);
}
: undefined
}
onPointerMove={
editable && onMove
? (e) => {
const drag = dragRef.current;
if (drag?.pointerId !== e.pointerId) return;
const p = point(e);
const rawNx = Math.max(0, Math.min(1, drag.startNx + p.x - drag.pointerNx));
const rawNy = Math.max(0, Math.min(1, drag.startNy + p.y - drag.pointerNy));
const snapped = snapNorm ? snapNorm(rawNx, rawNy) : { nx: rawNx, ny: rawNy };
drag.lastNx = snapped.nx;
drag.lastNy = snapped.ny;
setLocalPos({ nx: drag.lastNx, ny: drag.lastNy });
schedule(drag.lastNx, drag.lastNy);
}
: undefined
}
onPointerUp={end}
onPointerCancel={end}
>
<PlayerTokenView
name={player.name}
imageUrl={imageUrl}
ringColor={player.ringColor}
imageOffset={player.imageOffset}
imageScale={player.imageScale}
sizePx={sizePx}
/>
</div>
);
}
export function ScenePlayerTokensOverlay({
library,
session,
displayScale = DEFAULT_NPC_TOKEN_SESSION_SCALE,
viewport,
grid = null,
editable = false,
onMove,
snapNorm,
}: {
library: readonly AppPlayer[];
session: ScenePlayerTokensSessionState | null;
/** Общий масштаб с НПС-токенами. */
displayScale?: number;
viewport: Viewport | null;
grid?: SceneGrid | null;
editable?: boolean;
onMove?: (playerId: string, nx: number, ny: number) => void;
snapNorm?: (nx: number, ny: number) => { nx: number; ny: number };
}) {
if (!viewport || !session?.visible) return null;
const byId = new Map(library.map((p) => [String(p.id), p]));
const gridFit = sceneGridTokenFitFactor(grid);
return (
<div className={styles.layer}>
{session.selectedPlayerIds.map((playerId) => {
const player = byId.get(playerId);
const placement = session.byPlayerId[playerId];
if (!player || !placement) return null;
return (
<PlayerSprite
key={playerId}
player={player}
nx={placement.nx}
ny={placement.ny}
sizeN={placement.sizeN}
viewport={viewport}
editable={editable}
displayScale={displayScale}
gridFit={gridFit}
{...(onMove ? { onMove } : {})}
{...(snapNorm ? { snapNorm } : {})}
/>
);
})}
</div>
);
}
@@ -0,0 +1,24 @@
import { useEffect, useState } from 'react';
import { ipcChannels } from '../../../shared/ipc/contracts';
import type { AppPlayer, AppPlayerTeam } from '../../../shared/types';
import { getDndApi } from '../dndApi';
export function useAppPlayers(): { players: AppPlayer[]; teams: AppPlayerTeam[] } {
const api = getDndApi();
const [players, setPlayers] = useState<AppPlayer[]>([]);
const [teams, setTeams] = useState<AppPlayerTeam[]>([]);
useEffect(() => {
void api.invoke(ipcChannels.players.list, {}).then((res) => {
setPlayers(res.players);
setTeams(res.teams);
});
return api.on(ipcChannels.players.stateChanged, ({ players: nextPlayers, teams: nextTeams }) => {
setPlayers(nextPlayers);
setTeams(nextTeams);
});
}, [api]);
return { players, teams };
}
@@ -0,0 +1,48 @@
import { useCallback, useEffect, useRef } from 'react';
/** Во время drag шлёт onMove не чаще одного раза за кадр (для live-синхронизации презентации). */
export function useLiveDragBroadcast(
onMove: ((id: string, nx: number, ny: number) => void) | undefined,
id: string,
): {
schedule: (nx: number, ny: number) => void;
flush: (nx: number, ny: number) => void;
} {
const rafRef = useRef(0);
const pendingRef = useRef<{ nx: number; ny: number } | null>(null);
const onMoveRef = useRef(onMove);
onMoveRef.current = onMove;
const idRef = useRef(id);
idRef.current = id;
useEffect(
() => () => {
if (rafRef.current) cancelAnimationFrame(rafRef.current);
},
[],
);
const schedule = useCallback((nx: number, ny: number) => {
if (!onMoveRef.current) return;
pendingRef.current = { nx, ny };
if (rafRef.current) return;
rafRef.current = requestAnimationFrame(() => {
rafRef.current = 0;
const pending = pendingRef.current;
const cb = onMoveRef.current;
if (!pending || !cb) return;
cb(idRef.current, pending.nx, pending.ny);
});
}, []);
const flush = useCallback((nx: number, ny: number) => {
if (rafRef.current) {
cancelAnimationFrame(rafRef.current);
rafRef.current = 0;
}
pendingRef.current = null;
onMoveRef.current?.(idRef.current, nx, ny);
}, []);
return { schedule, flush };
}
@@ -0,0 +1,26 @@
import { useEffect, useState } from 'react';
import { ipcChannels } from '../../../shared/ipc/contracts';
import type { PlayerId } from '../../../shared/types';
import { getDndApi } from '../dndApi';
export function usePlayerImageUrl(playerId: PlayerId | null | undefined): string | null {
const api = getDndApi();
const [url, setUrl] = useState<string | null>(null);
useEffect(() => {
if (!playerId) {
setUrl(null);
return;
}
let cancelled = false;
void api.invoke(ipcChannels.players.imageUrl, { id: playerId }).then((res) => {
if (!cancelled) setUrl(res.url);
});
return () => {
cancelled = true;
};
}, [api, playerId]);
return url;
}
@@ -0,0 +1,152 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { ipcChannels } from '../../../shared/ipc/contracts';
import type {
SceneNpcTokensSessionEvent,
SceneNpcTokensSessionPlacement,
SceneNpcTokensSessionState,
} from '../../../shared/types';
import {
clampNpcTokenSessionScale,
DEFAULT_NPC_TOKEN_SESSION_SCALE,
} from '../../../shared/types/appPlayers';
import { normalizeNpcDisposition } from '../../../shared/types/npcDisposition';
import { getDndApi } from '../dndApi';
function withScale(state: SceneNpcTokensSessionState): SceneNpcTokensSessionState {
return {
...state,
scale: clampNpcTokenSessionScale(state.scale),
};
}
function isEmptyPlacement(p: SceneNpcTokensSessionPlacement): boolean {
return p.nx === undefined && p.ny === undefined && !p.disposition && !p.inactive;
}
function applyEvent(
prev: SceneNpcTokensSessionState,
event: SceneNpcTokensSessionEvent,
): SceneNpcTokensSessionState {
if (event.kind === 'clear') {
return {
revision: prev.revision + 1,
byPlacementId: {},
scale: DEFAULT_NPC_TOKEN_SESSION_SCALE,
};
}
if (event.kind === 'setScale') {
const scale = clampNpcTokenSessionScale(event.scale);
if (prev.scale === scale) return prev;
return { ...prev, revision: prev.revision + 1, scale };
}
if (event.kind === 'setDisposition') {
const placementId = String(event.placementId ?? '');
if (!placementId) return prev;
const disposition = normalizeNpcDisposition(event.disposition);
const cur = prev.byPlacementId[placementId];
if (cur?.disposition === disposition) return prev;
return {
revision: prev.revision + 1,
byPlacementId: {
...prev.byPlacementId,
[placementId]: {
...(cur?.nx !== undefined ? { nx: cur.nx } : {}),
...(cur?.ny !== undefined ? { ny: cur.ny } : {}),
disposition,
...(cur?.inactive ? { inactive: true } : {}),
},
},
scale: prev.scale ?? DEFAULT_NPC_TOKEN_SESSION_SCALE,
};
}
if (event.kind === 'setInactive') {
const placementId = String(event.placementId ?? '');
if (!placementId) return prev;
const inactive = Boolean(event.inactive);
const cur = prev.byPlacementId[placementId];
if (Boolean(cur?.inactive) === inactive) return prev;
const next: SceneNpcTokensSessionPlacement = {
...(cur?.nx !== undefined ? { nx: cur.nx } : {}),
...(cur?.ny !== undefined ? { ny: cur.ny } : {}),
...(cur?.disposition ? { disposition: cur.disposition } : {}),
...(inactive ? { inactive: true } : {}),
};
if (isEmptyPlacement(next)) {
const { [placementId]: _removed, ...rest } = prev.byPlacementId;
return {
revision: prev.revision + 1,
byPlacementId: rest,
scale: prev.scale ?? DEFAULT_NPC_TOKEN_SESSION_SCALE,
};
}
return {
revision: prev.revision + 1,
byPlacementId: {
...prev.byPlacementId,
[placementId]: next,
},
scale: prev.scale ?? DEFAULT_NPC_TOKEN_SESSION_SCALE,
};
}
// move
const placementId = String(event.placementId ?? '');
if (!placementId) return prev;
const cur = prev.byPlacementId[placementId];
return {
revision: prev.revision + 1,
byPlacementId: {
...prev.byPlacementId,
[placementId]: {
nx: event.nx,
ny: event.ny,
...(cur?.disposition ? { disposition: cur.disposition } : {}),
...(cur?.inactive ? { inactive: true } : {}),
},
},
scale: prev.scale ?? DEFAULT_NPC_TOKEN_SESSION_SCALE,
};
}
export function useSceneNpcTokensSession(): [
SceneNpcTokensSessionState,
{ dispatch: (event: SceneNpcTokensSessionEvent) => void },
] {
const api = getDndApi();
const [state, setState] = useState<SceneNpcTokensSessionState>({
revision: 0,
byPlacementId: {},
scale: DEFAULT_NPC_TOKEN_SESSION_SCALE,
});
const localRevRef = useRef(0);
useEffect(() => {
void api.invoke(ipcChannels.sceneNpcTokensSession.getState, {}).then((res) => {
const next = withScale(res.state);
// Не затираем более свежий optimistic/broadcast стейт устаревшим getState.
if (next.revision < localRevRef.current) return;
localRevRef.current = next.revision;
setState(next);
});
return api.on(ipcChannels.sceneNpcTokensSession.stateChanged, ({ state: incoming }) => {
const next = withScale(incoming);
if (next.revision < localRevRef.current) return;
localRevRef.current = next.revision;
setState(next);
});
}, [api]);
const dispatch = useCallback(
(event: SceneNpcTokensSessionEvent) => {
setState((prev) => {
const next = applyEvent(prev, event);
localRevRef.current = Math.max(localRevRef.current, next.revision);
return next;
});
void api.invoke(ipcChannels.sceneNpcTokensSession.dispatch, { event });
},
[api],
);
return [state, { dispatch }];
}
@@ -0,0 +1,102 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { ipcChannels } from '../../../shared/ipc/contracts';
import type {
ScenePlayerTokensSessionEvent,
ScenePlayerTokensSessionState,
} from '../../../shared/types';
import { getDndApi } from '../dndApi';
function applyEvent(
prev: ScenePlayerTokensSessionState,
event: ScenePlayerTokensSessionEvent,
): ScenePlayerTokensSessionState {
if (event.kind === 'clear') {
return { revision: prev.revision + 1, selectedPlayerIds: [], visible: false, byPlayerId: {} };
}
if (event.kind === 'clearPlacements') {
return { ...prev, revision: prev.revision + 1, visible: false, byPlayerId: {} };
}
if (event.kind === 'setSelection') {
const seen = new Set<string>();
const selectedPlayerIds: string[] = [];
for (const id of event.playerIds) {
const s = String(id ?? '').trim();
if (!s || seen.has(s)) continue;
seen.add(s);
selectedPlayerIds.push(s);
}
return { revision: prev.revision + 1, selectedPlayerIds, visible: false, byPlayerId: {} };
}
if (event.kind === 'setVisible') {
if (event.visible && prev.selectedPlayerIds.length === 0) return prev;
return { ...prev, revision: prev.revision + 1, visible: Boolean(event.visible) };
}
if (event.kind === 'show') {
if (prev.selectedPlayerIds.length === 0) return prev;
// placements приходят с main; локально только включаем visible после seed через broadcast
return { ...prev, revision: prev.revision + 1, visible: true };
}
if (event.kind === 'seedBottom') {
return prev;
}
if (event.kind === 'move') {
const prevPlacement = prev.byPlayerId[event.playerId];
return {
...prev,
revision: prev.revision + 1,
byPlayerId: {
...prev.byPlayerId,
[event.playerId]: {
nx: event.nx,
ny: event.ny,
sizeN: prevPlacement?.sizeN ?? 0.1,
},
},
};
}
return prev;
}
export function useScenePlayerTokensSession(): [
ScenePlayerTokensSessionState,
{ dispatch: (event: ScenePlayerTokensSessionEvent) => void },
] {
const api = getDndApi();
const [state, setState] = useState<ScenePlayerTokensSessionState>({
revision: 0,
selectedPlayerIds: [],
visible: false,
byPlayerId: {},
});
const localRevRef = useRef(0);
useEffect(() => {
void api.invoke(ipcChannels.scenePlayerTokensSession.getState, {}).then((res) => {
if (res.state.revision < localRevRef.current) return;
localRevRef.current = res.state.revision;
setState(res.state);
});
return api.on(ipcChannels.scenePlayerTokensSession.stateChanged, ({ state: next }) => {
if (next.revision < localRevRef.current) return;
localRevRef.current = next.revision;
setState(next);
});
}, [api]);
const dispatch = useCallback(
(event: ScenePlayerTokensSessionEvent) => {
if (event.kind !== 'seedBottom' && event.kind !== 'show') {
setState((prev) => {
const next = applyEvent(prev, event);
localRevRef.current = Math.max(localRevRef.current, next.revision);
return next;
});
}
void api.invoke(ipcChannels.scenePlayerTokensSession.dispatch, { event });
},
[api],
);
return [state, { dispatch }];
}
@@ -15,9 +15,12 @@ export type SceneOverlayCloseAction = {
type SceneOverlayHostProps = {
/** Есть ли что показывать (материал и/или NPC). */
active: boolean;
/** Область картинки сцены (contain); координаты относительно родителя. */
/**
* Область раскладки кадров материалов/NPC (и жёлтой рамки).
* На пульте прямоугольник соотношения сторон презентации; на презентации обычно не задаётся (весь экран).
*/
viewport?: SceneOverlayViewport | null;
/** Рамка видимой области (предпросмотр пульта). */
/** Жёлтая рамка видимой области презентации (предпросмотр пульта). Без dim. */
showViewportGuide?: boolean;
zoomTool?: MaterialsZoomTool | NpcsZoomTool;
onZoomAt?: (nx: number, ny: number, target: EventTarget | null) => void;
@@ -26,8 +29,9 @@ type SceneOverlayHostProps = {
};
/**
* Общий слой подложки для Materials + NPCs: один root и один `.dim`.
* Кадры остаются в дочерних оверлеях (`embedded`).
* Общий слой подложки для Materials + NPCs.
* Dim только при `active`, на весь родитель (экран презентации / рамка превью пульта).
* Кадры остаются в дочерних оверлеях (`embedded`) внутри `viewport`.
*/
export function SceneOverlayHost({
active,
@@ -61,7 +65,7 @@ export function SceneOverlayHost({
ro.disconnect();
if (raf !== 0) window.cancelAnimationFrame(raf);
};
}, [active]);
}, [active, showViewportGuide, viewport]);
const ctx = useMemo(() => ({ rootRef, view }), [view]);
@@ -83,6 +87,7 @@ export function SceneOverlayHost({
return (
<SceneOverlayViewContext.Provider value={ctx}>
{active ? <div className={styles.dim} aria-hidden /> : null}
<div
ref={rootRef}
className={[styles.root, styles.hostHitThrough, captureZoom ? styles.captureZoom : '', zoomCursor]
@@ -98,7 +103,6 @@ export function SceneOverlayHost({
}}
>
{showViewportGuide ? <div className={styles.viewportGuide} aria-hidden /> : null}
<div className={styles.dim} />
{children}
{closes.length > 0 ? (
<div className={styles.closeStack}>
@@ -18,6 +18,9 @@ void test('SceneOverlayHost: один dim для materials + npcs в Control и
assert.ok(host.includes('styles.dim'));
assert.ok(host.includes('hostHitThrough'));
// Dim только при active; жёлтая рамка без затемнения.
assert.match(host, /\{active \? <div className=\{styles\.dim\}/);
assert.ok(host.includes('showViewportGuide'));
assert.ok(control.includes('SceneOverlayHost'));
assert.ok(control.includes('embedded'));
assert.ok(presentation.includes('SceneOverlayHost'));
@@ -29,6 +32,7 @@ void test('SceneOverlayHost: один dim для materials + npcs в Control и
assert.ok(control.includes('embedded'));
assert.ok(presentation.includes('embedded'));
assert.match(css, /\.hostHitThrough\s*\{[^}]*pointer-events:\s*none/s);
assert.match(css, /\.dim\s*\{[^}]*inset:\s*0/s);
});
void test('MaterialOverlay / NpcsSceneOverlay поддерживают embedded без собственного dim', () => {
@@ -26,6 +26,11 @@
cursor: grabbing;
}
.tokenInteractive {
pointer-events: auto;
cursor: context-menu;
}
.tokenImg {
width: 100%;
height: 100%;
@@ -7,6 +7,12 @@ import styles from './SceneTokensOverlay.module.css';
type Viewport = { x: number; y: number; w: number; h: number };
export type TokenPoseOverride = {
nx: number;
ny: number;
rotationDeg?: number;
};
type Props = {
placements: readonly SceneToken[];
library: readonly AppToken[];
@@ -14,22 +20,37 @@ type Props = {
viewport: Viewport | null;
editable?: boolean;
onMove?: (placementId: string, nx: number, ny: number) => void;
/** Snap во время drag (пульт, привязка к сетке). */
snapNorm?: (nx: number, ny: number) => { nx: number; ny: number };
onContextMenu?: (e: React.MouseEvent, placement: SceneToken) => void;
/** Live path playback / other pose overrides by placement id. */
poseOverrides?: Record<string, TokenPoseOverride> | null;
/** Per-placement drag lock (e.g. while path is animating). Default: all editable. */
dragEnabledById?: Record<string, boolean> | null;
};
function TokenSprite({
placement,
nx,
ny,
rotationDeg,
viewport,
editable,
dragEnabled,
onMove,
snapNorm,
onContextMenu,
}: {
placement: SceneToken;
nx: number;
ny: number;
rotationDeg: number;
viewport: Viewport;
editable: boolean;
dragEnabled: boolean;
onMove?: (placementId: string, nx: number, ny: number) => void;
snapNorm?: (nx: number, ny: number) => { nx: number; ny: number };
onContextMenu?: (e: React.MouseEvent, placement: SceneToken) => void;
}) {
const url = useTokenImageUrl(placement.tokenId);
const dragRef = useRef<{
@@ -62,6 +83,8 @@ function TokenSprite({
const sizePx = Math.max(16, placement.sizeN * minDim);
const left = viewport.x + posNx * viewport.w;
const top = viewport.y + posNy * viewport.h;
const canDrag = editable && dragEnabled && Boolean(onMove);
const interactive = canDrag || Boolean(onContextMenu);
const hostToNorm = (clientX: number, clientY: number, host: HTMLElement) => {
const r = host.getBoundingClientRect();
@@ -81,7 +104,6 @@ function TokenSprite({
cancelAnimationFrame(frameRef.current);
frameRef.current = 0;
}
// Финальный commit в session store — один раз на отпускание.
onMove?.(String(placement.id), d.lastNx, d.lastNy);
setLocalPos({ nx: d.lastNx, ny: d.lastNy });
try {
@@ -93,16 +115,31 @@ function TokenSprite({
return (
<div
className={[styles.token, editable ? styles.tokenEditable : ''].filter(Boolean).join(' ')}
className={[
styles.token,
canDrag ? styles.tokenEditable : '',
interactive && !canDrag ? styles.tokenInteractive : '',
]
.filter(Boolean)
.join(' ')}
style={{
left,
top,
width: sizePx,
height: sizePx,
transform: `translate(-50%, -50%) rotate(${String(placement.rotationDeg)}deg)`,
transform: `translate(-50%, -50%) rotate(${String(rotationDeg)}deg)`,
}}
onContextMenu={
onContextMenu
? (e) => {
e.preventDefault();
e.stopPropagation();
onContextMenu(e, placement);
}
: undefined
}
onPointerDown={
editable && onMove
canDrag
? (e) => {
if (e.button !== 0) return;
e.stopPropagation();
@@ -124,7 +161,7 @@ function TokenSprite({
: undefined
}
onPointerMove={
editable && onMove
canDrag
? (e) => {
const d = dragRef.current;
if (!d || d.pointerId !== e.pointerId) return;
@@ -132,8 +169,9 @@ function TokenSprite({
const p = hostToNorm(e.clientX, e.clientY, host);
const nextNx = Math.max(0, Math.min(1, d.startNx + (p.x - d.pointerNx)));
const nextNy = Math.max(0, Math.min(1, d.startNy + (p.y - d.pointerNy)));
d.lastNx = nextNx;
d.lastNy = nextNy;
const snapped = snapNorm ? snapNorm(nextNx, nextNy) : { nx: nextNx, ny: nextNy };
d.lastNx = snapped.nx;
d.lastNy = snapped.ny;
if (frameRef.current) return;
frameRef.current = requestAnimationFrame(() => {
frameRef.current = 0;
@@ -163,6 +201,10 @@ export function SceneTokensOverlay({
viewport,
editable = false,
onMove,
snapNorm,
onContextMenu,
poseOverrides = null,
dragEnabledById = null,
}: Props) {
if (!viewport || placements.length === 0) return null;
const known = new Set(library.map((t) => t.id));
@@ -173,18 +215,25 @@ export function SceneTokensOverlay({
.filter((p) => known.has(p.tokenId))
.map((placement) => {
const key = String(placement.id);
const pose = poseOverrides?.[key];
const override = session?.byPlacementId[key] ?? session?.byPlacementId[placement.id];
const nx = override?.nx ?? placement.nx;
const ny = override?.ny ?? placement.ny;
const nx = pose?.nx ?? override?.nx ?? placement.nx;
const ny = pose?.ny ?? override?.ny ?? placement.ny;
const rotationDeg = pose?.rotationDeg ?? placement.rotationDeg;
const dragEnabled = dragEnabledById ? Boolean(dragEnabledById[key]) : true;
return (
<TokenSprite
key={key}
placement={placement}
nx={nx}
ny={ny}
rotationDeg={rotationDeg}
viewport={viewport}
editable={editable}
onMove={onMove}
dragEnabled={dragEnabled}
{...(onMove ? { onMove } : {})}
{...(snapNorm ? { snapNorm } : {})}
{...(onContextMenu ? { onContextMenu } : {})}
/>
);
})}
@@ -0,0 +1,42 @@
.layer {
position: absolute;
inset: 0;
pointer-events: none;
z-index: 7;
overflow: visible;
}
.lineGlow {
stroke: rgba(40, 180, 255, 0.28);
stroke-width: 6;
stroke-linecap: round;
stroke-linejoin: round;
}
.line {
stroke: rgba(90, 210, 255, 0.92);
stroke-width: 2;
stroke-linecap: round;
stroke-linejoin: round;
stroke-dasharray: 7 5;
}
.start {
fill: rgba(120, 230, 255, 0.95);
stroke: rgba(0, 0, 0, 0.45);
stroke-width: 1;
}
.closed {
stroke: rgba(255, 200, 80, 0.9);
stroke-width: 1.5;
}
.emphasized .line {
stroke: rgba(255, 220, 120, 0.95);
stroke-dasharray: none;
}
.emphasized .lineGlow {
stroke: rgba(255, 200, 80, 0.35);
}
@@ -0,0 +1,92 @@
import React from 'react';
import type { TokenPath } from '../../../shared/types/tokenPath';
import { tokenPathPolyline } from '../../../shared/types/tokenPath';
import type { SceneNpcToken, SceneToken } from '../../../shared/types';
import { tokenPathKey, type TokenPathSessionState } from '../../../shared/types/tokenPathSession';
import styles from './TokenPathsOverlay.module.css';
type Viewport = { x: number; y: number; w: number; h: number };
type PathItem = {
key: string;
path: TokenPath;
emphasized?: boolean;
};
type Props = {
tokens: readonly SceneToken[];
npcTokens?: readonly SceneNpcToken[];
viewport: Viewport | null;
/** control/editor: always; presentation: only presentationVisible */
mode: 'always' | 'presentation';
pathSession?: TokenPathSessionState | null;
/** Highlight path currently edited */
emphasizeKey?: string | null;
};
function toSvgPoints(path: TokenPath, viewport: Viewport): string {
const pts = tokenPathPolyline(path);
return pts
.map((p) => {
const x = viewport.x + p.nx * viewport.w;
const y = viewport.y + p.ny * viewport.h;
return `${x},${y}`;
})
.join(' ');
}
export function TokenPathsOverlay({
tokens,
npcTokens = [],
viewport,
mode,
pathSession = null,
emphasizeKey = null,
}: Props) {
if (!viewport) return null;
const items: PathItem[] = [];
for (const t of tokens) {
if (!t.path || t.path.points.length < 2) continue;
const key = tokenPathKey('token', String(t.id));
if (mode === 'presentation' && !pathSession?.presentationVisible[key]) continue;
items.push({ key, path: t.path, emphasized: emphasizeKey === key });
}
for (const t of npcTokens) {
if (!t.path || t.path.points.length < 2) continue;
const key = tokenPathKey('npcToken', String(t.id));
if (mode === 'presentation' && !pathSession?.presentationVisible[key]) continue;
items.push({ key, path: t.path, emphasized: emphasizeKey === key });
}
if (items.length === 0) return null;
return (
<svg className={styles.layer} width="100%" height="100%" aria-hidden>
{items.map((item) => {
const pts = toSvgPoints(item.path, viewport);
if (!pts) return null;
const first = item.path.points[0]!;
const fx = viewport.x + first.nx * viewport.w;
const fy = viewport.y + first.ny * viewport.h;
return (
<g key={item.key} className={item.emphasized ? styles.emphasized : undefined}>
<polyline className={styles.lineGlow} points={pts} fill="none" />
<polyline className={styles.line} points={pts} fill="none" />
<circle className={styles.start} cx={fx} cy={fy} r={4} />
{item.path.closed ? (
<circle
className={styles.closed}
cx={fx}
cy={fy}
r={7}
fill="none"
/>
) : null}
</g>
);
})}
</svg>
);
}
@@ -0,0 +1,33 @@
import { useCallback, useEffect, useState } from 'react';
import { ipcChannels } from '../../../shared/ipc/contracts';
import { getDndApi } from '../dndApi';
export function useTokenGridSnapSession(): [
boolean,
{ setEnabled: (enabled: boolean) => Promise<boolean> },
] {
const api = getDndApi();
const [enabled, setEnabledState] = useState(false);
useEffect(() => {
void api.invoke(ipcChannels.tokenGridSnap.getState, {}).then((res) => {
setEnabledState(Boolean(res.enabled));
});
return api.on(ipcChannels.tokenGridSnap.stateChanged, ({ enabled: next }) => {
setEnabledState(Boolean(next));
});
}, [api]);
const setEnabled = useCallback(
async (next: boolean) => {
setEnabledState(next);
const res = await api.invoke(ipcChannels.tokenGridSnap.setEnabled, { enabled: next });
setEnabledState(Boolean(res.enabled));
return Boolean(res.enabled);
},
[api],
);
return [enabled, { setEnabled }];
}
@@ -0,0 +1,155 @@
import { useEffect, useRef, useState } from 'react';
import { computePathPlaybackSample } from '../../../shared/types/tokenPathPlayback';
import {
tokenPathKey,
type TokenPathPlaybackPhase,
type TokenPathSessionState,
} from '../../../shared/types/tokenPathSession';
import type { SceneNpcToken, SceneToken } from '../../../shared/types';
export type TokenPathLivePose = {
nx: number;
ny: number;
rotationDeg: number;
phase: TokenPathPlaybackPhase;
dist: number;
};
type PoseMaps = {
tokenPoses: Record<string, TokenPathLivePose>;
npcPoses: Record<string, TokenPathLivePose>;
};
const EMPTY: PoseMaps = { tokenPoses: {}, npcPoses: {} };
function posesEqual(a: PoseMaps, b: PoseMaps): boolean {
const aT = a.tokenPoses;
const bT = b.tokenPoses;
const aN = a.npcPoses;
const bN = b.npcPoses;
const aTk = Object.keys(aT);
const bTk = Object.keys(bT);
const aNk = Object.keys(aN);
const bNk = Object.keys(bN);
if (aTk.length !== bTk.length || aNk.length !== bNk.length) return false;
for (const k of aTk) {
const x = aT[k];
const y = bT[k];
if (!y || x!.nx !== y.nx || x!.ny !== y.ny || x!.rotationDeg !== y.rotationDeg || x!.phase !== y.phase) {
return false;
}
}
for (const k of aNk) {
const x = aN[k];
const y = bN[k];
if (!y || x!.nx !== y.nx || x!.ny !== y.ny || x!.rotationDeg !== y.rotationDeg || x!.phase !== y.phase) {
return false;
}
}
return true;
}
/**
* RAF poses for control/presentation while path playback is active.
* When phase === 'stopped', pose is omitted so session/placement (drag) wins.
*
* Uses local Date.now() segmentStartedAtMs is also wall-clock from main (same machine).
* Do NOT clamp to stale serverNowMs: that froze motion after ~250ms until the next IPC bump.
*/
export function useTokenPathLivePoses(args: {
tokens: readonly SceneToken[];
npcTokens: readonly SceneNpcToken[];
pathSession: TokenPathSessionState | null;
enabled?: boolean;
onMarkDone?: (kind: 'token' | 'npcToken', placementId: string, atDist: number) => void;
}): PoseMaps {
const { tokens, npcTokens, pathSession, enabled = true, onMarkDone } = args;
const [poses, setPoses] = useState<PoseMaps>(EMPTY);
const markedDoneRef = useRef<Set<string>>(new Set());
const onMarkDoneRef = useRef(onMarkDone);
onMarkDoneRef.current = onMarkDone;
const pathSessionRef = useRef(pathSession);
pathSessionRef.current = pathSession;
const tokensRef = useRef(tokens);
tokensRef.current = tokens;
const npcTokensRef = useRef(npcTokens);
npcTokensRef.current = npcTokens;
useEffect(() => {
markedDoneRef.current.clear();
}, [pathSession?.revision]);
useEffect(() => {
if (!enabled) {
setPoses(EMPTY);
return;
}
let raf = 0;
let alive = true;
const tick = () => {
if (!alive) return;
const session = pathSessionRef.current;
if (!session) {
setPoses((prev) => (prev === EMPTY || Object.keys(prev.tokenPoses).length + Object.keys(prev.npcPoses).length === 0 ? prev : EMPTY));
raf = requestAnimationFrame(tick);
return;
}
// Wall clock: matches main's Date.now() for segmentStartedAtMs (Electron, one host).
const sampleNow = Date.now();
const tokenPoses: Record<string, TokenPathLivePose> = {};
const npcPoses: Record<string, TokenPathLivePose> = {};
const sampleOne = (
kind: 'token' | 'npcToken',
placementId: string,
path: NonNullable<SceneToken['path']>,
out: Record<string, TokenPathLivePose>,
) => {
const key = tokenPathKey(kind, placementId);
const entry = session.playback[key];
if (!entry) return;
if (entry.phase === 'stopped') return;
const result = computePathPlaybackSample({ path, entry, nowMs: sampleNow });
if (!result) return;
out[placementId] = {
nx: result.sample.nx,
ny: result.sample.ny,
rotationDeg: result.sample.rotationDeg,
phase: result.phase,
dist: result.sample.dist,
};
if (result.markDone && !markedDoneRef.current.has(key)) {
markedDoneRef.current.add(key);
onMarkDoneRef.current?.(kind, placementId, result.sample.dist);
}
};
for (const t of tokensRef.current) {
if (t.path && t.path.points.length >= 2) {
sampleOne('token', String(t.id), t.path, tokenPoses);
}
}
for (const t of npcTokensRef.current) {
if (t.path && t.path.points.length >= 2) {
sampleOne('npcToken', String(t.id), t.path, npcPoses);
}
}
const next: PoseMaps = { tokenPoses, npcPoses };
setPoses((prev) => (posesEqual(prev, next) ? prev : next));
raf = requestAnimationFrame(tick);
};
raf = requestAnimationFrame(tick);
return () => {
alive = false;
cancelAnimationFrame(raf);
};
}, [enabled]);
return poses;
}
@@ -0,0 +1,34 @@
import { useEffect, useMemo, useState } from 'react';
import { ipcChannels } from '../../../shared/ipc/contracts';
import type { TokenPathSessionEvent, TokenPathSessionState } from '../../../shared/types';
import { getDndApi } from '../dndApi';
export function useTokenPathSession(): [
TokenPathSessionState | null,
{ dispatch: (event: TokenPathSessionEvent) => Promise<void> },
] {
const api = getDndApi();
const [state, setState] = useState<TokenPathSessionState | null>(null);
useEffect(() => {
void api.invoke(ipcChannels.tokenPathSession.getState, {}).then(({ state: s }) => {
setState(s);
});
return api.on(ipcChannels.tokenPathSession.stateChanged, ({ state: s }) => {
setState(s);
});
}, [api]);
const apiWrap = useMemo(
() => ({
dispatch: async (event: TokenPathSessionEvent) => {
const res = await api.invoke(ipcChannels.tokenPathSession.dispatch, { event });
void res;
},
}),
[api],
);
return [state, apiWrap];
}
@@ -11,13 +11,15 @@
position: absolute;
transform: translate(-50%, -50%);
border-radius: 50%;
border: 2px solid rgba(255, 255, 255, 0.5);
background: rgba(0, 0, 0, 0.5);
border: 2px solid rgba(255, 255, 255, 0.72);
background: rgba(12, 14, 20, 0.62);
display: grid;
place-items: center;
pointer-events: auto;
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 {
@@ -30,12 +32,22 @@
.trapDisarmed {
border-color: #9ca3af;
filter: grayscale(0.7);
opacity: 0.75;
opacity: 0.8;
}
.trapGmHidden {
opacity: 0.55;
/* Hidden from players, but still readable for the GM on control preview. */
opacity: 0.88;
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 {
pointer-events: none;
}
.label {
@@ -21,6 +21,8 @@ type Props = {
viewport: { x: number; y: number; w: number; h: number } | null;
/** Пульт: показывать все ловушки + RMB меню. Презентация: только revealed. */
mode: 'control' | 'presentation';
/** На пульте: false — без контекстного меню (например, активна кисть эффектов). */
interactive?: boolean;
onReveal?: (trapId: string) => void;
onActivate?: (trapId: string) => void;
onDisarm?: (trapId: string) => void;
@@ -47,6 +49,7 @@ export function SceneTrapsOverlay({
session,
viewport,
mode,
interactive = true,
onReveal,
onActivate,
onDisarm,
@@ -54,6 +57,10 @@ export function SceneTrapsOverlay({
const [menu, setMenu] = useState<{ trapId: string; x: number; y: number } | null>(null);
const [activationFx, setActivationFx] = useState<ActivationFx | null>(null);
useEffect(() => {
if (!interactive) setMenu(null);
}, [interactive]);
useEffect(() => {
const act = session?.lastActivation;
if (!act) return;
@@ -112,6 +119,7 @@ export function SceneTrapsOverlay({
rt.status === 'active' ? styles.trapActive : '',
rt.status === 'disarmed' ? styles.trapDisarmed : '',
mode === 'control' && !rt.revealed ? styles.trapGmHidden : '',
mode === 'control' && !interactive ? styles.trapNonInteractive : '',
]
.filter(Boolean)
.join(' ');
@@ -121,7 +129,7 @@ export function SceneTrapsOverlay({
className={cls}
style={{ left, top, width: sizePx, height: sizePx }}
onContextMenu={
mode === 'control'
mode === 'control' && interactive
? (e) => {
e.preventDefault();
e.stopPropagation();
@@ -163,7 +171,7 @@ export function SceneTrapsOverlay({
}}
/>
) : null}
{menu && mode === 'control'
{menu && mode === 'control' && interactive
? createPortal(
<div
role="menu"
+3
View File
@@ -17,6 +17,7 @@ type ButtonProps = {
iconOnly?: boolean;
/** Позиция тултипа относительно кнопки. */
tooltipPlacement?: 'top' | 'bottom' | 'bottom-left';
'data-testid'?: string;
};
export function Button({
@@ -28,6 +29,7 @@ export function Button({
ariaLabel,
iconOnly = false,
tooltipPlacement = 'top',
'data-testid': testId,
}: ButtonProps) {
const btnRef = useRef<HTMLButtonElement | null>(null);
const hostRef = useRef<HTMLSpanElement | null>(null);
@@ -85,6 +87,7 @@ export function Button({
className={btnClass}
disabled={disabled}
aria-label={ariaLabel}
data-testid={testId}
onClick={disabled ? undefined : onClick}
onMouseEnter={disabled ? undefined : showTip}
onMouseLeave={disabled ? undefined : hideTip}
@@ -70,3 +70,63 @@ void test('WindowErrorBoundary component exists and catches errors', () => {
assert.ok(src.includes('componentDidCatch'));
assert.ok(src.includes('role="alert"'));
});
void test('EditorApp: Players header after File, opens modal', () => {
const src = fs.readFileSync(path.join(rendererRoot, 'editor/EditorApp.tsx'), 'utf8');
const fileIdx = src.indexOf("t('top.file')");
const playersIdx = src.indexOf('data-testid="players-header-btn"');
assert.ok(fileIdx > 0, 'File menu present');
assert.ok(playersIdx > fileIdx, 'Players button must follow File in source order');
assert.ok(src.includes('PlayersManagerModal'));
assert.ok(src.includes('setPlayersManagerOpen(true)'));
});
void test('Players modal: flat teams only, progress overlay, PlayerTokenView', () => {
const src = fs.readFileSync(path.join(rendererRoot, 'editor/PlayersModals.tsx'), 'utf8');
assert.ok(src.includes('PlayerTokenView'));
assert.ok(src.includes('data-testid="players-modal"'));
assert.ok(src.includes('data-testid="players-save-progress"'));
assert.doesNotMatch(src, /parentId|подкоманд|subteam|sub-team/i);
assert.ok(src.includes("application/x-dnd-player-id"));
});
void test('Scene NPC accordion: separate mime and PlayerTokenView markers', () => {
const scene = fs.readFileSync(path.join(rendererRoot, 'sceneEditor/SceneEditorApp.tsx'), 'utf8');
const tokenTile = fs.readFileSync(path.join(rendererRoot, 'sceneEditor/TokenTile.tsx'), 'utf8');
assert.ok(scene.includes('data-testid="scene-npc-accordion"'));
assert.ok(scene.includes("application/x-dnd-scene-npc-id"));
assert.ok(tokenTile.includes("application/x-dnd-app-token-id"));
assert.notEqual(
'application/x-dnd-scene-npc-id',
'application/x-dnd-app-token-id',
'NPC scene mime must differ from app token mime',
);
assert.ok(scene.includes('PlayerTokenView'));
assert.ok(scene.includes('persistNpcTokens([])'));
assert.doesNotMatch(scene, /SceneTokenMarker[\s\S]{0,80}npcTokens/);
});
void test('Control and Presentation use SceneNpcTokensOverlay', () => {
const control = fs.readFileSync(path.join(rendererRoot, 'control/ControlApp.tsx'), 'utf8');
const presentation = fs.readFileSync(path.join(rendererRoot, 'shared/PresentationView.tsx'), 'utf8');
assert.ok(control.includes('SceneNpcTokensOverlay'));
assert.ok(presentation.includes('SceneNpcTokensOverlay'));
assert.ok(control.includes('sceneNpcTokensSession'));
assert.ok(control.includes('ScenePlayerTokensOverlay'));
assert.ok(presentation.includes('ScenePlayerTokensOverlay'));
assert.ok(control.includes('toggle-session-players'));
});
void test('EditorApp: split Run button and launch-with-players modal', () => {
const editor = fs.readFileSync(path.join(rendererRoot, 'editor/EditorApp.tsx'), 'utf8');
assert.ok(editor.includes('splitRun'));
assert.ok(editor.includes('run-menu-btn'));
assert.ok(editor.includes('LaunchPlayersModal'));
assert.ok(editor.includes('top.runWithPlayers'));
});
void test('NpcsEditorApp: token appearance via PlayerTokenView', () => {
const src = fs.readFileSync(path.join(rendererRoot, 'npcs/NpcsEditorApp.tsx'), 'utf8');
assert.ok(src.includes('PlayerTokenView'));
assert.ok(src.includes('disposition') || src.includes('updateNpcFields'));
});
@@ -0,0 +1,63 @@
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(editor.includes('ContainedVideo'));
assert.ok(editor.includes('onRotatePreview'));
assert.match(
editor,
/previewAssetId && \(previewAssetType === 'image' \|\| previewAssetType === 'video'\) \? \([\s\S]*?onRotatePreview/,
);
assert.ok(fs.readFileSync(path.join(rendererRoot, 'shared/ContainedVideo.tsx'), 'utf8').includes('rotationDeg'));
assert.ok(
fs
.readFileSync(path.join(rendererRoot, 'control/ControlScenePreview.tsx'), 'utf8')
.includes('rotationDeg={rot}'),
);
assert.ok(presentation.includes('rotationDeg={rot}'));
assert.ok(sceneEditor.includes('rotationDeg={rot}'));
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]/);
});
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" href="/app-window-icon.png" type="image/png" />
<title>TTRPG</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/tokenPathEditor/main.tsx"></script>
</body>
</html>
@@ -0,0 +1,183 @@
.page {
display: grid;
grid-template-columns: 280px 1fr;
height: 100vh;
width: 100vw;
overflow: hidden;
background: var(--bg, #12141a);
color: var(--text, #e8eaef);
}
.sidebar {
border-right: 1px solid var(--stroke, #2a2f3a);
padding: 12px;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 10px;
}
.title {
font-weight: 800;
font-size: 14px;
letter-spacing: 0.02em;
}
.hint {
font-size: 12px;
opacity: 0.7;
line-height: 1.4;
margin: 0;
}
.field {
display: grid;
gap: 4px;
font-size: 12px;
}
.actions {
display: grid;
gap: 8px;
margin-top: 4px;
width: 100%;
}
.actions > * {
width: 100%;
max-width: 100%;
display: flex;
box-sizing: border-box;
}
.actions button {
width: 100%;
box-sizing: border-box;
}
.meta {
font-size: 11px;
opacity: 0.65;
line-height: 1.35;
}
.main {
min-width: 0;
min-height: 0;
position: relative;
background: #0b0d12;
}
.host {
position: absolute;
inset: 0;
overflow: hidden;
cursor: crosshair;
touch-action: none;
user-select: none;
}
.empty {
display: grid;
place-items: center;
height: 100%;
padding: 24px;
text-align: center;
opacity: 0.75;
}
.pathSvg {
position: absolute;
inset: 0;
pointer-events: none;
z-index: 2;
}
.pathLine {
stroke: rgba(90, 210, 255, 0.95);
stroke-width: 2.5;
stroke-linecap: round;
stroke-linejoin: round;
stroke-dasharray: 8 5;
}
.point {
position: absolute;
z-index: 4;
width: 22px;
height: 22px;
margin: 0;
padding: 0;
border-radius: 999px;
border: 1px solid rgba(255, 255, 255, 0.55);
background: rgba(20, 90, 140, 0.92);
color: #fff;
font-size: 10px;
font-weight: 700;
transform: translate(-50%, -50%);
cursor: grab;
touch-action: none;
}
.point:active {
cursor: grabbing;
}
.tokenPreview {
position: absolute;
z-index: 3;
pointer-events: none;
border-radius: 8px;
overflow: hidden;
border: 1px solid rgba(255, 255, 255, 0.28);
background: rgba(0, 0, 0, 0.25);
}
.tokenPreview img {
width: 100%;
height: 100%;
object-fit: contain;
display: block;
}
.ctxMenuBackdrop {
position: fixed;
inset: 0;
z-index: 40;
border: 0;
background: transparent;
cursor: default;
}
.ctxMenu {
position: fixed;
z-index: 41;
min-width: 160px;
padding: 4px;
border-radius: 8px;
border: 1px solid var(--stroke, #2a2f3a);
background: #1a1e27;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.45);
display: grid;
}
.ctxItem,
.ctxItemDanger {
text-align: left;
border: 0;
background: transparent;
color: inherit;
padding: 8px 10px;
border-radius: 6px;
cursor: pointer;
font-size: 13px;
}
.ctxItemDanger {
color: #ff8f8f;
}
.ctxItem:hover,
.ctxItemDanger:hover {
background: rgba(255, 255, 255, 0.06);
}
@@ -0,0 +1,679 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { ipcChannels, type SessionState } from '../../shared/ipc/contracts';
import type { SceneNpcToken, SceneToken, TokenPath, TokenPathPoint } from '../../shared/types';
import {
createEmptyTokenPath,
normalizeTokenPath,
reverseTokenPathPoints,
sampleTokenPathAtProgress,
tokenPathPolyline,
tryAppendPathPoint,
} from '../../shared/types/tokenPath';
import type { TokenPathTargetKind } from '../../shared/types/tokenPathSession';
import { USERS_BRANCH_FEATURES_ENABLED } from '../../shared/features/usersBranchFeatures';
import { getDndApi } from '../shared/dndApi';
import { ContainedVideo } from '../shared/ContainedVideo';
import { RotatedImage } from '../shared/RotatedImage';
import { useAppTokens } from '../shared/tokens/useAppTokens';
import { useTokenImageUrl } from '../shared/tokens/useTokenImageUrl';
import { PlayerTokenView } from '../shared/playerToken/PlayerTokenView';
import { normalizeNpcDisposition, npcDispositionRingColor } from '../../shared/types/npcDisposition';
import { sceneGridTokenFitFactor } from '../../shared/types/sceneGrid';
import { useAssetUrl } from '../shared/useAssetImageUrl';
import { Button, Input, Select } from '../shared/ui/controls';
import styles from './TokenPathEditorApp.module.css';
type Target = { kind: TokenPathTargetKind; placementId: string };
type Draft = TokenPath;
type PointMenu = { x: number; y: number; index: number };
function cloneDraft(path: TokenPath | null | undefined): Draft {
if (!path) return createEmptyTokenPath();
return {
...path,
points: path.points.map((p) => ({ ...p })),
};
}
function TokenPreview({
kind,
token,
npcToken,
npcName,
npcAvatarUrl,
ringColor,
imageOffset,
imageScale,
left,
top,
sizePx,
rotationDeg,
}: {
kind: TokenPathTargetKind;
token?: SceneToken;
npcToken?: SceneNpcToken;
npcName?: string;
npcAvatarUrl?: string | null;
ringColor?: string;
imageOffset?: { x: number; y: number };
imageScale?: number;
left: number;
top: number;
sizePx: number;
rotationDeg: number;
}) {
const url = useTokenImageUrl(token?.tokenId ?? null);
if (kind === 'token' && token) {
return (
<div
className={styles.tokenPreview}
style={{
left,
top,
width: sizePx,
height: sizePx,
transform: `translate(-50%, -50%) rotate(${String(rotationDeg)}deg)`,
}}
>
{url ? <img src={url} alt="" draggable={false} /> : null}
</div>
);
}
if (kind === 'npcToken' && npcToken) {
return (
<div className={styles.tokenPreview} style={{ left, top, width: sizePx, height: sizePx }}>
<PlayerTokenView
name={npcName ?? ''}
imageUrl={npcAvatarUrl ?? null}
ringColor={ringColor ?? '#888'}
sizePx={sizePx}
{...(imageOffset ? { imageOffset } : {})}
{...(typeof imageScale === 'number' ? { imageScale } : {})}
/>
</div>
);
}
return null;
}
export function TokenPathEditorApp() {
const api = getDndApi();
const appTokens = useAppTokens();
const [session, setSession] = useState<SessionState | null>(null);
const [target, setTarget] = useState<Target | null>(null);
const [draft, setDraft] = useState<Draft>(createEmptyTokenPath());
const [contentRect, setContentRect] = useState<{ x: number; y: number; w: number; h: number } | null>(
null,
);
const [pointMenu, setPointMenu] = useState<PointMenu | null>(null);
const [previewPlaying, setPreviewPlaying] = useState(false);
const [previewU, setPreviewU] = useState(0);
const [dirty, setDirty] = useState(false);
const [status, setStatus] = useState<string | null>(null);
const hostRef = useRef<HTMLDivElement | null>(null);
const dragPointRef = useRef<{ index: number; pointerId: number } | null>(null);
const saveTimerRef = useRef(0);
const draftRef = useRef(draft);
draftRef.current = draft;
const project = session?.project ?? null;
const sceneId = project?.currentSceneId ?? null;
const scene = sceneId && project ? project.scenes[sceneId] : undefined;
const url = useAssetUrl(scene?.previewAssetId ?? null);
const rot = scene?.previewRotationDeg ?? 0;
const isImage = scene?.previewAssetType === 'image';
const isVideo = scene?.previewAssetType === 'video';
const placement = useMemo(() => {
if (!target || !scene) return null;
if (target.kind === 'token') {
return (scene.tokens ?? []).find((t) => String(t.id) === target.placementId) ?? null;
}
return (scene.npcTokens ?? []).find((t) => String(t.id) === target.placementId) ?? null;
}, [scene, target]);
const npcMeta = useMemo(() => {
if (!target || target.kind !== 'npcToken' || !placement || !('npcId' in placement)) return null;
const npc = project?.npcs.find((n) => n.id === placement.npcId);
return npc ?? null;
}, [placement, project?.npcs, target]);
const npcAvatarUrl = useAssetUrl(npcMeta?.avatarAssetId ?? null);
useEffect(() => {
void api.invoke(ipcChannels.project.get, {}).then(({ project: p }) => {
setSession({ project: p, currentSceneId: p?.currentSceneId ?? null });
});
return api.on(ipcChannels.session.stateChanged, ({ state }) => setSession(state));
}, [api]);
useEffect(() => {
void api.invoke(ipcChannels.windows.getTokenPathEditorTarget, {}).then((t) => {
setTarget(t);
});
return api.on(ipcChannels.windows.tokenPathEditorTargetChanged, (t) => {
setTarget(t);
});
}, [api]);
useEffect(() => {
if (!placement) {
setDraft(createEmptyTokenPath());
setDirty(false);
return;
}
setDraft(cloneDraft(placement.path ?? null));
setDirty(false);
setPreviewPlaying(false);
setPreviewU(0);
setStatus(null);
}, [placement?.id, target?.kind, target?.placementId]);
const persistDraft = useCallback(
(next: Draft, immediate = false) => {
if (!sceneId || !target) return;
const normalized = normalizeTokenPath(next);
const run = () => {
if (target.kind === 'token') {
const tokens = (scene?.tokens ?? []).map((t) =>
String(t.id) === target.placementId ? { ...t, path: normalized } : t,
);
void api.invoke(ipcChannels.project.updateScene, { sceneId, patch: { tokens } });
} else {
const npcTokens = (scene?.npcTokens ?? []).map((t) =>
String(t.id) === target.placementId ? { ...t, path: normalized } : t,
);
void api.invoke(ipcChannels.project.updateScene, { sceneId, patch: { npcTokens } });
}
setDirty(false);
setStatus(normalized ? 'Сохранено' : 'Путь очищен (нужно ≥2 точки)');
};
if (saveTimerRef.current) window.clearTimeout(saveTimerRef.current);
if (immediate) {
run();
return;
}
saveTimerRef.current = window.setTimeout(run, 180);
},
[api, scene?.npcTokens, scene?.tokens, sceneId, target],
);
const updateDraft = useCallback(
(updater: (prev: Draft) => Draft, opts?: { save?: boolean; immediate?: boolean }) => {
setDraft((prev) => {
const next = updater(prev);
draftRef.current = next;
if (opts?.save !== false) {
setDirty(true);
persistDraft(next, opts?.immediate);
}
return next;
});
},
[persistDraft],
);
useEffect(() => {
if (!previewPlaying) return;
const started = performance.now();
const durationMs = Math.max(0.5, draft.durationSec) * 1000;
const loopMode = draft.loopMode;
const closed = draft.closed;
let raf = 0;
let stopped = false;
const tick = (now: number) => {
if (stopped) return;
const elapsed = Math.max(0, now - started);
let u = 0;
if (loopMode === 'pingpong') {
const period = Math.max(durationMs * 2, 1e-9);
let t = elapsed % period;
if (t > durationMs) t = period - t;
u = t / durationMs;
} else if (loopMode === 'loop' && closed) {
u = (elapsed % durationMs) / durationMs;
} else {
// once (и loop без замыкания)
u = Math.min(1, elapsed / durationMs);
setPreviewU(u);
if (u >= 1) {
stopped = true;
setPreviewPlaying(false);
return;
}
raf = requestAnimationFrame(tick);
return;
}
setPreviewU(u);
raf = requestAnimationFrame(tick);
};
raf = requestAnimationFrame(tick);
return () => {
stopped = true;
cancelAnimationFrame(raf);
};
}, [previewPlaying, draft.durationSec, draft.points, draft.closed, draft.loopMode]);
const hostToNorm = useCallback(
(clientX: number, clientY: number) => {
const host = hostRef.current;
if (!host || !contentRect) return null;
const r = host.getBoundingClientRect();
return {
nx: Math.max(0, Math.min(1, (clientX - (r.left + contentRect.x)) / Math.max(1e-6, contentRect.w))),
ny: Math.max(0, Math.min(1, (clientY - (r.top + contentRect.y)) / Math.max(1e-6, contentRect.h))),
};
},
[contentRect],
);
const previewSample = useMemo(() => {
if (!previewPlaying || draft.points.length < 2) return null;
const normalized = normalizeTokenPath(draft);
if (!normalized) return null;
return sampleTokenPathAtProgress(normalized, previewU);
}, [draft, previewPlaying, previewU]);
const tokenLeftTop = useMemo(() => {
if (!contentRect || !placement) return null;
const nx = previewSample?.nx ?? placement.nx;
const ny = previewSample?.ny ?? placement.ny;
const minDim = Math.min(contentRect.w, contentRect.h);
const sizeN =
target?.kind === 'npcToken' && 'sizeN' in placement
? placement.sizeN * sceneGridTokenFitFactor(scene?.grid ?? null)
: placement.sizeN;
const sizePx = Math.max(16, sizeN * minDim);
return {
left: contentRect.x + nx * contentRect.w,
top: contentRect.y + ny * contentRect.h,
sizePx,
rotationDeg:
previewSample?.rotationDeg ??
(target?.kind === 'token' && 'rotationDeg' in placement ? placement.rotationDeg : 0),
};
}, [contentRect, placement, previewSample, scene?.grid, target?.kind]);
const title = useMemo(() => {
if (!target) return 'Движение токена';
if (target.kind === 'token') {
const tok = placement && 'tokenId' in placement ? appTokens.find((a) => a.id === placement.tokenId) : null;
return tok ? `Движение: ${tok.name}` : 'Движение токена';
}
return npcMeta ? `Движение: ${npcMeta.name}` : 'Движение НПС';
}, [appTokens, npcMeta, placement, target]);
if (!USERS_BRANCH_FEATURES_ENABLED && target?.kind === 'npcToken') {
return (
<div className={styles.page}>
<div className={styles.empty}>НПС недоступны в этой сборке.</div>
</div>
);
}
return (
<div className={styles.page}>
<aside className={styles.sidebar}>
<div className={styles.title}>{title}</div>
<p className={styles.hint}>
ЛКМ по карте добавить точку. Перетаскивайте точки для правки. ПКМ по точке замкнуть или удалить.
</p>
<label className={styles.field}>
<span>Длительность, сек</span>
<Input
value={String(draft.durationSec)}
onChange={(v) => {
const n = Number(v);
updateDraft((d) => ({
...d,
durationSec: Number.isFinite(n) ? n : d.durationSec,
}));
}}
/>
</label>
<label className={styles.field}>
<span>Режим цикла</span>
<Select
value={draft.loopMode}
options={[
{ value: 'once', label: 'Один раз' },
{ value: 'pingpong', label: 'Туда-обратно' },
{
value: 'loop',
label: draft.closed ? 'Зациклить' : 'Зациклить (нужно замкнуть)',
disabled: !draft.closed,
},
]}
onChange={(v) => {
updateDraft((d) => ({
...d,
loopMode: v === 'loop' && !d.closed ? 'once' : (v as Draft['loopMode']),
}));
}}
/>
</label>
<label className={styles.field}>
<span>Старт</span>
<Select
value={draft.startMode}
options={[
{ value: 'onEnter', label: 'При входе в сцену' },
{ value: 'delayed', label: 'С задержкой' },
]}
onChange={(v) => {
updateDraft((d) => ({
...d,
startMode: v === 'delayed' ? 'delayed' : 'onEnter',
}));
}}
/>
</label>
{draft.startMode === 'delayed' ? (
<label className={styles.field}>
<span>Задержка, сек</span>
<Input
value={String(draft.delaySec)}
onChange={(v) => {
const n = Number(v);
updateDraft((d) => ({
...d,
delaySec: Number.isFinite(n) ? n : d.delaySec,
}));
}}
/>
</label>
) : null}
<label className={styles.field}>
<span>Ориентация</span>
<Select
value={draft.facingMode}
options={[
{ value: 'tangentSmooth', label: 'По касательной' },
{ value: 'fixed', label: 'Фиксированный угол' },
]}
onChange={(v) => {
updateDraft((d) => ({
...d,
facingMode: v === 'fixed' ? 'fixed' : 'tangentSmooth',
}));
}}
/>
</label>
{draft.facingMode === 'fixed' ? (
<label className={styles.field}>
<span>Угол, °</span>
<Input
value={String(draft.fixedRotationDeg)}
onChange={(v) => {
const n = Number(v);
updateDraft((d) => ({
...d,
fixedRotationDeg: Number.isFinite(n) ? n : d.fixedRotationDeg,
}));
}}
/>
</label>
) : null}
<div className={styles.actions}>
<Button
onClick={() => {
updateDraft((d) => ({
...d,
points: reverseTokenPathPoints(d.points),
}));
}}
disabled={draft.points.length < 2}
>
Обратить путь
</Button>
<Button
onClick={() => {
setPreviewPlaying((p) => !p);
setPreviewU(0);
}}
disabled={draft.points.length < 2}
>
{previewPlaying ? 'Стоп превью' : 'Превью'}
</Button>
<Button
onClick={() => {
updateDraft(() => createEmptyTokenPath(), { immediate: true });
setPreviewPlaying(false);
}}
>
Очистить путь
</Button>
<Button
onClick={() => {
persistDraft(draftRef.current, true);
}}
>
Сохранить
</Button>
</div>
<div className={styles.meta}>
Точек: {draft.points.length}
{draft.closed ? ' · замкнут' : ''}
{dirty ? ' · есть изменения' : ''}
{status ? ` · ${status}` : ''}
</div>
</aside>
<main className={styles.main}>
{!scene || (!isImage && !isVideo) || !url ? (
<div className={styles.empty}>Нет карты сцены для редактирования пути.</div>
) : !target || !placement ? (
<div className={styles.empty}>Выберите токен в редакторе сцены: ПКМ «Указать движение».</div>
) : (
<div
ref={hostRef}
className={styles.host}
onContextMenu={(e) => e.preventDefault()}
onPointerDown={(e) => {
if (e.button !== 0) return;
if ((e.target as HTMLElement).closest('[data-path-point]')) return;
const p = hostToNorm(e.clientX, e.clientY);
if (!p) return;
updateDraft((d) => {
const next = tryAppendPathPoint(d.points, p);
if (!next) return d;
return { ...d, points: next, closed: false, loopMode: d.loopMode === 'loop' ? 'once' : d.loopMode };
});
}}
onPointerMove={(e) => {
const drag = dragPointRef.current;
if (!drag || drag.pointerId !== e.pointerId) return;
const p = hostToNorm(e.clientX, e.clientY);
if (!p) return;
updateDraft((d) => {
const points = d.points.map((pt, i) => (i === drag.index ? p : pt));
return { ...d, points };
});
}}
onPointerUp={(e) => {
if (dragPointRef.current?.pointerId === e.pointerId) {
dragPointRef.current = null;
persistDraft(draftRef.current, true);
}
}}
onPointerCancel={(e) => {
if (dragPointRef.current?.pointerId === e.pointerId) {
dragPointRef.current = null;
}
}}
>
{isImage ? (
<RotatedImage url={url} rotationDeg={rot} mode="contain" onContentRectChange={setContentRect} />
) : (
<ContainedVideo
url={url}
rotationDeg={rot}
muted
playsInline
loop
preload="metadata"
onContentRectChange={setContentRect}
/>
)}
{contentRect ? (
<svg className={styles.pathSvg} width="100%" height="100%" aria-hidden>
{draft.points.length >= 2 ? (
<polyline
className={styles.pathLine}
fill="none"
points={tokenPathPolyline(draft)
.map((p) => {
const x = contentRect.x + p.nx * contentRect.w;
const y = contentRect.y + p.ny * contentRect.h;
return `${x},${y}`;
})
.join(' ')}
/>
) : null}
</svg>
) : null}
{contentRect
? draft.points.map((p: TokenPathPoint, index: number) => {
const left = contentRect.x + p.nx * contentRect.w;
const top = contentRect.y + p.ny * contentRect.h;
return (
<button
key={`${index}_${p.nx}_${p.ny}`}
type="button"
data-path-point
className={styles.point}
style={{ left, top }}
onPointerDown={(e) => {
if (e.button !== 0) return;
e.stopPropagation();
e.preventDefault();
(e.currentTarget as HTMLButtonElement).setPointerCapture(e.pointerId);
dragPointRef.current = { index, pointerId: e.pointerId };
}}
onContextMenu={(e) => {
e.preventDefault();
e.stopPropagation();
setPointMenu({ x: e.clientX, y: e.clientY, index });
}}
>
{index + 1}
</button>
);
})
: null}
{contentRect && tokenLeftTop && target ? (
<TokenPreview
kind={target.kind}
left={tokenLeftTop.left}
top={tokenLeftTop.top}
sizePx={tokenLeftTop.sizePx}
rotationDeg={tokenLeftTop.rotationDeg}
{...(target.kind === 'token' && placement && 'tokenId' in placement
? { token: placement as SceneToken }
: {})}
{...(target.kind === 'npcToken' && placement && 'npcId' in placement
? { npcToken: placement as SceneNpcToken }
: {})}
{...(npcMeta?.name ? { npcName: npcMeta.name } : {})}
{...(npcAvatarUrl ? { npcAvatarUrl } : {})}
{...(npcMeta
? {
ringColor: npcDispositionRingColor(
normalizeNpcDisposition(
(placement && 'disposition' in placement ? placement.disposition : undefined) ??
npcMeta.disposition,
),
),
}
: {})}
{...(npcMeta?.imageOffset ? { imageOffset: npcMeta.imageOffset } : {})}
{...(typeof npcMeta?.imageScale === 'number'
? { imageScale: npcMeta.imageScale }
: {})}
/>
) : null}
</div>
)}
</main>
{pointMenu
? createPortal(
<>
<button
type="button"
className={styles.ctxMenuBackdrop}
aria-label="Закрыть"
onClick={() => setPointMenu(null)}
/>
<div className={styles.ctxMenu} style={{ left: pointMenu.x, top: pointMenu.y }} role="menu">
<button
type="button"
className={styles.ctxItem}
role="menuitem"
onClick={() => {
updateDraft((d) => ({
...d,
closed: true,
loopMode: d.loopMode === 'once' ? d.loopMode : d.loopMode,
}));
setPointMenu(null);
}}
>
Замкнуть путь
</button>
<button
type="button"
className={styles.ctxItem}
role="menuitem"
onClick={() => {
updateDraft((d) => ({
...d,
closed: false,
loopMode: d.loopMode === 'loop' ? 'once' : d.loopMode,
}));
setPointMenu(null);
}}
>
Разомкнуть
</button>
<button
type="button"
className={styles.ctxItemDanger}
role="menuitem"
onClick={() => {
const idx = pointMenu.index;
updateDraft((d) => {
const points = d.points.filter((_, i) => i !== idx);
return {
...d,
points,
closed: points.length >= 2 ? d.closed : false,
loopMode: points.length >= 2 && d.closed ? d.loopMode : d.loopMode === 'loop' ? 'once' : d.loopMode,
};
});
setPointMenu(null);
}}
>
Удалить точку
</button>
</div>
</>,
document.body,
)
: null}
</div>
);
}
+23
View File
@@ -0,0 +1,23 @@
import React from 'react';
import { createRoot } from 'react-dom/client';
import '../shared/ui/globals.css';
import { EditorI18nProvider } from '../editor/i18n/EditorI18nContext';
import { WindowErrorBoundary } from '../shared/ui/WindowErrorBoundary';
import { TokenPathEditorApp } from './TokenPathEditorApp';
const rootEl = document.getElementById('root');
if (!rootEl) {
throw new Error('Missing #root element');
}
createRoot(rootEl).render(
<React.StrictMode>
<WindowErrorBoundary title="Движение токена">
<EditorI18nProvider>
<TokenPathEditorApp />
</EditorI18nProvider>
</WindowErrorBoundary>
</React.StrictMode>,
);
+2
View File
@@ -24,6 +24,7 @@ export type AppWindowKind =
| 'materials'
| 'npcsEditor'
| 'sceneEditor'
| 'tokenPathEditor'
| 'npcs';
const WINDOW_SUFFIX: Record<AppWindowKind, { ru: string; en: string }> = {
@@ -35,6 +36,7 @@ const WINDOW_SUFFIX: Record<AppWindowKind, { ru: string; en: string }> = {
materials: { ru: 'Материалы', en: 'Materials' },
npcsEditor: { ru: 'НПС', en: 'NPCs' },
sceneEditor: { ru: 'Редактор сцены', en: 'Scene editor' },
tokenPathEditor: { ru: 'Движение токена', en: 'Token path' },
npcs: { ru: 'НПС', en: 'NPCs' },
};
@@ -0,0 +1,6 @@
/**
* Hotfix release: set to `false` to hide everything merged from branch `users`
* (Players library, run-with-players, circular NPC/player session tokens, disposition UI).
* Re-enable after QA.
*/
export const USERS_BRANCH_FEATURES_ENABLED = true;
+1
View File
@@ -24,6 +24,7 @@ function scene(id: string): Scene {
darkenScene: false,
traps: [],
tokens: [],
npcTokens: [],
grid: { enabled: false, type: 'square', sizeN: 0.06, color: '#ffffff' },
media: { videos: [], audios: [] },
settings: { autoplayVideo: false, autoplayAudio: true, loopVideo: true, loopAudio: true },
@@ -10,6 +10,7 @@ import {
asNpcRelationId,
asProjectId,
asSceneId,
asSceneNpcTokenId,
} from '../types/ids';
import { PROJECT_SCHEMA_VERSION } from '../types';
@@ -40,6 +41,7 @@ function scene(id: string, title: string): Scene {
darkenScene: false,
traps: [],
tokens: [],
npcTokens: [],
grid: { enabled: false, type: 'square', sizeN: 0.06, color: '#ffffff' },
media: { videos: [], audios: [] },
settings: { autoplayVideo: false, autoplayAudio: false, loopVideo: false, loopAudio: false },
@@ -242,6 +244,10 @@ void test('selectNpcsByIds / buildPartialExportProject: explicit NPCs, relations
x: 0,
y: 0,
groupId: gChild,
ringColor: '#c9a227',
disposition: 'neutral',
imageOffset: { x: 0, y: 0 },
imageScale: 1,
},
{
id: n2,
@@ -251,6 +257,10 @@ void test('selectNpcsByIds / buildPartialExportProject: explicit NPCs, relations
x: 10,
y: 0,
groupId: gChild,
ringColor: '#c9a227',
disposition: 'neutral',
imageOffset: { x: 0, y: 0 },
imageScale: 1,
},
{
id: n3,
@@ -260,6 +270,10 @@ void test('selectNpcsByIds / buildPartialExportProject: explicit NPCs, relations
x: 20,
y: 0,
groupId: asNpcGroupId('g_other'),
ringColor: '#c9a227',
disposition: 'neutral',
imageOffset: { x: 0, y: 0 },
imageScale: 1,
},
];
const relations: ProjectNpcRelation[] = [
@@ -308,6 +322,142 @@ void test('selectNpcsByIds / buildPartialExportProject: explicit NPCs, relations
assert.ok(!partial.npcGroups.some((g) => g.id === asNpcGroupId('g_other')));
});
void test('buildPartialExportProject: keeps npcTokens only for exported NPCs', () => {
const n1 = asNpcId('npc1');
const n2 = asNpcId('npc2');
const avatar = asAssetId('a1');
const sceneId = asSceneId('s1');
const source = minimalProject({
scenes: {
[sceneId]: {
...scene('s1', 'Start'),
npcTokens: [
{ id: asSceneNpcTokenId('nt1'), npcId: n1, nx: 0.2, ny: 0.3, sizeN: 0.1, disposition: 'neutral' },
{ id: asSceneNpcTokenId('nt2'), npcId: n2, nx: 0.5, ny: 0.5, sizeN: 0.1, disposition: 'hostile' },
{ id: asSceneNpcTokenId('nt3'), npcId: asNpcId('missing'), nx: 0.1, ny: 0.1, sizeN: 0.1, disposition: 'neutral' },
],
},
},
sceneGraphNodes: [node('main', 's1', { isStartScene: true })],
assets: {
[avatar]: {
id: avatar,
type: 'image',
mime: 'image/png',
originalName: 'a.png',
relPath: 'assets/a.png',
sha256: 'abc',
sizeBytes: 1,
createdAt: '2020-01-01T00:00:00.000Z',
},
},
npcs: [
{
id: n1,
name: 'A',
avatarAssetId: avatar,
description: '',
x: 0,
y: 0,
groupId: null,
ringColor: '#c9a227',
disposition: 'neutral',
imageOffset: { x: 0, y: 0 },
imageScale: 1,
},
{
id: n2,
name: 'B',
avatarAssetId: avatar,
description: '',
x: 10,
y: 0,
groupId: null,
ringColor: '#c9a227',
disposition: 'neutral',
imageOffset: { x: 0, y: 0 },
imageScale: 1,
},
],
});
const partial = buildPartialExportProject(source, [{ kind: 'main' }], {
newProjectId: newExportBundleProjectId(),
exportTitle: 'Export',
labels: LABELS,
npcIds: [n1],
});
const tokens = partial.scenes[sceneId]?.npcTokens ?? [];
assert.equal(tokens.length, 1);
assert.equal(tokens[0]!.npcId, n1);
});
void test('mergeStorylinesIntoProject: remaps npcTokens to created NPC ids', () => {
const avatar = asAssetId('a1');
const sourceNpcId = asNpcId('src_npc');
const source = minimalProject({
scenes: {
[asSceneId('s1')]: {
...scene('s1', 'Side'),
npcTokens: [
{ id: asSceneNpcTokenId('nt1'), npcId: sourceNpcId, nx: 0.4, ny: 0.6, sizeN: 0.12, disposition: 'friendly' },
],
},
},
sceneGraphNodes: [node('side', 's1', { isSideStoryStart: true, sideStoryLineTitle: 'Side', x: 0 })],
assets: {
[avatar]: {
id: avatar,
type: 'image',
mime: 'image/png',
originalName: 'a.png',
relPath: 'assets/a.png',
sha256: 'npcsha',
sizeBytes: 1,
createdAt: '2020-01-01T00:00:00.000Z',
},
},
npcs: [
{
id: sourceNpcId,
name: 'Hero',
avatarAssetId: avatar,
description: '',
x: 0,
y: 0,
groupId: null,
ringColor: '#aabbcc',
disposition: 'neutral',
imageOffset: { x: 0.1, y: -0.1 },
imageScale: 1,
},
],
});
const target = minimalProject({
scenes: { [asSceneId('t1')]: scene('t1', 'Existing') },
sceneGraphNodes: [node('tgn', 't1', { x: 0 })],
});
const { project: merged } = mergeStorylinesIntoProject(
target,
source,
[{ kind: 'side', startGraphNodeId: asGraphNodeId('side') }],
[{ sourceSceneId: asSceneId('s1'), mode: 'create' }],
{
graphOffsetX: 200,
npcResolutions: [{ sourceNpcId, mode: 'create' }],
},
);
assert.equal(merged.npcs.length, 1);
const importedScene = Object.values(merged.scenes).find((s) => s.title === 'Side');
assert.ok(importedScene);
assert.equal(importedScene!.npcTokens.length, 1);
assert.equal(importedScene!.npcTokens[0]!.npcId, merged.npcs[0]!.id);
assert.notEqual(importedScene!.npcTokens[0]!.npcId, sourceNpcId);
assert.equal(merged.npcs[0]!.ringColor, '#aabbcc');
});
void test('mergeStorylinesIntoProject: imports all NPCs from export bundle', () => {
const avatar = asAssetId('a1');
const sourceNpcId = asNpcId('src_npc');
@@ -335,6 +485,10 @@ void test('mergeStorylinesIntoProject: imports all NPCs from export bundle', ()
x: 0,
y: 0,
groupId: null,
ringColor: '#c9a227',
disposition: 'neutral',
imageOffset: { x: 0, y: 0 },
imageScale: 1,
},
],
});
+38
View File
@@ -19,6 +19,7 @@ import {
asNpcRelationId,
asProjectId,
asSceneId,
asSceneNpcTokenId,
asTokenId,
} from '../types/ids';
@@ -291,6 +292,15 @@ export function buildPartialExportProject(
npcs: exportedNpcs.map((n) => ({ ...n })),
npcGroups: exportedGroups.map((g) => ({ ...g })),
npcRelations: exportedRelations.map((r) => ({ ...r })),
scenes: Object.fromEntries(
Object.entries(draft.scenes).map(([sid, sc]) => [
sid,
{
...sc,
npcTokens: (sc.npcTokens ?? []).filter((t) => exportedNpcIds.has(t.npcId)),
},
]),
) as Project['scenes'],
};
const assetIds = collectReferencedAssetIdsForProject(draft);
@@ -686,11 +696,39 @@ export function mergeStorylinesIntoProject(
x: n.x,
y: n.y,
groupId: mappedGroupId && npcGroups.some((g) => g.id === mappedGroupId) ? mappedGroupId : null,
ringColor: n.ringColor ?? '#c9a227',
disposition: n.disposition === 'hostile' || n.disposition === 'friendly' ? n.disposition : 'neutral',
imageOffset: n.imageOffset ?? { x: 0, y: 0 },
imageScale: typeof n.imageScale === 'number' && Number.isFinite(n.imageScale) ? n.imageScale : 1,
});
npcNameKeys.add(name.toLowerCase());
npcsCreated += 1;
}
// Remap npcTokens on newly created scenes to imported NPC ids.
for (const sid of sourceSceneIds) {
const res = resolutionBySource.get(sid);
if (res?.mode === 'use') continue;
const newSid = sceneIdMap.get(sid);
if (!newSid) continue;
const sc = scenes[newSid];
if (!sc) continue;
scenes[newSid] = {
...sc,
npcTokens: (sc.npcTokens ?? [])
.map((t) => {
const mappedNpc = npcIdMap.get(t.npcId);
if (!mappedNpc) return null;
return {
...t,
id: asSceneNpcTokenId(`snt_${generateId()}`),
npcId: asNpcId(mappedNpc),
};
})
.filter((t): t is NonNullable<typeof t> => Boolean(t)),
};
}
const npcRelations = [...(target.npcRelations ?? [])];
const exportedNpcIdSet = new Set(exportedNpcs.map((n) => n.id));
for (const r of source.npcRelations ?? []) {
+20
View File
@@ -0,0 +1,20 @@
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 contractsPath = path.join(here, 'contracts.ts');
void test('contracts: players and sceneNpcTokensSession channels exist', () => {
const src = fs.readFileSync(contractsPath, 'utf8');
assert.match(src, /players:\s*\{/);
assert.match(src, /list:\s*'players\.list'/);
assert.match(src, /upsertProgress:\s*'players\.upsertProgress'/);
assert.match(src, /sceneNpcTokensSession:\s*\{/);
assert.match(src, /scenePlayerTokensSession:\s*\{/);
assert.match(src, /tokenGridSnap:\s*\{/);
assert.match(src, /tokenGridSnap\.setEnabled/);
assert.match(src, /npcTokens\?:\s*SceneNpcToken\[\]/);
});
+172 -2
View File
@@ -12,16 +12,28 @@ import type {
NpcId,
NpcRelationId,
NpcGroupId,
NpcDisposition,
NpcsOverlayEvent,
NpcsOverlayState,
Project,
ProjectId,
AppToken,
AppPlayer,
AppPlayerTeam,
PlayerId,
PlayerTeamId,
PlayerImageOffset,
PlayersUpsertProgressEvent,
Scene,
SceneDarknessEvent,
SceneDarknessState,
SceneGrid,
SceneId,
SceneNpcToken,
SceneNpcTokensSessionEvent,
SceneNpcTokensSessionState,
ScenePlayerTokensSessionEvent,
ScenePlayerTokensSessionState,
SceneToken,
SceneTokensSessionEvent,
SceneTokensSessionState,
@@ -31,6 +43,9 @@ import type {
SceneViewEvent,
SceneViewState,
TokenId,
TokenPathSessionEvent,
TokenPathSessionState,
TokenPathTargetKind,
VideoPlaybackEvent,
VideoPlaybackState,
} from '../types';
@@ -135,6 +150,10 @@ export const ipcChannels = {
closeNpcs: 'windows.closeNpcs',
openSceneEditor: 'windows.openSceneEditor',
closeSceneEditor: 'windows.closeSceneEditor',
openTokenPathEditor: 'windows.openTokenPathEditor',
closeTokenPathEditor: 'windows.closeTokenPathEditor',
getTokenPathEditorTarget: 'windows.getTokenPathEditorTarget',
tokenPathEditorTargetChanged: 'windows.tokenPathEditorTargetChanged',
syncChromeTitles: 'windows.syncChromeTitles',
getPresentationContentSize: 'windows.getPresentationContentSize',
presentationContentSizeChanged: 'windows.presentationContentSizeChanged',
@@ -185,6 +204,40 @@ export const ipcChannels = {
dispatch: 'sceneTokensSession.dispatch',
stateChanged: 'sceneTokensSession.stateChanged',
},
tokenPathSession: {
getState: 'tokenPathSession.getState',
dispatch: 'tokenPathSession.dispatch',
stateChanged: 'tokenPathSession.stateChanged',
},
tokenGridSnap: {
getState: 'tokenGridSnap.getState',
setEnabled: 'tokenGridSnap.setEnabled',
stateChanged: 'tokenGridSnap.stateChanged',
},
players: {
list: 'players.list',
upsert: 'players.upsert',
delete: 'players.delete',
setOrder: 'players.setOrder',
upsertTeam: 'players.upsertTeam',
deleteTeam: 'players.deleteTeam',
setTeamsOrder: 'players.setTeamsOrder',
assignTeam: 'players.assignTeam',
pickImage: 'players.pickImage',
imageUrl: 'players.imageUrl',
upsertProgress: 'players.upsertProgress',
stateChanged: 'players.stateChanged',
},
sceneNpcTokensSession: {
getState: 'sceneNpcTokensSession.getState',
dispatch: 'sceneNpcTokensSession.dispatch',
stateChanged: 'sceneNpcTokensSession.stateChanged',
},
scenePlayerTokensSession: {
getState: 'scenePlayerTokensSession.getState',
dispatch: 'scenePlayerTokensSession.dispatch',
stateChanged: 'scenePlayerTokensSession.stateChanged',
},
video: {
getState: 'video.getState',
dispatch: 'video.dispatch',
@@ -257,6 +310,16 @@ export type IpcEventMap = {
[ipcChannels.sceneView.stateChanged]: { state: SceneViewState };
[ipcChannels.tokens.stateChanged]: { tokens: AppToken[] };
[ipcChannels.sceneTokensSession.stateChanged]: { state: SceneTokensSessionState };
[ipcChannels.tokenPathSession.stateChanged]: { state: TokenPathSessionState };
[ipcChannels.windows.tokenPathEditorTargetChanged]: {
kind: TokenPathTargetKind;
placementId: string;
} | null;
[ipcChannels.tokenGridSnap.stateChanged]: { enabled: boolean };
[ipcChannels.players.stateChanged]: { players: AppPlayer[]; teams: AppPlayerTeam[] };
[ipcChannels.players.upsertProgress]: PlayersUpsertProgressEvent;
[ipcChannels.sceneNpcTokensSession.stateChanged]: { state: SceneNpcTokensSessionState };
[ipcChannels.scenePlayerTokensSession.stateChanged]: { state: ScenePlayerTokensSessionState };
[ipcChannels.video.stateChanged]: { state: VideoPlaybackState };
[ipcChannels.license.statusChanged]: { snapshot: LicenseSnapshot };
[ipcChannels.windows.multiWindowStateChanged]: { open: boolean };
@@ -372,6 +435,10 @@ export type IpcInvokeMap = {
description?: string;
filePath?: string;
groupId?: NpcGroupId | null;
ringColor?: string;
disposition?: NpcDisposition;
imageOffset?: PlayerImageOffset;
imageScale?: number;
};
res: { project: Project };
};
@@ -381,6 +448,10 @@ export type IpcInvokeMap = {
name?: string;
description?: string;
groupId?: NpcGroupId | null;
ringColor?: string;
disposition?: NpcDisposition;
imageOffset?: PlayerImageOffset;
imageScale?: number;
};
res: { project: Project };
};
@@ -577,7 +648,7 @@ export type IpcInvokeMap = {
res: { ok: true };
};
[ipcChannels.windows.openMultiWindow]: {
req: Record<string, never>;
req: { playerIds?: string[] };
res: { ok: true };
};
[ipcChannels.windows.closeMultiWindow]: {
@@ -625,7 +696,7 @@ export type IpcInvokeMap = {
res: { ok: true };
};
[ipcChannels.windows.openNpcs]: {
req: Record<string, never>;
req: { npcId?: NpcId | null };
res: { ok: true };
};
[ipcChannels.windows.closeNpcs]: {
@@ -640,6 +711,18 @@ export type IpcInvokeMap = {
req: Record<string, never>;
res: { ok: true };
};
[ipcChannels.windows.openTokenPathEditor]: {
req: { kind: TokenPathTargetKind; placementId: string };
res: { ok: true };
};
[ipcChannels.windows.closeTokenPathEditor]: {
req: Record<string, never>;
res: { ok: true };
};
[ipcChannels.windows.getTokenPathEditorTarget]: {
req: Record<string, never>;
res: { kind: TokenPathTargetKind; placementId: string } | null;
};
[ipcChannels.windows.syncChromeTitles]: {
req: { localeTag: string };
res: { ok: true };
@@ -720,6 +803,86 @@ export type IpcInvokeMap = {
req: { event: SceneTokensSessionEvent };
res: { ok: true };
};
[ipcChannels.tokenPathSession.getState]: {
req: Record<string, never>;
res: { state: TokenPathSessionState };
};
[ipcChannels.tokenPathSession.dispatch]: {
req: { event: TokenPathSessionEvent };
res: { ok: true };
};
[ipcChannels.tokenGridSnap.getState]: {
req: Record<string, never>;
res: { enabled: boolean };
};
[ipcChannels.tokenGridSnap.setEnabled]: {
req: { enabled: boolean };
res: { enabled: boolean };
};
[ipcChannels.players.list]: {
req: Record<string, never>;
res: { players: AppPlayer[]; teams: AppPlayerTeam[] };
};
[ipcChannels.players.upsert]: {
req: {
id?: PlayerId | null;
name: string;
filePath?: string | null;
teamId?: PlayerTeamId | null;
ringColor?: string;
imageOffset?: PlayerImageOffset;
imageScale?: number;
};
res: { player: AppPlayer };
};
[ipcChannels.players.delete]: {
req: { id: PlayerId };
res: { ok: true };
};
[ipcChannels.players.setOrder]: {
req: { playerIds: PlayerId[] };
res: { players: AppPlayer[] };
};
[ipcChannels.players.upsertTeam]: {
req: { id?: PlayerTeamId | null; name: string; color?: string };
res: { team: AppPlayerTeam };
};
[ipcChannels.players.deleteTeam]: {
req: { id: PlayerTeamId };
res: { ok: true };
};
[ipcChannels.players.setTeamsOrder]: {
req: { teamIds: PlayerTeamId[] };
res: { teams: AppPlayerTeam[] };
};
[ipcChannels.players.assignTeam]: {
req: { playerId: PlayerId; teamId: PlayerTeamId | null };
res: { player: AppPlayer | null };
};
[ipcChannels.players.pickImage]: {
req: Record<string, never>;
res: { canceled: true } | { canceled: false; filePath: string; previewDataUrl: string };
};
[ipcChannels.players.imageUrl]: {
req: { id: PlayerId };
res: { url: string | null };
};
[ipcChannels.sceneNpcTokensSession.getState]: {
req: Record<string, never>;
res: { state: SceneNpcTokensSessionState };
};
[ipcChannels.sceneNpcTokensSession.dispatch]: {
req: { event: SceneNpcTokensSessionEvent };
res: { ok: true };
};
[ipcChannels.scenePlayerTokensSession.getState]: {
req: Record<string, never>;
res: { state: ScenePlayerTokensSessionState };
};
[ipcChannels.scenePlayerTokensSession.dispatch]: {
req: { event: ScenePlayerTokensSessionEvent };
res: { ok: true };
};
[ipcChannels.video.getState]: {
req: Record<string, never>;
res: { state: VideoPlaybackState };
@@ -761,6 +924,12 @@ export type LegacyIpcEventMap = {
[ipcChannels.sceneView.stateChanged]: { state: SceneViewState };
[ipcChannels.tokens.stateChanged]: { tokens: AppToken[] };
[ipcChannels.sceneTokensSession.stateChanged]: { state: SceneTokensSessionState };
[ipcChannels.tokenPathSession.stateChanged]: { state: TokenPathSessionState };
[ipcChannels.tokenGridSnap.stateChanged]: { enabled: boolean };
[ipcChannels.players.stateChanged]: { players: AppPlayer[]; teams: AppPlayerTeam[] };
[ipcChannels.players.upsertProgress]: PlayersUpsertProgressEvent;
[ipcChannels.sceneNpcTokensSession.stateChanged]: { state: SceneNpcTokensSessionState };
[ipcChannels.scenePlayerTokensSession.stateChanged]: { state: ScenePlayerTokensSessionState };
[ipcChannels.video.stateChanged]: { state: VideoPlaybackState };
[ipcChannels.license.statusChanged]: Record<string, never>;
};
@@ -776,6 +945,7 @@ export type ScenePatch = {
darkenScene?: boolean;
traps?: SceneTrap[];
tokens?: SceneToken[];
npcTokens?: SceneNpcToken[];
grid?: SceneGrid;
settings?: Partial<Scene['settings']>;
media?: Partial<Scene['media']>;
@@ -0,0 +1,43 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { asPlayerId, asPlayerTeamId } from '../types/ids';
import { layoutPlayerTokensBottom } from '../types/appPlayers';
import { resolveLaunchPlayerIds } from './resolveLaunchPlayerIds';
void test('layoutPlayerTokensBottom spaces tokens along bottom', () => {
const layout = layoutPlayerTokensBottom(['a', 'b', 'c'], 0.1);
assert.equal(layout.a?.ny, 0.88);
assert.equal(layout.a?.nx, 0.25);
assert.equal(layout.b?.nx, 0.5);
assert.equal(layout.c?.nx, 0.75);
});
void test('resolveLaunchPlayerIds merges players and teams with dedupe', () => {
const teamId = asPlayerTeamId('t1');
const players = [
{
id: asPlayerId('p1'),
name: 'A',
imageRelPath: 'x',
sha256: '1',
teamId,
ringColor: '#fff',
imageOffset: { x: 0, y: 0 },
imageScale: 1,
},
{
id: asPlayerId('p2'),
name: 'B',
imageRelPath: 'y',
sha256: '2',
teamId: null,
ringColor: '#fff',
imageOffset: { x: 0, y: 0 },
imageScale: 1,
},
];
const ids = resolveLaunchPlayerIds(players, new Set(['p1', 'p2']), new Set(['t1']));
assert.deepEqual([...ids].sort(), ['p1', 'p2']);
});
+62
View File
@@ -0,0 +1,62 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
assignPlayerToTeam,
createPlayerTeamDraft,
deletePlayerTeam,
normalizeAppPlayerTeams,
uniquePlayerTeamName,
} from './playerTeams';
import type { AppPlayer, AppPlayerTeam } from '../types/appPlayers';
import { asPlayerId, asPlayerTeamId } from '../types/ids';
void test('uniquePlayerTeamName appends suffix on collision', () => {
const teams: AppPlayerTeam[] = [
{ id: asPlayerTeamId('t1'), name: 'Alpha', color: '#ffffff' },
];
assert.equal(uniquePlayerTeamName('Alpha', teams), 'Alpha (2)');
assert.equal(uniquePlayerTeamName('Beta', teams), 'Beta');
});
void test('normalizeAppPlayerTeams drops invalid and duplicates', () => {
const teams = normalizeAppPlayerTeams([
{ id: 't1', name: 'A', color: '#abc' },
{ id: 't1', name: 'Dup', color: '#ffffff' },
{ id: '', name: 'Bad', color: '#ffffff' },
null,
{ id: 't2', name: 'B', color: '#112233' },
]);
assert.equal(teams.length, 2);
assert.equal(teams[0]!.id, 't1');
assert.equal(teams[0]!.color, '#aabbcc'); // #abc → expanded
assert.equal(teams[1]!.color, '#112233');
});
void test('createPlayerTeamDraft has no parentId field', () => {
const team = createPlayerTeamDraft('Team', '#ff0000', []);
assert.equal(team.name, 'Team');
assert.ok(!('parentId' in team));
});
void test('assignPlayerToTeam and deletePlayerTeam ungroup players', () => {
const t1 = asPlayerTeamId('t1');
const players: AppPlayer[] = [
{
id: asPlayerId('p1'),
name: 'P',
imageRelPath: 'files/a.png',
sha256: 'x',
teamId: t1,
ringColor: '#c9a227',
imageOffset: { x: 0, y: 0 },
imageScale: 1,
},
];
const teams: AppPlayerTeam[] = [{ id: t1, name: 'T', color: '#ffffff' }];
const assigned = assignPlayerToTeam(players, 'p1', null, new Set([t1]));
assert.equal(assigned[0]!.teamId, null);
const del = deletePlayerTeam(teams, players, t1);
assert.equal(del.teams.length, 0);
assert.equal(del.players[0]!.teamId, null);
});
+71
View File
@@ -0,0 +1,71 @@
import type { AppPlayer, AppPlayerTeam, PlayerTeamId } from '../types/appPlayers';
import { asPlayerTeamId } from '../types/ids';
import { DEFAULT_PLAYER_RING_COLOR, normalizeAppPlayerTeam } from '../types/appPlayers';
import { normalizeHexColor } from '../npcs/npcGroups';
/** Имя команды уникально среди плоского списка (без вложенности). */
export function uniquePlayerTeamName(
base: string,
teams: readonly AppPlayerTeam[],
exceptId?: PlayerTeamId | null,
): string {
const root = base.trim() || 'Team';
const used = new Set(
teams.filter((t) => t.id !== exceptId).map((t) => t.name.trim().toLowerCase()),
);
if (!used.has(root.toLowerCase())) return root;
let i = 2;
while (used.has(`${root.toLowerCase()} (${String(i)})`)) i += 1;
return `${root} (${String(i)})`;
}
export function normalizeAppPlayerTeams(raw: unknown): AppPlayerTeam[] {
if (!Array.isArray(raw)) return [];
const out: AppPlayerTeam[] = [];
const ids = new Set<string>();
for (const item of raw) {
const t = normalizeAppPlayerTeam(item);
if (!t || ids.has(t.id)) continue;
ids.add(t.id);
out.push(t);
}
return out;
}
export function assignPlayerToTeam(
players: readonly AppPlayer[],
playerId: string,
teamId: PlayerTeamId | null,
teamIds: Set<string>,
): AppPlayer[] {
return players.map((p) => {
if (p.id !== playerId) return p;
if (teamId && !teamIds.has(teamId)) return { ...p, teamId: null };
return { ...p, teamId };
});
}
/** Удаление команды: игроки этой команды становятся без команды. */
export function deletePlayerTeam(
teams: readonly AppPlayerTeam[],
players: readonly AppPlayer[],
teamId: PlayerTeamId,
): { teams: AppPlayerTeam[]; players: AppPlayer[] } {
return {
teams: teams.filter((t) => t.id !== teamId),
players: players.map((p) => (p.teamId === teamId ? { ...p, teamId: null } : p)),
};
}
export function createPlayerTeamDraft(
name: string,
color: string | undefined,
teams: readonly AppPlayerTeam[],
): AppPlayerTeam {
const id = asPlayerTeamId(`pteam_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`);
return {
id,
name: uniquePlayerTeamName(name, teams),
color: normalizeHexColor(color, DEFAULT_PLAYER_RING_COLOR),
};
}
@@ -0,0 +1,15 @@
import type { AppPlayer } from '../types';
/** Игроки + члены выбранных команд, без дублей. */
export function resolveLaunchPlayerIds(
players: readonly AppPlayer[],
selectedPlayerIds: ReadonlySet<string>,
selectedTeamIds: ReadonlySet<string>,
): string[] {
const out = new Set<string>();
for (const id of selectedPlayerIds) out.add(id);
for (const p of players) {
if (p.teamId && selectedTeamIds.has(String(p.teamId))) out.add(String(p.id));
}
return [...out];
}
+73
View File
@@ -0,0 +1,73 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
clampPlayerImageOffset,
clampPlayerImageScale,
DEFAULT_PLAYER_IMAGE_SCALE,
DEFAULT_PLAYER_RING_COLOR,
normalizeAppPlayer,
normalizeSceneNpcToken,
PLAYER_IMAGE_OFFSET_MAX,
PLAYER_IMAGE_SCALE_MAX,
PLAYER_IMAGE_SCALE_MIN,
} from './appPlayers';
import { asNpcId, asSceneNpcTokenId } from './ids';
void test('clampPlayerImageOffset clamps and defaults', () => {
assert.deepEqual(clampPlayerImageOffset(null), { x: 0, y: 0 });
assert.deepEqual(clampPlayerImageOffset({ x: 99, y: -99 }), {
x: PLAYER_IMAGE_OFFSET_MAX,
y: -PLAYER_IMAGE_OFFSET_MAX,
});
});
void test('clampPlayerImageScale clamps and defaults', () => {
assert.equal(clampPlayerImageScale(null), DEFAULT_PLAYER_IMAGE_SCALE);
assert.equal(clampPlayerImageScale(0.1), PLAYER_IMAGE_SCALE_MIN);
assert.equal(clampPlayerImageScale(9), PLAYER_IMAGE_SCALE_MAX);
});
void test('normalizeAppPlayer fills ringColor and offset', () => {
const p = normalizeAppPlayer({
id: 'player_1',
name: 'Ada',
imageRelPath: 'files/a.png',
sha256: 'abc',
});
assert.ok(p);
assert.equal(p!.ringColor, DEFAULT_PLAYER_RING_COLOR);
assert.deepEqual(p!.imageOffset, { x: 0, y: 0 });
assert.equal(p!.imageScale, DEFAULT_PLAYER_IMAGE_SCALE);
assert.equal(p!.teamId, null);
});
void test('normalizeAppPlayer drops unknown teamId when set provided', () => {
const p = normalizeAppPlayer(
{
id: 'player_1',
name: 'Ada',
imageRelPath: 'files/a.png',
sha256: 'abc',
teamId: 'missing',
},
new Set(['other']),
);
assert.equal(p!.teamId, null);
});
void test('normalizeSceneNpcToken validates and clamps', () => {
const t = normalizeSceneNpcToken({
id: 'snt_1',
npcId: 'npc_1',
nx: 1.5,
ny: -0.2,
sizeN: 0.2,
});
assert.ok(t);
assert.equal(t!.id, asSceneNpcTokenId('snt_1'));
assert.equal(t!.npcId, asNpcId('npc_1'));
assert.equal(t!.nx, 1);
assert.equal(t!.ny, 0);
assert.equal(normalizeSceneNpcToken({ id: 'x' }), null);
});
+218
View File
@@ -0,0 +1,218 @@
/** App-local библиотека живых игроков (userData, не в project zip). */
import type { NpcDisposition } from './npcDisposition';
import { normalizeNpcDisposition } from './npcDisposition';
import type { NpcId, PlayerId, PlayerTeamId, SceneNpcTokenId } from './ids';
import { asNpcId, asPlayerId, asPlayerTeamId, asSceneNpcTokenId } from './ids';
import { normalizeHexColor } from '../npcs/npcGroups';
import { normalizeTokenPath, type TokenPath } from './tokenPath';
export type { PlayerId, PlayerTeamId, SceneNpcTokenId };
export { asPlayerId, asPlayerTeamId, asSceneNpcTokenId };
export type PlayerImageOffset = { x: number; y: number };
/** Плоская команда игроков (без вложенности). */
export type AppPlayerTeam = {
id: PlayerTeamId;
name: string;
/** Hex `#rrggbb`. */
color: string;
};
export type AppPlayer = {
id: PlayerId;
name: string;
/** Относительный путь файла в каталоге `userData/players/`. */
imageRelPath: string;
sha256: string;
teamId: PlayerTeamId | null;
ringColor: string;
imageOffset: PlayerImageOffset;
/** Масштаб аватара внутри круга (1 = по умолчанию). */
imageScale: number;
};
/** Расстановка кампанийного НПС на карте как игрового токена (в проекте). */
export type SceneNpcToken = {
id: SceneNpcTokenId;
npcId: NpcId;
nx: number;
ny: number;
sizeN: number;
/** Состояние экземпляра на карте (копируется из НПС при постановке). */
disposition: NpcDisposition;
/** Optional movement path (editor → session playback). */
path?: TokenPath | null;
};
export const DEFAULT_PLAYER_RING_COLOR = '#c9a227';
export const DEFAULT_PLAYER_IMAGE_OFFSET: PlayerImageOffset = { x: 0, y: 0 };
export const PLAYER_IMAGE_OFFSET_MIN = -0.45;
export const PLAYER_IMAGE_OFFSET_MAX = 0.45;
export const DEFAULT_PLAYER_IMAGE_SCALE = 1;
export const PLAYER_IMAGE_SCALE_MIN = 0.5;
export const PLAYER_IMAGE_SCALE_MAX = 3;
export const PLAYER_IMAGE_SCALE_STEP = 0.08;
export const DEFAULT_SCENE_NPC_TOKEN_SIZE_N = 0.1;
export const SCENE_NPC_TOKEN_SIZE_MIN = 0.04;
export const SCENE_NPC_TOKEN_SIZE_MAX = 0.45;
/** Множитель размера всех НПС-токенов на пульте/презентации (session-only). */
export const DEFAULT_NPC_TOKEN_SESSION_SCALE = 1;
export const NPC_TOKEN_SESSION_SCALE_MIN = 0.4;
export const NPC_TOKEN_SESSION_SCALE_MAX = 2.5;
export type SceneNpcTokensSessionPlacement = {
/** Есть после move; без move позиция берётся из сцены. */
nx?: number;
ny?: number;
/** Session-only override типа экземпляра. */
disposition?: NpcDisposition;
/** Session-only: серая рамка и grayscale. */
inactive?: boolean;
};
export type SceneNpcTokensSessionState = {
revision: number;
byPlacementId: Record<string, SceneNpcTokensSessionPlacement>;
/** Общий масштаб отображения всех НПС-токенов (не пишется в проект). */
scale: number;
};
export type SceneNpcTokensSessionEvent =
| { kind: 'move'; placementId: string; nx: number; ny: number }
| { kind: 'setDisposition'; placementId: string; disposition: NpcDisposition }
| { kind: 'setInactive'; placementId: string; inactive: boolean }
| { kind: 'setScale'; scale: number }
| { kind: 'clear' };
/** Session-only токены живых игроков на карте во время показа. */
export type ScenePlayerTokenPlacement = { nx: number; ny: number; sizeN: number };
export type ScenePlayerTokensSessionState = {
revision: number;
selectedPlayerIds: string[];
visible: boolean;
byPlayerId: Record<string, ScenePlayerTokenPlacement>;
};
export type ScenePlayerTokensSessionEvent =
| { kind: 'setSelection'; playerIds: readonly string[] }
| { kind: 'setVisible'; visible: boolean }
| { kind: 'show'; sizeN: number }
| { kind: 'seedBottom'; sizeN: number }
| { kind: 'move'; playerId: string; nx: number; ny: number }
| { kind: 'clearPlacements' }
| { kind: 'clear' };
export function clampNpcTokenSessionScale(raw: unknown): number {
const n = typeof raw === 'number' && Number.isFinite(raw) ? raw : DEFAULT_NPC_TOKEN_SESSION_SCALE;
return Math.max(NPC_TOKEN_SESSION_SCALE_MIN, Math.min(NPC_TOKEN_SESSION_SCALE_MAX, n));
}
/** Ряд токенов внизу карты (первый показ «Показать игроков»). */
export function layoutPlayerTokensBottom(
playerIds: readonly string[],
sizeN: number,
): Record<string, ScenePlayerTokenPlacement> {
const clamped = clampSceneNpcTokenSizeN(sizeN);
const n = playerIds.length;
const out: Record<string, ScenePlayerTokenPlacement> = {};
const ny = 0.88;
for (let i = 0; i < n; i += 1) {
const id = playerIds[i];
if (!id) continue;
out[id] = { nx: (i + 1) / (n + 1), ny, sizeN: clamped };
}
return out;
}
export type PlayersUpsertProgressEvent = {
percent: number;
stage: string;
detail?: string;
};
export function clampPlayerImageOffset(raw: unknown): PlayerImageOffset {
if (!raw || typeof raw !== 'object') return { ...DEFAULT_PLAYER_IMAGE_OFFSET };
const obj = raw as { x?: unknown; y?: unknown };
const x = typeof obj.x === 'number' && Number.isFinite(obj.x) ? obj.x : 0;
const y = typeof obj.y === 'number' && Number.isFinite(obj.y) ? obj.y : 0;
return {
x: Math.max(PLAYER_IMAGE_OFFSET_MIN, Math.min(PLAYER_IMAGE_OFFSET_MAX, x)),
y: Math.max(PLAYER_IMAGE_OFFSET_MIN, Math.min(PLAYER_IMAGE_OFFSET_MAX, y)),
};
}
export function clampPlayerImageScale(raw: unknown): number {
const n = typeof raw === 'number' && Number.isFinite(raw) ? raw : DEFAULT_PLAYER_IMAGE_SCALE;
return Math.max(PLAYER_IMAGE_SCALE_MIN, Math.min(PLAYER_IMAGE_SCALE_MAX, n));
}
export function clampSceneNpcTokenSizeN(sizeN: number): number {
if (!Number.isFinite(sizeN)) return DEFAULT_SCENE_NPC_TOKEN_SIZE_N;
return Math.max(SCENE_NPC_TOKEN_SIZE_MIN, Math.min(SCENE_NPC_TOKEN_SIZE_MAX, sizeN));
}
export function normalizeAppPlayerTeam(raw: unknown): AppPlayerTeam | null {
if (!raw || typeof raw !== 'object') return null;
const obj = raw as Partial<AppPlayerTeam>;
if (typeof obj.id !== 'string' || !obj.id) return null;
if (typeof obj.name !== 'string') return null;
const name = obj.name.trim();
if (!name) return null;
return {
id: asPlayerTeamId(obj.id),
name,
color: normalizeHexColor(obj.color, DEFAULT_PLAYER_RING_COLOR),
};
}
export function normalizeAppPlayer(raw: unknown, teamIds?: Set<string>): AppPlayer | null {
if (!raw || typeof raw !== 'object') return null;
const obj = raw as Partial<AppPlayer> & { teamId?: string | null };
if (typeof obj.id !== 'string' || !obj.id) return null;
if (typeof obj.name !== 'string') return null;
const name = obj.name.trim();
if (!name) return null;
if (typeof obj.imageRelPath !== 'string' || !obj.imageRelPath) return null;
if (typeof obj.sha256 !== 'string' || !obj.sha256) return null;
let teamId: PlayerTeamId | null = null;
if (typeof obj.teamId === 'string' && obj.teamId) {
if (!teamIds || teamIds.has(obj.teamId)) teamId = asPlayerTeamId(obj.teamId);
}
return {
id: asPlayerId(obj.id),
name,
imageRelPath: obj.imageRelPath,
sha256: obj.sha256,
teamId,
ringColor: normalizeHexColor(obj.ringColor, DEFAULT_PLAYER_RING_COLOR),
imageOffset: clampPlayerImageOffset(obj.imageOffset),
imageScale: clampPlayerImageScale((obj as { imageScale?: unknown }).imageScale),
};
}
export function normalizeSceneNpcToken(raw: unknown): SceneNpcToken | null {
if (!raw || typeof raw !== 'object') return null;
const obj = raw as Partial<SceneNpcToken>;
if (typeof obj.id !== 'string' || !obj.id) return null;
if (typeof obj.npcId !== 'string' || !obj.npcId) return null;
const nx = typeof obj.nx === 'number' && Number.isFinite(obj.nx) ? obj.nx : null;
const ny = typeof obj.ny === 'number' && Number.isFinite(obj.ny) ? obj.ny : null;
if (nx === null || ny === null) return null;
return {
id: asSceneNpcTokenId(obj.id),
npcId: asNpcId(obj.npcId),
nx: Math.max(0, Math.min(1, nx)),
ny: Math.max(0, Math.min(1, ny)),
sizeN: clampSceneNpcTokenSizeN(typeof obj.sizeN === 'number' ? obj.sizeN : DEFAULT_SCENE_NPC_TOKEN_SIZE_N),
disposition: normalizeNpcDisposition((obj as { disposition?: unknown }).disposition),
...(() => {
const path = normalizeTokenPath((obj as { path?: unknown }).path);
return path ? { path } : {};
})(),
};
}
+5
View File
@@ -2,6 +2,7 @@
import type { SceneTokenId, TokenId } from './ids';
import { asSceneTokenId, asTokenId } from './ids';
import { normalizeTokenPath, type TokenPath } from './tokenPath';
export type { SceneTokenId, TokenId };
export { asSceneTokenId, asTokenId };
@@ -24,6 +25,8 @@ export type SceneToken = {
sizeN: number;
/** Непрерывный угол поворота в градусах. */
rotationDeg: number;
/** Optional movement path (editor → session playback). */
path?: TokenPath | null;
};
export const DEFAULT_SCENE_TOKEN_SIZE_N = 0.08;
@@ -56,6 +59,7 @@ export function normalizeSceneToken(raw: unknown): SceneToken | null {
const sizeN = clampSceneTokenSizeN(typeof obj.sizeN === 'number' ? obj.sizeN : DEFAULT_SCENE_TOKEN_SIZE_N);
const rotationDeg =
typeof obj.rotationDeg === 'number' && Number.isFinite(obj.rotationDeg) ? obj.rotationDeg : 0;
const path = normalizeTokenPath((obj as { path?: unknown }).path);
return {
id: asSceneTokenId(obj.id),
tokenId: asTokenId(obj.tokenId),
@@ -63,6 +67,7 @@ export function normalizeSceneToken(raw: unknown): SceneToken | null {
ny: Math.max(0, Math.min(1, ny)),
sizeN,
rotationDeg,
...(path ? { path } : {}),
};
}
+64
View File
@@ -0,0 +1,64 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { containMediaLayout, 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);
});
void test('containMediaLayout: 90° swaps fit axes and element stays unrotated size', () => {
const layout = containMediaLayout({
hostW: 400,
hostH: 400,
mediaW: 1920,
mediaH: 1080,
scale: 1,
ox: 0.5,
oy: 0.5,
rotationDeg: 90,
});
assert.ok(layout);
// After 90°, layout AABB is portrait 1080x1920 fitted into square → height fills.
assert.ok(Math.abs(layout!.contentRect.h - 400) < 0.01);
assert.ok(Math.abs(layout!.contentRect.w - (400 * 1080) / 1920) < 0.01);
assert.ok(Math.abs(layout!.elementW - layout!.contentRect.h) < 0.01);
assert.ok(Math.abs(layout!.elementH - layout!.contentRect.w) < 0.01);
});
+74
View File
@@ -0,0 +1,74 @@
/**
* Pure layout math shared by ContainedVideo / RotatedImage contain-mode.
* Kept free of DOM so unit tests can lock overlay alignment for video scenes.
*/
export type MediaRotationDeg = 0 | 90 | 180 | 270;
export type ContainMediaRect = { x: number; y: number; w: number; h: number };
export type ContainMediaLayout = {
/** Bounding box of the visible media after rotation (overlay coordinate space). */
contentRect: ContainMediaRect;
/** Unrotated element size; apply CSS rotate(rotationDeg) on the media node. */
elementW: number;
elementH: number;
};
export function containMediaLayout(args: {
hostW: number;
hostH: number;
mediaW: number;
mediaH: number;
scale: number;
ox: number;
oy: number;
rotationDeg?: MediaRotationDeg;
mode?: 'contain' | 'cover';
}): ContainMediaLayout | null {
const {
hostW,
hostH,
mediaW,
mediaH,
scale,
ox,
oy,
rotationDeg = 0,
mode = 'contain',
} = args;
if (hostW <= 1 || hostH <= 1 || mediaW <= 0 || mediaH <= 0) return null;
const rotated = rotationDeg === 90 || rotationDeg === 270;
const layoutW = rotated ? mediaH : mediaW;
const layoutH = rotated ? mediaW : mediaH;
const sx = hostW / layoutW;
const sy = hostH / layoutH;
const fit = mode === 'cover' ? Math.max(sx, sy) : Math.min(sx, sy);
const s = fit * Math.max(1, scale);
const w = layoutW * s;
const h = layoutH * s;
return {
contentRect: {
x: hostW / 2 - ox * w,
y: hostH / 2 - oy * h,
w,
h,
},
elementW: mediaW * s,
elementH: mediaH * s,
};
}
export function containMediaRect(args: {
hostW: number;
hostH: number;
mediaW: number;
mediaH: number;
scale: number;
ox: number;
oy: number;
rotationDeg?: MediaRotationDeg;
mode?: 'contain' | 'cover';
}): ContainMediaRect | null {
return containMediaLayout(args)?.contentRect ?? null;
}
+15 -1
View File
@@ -10,10 +10,12 @@ import type {
} from './ids';
import type { MaterialLegend } from './materialLegend';
import type { SceneToken } from './appTokens';
import type { SceneNpcToken, PlayerImageOffset } from './appPlayers';
import type { NpcDisposition } from './npcDisposition';
import type { SceneGrid } from './sceneGrid';
import type { SceneTrap } from './sceneTraps';
export const PROJECT_SCHEMA_VERSION = 10 as const;
export const PROJECT_SCHEMA_VERSION = 11 as const;
/** Материал кампании: изображение, показываемое поверх сцены во время игры. */
export type ProjectMaterial = {
@@ -46,6 +48,16 @@ export type ProjectNpc = {
y: number;
/** `null` — системная секция «Без группы». */
groupId: NpcGroupId | null;
/**
* @deprecated Цвет кольца выводится из `disposition`. Поле оставлено для совместимости старых проектов.
*/
ringColor: string;
/** Дефолтный тип токена при постановке на карту. */
disposition: NpcDisposition;
/** Сдвиг аватара внутри круга токена. */
imageOffset: PlayerImageOffset;
/** Масштаб аватара внутри круга токена. */
imageScale: number;
};
/** Однонаправленная связь: от `sourceNpcId` к `targetNpcId`; подпись на линии. */
@@ -154,6 +166,8 @@ export type Scene = {
traps: SceneTrap[];
/** Неигровые токены на карте (ссылки на app-local пул). */
tokens: SceneToken[];
/** Кампанийные НПС на карте как игровые токены (отдельно от неигровых). */
npcTokens: SceneNpcToken[];
/** Боевая сетка поверх превью (под ловушками/эффектами). */
grid: SceneGrid;
media: SceneMediaRefs;
+15
View File
@@ -10,6 +10,9 @@ export type NpcRelationId = Brand<string, 'NpcRelationId'>;
export type NpcGroupId = Brand<string, 'NpcGroupId'>;
export type TokenId = Brand<string, 'TokenId'>;
export type SceneTokenId = Brand<string, 'SceneTokenId'>;
export type PlayerId = Brand<string, 'PlayerId'>;
export type PlayerTeamId = Brand<string, 'PlayerTeamId'>;
export type SceneNpcTokenId = Brand<string, 'SceneNpcTokenId'>;
export function asProjectId(value: string): ProjectId {
return value as ProjectId;
@@ -50,3 +53,15 @@ export function asTokenId(value: string): TokenId {
export function asSceneTokenId(value: string): SceneTokenId {
return value as SceneTokenId;
}
export function asPlayerId(value: string): PlayerId {
return value as PlayerId;
}
export function asPlayerTeamId(value: string): PlayerTeamId {
return value as PlayerTeamId;
}
export function asSceneNpcTokenId(value: string): SceneNpcTokenId {
return value as SceneNpcTokenId;
}
+7
View File
@@ -1,12 +1,19 @@
export * from './appPlayers';
export * from './appTokens';
export * from './domain';
export * from './effects';
export * from './ids';
export * from './materialLegend';
export * from './materials';
export * from './npcDisposition';
export * from './npcs';
export * from './sceneDarkness';
export * from './sceneGrid';
export * from './sceneGridSnap';
export * from './tokenPath';
export * from './tokenPathSession';
export * from './tokenPathPlayback';
export * from './scenePreviewRotation';
export * from './sceneTraps';
export * from './sceneView';
export * from './videoPlayback';
+28
View File
@@ -0,0 +1,28 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
DEFAULT_NPC_DISPOSITION,
normalizeNpcDisposition,
npcDispositionRingColor,
otherNpcDispositions,
} from './npcDisposition';
void test('normalizeNpcDisposition defaults to neutral', () => {
assert.equal(normalizeNpcDisposition(undefined), DEFAULT_NPC_DISPOSITION);
assert.equal(normalizeNpcDisposition('hostile'), 'hostile');
assert.equal(normalizeNpcDisposition('friendly'), 'friendly');
assert.equal(normalizeNpcDisposition('nope'), 'neutral');
});
void test('npcDispositionRingColor and inactive', () => {
assert.equal(npcDispositionRingColor('hostile'), '#e53935');
assert.equal(npcDispositionRingColor('neutral'), '#c9a227');
assert.equal(npcDispositionRingColor('friendly'), '#43a047');
assert.equal(npcDispositionRingColor('hostile', true), '#9e9e9e');
});
void test('otherNpcDispositions hides current', () => {
assert.deepEqual(otherNpcDispositions('neutral'), ['hostile', 'friendly']);
assert.deepEqual(otherNpcDispositions('hostile'), ['neutral', 'friendly']);
});
+29
View File
@@ -0,0 +1,29 @@
/** Отношение НПС: задаёт цвет кольца токена. */
export const NPC_DISPOSITIONS = ['hostile', 'neutral', 'friendly'] as const;
export type NpcDisposition = (typeof NPC_DISPOSITIONS)[number];
export const DEFAULT_NPC_DISPOSITION: NpcDisposition = 'neutral';
export const NPC_DISPOSITION_RING_COLOR: Record<NpcDisposition, string> = {
hostile: '#e53935',
neutral: '#c9a227',
friendly: '#43a047',
};
/** Серый для session-only «Неактивен». */
export const NPC_INACTIVE_RING_COLOR = '#9e9e9e';
export function normalizeNpcDisposition(raw: unknown): NpcDisposition {
if (raw === 'hostile' || raw === 'friendly' || raw === 'neutral') return raw;
return DEFAULT_NPC_DISPOSITION;
}
export function npcDispositionRingColor(disposition: NpcDisposition, inactive = false): string {
if (inactive) return NPC_INACTIVE_RING_COLOR;
return NPC_DISPOSITION_RING_COLOR[disposition];
}
export function otherNpcDispositions(current: NpcDisposition): NpcDisposition[] {
return NPC_DISPOSITIONS.filter((d) => d !== current);
}

Some files were not shown because too many files have changed in this diff Show More