Редактор: превью с поворотом, проекты, безопасное сохранение zip, dev-меню

RotatedImage: размер контейнера через clientWidth/Height (не getBoundingClientRect), чтобы cover при 90°/270° работал под zoom React Flow; убраны отладочные логи.

Главное меню в dev: пункт «Вид» с DevTools (Ctrl+Shift+I без пустого application menu).

Список проектов: project.list без лицензии; список подгружается при неактивной лицензии; ProjectPicker с подсказками; listProjects пропускает битые zip.

Сохранение проектов: atomicReplace — замена zip без rm до commit; восстановление *.dnd.zip.tmp при старте; тесты.

EditorApp: блокировка UI при открытых окнах презентации и пульта; стили оверлея.
Made-with: Cursor
This commit is contained in:
Ivan Fontosh
2026-04-24 07:04:42 +08:00
parent a24e87035a
commit d94a11d466
14 changed files with 395 additions and 81 deletions
+34 -1
View File
@@ -21,6 +21,7 @@ import {
createEditorWindowDeferred,
createWindows,
focusEditorWindow,
isMultiWindowOpen,
markAppQuitting,
openMultiWindow,
togglePresentationFullscreen,
@@ -77,6 +78,35 @@ if (!gotTheLock) {
}
const projectStore = new ZipProjectStore();
/** Без меню Electron не вешает горячие клавиши DevTools (Ctrl+Shift+I / F12). */
function wantsDevToolsMenu(): boolean {
return (
process.env.NODE_ENV === 'development' ||
Boolean(process.env.VITE_DEV_SERVER_URL) ||
process.env.DND_OPEN_DEVTOOLS === '1'
);
}
function installAppMenuForSession(): void {
if (!wantsDevToolsMenu()) {
Menu.setApplicationMenu(null);
return;
}
const template: Electron.MenuItemConstructorOptions[] = [];
if (process.platform === 'darwin') {
template.push({
label: app.name,
submenu: [{ role: 'about' }, { type: 'separator' }, { role: 'quit' }],
});
}
template.push({
label: 'Вид',
submenu: [{ role: 'reload' }, { role: 'forceReload' }, { type: 'separator' }, { role: 'toggleDevTools' }],
});
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
}
const effectsStore = new EffectsStore();
const videoStore = new VideoPlaybackStore();
@@ -211,7 +241,7 @@ async function main() {
setLicenseAssert(() => {
licenseService.assertForIpc();
});
Menu.setApplicationMenu(null);
installAppMenuForSession();
registerDndAssetProtocol(projectStore);
registerHandler(ipcChannels.app.quit, () => {
markAppQuitting();
@@ -238,6 +268,9 @@ async function main() {
const isFullScreen = togglePresentationFullscreen();
return { ok: true, isFullScreen };
});
registerHandler(ipcChannels.windows.getMultiWindowState, () => {
return { open: isMultiWindowOpen() };
});
registerHandler(ipcChannels.project.list, async () => {
const projects = await projectStore.listProjects();
+2
View File
@@ -19,6 +19,8 @@ function channelRequiresLicense(channel: string): boolean {
if (channel.startsWith('app.')) return false;
if (channel === ipcChannels.windows.closeMultiWindow) return false;
if (channel === ipcChannels.windows.togglePresentationFullscreen) return false;
// Список файлов в %userData%/projects — только чтение; без лицензии список не должен «пропадать».
if (channel === ipcChannels.project.list) return false;
return true;
}
+82
View File
@@ -0,0 +1,82 @@
import crypto from 'node:crypto';
import fs from 'node:fs/promises';
import path from 'node:path';
import { readProjectJsonFromZip } from './yauzlProjectZip';
/**
* Подменяет файл `finalPath` готовым `completedSrc` (обычно `*.dnd.zip.tmp`).
* Нельзя сначала удалять `finalPath`: при сбое rename после rm проект теряется (Windows/антивирус).
*/
export async function replaceFileAtomic(completedSrc: string, finalPath: string): Promise<void> {
if (completedSrc === finalPath) return;
const stSrc = await fs.stat(completedSrc).catch(() => null);
if (!stSrc?.isFile() || stSrc.size === 0) {
throw new Error(`replaceFileAtomic: нет или пустой источник: ${completedSrc}`);
}
try {
await fs.rename(completedSrc, finalPath);
return;
} catch (first: unknown) {
const c = (first as NodeJS.ErrnoException).code;
if (c === 'EXDEV') {
await fs.copyFile(completedSrc, finalPath);
await fs.unlink(completedSrc).catch(() => undefined);
return;
}
// Windows: чаще всего EEXIST — целевой файл есть, rename не перезаписывает; идём через backup ниже.
}
const stFinal = await fs.stat(finalPath).catch(() => null);
if (!stFinal?.isFile()) {
try {
await fs.rename(completedSrc, finalPath);
return;
} catch (again: unknown) {
throw again instanceof Error ? again : new Error(String(again));
}
}
const backupPath = `${finalPath}.bak.${Date.now().toString(36)}_${crypto.randomBytes(4).toString('hex')}`;
await fs.rename(finalPath, backupPath);
try {
await fs.rename(completedSrc, finalPath);
} catch (place: unknown) {
await fs.rename(backupPath, finalPath).catch(() => undefined);
throw place instanceof Error ? place : new Error(String(place));
}
await fs.unlink(backupPath).catch(() => undefined);
}
/** Если сохранение оборвалось, остаётся только `*.dnd.zip.tmp` — восстанавливаем в `*.dnd.zip`. */
export async function recoverOrphanDndZipTmpInRoot(root: string): Promise<void> {
let names: string[];
try {
names = await fs.readdir(root);
} catch {
return;
}
for (const name of names) {
if (!name.endsWith('.dnd.zip.tmp')) continue;
const tmpPath = path.join(root, name);
const finalName = name.slice(0, -'.tmp'.length);
if (!finalName.endsWith('.dnd.zip')) continue;
const finalPath = path.join(root, finalName);
try {
await fs.access(finalPath);
continue;
} catch {
/* final отсутствует — пробуем поднять из tmp */
}
try {
const st = await fs.stat(tmpPath);
if (!st.isFile() || st.size < 22) continue;
await readProjectJsonFromZip(tmpPath);
await fs.rename(tmpPath, finalPath);
} catch {
/* битый tmp не трогаем */
}
}
}
@@ -0,0 +1,28 @@
import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import test from 'node:test';
import { replaceFileAtomic } from './atomicReplace';
void test('replaceFileAtomic: replaces existing file without deleting before rename succeeds', async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'dnd-replace-'));
const finalPath = path.join(dir, 'out.bin');
const tmpPath = path.join(dir, 'out.bin.tmp');
await fs.writeFile(finalPath, 'previous', 'utf8');
await fs.writeFile(tmpPath, 'updated-content', 'utf8');
await replaceFileAtomic(tmpPath, finalPath);
assert.equal(await fs.readFile(finalPath, 'utf8'), 'updated-content');
await assert.rejects(() => fs.stat(tmpPath));
});
void test('replaceFileAtomic: rejects empty source', async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'dnd-replace-'));
const finalPath = path.join(dir, 'out.bin');
const tmpPath = path.join(dir, 'out.bin.tmp');
await fs.writeFile(finalPath, 'x', 'utf8');
await fs.writeFile(tmpPath, '', 'utf8');
await assert.rejects(() => replaceFileAtomic(tmpPath, finalPath));
assert.equal(await fs.readFile(finalPath, 'utf8'), 'x');
});
@@ -45,3 +45,22 @@ void test('zipStore: normalizeScene defaults previewThumbAssetId for older proje
assert.match(src, /previewThumbAssetId/);
assert.match(src, /function normalizeScene\(/);
});
void test('zipStore: listProjects skips unreadable archives', () => {
const src = fs.readFileSync(path.join(here, 'zipStore.ts'), 'utf8');
assert.match(
src,
/async listProjects[\s\S]+?for \(const filePath of files\)[\s\S]+?try \{[\s\S]+?readProjectJsonFromZip/,
);
});
void test('atomicReplace: replaceFileAtomic must not rm destination before successful commit', () => {
const src = fs.readFileSync(path.join(here, 'atomicReplace.ts'), 'utf8');
const i = src.indexOf('export async function replaceFileAtomic');
assert.ok(i >= 0);
const j = src.indexOf('export async function recoverOrphanDndZipTmpInRoot', i);
assert.ok(j > i);
const block = src.slice(i, j);
assert.match(block, /rename\(finalPath, backupPath\)/);
assert.doesNotMatch(block, /\.rm\(\s*finalPath/);
});
+19 -32
View File
@@ -24,6 +24,7 @@ import { asAssetId, asGraphNodeId, asProjectId } from '../../shared/types/ids';
import { getAppSemanticVersion } from '../versionInfo';
import { reconcileAssetFiles } from './assetPrune';
import { recoverOrphanDndZipTmpInRoot, replaceFileAtomic } from './atomicReplace';
import { rmWithRetries } from './fsRetry';
import { optimizeImageBufferVisuallyLossless } from './optimizeImageImport.lib.mjs';
import { getLegacyProjectsRootDirs, getProjectsCacheRootDir, getProjectsRootDir } from './paths';
@@ -75,6 +76,7 @@ export class ZipProjectStore {
await fs.mkdir(getProjectsRootDir(), { recursive: true });
await fs.mkdir(getProjectsCacheRootDir(), { recursive: true });
await this.migrateLegacyProjectZipsIfNeeded();
await recoverOrphanDndZipTmpInRoot(getProjectsRootDir());
}
/** Копирует .dnd.zip из каталогов с «чужим» app name, если в текущем каталоге такого файла ещё нет. */
@@ -135,13 +137,17 @@ export class ZipProjectStore {
const out: ProjectIndexEntry[] = [];
for (const filePath of files) {
const project = await readProjectJsonFromZip(filePath);
out.push({
id: project.id,
name: project.meta.name,
updatedAt: project.meta.updatedAt,
fileName: path.basename(filePath),
});
try {
const project = await readProjectJsonFromZip(filePath);
out.push({
id: project.id,
name: project.meta.name,
updatedAt: project.meta.updatedAt,
fileName: path.basename(filePath),
});
} catch {
// Один битый архив не должен скрывать остальные проекты в списке.
}
}
out.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
return out;
@@ -868,6 +874,11 @@ export class ZipProjectStore {
const tmpPath = `${zipPath}.tmp`;
await fs.mkdir(path.dirname(zipPath), { recursive: true });
await zipDir(cacheDir, tmpPath);
const st = await fs.stat(tmpPath).catch(() => null);
if (!st?.isFile() || st.size < 22) {
await fs.unlink(tmpPath).catch(() => undefined);
throw new Error('Сборка архива проекта не удалась (пустой или повреждённый временный файл)');
}
await replaceFileAtomic(tmpPath, zipPath);
}
@@ -1226,20 +1237,6 @@ async function uniqueDndZipFileName(root: string, preferredBaseFileName: string)
}
}
async function replaceFileAtomic(srcPath: string, destPath: string): Promise<void> {
try {
await fs.rename(srcPath, destPath);
} catch {
try {
await fs.rm(destPath, { force: true });
await fs.rename(srcPath, destPath);
} catch (second: unknown) {
await fs.unlink(srcPath).catch(() => undefined);
throw second instanceof Error ? second : new Error(String(second));
}
}
}
async function copyFileWithProgress(
src: string,
dest: string,
@@ -1339,17 +1336,7 @@ async function atomicWriteFile(filePath: string, contents: string): Promise<void
await fs.mkdir(dir, { recursive: true });
const tmp = path.join(dir, `.tmp_${path.basename(filePath)}_${crypto.randomBytes(8).toString('hex')}`);
await fs.writeFile(tmp, contents, 'utf8');
try {
await fs.rename(tmp, filePath);
} catch {
try {
await fs.rm(filePath, { force: true });
await fs.rename(tmp, filePath);
} catch (second: unknown) {
await fs.unlink(tmp).catch(() => undefined);
throw second instanceof Error ? second : new Error(String(second));
}
}
await replaceFileAtomic(tmp, filePath);
}
/** Уже сжатые контейнеры/кодеки — в ZIP кладём без deflate, качество не трогаем; project.json и сырьё — deflate 9. */
+17
View File
@@ -3,6 +3,8 @@ import path from 'node:path';
import { app, BrowserWindow, nativeImage, screen } from 'electron';
import { ipcChannels } from '../../shared/ipc/contracts';
import { getBootSplashWindow } from './bootWindow';
type WindowKind = 'editor' | 'presentation' | 'control';
@@ -207,6 +209,13 @@ function createWindow(kind: WindowKind, opts?: CreateWindowOpts): BrowserWindow
});
}
win.on('closed', () => windows.delete(kind));
win.on('closed', () => {
if (kind !== 'presentation' && kind !== 'control') return;
const open = windows.has('presentation') || windows.has('control');
for (const w of BrowserWindow.getAllWindows()) {
w.webContents.send(ipcChannels.windows.multiWindowStateChanged, { open });
}
});
windows.set(kind, win);
return win;
}
@@ -283,6 +292,10 @@ export function openMultiWindow() {
// Keep control window independent on darwin.
createWindow('control', process.platform === 'darwin' ? undefined : { parent: presentation });
}
const open = true;
for (const w of BrowserWindow.getAllWindows()) {
w.webContents.send(ipcChannels.windows.multiWindowStateChanged, { open });
}
}
export function closeMultiWindow(): void {
@@ -292,6 +305,10 @@ export function closeMultiWindow(): void {
if (ctrl) ctrl.close();
}
export function isMultiWindowOpen(): boolean {
return windows.has('presentation') || windows.has('control');
}
export function togglePresentationFullscreen(): boolean {
const pres = windows.get('presentation');
if (!pres) return false;
+37
View File
@@ -134,6 +134,38 @@
z-index: 10000;
}
.editorLockOverlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.35);
display: flex;
align-items: center;
justify-content: center;
z-index: 11000;
}
.editorLockModal {
width: min(520px, calc(100vw - 32px));
border-radius: 12px;
padding: 14px;
background: rgba(25, 28, 38, 0.92);
border: 1px solid rgba(255, 255, 255, 0.12);
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.55);
display: grid;
gap: 8px;
}
.editorLockTitle {
font-weight: 800;
opacity: 0.95;
}
.editorLockText {
opacity: 0.85;
font-size: 12px;
line-height: 1.45;
}
.progressModal {
width: min(520px, calc(100vw - 32px));
border-radius: 12px;
@@ -465,6 +497,11 @@
position: relative;
}
.previewFill {
position: absolute;
inset: 0;
}
.previewBusyOverlay {
position: absolute;
inset: 0;
+83 -14
View File
@@ -65,6 +65,7 @@ export function EditorApp() {
const [renameOpen, setRenameOpen] = useState(false);
const [exportModalOpen, setExportModalOpen] = useState(false);
const [previewBusy, setPreviewBusy] = useState(false);
const [presentationOpen, setPresentationOpen] = useState(false);
const [licenseSnap, setLicenseSnap] = useState<LicenseSnapshot | null>(null);
const [licenseKeyModalOpen, setLicenseKeyModalOpen] = useState(false);
const [eulaModalOpen, setEulaModalOpen] = useState(false);
@@ -216,6 +217,24 @@ export function EditorApp() {
return () => window.removeEventListener('mousedown', onDown);
}, [settingsMenuOpen]);
useEffect(() => {
let off: (() => void) | null = null;
void (async () => {
try {
const snap = await getDndApi().invoke(ipcChannels.windows.getMultiWindowState, {});
setPresentationOpen(snap.open);
} catch {
// ignore
}
off = getDndApi().on(ipcChannels.windows.multiWindowStateChanged, ({ open }) => {
setPresentationOpen(open);
});
})();
return () => {
off?.();
};
}, []);
const reloadLicense = useCallback(() => {
void (async () => {
try {
@@ -266,6 +285,19 @@ export function EditorApp() {
return (
<>
{presentationOpen
? createPortal(
<div className={styles.editorLockOverlay} role="dialog" aria-label="Презентация запущена">
<div className={styles.editorLockModal}>
<div className={styles.editorLockTitle}>Презентация запущена</div>
<div className={styles.editorLockText}>
Редактор заблокирован. Закройте окна «Презентация» и «Панель управления», чтобы продолжить.
</div>
</div>
</div>,
document.body,
)
: null}
{state.zipProgress
? createPortal(
<div className={styles.progressOverlay} role="dialog" aria-label="Прогресс операции">
@@ -413,6 +445,7 @@ export function EditorApp() {
) : (
<ProjectPicker
projects={state.projects}
licenseActive={licenseActive}
onCreate={actions.createProject}
onOpen={actions.openProject}
onDelete={actions.deleteProject}
@@ -928,12 +961,13 @@ function RenameProjectModal({
type ProjectPickerProps = {
projects: { id: ProjectId; name: string; updatedAt: string }[];
licenseActive: boolean;
onCreate: (name: string) => Promise<void>;
onOpen: (id: ProjectId) => Promise<void>;
onDelete: (id: ProjectId) => Promise<void>;
};
function ProjectPicker({ projects, onCreate, onOpen, onDelete }: ProjectPickerProps) {
function ProjectPicker({ projects, licenseActive, onCreate, onOpen, onDelete }: ProjectPickerProps) {
const [name, setName] = useState('Моя кампания');
const [rowMenuFor, setRowMenuFor] = useState<ProjectId | null>(null);
const [rowMenuPos, setRowMenuPos] = useState<{ left: number; top: number } | null>(null);
@@ -956,23 +990,46 @@ function ProjectPicker({ projects, onCreate, onOpen, onDelete }: ProjectPickerPr
<div className={styles.projectPickerTitle}>Проекты</div>
<div className={styles.projectPickerForm}>
<Input value={name} onChange={setName} placeholder="Название нового проекта…" />
<Button variant="primary" onClick={() => void onCreate(name)}>
<Button
variant="primary"
disabled={!licenseActive}
title={!licenseActive ? 'Доступно после активации лицензии' : undefined}
onClick={() => {
if (!licenseActive) return;
void onCreate(name);
}}
>
Создать проект
</Button>
</div>
<div className={styles.spacer6} />
<div className={styles.sectionLabel}>СУЩЕСТВУЮЩИЕ</div>
{!licenseActive && projects.length > 0 ? (
<>
<div className={styles.muted}>
Открытие и создание после активации лицензии. Список показывает файлы в папке приложения.
</div>
<div className={styles.spacer6} />
</>
) : null}
<div className={styles.projectListScroll}>
<div className={styles.projectList}>
{projects.map((p) => (
<div key={p.id} className={styles.projectCard}>
<div
className={styles.projectCardBody}
onClick={() => void onOpen(p.id)}
onClick={() => {
if (!licenseActive) return;
void onOpen(p.id);
}}
role="button"
tabIndex={0}
title={!licenseActive ? 'Открытие проекта — после активации лицензии' : undefined}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') void onOpen(p.id);
if (e.key === 'Enter' || e.key === ' ') {
if (!licenseActive) return;
void onOpen(p.id);
}
}}
>
<div className={styles.projectCardName}>{p.name}</div>
@@ -985,8 +1042,11 @@ function ProjectPicker({ projects, onCreate, onOpen, onDelete }: ProjectPickerPr
aria-label="Меню проекта"
aria-haspopup="menu"
aria-expanded={rowMenuFor === p.id}
disabled={!licenseActive}
title={!licenseActive ? 'Доступно после активации лицензии' : undefined}
onClick={(e) => {
e.stopPropagation();
if (!licenseActive) return;
const r = e.currentTarget.getBoundingClientRect();
const menuW = 220;
const left = Math.max(8, Math.min(r.right - menuW, window.innerWidth - menuW - 8));
@@ -1189,17 +1249,26 @@ function SceneInspector({
<div className={styles.hint}>Файл изображения (PNG, JPG, WebP, GIF и т.д.).</div>
<div className={styles.previewBox}>
{previewUrl && previewAssetType === 'image' ? (
<RotatedImage url={previewUrl} rotationDeg={previewRotationDeg} mode="cover" />
<div className={styles.previewFill}>
<RotatedImage
url={previewUrl}
rotationDeg={previewRotationDeg}
mode="cover"
style={{ width: '100%', height: '100%' }}
/>
</div>
) : previewUrl && previewAssetType === 'video' ? (
<video
src={previewUrl}
muted
playsInline
autoPlay={previewVideoAutostart}
loop
preload="metadata"
className={styles.videoCover}
/>
<div className={styles.previewFill}>
<video
src={previewUrl}
muted
playsInline
autoPlay={previewVideoAutostart}
loop
preload="metadata"
className={styles.videoCover}
/>
</div>
) : (
<div className={styles.previewEmpty}>Превью не задано</div>
)}
@@ -9,7 +9,7 @@ const here = path.dirname(fileURLToPath(import.meta.url));
void test('projectState: list/get after delete invalidates in-flight initial load (epoch guard)', () => {
const src = fs.readFileSync(path.join(here, 'projectState.ts'), 'utf8');
assert.match(src, /projectDataEpochRef/);
assert.match(src, /const epoch = projectDataEpochRef\.current/);
assert.match(src, /const epoch = \+\+projectDataEpochRef\.current/);
assert.match(src, /if \(projectDataEpochRef\.current !== epoch\) return/);
assert.match(
src,
@@ -21,3 +21,8 @@ void test('projectState: list/get after delete invalidates in-flight initial loa
);
assert.match(src, /const refreshProjects = async \(\) => \{[\s\S]+?projectDataEpochRef\.current \+= 1/);
});
void test('ipc router: project.list does not require license', () => {
const routerSrc = fs.readFileSync(path.join(here, '..', '..', '..', 'main', 'ipc', 'router.ts'), 'utf8');
assert.match(routerSrc, /if \(channel === ipcChannels\.project\.list\) return false/);
});
+29 -16
View File
@@ -131,7 +131,7 @@ export function useProjectState(licenseActive: boolean): readonly [State, Action
const closeProject = async () => {
setState((s) => ({ ...s, project: null, selectedSceneId: null }));
if (licenseActive) await refreshProjects();
await refreshProjects();
};
const createScene = async () => {
@@ -385,24 +385,37 @@ export function useProjectState(licenseActive: boolean): readonly [State, Action
exportProject,
deleteProject,
};
}, [api, licenseActive]);
}, [api]);
useEffect(() => {
if (!licenseActive) {
queueMicrotask(() => {
projectDataEpochRef.current += 1;
setState({ projects: [], project: null, selectedSceneId: null, zipProgress: null });
});
return;
}
const epoch = ++projectDataEpochRef.current;
void (async () => {
const epoch = projectDataEpochRef.current;
const listRes = await api.invoke(ipcChannels.project.list, {});
if (projectDataEpochRef.current !== epoch) return;
setState((s) => ({ ...s, projects: listRes.projects }));
const res = await api.invoke(ipcChannels.project.get, {});
if (projectDataEpochRef.current !== epoch) return;
setState((s) => ({ ...s, project: res.project, selectedSceneId: res.project?.currentSceneId ?? null }));
try {
const listRes = await api.invoke(ipcChannels.project.list, {});
if (projectDataEpochRef.current !== epoch) return;
if (!licenseActive) {
setState((s) => ({
...s,
projects: listRes.projects,
project: null,
selectedSceneId: null,
}));
return;
}
setState((s) => ({ ...s, projects: listRes.projects }));
const res = await api.invoke(ipcChannels.project.get, {});
if (projectDataEpochRef.current !== epoch) return;
setState((s) => ({
...s,
project: res.project,
selectedSceneId: res.project?.currentSceneId ?? null,
}));
} catch {
if (projectDataEpochRef.current !== epoch) return;
if (!licenseActive) {
setState((s) => ({ ...s, project: null, selectedSceneId: null }));
}
}
})();
}, [licenseActive, api]);
+31 -16
View File
@@ -1,4 +1,4 @@
import React, { useEffect, useMemo, useRef, useState } from 'react';
import React, { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import styles from './RotatedImage.module.css';
@@ -24,13 +24,15 @@ function useElementSize<T extends HTMLElement>() {
useEffect(() => {
const el = ref.current;
if (!el) return;
// clientWidth/Height — локальная вёрстка; getBoundingClientRect учитывает transform предков (React Flow zoom).
const readLayoutSize = () => {
setSize({ w: el.clientWidth, h: el.clientHeight });
};
const ro = new ResizeObserver(() => {
const r = el.getBoundingClientRect();
setSize({ w: r.width, h: r.height });
readLayoutSize();
});
ro.observe(el);
const r = el.getBoundingClientRect();
setSize({ w: r.width, h: r.height });
readLayoutSize();
return () => ro.disconnect();
}, []);
@@ -49,18 +51,19 @@ export function RotatedImage({
}: RotatedImageProps) {
const [ref, size] = useElementSize<HTMLDivElement>();
const [imgSize, setImgSize] = useState<{ w: number; h: number } | null>(null);
const imgRef = useRef<HTMLImageElement | null>(null);
useEffect(() => {
let cancelled = false;
const img = new Image();
img.onload = () => {
if (cancelled) return;
setImgSize({ w: img.naturalWidth || 1, h: img.naturalHeight || 1 });
};
img.src = url;
return () => {
cancelled = true;
};
useLayoutEffect(() => {
// If the image is served from cache, onLoad may fire before listeners attach.
// Reading from the <img> element itself is the most reliable source.
const el = imgRef.current;
if (!el) return;
if (!el.complete) return;
const w0 = el.naturalWidth || 0;
const h0 = el.naturalHeight || 0;
if (w0 <= 0 || h0 <= 0) return;
// eslint-disable-next-line react-hooks/set-state-in-effect, @typescript-eslint/prefer-optional-chain -- read cached <img> dimensions when onLoad may not fire
setImgSize((prev) => (prev && prev.w === w0 && prev.h === h0 ? prev : { w: w0, h: h0 }));
}, [url]);
const scale = useMemo(() => {
@@ -93,11 +96,23 @@ export function RotatedImage({
return (
<div ref={ref} className={styles.root} style={style}>
<img
ref={imgRef}
alt={alt}
src={url}
loading={loading}
decoding={decoding}
className={styles.img}
onLoad={(e) => {
const el = e.currentTarget;
const w0 = el.naturalWidth || 0;
const h0 = el.naturalHeight || 0;
if (w0 <= 0 || h0 <= 0) return;
setImgSize((prev) => {
// eslint-disable-next-line @typescript-eslint/prefer-optional-chain -- rule can misfire on React state unions
if (prev && prev.w === w0 && prev.h === h0) return prev;
return { w: w0, h: h0 };
});
}}
style={{
width: w ?? '100%',
height: h ?? '100%',
+7
View File
@@ -52,6 +52,8 @@ export const ipcChannels = {
openMultiWindow: 'windows.openMultiWindow',
closeMultiWindow: 'windows.closeMultiWindow',
togglePresentationFullscreen: 'windows.togglePresentationFullscreen',
getMultiWindowState: 'windows.getMultiWindowState',
multiWindowStateChanged: 'windows.multiWindowStateChanged',
},
session: {
stateChanged: 'session.stateChanged',
@@ -87,6 +89,7 @@ export type IpcEventMap = {
[ipcChannels.effects.stateChanged]: { state: EffectsState };
[ipcChannels.video.stateChanged]: { state: VideoPlaybackState };
[ipcChannels.license.statusChanged]: { snapshot: LicenseSnapshot };
[ipcChannels.windows.multiWindowStateChanged]: { open: boolean };
[ipcChannels.project.importZipProgress]: ZipProgressEvent;
[ipcChannels.project.exportZipProgress]: ZipProgressEvent;
};
@@ -216,6 +219,10 @@ export type IpcInvokeMap = {
req: Record<string, never>;
res: { ok: true; isFullScreen: boolean };
};
[ipcChannels.windows.getMultiWindowState]: {
req: Record<string, never>;
res: { open: boolean };
};
[ipcChannels.effects.getState]: {
req: Record<string, never>;
res: { state: EffectsState };
+1 -1
View File
@@ -10,7 +10,7 @@
"build:obfuscate": "node scripts/build.mjs --production --obfuscate",
"lint": "eslint . --max-warnings 0",
"typecheck": "tsc -p tsconfig.eslint.json --noEmit",
"test": "tsx --test app/renderer/shared/ui/controls.tooltip.test.ts app/renderer/editor/state/projectState.race.test.ts app/renderer/editor/graph/sceneCardById.test.ts app/shared/ipc/contracts.mediaRemoval.test.ts app/shared/effectEraserHitTest.test.ts app/renderer/control/controlApp.effectsPanel.test.ts app/renderer/shared/effects/PxiEffectsOverlay.pointer.test.ts app/main/windows/createWindows.editorClose.test.ts app/main/windows/bootWindow.test.ts app/main/effects/effectsStore.test.ts app/main/project/assetPrune.test.ts app/main/project/optimizeImageImport.test.ts app/main/project/scenePreviewThumbnail.test.ts app/main/project/fsRetry.test.ts app/main/project/zipRead.test.ts app/main/project/zipStore.legacyContract.test.ts app/shared/package.build.test.ts app/shared/license/canonicalJson.test.ts app/shared/license/productKey.test.ts app/shared/license/licenseService.networkRegression.test.ts app/shared/video/videoPlaybackPerf.networkRegression.test.ts app/shared/video/videoPlaybackLoop.networkRegression.test.ts app/main/license/verifyLicenseToken.test.ts && node --test scripts/build-env.test.mjs scripts/obfuscate-main.test.mjs",
"test": "tsx --test app/renderer/shared/ui/controls.tooltip.test.ts app/renderer/editor/state/projectState.race.test.ts app/renderer/editor/graph/sceneCardById.test.ts app/shared/ipc/contracts.mediaRemoval.test.ts app/shared/effectEraserHitTest.test.ts app/renderer/control/controlApp.effectsPanel.test.ts app/renderer/shared/effects/PxiEffectsOverlay.pointer.test.ts app/main/windows/createWindows.editorClose.test.ts app/main/windows/bootWindow.test.ts app/main/effects/effectsStore.test.ts app/main/project/assetPrune.test.ts app/main/project/optimizeImageImport.test.ts app/main/project/scenePreviewThumbnail.test.ts app/main/project/fsRetry.test.ts app/main/project/zipRead.test.ts app/main/project/replaceFileAtomic.test.ts app/main/project/zipStore.legacyContract.test.ts app/shared/package.build.test.ts app/shared/license/canonicalJson.test.ts app/shared/license/productKey.test.ts app/shared/license/licenseService.networkRegression.test.ts app/shared/video/videoPlaybackPerf.networkRegression.test.ts app/shared/video/videoPlaybackLoop.networkRegression.test.ts app/main/license/verifyLicenseToken.test.ts && node --test scripts/build-env.test.mjs scripts/obfuscate-main.test.mjs",
"format": "prettier . --check",
"format:write": "prettier . --write",
"release:info": "node scripts/print-release-info.mjs",