diff --git a/desktop/apps/electron/src/main/__tests__/embedded-powerpoint-manager.test.ts b/desktop/apps/electron/src/main/__tests__/embedded-powerpoint-manager.test.ts index 6ec843a3..18cd7278 100644 --- a/desktop/apps/electron/src/main/__tests__/embedded-powerpoint-manager.test.ts +++ b/desktop/apps/electron/src/main/__tests__/embedded-powerpoint-manager.test.ts @@ -39,8 +39,8 @@ class FakeContents { return { ok: true, value: { - identity: { document_id: 'opened-document', name: 'Opened deck' }, - meta: { total_pages: 3 }, + document_id: 'opened-document', + deck: { id: 'opened-document', title: 'Opened deck', total_pages: 3 }, reused: false, }, } @@ -93,6 +93,8 @@ it('owns exactly one CDP target per Session and presents only the active one', a const second = await manager.ensureSession('session-b') expect(first.targetId).toBe('ppt-target-1') expect(second.targetId).toBe('ppt-target-2') + expect(first.documentCount).toBeNull() + expect(second.documentCount).toBeNull() expect(views).toHaveLength(2) manager.setBounds({ x: 12, y: 24, width: 900, height: 600 }) @@ -117,7 +119,7 @@ it('owns exactly one CDP target per Session and presents only the active one', a slideCount: 3, title: 'Opened deck', }) - expect(views[0]!.webContents.executedScripts.at(-1)).toContain('"method":"view_ppt"') + expect(views[0]!.webContents.executedScripts.at(-1)).toContain('"method":"open"') expect(views[0]!.webContents.executedScripts.at(-1)).toContain('"content_base64":"BAUG"') await expect(manager.openFile('session-a', path.join(presentationDirectory, 'deck.txt'))) .rejects.toThrow('must end with .pptx') @@ -130,6 +132,41 @@ it('owns exactly one CDP target per Session and presents only the active one', a expect(manager.snapshot().sessions.map((item) => item.sessionId)).toEqual(['session-a']) }) +it('publishes authoritative project counts without treating the native target as a document', async () => { + const views: FakeView[] = [] + const snapshots: Array> = [] + const manager = new EmbeddedPowerPointManager( + () => { + const view = new FakeView(views.length + 1) + views.push(view) + return view as unknown as WebContentsView + }, + async () => {}, + (snapshot) => snapshots.push(snapshot), + ) + manager.attachHost({ + isDestroyed: () => false, + contentView: { addChildView: () => {}, removeChildView: () => {} }, + } as unknown as BrowserWindow) + + const session = await manager.ensureSession('session-a') + expect(session.documentCount).toBeNull() + manager.reportState(session.webContentsId, { documentCount: 0 }) + expect(manager.sessionInfo('session-a')?.documentCount).toBe(0) + manager.reportState(session.webContentsId, { documentCount: 2 }) + expect(manager.snapshot().sessions[0]?.documentCount).toBe(2) + const publishCount = snapshots.length + manager.reportState(session.webContentsId, { documentCount: 2 }) + expect(snapshots).toHaveLength(publishCount) + + views[0]!.webContents.emit('did-start-loading') + expect(manager.sessionInfo('session-a')?.documentCount).toBeNull() + expect(() => manager.reportState(session.webContentsId, { documentCount: -1 })) + .toThrow('Invalid PowerPoint runtime document count') + expect(() => manager.reportState(999, { documentCount: 1 })).toThrow('does not own') + manager.closeAll() +}) + it('rejects unknown close senders and preserves a replacement target during deferred close', async () => { const views: FakeView[] = [] const manager = new EmbeddedPowerPointManager( @@ -147,6 +184,8 @@ it('rejects unknown close senders and preserves a replacement target during defe const first = await manager.ensureSession('session-a') const other = await manager.ensureSession('session-b') expect(manager.sessionForContents(first.webContentsId)).toBe('session-a') + expect(manager.ownedSessionForContents(first.webContentsId)).toBe('session-a') + expect(manager.ownedSessionForContents(99)).toBeNull() expect(() => manager.sessionForContents(99)).toThrow('does not own') manager.closeSession('session-a') const replacement = await manager.ensureSession('session-a') diff --git a/desktop/apps/electron/src/main/__tests__/excel-host-handler.test.ts b/desktop/apps/electron/src/main/__tests__/excel-host-handler.test.ts index 1945319a..d133997e 100644 --- a/desktop/apps/electron/src/main/__tests__/excel-host-handler.test.ts +++ b/desktop/apps/electron/src/main/__tests__/excel-host-handler.test.ts @@ -11,6 +11,22 @@ const { IPC } = await import('../../shared/ipc-channels') const { registerExcelHostHandlers } = await import('../handlers/excel-host') describe('Excel host close requests', () => { + it('binds renderer state reports to the sending Excel target', async () => { + const calls: unknown[][] = [] + const excel = { + reportState: (sender: number, state: unknown) => { calls.push([sender, state]) }, + } as unknown as ExcelHost + testIpcHandlers.clear() + registerExcelHostHandlers(excel, {} as EmbeddedBrowserManager, () => undefined) + + await testIpcHandlers.get(IPC.excelHost.reportState)?.( + { sender: { id: 17 } } as IpcMainInvokeEvent, + { documentCount: 0, dirty: false }, + ) + + expect(calls).toEqual([[17, { documentCount: 0, dirty: false }]]) + }) + it('resolves the owning Session from the sender and retracts its panel before deferred destruction', async () => { const events: unknown[][] = [] const closed: number[] = [] diff --git a/desktop/apps/electron/src/main/__tests__/excel-host.test.ts b/desktop/apps/electron/src/main/__tests__/excel-host.test.ts index a6f15a5d..846f279a 100644 --- a/desktop/apps/electron/src/main/__tests__/excel-host.test.ts +++ b/desktop/apps/electron/src/main/__tests__/excel-host.test.ts @@ -131,6 +131,36 @@ function setup(openExternal?: (url: string) => void) { } describe('ExcelHost Session target ownership', () => { + it('publishes the renderer-owned workbook inventory only for its Session target', async () => { + const snapshots: Array> = [] + const views: FakeView[] = [] + const host = fakeHost() + const manager = new ExcelHost( + () => { + const view = new FakeView(new FakeWebContents(views.length + 1, `excel-target-${views.length + 1}`)) + views.push(view) + return view as unknown as WebContentsView + }, + '/dist/excel-host-preload.cjs', + 'http://localhost:5173', + '/dist/renderer/excel.html', + (snapshot) => snapshots.push(snapshot), + ) + manager.attachHost(host.window) + const session = await manager.ensureSession('session-a', { + sessionId: 'session-a', locale: 'en-US', theme: 'light', + }, false) + + expect(session.documentCount).toBeNull() + manager.reportState(session.webContentsId, { documentCount: 0, dirty: false }) + expect(manager.snapshot().sessions[0]?.documentCount).toBe(0) + manager.reportState(session.webContentsId, { documentCount: 2, dirty: true }) + expect(manager.snapshot().sessions[0]).toMatchObject({ documentCount: 2, dirty: true }) + expect(snapshots.at(-1)?.sessions[0]).toMatchObject({ documentCount: 2, dirty: true }) + expect(() => manager.reportState(session.webContentsId, { documentCount: -1, dirty: false })).toThrow('Invalid Excel runtime') + expect(() => manager.reportState(-1, { documentCount: 0, dirty: false })).toThrow('does not own') + }) + it('keeps serialized recovery scoped to the owning Session renderer', async () => { const { manager } = setup() const first = await manager.ensureSession('session-a', { sessionId: 'session-a', locale: 'en-US', theme: 'light' }) @@ -227,7 +257,7 @@ describe('ExcelHost Session target ownership', () => { const config = { sessionId: 'session-a', locale: 'en-US' as const, theme: 'light' as const } const first = await manager.ensureSession('session-a', config) await manager.ensureSession('session-b', { ...config, sessionId: 'session-b' }) - manager.setDirty(first.webContentsId, true) + manager.reportState(first.webContentsId, { documentCount: 1, dirty: true }) manager.setRecoveryState(first.webContentsId, '{"version":1}') manager.activateSession('session-b') manager.setVisible(true) @@ -251,7 +281,7 @@ describe('ExcelHost Session target ownership', () => { }) const checkpoint = JSON.stringify({ version: 1, tabs: [{ tabId: 'tab-a' }] }) manager.setRecoveryState(first.webContentsId, checkpoint) - manager.setDirty(first.webContentsId, true) + manager.reportState(first.webContentsId, { documentCount: 1, dirty: true }) views[0]?.webContents.emit('render-process-gone', {}, { reason: 'crashed' }) const recovered = await manager.ensureSession('session-a', { @@ -270,7 +300,7 @@ describe('ExcelHost Session target ownership', () => { const { manager, views, host } = setup() for (const sessionId of ['session-a', 'session-b']) { const session = await manager.ensureSession(sessionId, { sessionId, locale: 'en-US', theme: 'light' }) - manager.setDirty(session.webContentsId, true) + manager.reportState(session.webContentsId, { documentCount: 1, dirty: true }) } manager.shutdown() expect(manager.snapshot().sessions).toEqual([]) diff --git a/desktop/apps/electron/src/main/__tests__/mount-reference-handler.test.ts b/desktop/apps/electron/src/main/__tests__/mount-reference-handler.test.ts new file mode 100644 index 00000000..ce1ca42a --- /dev/null +++ b/desktop/apps/electron/src/main/__tests__/mount-reference-handler.test.ts @@ -0,0 +1,46 @@ +import { beforeEach, describe, expect, it, mock } from 'bun:test' +import type { IpcMainInvokeEvent } from 'electron' +import type { MountReferenceProvider } from '../handlers/mount-references' +import { electronModuleMock, loggerModuleMock, testIpcHandlers } from './electron-module-mock' + +mock.module('electron', () => electronModuleMock) +mock.module('../logger', () => loggerModuleMock) + +const { IPC } = await import('../../shared/ipc-channels') +const { registerMountReferenceHandlers } = await import('../handlers/mount-references') + +const compatibleProvider = (usage: { assetCount: number; elementCount: number; projectCount: number }): MountReferenceProvider => ({ + usage: async () => usage, + validateReplacement: async () => ({ compatible: true }), + remove: async () => usage, + refresh: async () => undefined, +}) + +describe('mount reference IPC boundary', () => { + beforeEach(() => testIpcHandlers.clear()) + + it('aggregates reference usage without exposing editor-specific APIs to Files', async () => { + registerMountReferenceHandlers([ + compatibleProvider({ assetCount: 2, elementCount: 3, projectCount: 1 }), + compatibleProvider({ assetCount: 1, elementCount: 4, projectCount: 1 }), + ]) + const usage = await testIpcHandlers.get(IPC.mountReferences.usage)?.({} as IpcMainInvokeEvent, 'session-a', 'mount-a') + expect(usage).toEqual({ assetCount: 3, elementCount: 7, projectCount: 2 }) + }) + + it('rejects relocation when any registered project type finds an incompatible reference', async () => { + const rejecting: MountReferenceProvider = { + ...compatibleProvider({ assetCount: 0, elementCount: 0, projectCount: 0 }), + validateReplacement: async () => ({ compatible: false, reason: 'content-mismatch', assetName: 'chart.png' }), + } + registerMountReferenceHandlers([ + compatibleProvider({ assetCount: 0, elementCount: 0, projectCount: 0 }), + rejecting, + ]) + const result = await testIpcHandlers.get(IPC.mountReferences.rebind)?.({} as IpcMainInvokeEvent, 'session-a', 'mount-a', '/tmp/chart.png') + expect(result).toEqual({ + ok: false, + validation: { compatible: false, reason: 'content-mismatch', assetName: 'chart.png' }, + }) + }) +}) diff --git a/desktop/apps/electron/src/main/__tests__/office-files.test.ts b/desktop/apps/electron/src/main/__tests__/office-files.test.ts index b2dadf73..67a5727c 100644 --- a/desktop/apps/electron/src/main/__tests__/office-files.test.ts +++ b/desktop/apps/electron/src/main/__tests__/office-files.test.ts @@ -54,14 +54,12 @@ describe('Office source files and durable recovery', () => { expect(await readFile(path, 'utf8')).toBe('external') }) } - it('restores independent Session drafts through a fresh store instance', async () => { + it('restores independent Excel Session drafts through a fresh store instance', async () => { const directory = await root() const first = createOfficeRecoveryStore(directory) - await Promise.all([first.write('excel', 'session-a', '{"draft":1}'), first.write('excel', 'session-b', '{"draft":2}'), first.write('presentation', 'session-a', '{"draft":3}')]) + await Promise.all([first.write('excel', 'session-a', '{"draft":1}'), first.write('excel', 'session-b', '{"draft":2}')]) const next = createOfficeRecoveryStore(directory) expect(await next.read('excel', 'session-a')).toBe('{"draft":1}') expect(await next.read('excel', 'session-b')).toBe('{"draft":2}') - expect(await next.read('presentation', 'session-a')).toBe('{"draft":3}') - expect(await next.read('word', 'session-a')).toBeNull() }) }) diff --git a/desktop/apps/electron/src/main/__tests__/office-workspace-files.test.ts b/desktop/apps/electron/src/main/__tests__/office-workspace-files.test.ts index b204328e..53fc6e7e 100644 --- a/desktop/apps/electron/src/main/__tests__/office-workspace-files.test.ts +++ b/desktop/apps/electron/src/main/__tests__/office-workspace-files.test.ts @@ -1,12 +1,22 @@ -import { afterEach, expect, it } from 'bun:test' +import { afterEach, describe, expect, it } from 'bun:test' import { copyFile, mkdir, mkdtemp, readFile, readdir, realpath, rm, utimes, writeFile } from 'node:fs/promises' -import { basename, join } from 'node:path' import { tmpdir } from 'node:os' +import { basename, join } from 'node:path' +import type { PresentationSourceMount } from '../../shared/presentation-host' import { inspectOfficeFile } from '../office-files' import { createOfficeWorkspaceFiles } from '../office-workspace-files' const roots: string[] = [] -afterEach(async () => { await Promise.all(roots.splice(0).map((path) => rm(path, { recursive: true, force: true }))) }) + +afterEach(async () => { + await Promise.all(roots.splice(0).map((path) => rm(path, { recursive: true, force: true }))) +}) + +async function testRoot(): Promise { + const path = await mkdtemp(join(tmpdir(), 'office-workspace-files-')) + roots.push(path) + return path +} for (const [kind, extension] of [['word', 'docx'], ['excel', 'xlsx'], ['presentation', 'pptx']] as const) { it(`${kind}: registers new and imported files, reuses identities and retries failed registration across process restarts`, async () => { @@ -18,13 +28,13 @@ for (const [kind, extension] of [['word', 'docx'], ['excel', 'xlsx'], ['presenta let fail = false let notifications = 0 const createService = () => createOfficeWorkspaceFiles(async (_endpoint, body) => { - if (!body) return [{ kind: 'folder', removable: false, path: work }] + if (!body) return [{ id: 'work', name: '.work', kind: 'folder', removable: false, path: work, exists: true }] if (fail) throw new Error('service unavailable') const path = (body as { path: string }).path const target = join(work, basename(path)) if (path !== target && !registered.has(target)) await copyFile(path, target) registered.add(target) - return { kind: 'file', path: target } + return { id: `file-${basename(target)}`, name: basename(target), kind: 'file', path: target, exists: true } }, () => { notifications++ }) let service = createService() const request = { kind, documentId: 'new-document', managed: true, suggestedName: `Report.${extension}`, bytes: new TextEncoder().encode('new content') } @@ -54,10 +64,57 @@ for (const [kind, extension] of [['word', 'docx'], ['excel', 'xlsx'], ['presenta expect((await service.prepare('session', kind, external)).path).toBe(imported.path) expect(await readFile(external, 'utf8')).toBe('original') expect(await readFile(imported.path, 'utf8')).toBe('new content') + const preserved = await service.save('session', { ...request, documentId: 'protected-import', source: await inspectOfficeFile(kind, imported.path), preserveSource: true, bytes: new TextEncoder().encode('editable copy') }) + expect(preserved.ok).toBe(true) + if (!preserved.ok) throw new Error('save failed') + expect(preserved.source.path).not.toBe(imported.path) + expect(await readFile(imported.path, 'utf8')).toBe('new content') + expect(await readFile(preserved.source.path, 'utf8')).toBe('editable copy') + service = createService() + const retried = await service.save('session', { ...request, documentId: 'protected-import', source: await inspectOfficeFile(kind, imported.path), preserveSource: true, bytes: new TextEncoder().encode('editable copy') }) + expect(retried.ok && retried.source.path).toBe(preserved.source.path) + let copy = preserved.source + for (const content of ['second edit', 'third edit']) { + service = createService() + const nextCopy = await service.save('session', { ...request, documentId: 'protected-import', suggestedName: basename(copy.path), source: copy, preserveSource: true, bytes: new TextEncoder().encode(content) }) + expect(nextCopy.ok).toBe(true) + if (!nextCopy.ok) throw new Error('copy save failed') + expect(nextCopy.source.path).toBe(preserved.source.path) + expect(await readFile(nextCopy.source.path, 'utf8')).toBe(content) + expect(await readFile(imported.path, 'utf8')).toBe('new content') + copy = nextCopy.source + } + await writeFile(copy.path, 'changed outside the editor') + await utimes(copy.path, new Date(), new Date(Date.now() + 10_000)) + expect(await service.save('session', { ...request, documentId: 'protected-import', source: copy, preserveSource: true })).toEqual({ ok: false, reason: 'conflict' }) + expect(await readFile(copy.path, 'utf8')).toBe('changed outside the editor') expect(notifications).toBeGreaterThan(0) const second = await service.save('session', { ...request, documentId: 'second' }) - expect(second.ok && second.fileName).toBe(`Report (2).${extension}`) + expect(second.ok && second.fileName).toBe(`Report (3).${extension}`) }) + + it(`${kind}: reuses protected saves of a new document and allocates a copy when protecting a previously saved original`, async () => { + const root = await realpath(await testRoot()) + const work = join(root, '.work') + await mkdir(work) + const service = createOfficeWorkspaceFiles(async (_endpoint, body) => { + if (!body) return [{ id: 'work', name: '.work', kind: 'folder', removable: false, path: work, exists: true }] + const path = (body as { path: string }).path + return { id: basename(path), name: basename(path), kind: 'file', path, exists: true } + }, () => undefined) + const input = { kind, documentId: 'new-protected', suggestedName: `New.${extension}`, preserveSource: true, bytes: new TextEncoder().encode('first edit') } + const first = await service.save('session', input) + if (!first.ok) throw new Error('save failed') + const second = await service.save('session', { ...input, source: first.source, bytes: new TextEncoder().encode('second edit') }) + expect(second.ok && second.source.path).toBe(first.source.path) + expect(await readdir(work)).toEqual([`New.${extension}`]) + const original = await service.save('session', { ...input, preserveSource: false, documentId: 'original', suggestedName: `Original.${extension}` }) + if (!original.ok) throw new Error('save failed') + const copy = await service.save('session', { ...input, documentId: 'original', source: original.source, bytes: new TextEncoder().encode('protected edit') }) + expect(copy.ok && copy.source.path).not.toBe(original.source.path) + expect(await readFile(original.source.path, 'utf8')).toBe('first edit') + }) + it(`${kind}: a recovery receipt never acknowledges unrelated file content`, async () => { const root = await realpath(await mkdtemp(join(tmpdir(), 'office-receipt-'))) roots.push(root) @@ -68,9 +125,10 @@ for (const [kind, extension] of [['word', 'docx'], ['excel', 'xlsx'], ['presenta const source = await inspectOfficeFile(kind, path) let fail = true const backend = async (_endpoint: string, body?: unknown) => { - if (!body) return [{ kind: 'folder', removable: false, path: work }] + if (!body) return [{ id: 'work', name: '.work', kind: 'folder', removable: false, path: work, exists: true }] if (fail) throw new Error('registration unavailable') - return body + const target = (body as { path: string }).path + return { id: `file-${basename(target)}`, name: basename(target), kind: 'file', path: target, exists: true } } const input = { kind, documentId: 'document', source, suggestedName: `Report.${extension}`, bytes: new TextEncoder().encode('my edit') } await expect(createOfficeWorkspaceFiles(backend, () => undefined).save('session', input)).rejects.toThrow('file was saved') @@ -80,5 +138,55 @@ for (const [kind, extension] of [['word', 'docx'], ['excel', 'xlsx'], ['presenta expect(await createOfficeWorkspaceFiles(backend, () => undefined).save('session', input)).toEqual({ ok: false, reason: 'conflict' }) expect(await readFile(path, 'utf8')).toBe('different file content') }) - } + +describe('PowerPoint Session source mounts', () => { + it('registers user-inserted sources without creating hidden presentation assets', async () => { + const root = await testRoot() + const workPath = join(root, '.work') + const externalPath = join(root, 'external.png') + await mkdir(workPath) + await writeFile(externalPath, 'external') + const workMount: PresentationSourceMount = { + id: 'work-mount', name: '.work', path: workPath, kind: 'folder', exists: true, + size_bytes: null, item_count: 0, removable: false, created_at: new Date(0).toISOString(), + } + const registered: string[] = [] + const request = async (_path: string, body?: unknown): Promise => { + if (!body) return [workMount] + const path = (body as { path: string }).path + registered.push(path) + return { + id: `mount-${basename(path)}`, name: basename(path), path, kind: 'file', exists: true, + size_bytes: 8, item_count: null, removable: true, created_at: new Date(0).toISOString(), + } satisfies PresentationSourceMount + } + const changed: string[] = [] + const files = createOfficeWorkspaceFiles(request, (sessionId) => { changed.push(sessionId) }) + + const external = await files.mountPresentationSource('session-a', { + fileName: 'external.png', mimeType: 'image/png', path: externalPath, + }) + expect(external).toMatchObject({ id: 'mount-external.png', name: 'external.png' }) + expect(registered).toHaveLength(1) + const registeredPath = registered[0]! + expect(external.path).toBe(registeredPath) + expect(basename(registeredPath)).toBe('external.png') + + const generated = await files.mountPresentationSource('session-a', { + dataBase64: Buffer.from('generated').toString('base64'), fileName: 'generated.txt', mimeType: 'text/plain', + }) + expect(generated).toMatchObject({ id: expect.stringMatching(/^mount-[a-f0-9]{64}-generated\.txt$/) }) + expect(generated.path).toMatch(/\.work\/[a-f0-9]{64}-generated\.txt$/) + expect(await readFile(generated.path, 'utf8')).toBe('generated') + expect(registered).toHaveLength(2) + expect(changed).toEqual(['session-a', 'session-a']) + + await expect(files.mountPresentationSource('session-a', { + fileName: 'escaped.png', mimeType: 'image/png', path: '../external.png', + })).rejects.toThrow('must stay inside the Session workspace') + await expect(files.mountPresentationSource('session-a', { + dataBase64: 'not=base64', fileName: 'invalid.png', mimeType: 'image/png', + })).rejects.toThrow('embedded source data is invalid') + }) +}) diff --git a/desktop/apps/electron/src/main/__tests__/powerpoint-handler.test.ts b/desktop/apps/electron/src/main/__tests__/powerpoint-handler.test.ts new file mode 100644 index 00000000..99156683 --- /dev/null +++ b/desktop/apps/electron/src/main/__tests__/powerpoint-handler.test.ts @@ -0,0 +1,52 @@ +import { describe, expect, it, mock } from 'bun:test' +import type { IpcMainInvokeEvent } from 'electron' +import type { EmbeddedPowerPointManager } from '../embedded-powerpoint-manager' +import { electronModuleMock, loggerModuleMock, testIpcHandlers } from './electron-module-mock' + +mock.module('electron', () => electronModuleMock) +mock.module('../logger', () => loggerModuleMock) + +const { IPC } = await import('../../shared/ipc-channels') +const { registerPowerPointHandlers } = await import('../handlers/powerpoint') + +describe('PowerPoint IPC boundary', () => { + it('opens a picked PPTX only in the sending child renderer Session', async () => { + const originalShowOpenDialog = electronModuleMock.dialog.showOpenDialog + const opened: unknown[][] = [] + electronModuleMock.dialog.showOpenDialog = async () => ({ canceled: false, filePaths: ['/tmp/Agent Report.pptx'] }) + const powerpoint = { + sessionForContents: (sender: number) => { + expect(sender).toBe(17) + return 'session-a' + }, + openFile: async (...args: unknown[]) => { opened.push(args) }, + } as unknown as EmbeddedPowerPointManager + testIpcHandlers.clear() + registerPowerPointHandlers(powerpoint, () => undefined) + try { + await testIpcHandlers.get(IPC.powerpoint.openDocument)?.({ sender: { id: 17 } } as IpcMainInvokeEvent) + expect(opened).toEqual([['session-a', '/tmp/Agent Report.pptx']]) + } finally { + electronModuleMock.dialog.showOpenDialog = originalShowOpenDialog + } + }) + + it('rejects a child renderer that names another Session while preserving trusted host routing', async () => { + const opened: unknown[][] = [] + const powerpoint = { + ownedSessionForContents: (sender: number) => sender === 17 ? 'session-a' : null, + openFile: async (...args: unknown[]) => { opened.push(args) }, + } as unknown as EmbeddedPowerPointManager + testIpcHandlers.clear() + registerPowerPointHandlers(powerpoint, () => undefined) + const openFile = testIpcHandlers.get(IPC.powerpoint.openFile)! + await expect(openFile({ sender: { id: 17 } } as IpcMainInvokeEvent, 'session-b', '/tmp/report.pptx')) + .rejects.toThrow('does not own') + await openFile({ sender: { id: 17 } } as IpcMainInvokeEvent, 'session-a', '/tmp/report.pptx') + await openFile({ sender: { id: 99 } } as IpcMainInvokeEvent, 'session-b', '/tmp/other.pptx') + expect(opened).toEqual([ + ['session-a', '/tmp/report.pptx'], + ['session-b', '/tmp/other.pptx'], + ]) + }) +}) diff --git a/desktop/apps/electron/src/main/__tests__/word-host-handler.test.ts b/desktop/apps/electron/src/main/__tests__/word-host-handler.test.ts index fb0c65d4..39c274aa 100644 --- a/desktop/apps/electron/src/main/__tests__/word-host-handler.test.ts +++ b/desktop/apps/electron/src/main/__tests__/word-host-handler.test.ts @@ -10,6 +10,32 @@ const { IPC } = await import('../../shared/ipc-channels') const { registerWordHostHandlers } = await import('../handlers/word-host') describe('Word host IPC boundary', () => { + it('opens a picked DOCX only in the sending child renderer Session', async () => { + const originalShowOpenDialog = electronModuleMock.dialog.showOpenDialog + const opened: unknown[][] = [] + electronModuleMock.dialog.showOpenDialog = async () => ({ canceled: false, filePaths: ['/tmp/Agent Report.docx'] }) + const word = { + sessionForContents: (sender: number) => { + expect(sender).toBe(17) + return 'session-a' + }, + openFile: async (...args: unknown[]) => { opened.push(args) }, + } as unknown as WordHost + testIpcHandlers.clear() + registerWordHostHandlers(word, () => undefined) + try { + await testIpcHandlers.get(IPC.wordHost.openDocument)?.({ sender: { id: 17 } } as IpcMainInvokeEvent) + expect(opened).toEqual([['session-a', { + id: 'renderer-open', + name: 'Agent Report.docx', + path: '/tmp/Agent Report.docx', + sessionId: 'session-a', + }]]) + } finally { + electronModuleMock.dialog.showOpenDialog = originalShowOpenDialog + } + }) + it('uses the sending child identity for runtime reports, completion and close requests', async () => { const calls: unknown[][] = [] const events: unknown[][] = [] diff --git a/desktop/apps/electron/src/main/__tests__/word-host-preload.test.ts b/desktop/apps/electron/src/main/__tests__/word-host-preload.test.ts index efcaf4ca..e983e7c6 100644 --- a/desktop/apps/electron/src/main/__tests__/word-host-preload.test.ts +++ b/desktop/apps/electron/src/main/__tests__/word-host-preload.test.ts @@ -32,6 +32,7 @@ it('buffers early Word runtime events and exposes only its narrow Session API', emit(IPC.events.wordHostOpenFileRequested, { ...request, id: 'second-ticket' }); exposed.api.onOpenFileRequested((value) => received.push(['replayed', value])); await exposed.api.readDocument('/tmp/a.docx'); + await exposed.api.openDocument(); await exposed.api.completeOpenFile('opaque-ticket'); await exposed.api.completeFlush('flush-ticket', true); await exposed.api.reportState({ documentCount: 1, persistenceStatus: 'saved' }); @@ -46,13 +47,14 @@ it('buffers early Word runtime events and exposes only its narrow Session API', const result = JSON.parse(stdout) as { name: string; keys: string[]; received: unknown[][]; invocations: unknown[][] } expect(result.name).toBe('wordHostApi') expect(result.keys.sort()).toEqual([ - 'completeFlush', 'completeOpenFile', 'getConfig', 'onConfigChanged', 'onExpandedChanged', + 'completeFlush', 'completeOpenFile', 'getConfig', 'onConfigChanged', 'onExpandedChanged', 'openDocument', 'onFlushRequested', 'onOpenFileRequested', 'readDocument', 'reportState', 'requestClose', 'setExpanded', ].sort()) expect(result.received.map(([kind]) => kind)).toEqual(['open', 'flush', 'config', 'expanded', 'replayed']) expect(result.received[2]).toEqual(['config', { locale: 'zh' }]) expect(result.invocations).toEqual([ ['word:read-document', '/tmp/a.docx'], + ['word-host:openDocument'], ['word-host:completeOpenFile', 'opaque-ticket', null], ['word-host:completeFlush', 'flush-ticket', true], ['word-host:reportState', { documentCount: 1, persistenceStatus: 'saved' }], diff --git a/desktop/apps/electron/src/main/embedded-powerpoint-manager.ts b/desktop/apps/electron/src/main/embedded-powerpoint-manager.ts index 3a01bc08..b5b845e0 100644 --- a/desktop/apps/electron/src/main/embedded-powerpoint-manager.ts +++ b/desktop/apps/electron/src/main/embedded-powerpoint-manager.ts @@ -9,6 +9,7 @@ import path from 'node:path' import type { EmbeddedPowerPointBounds, EmbeddedPowerPointOpenFileResult, + EmbeddedPowerPointRendererState, EmbeddedPowerPointSessionInfo, EmbeddedPowerPointSnapshot, } from '../shared/types' @@ -16,10 +17,12 @@ import { clampZoomLevel, type GuiSettings } from '@app/shared/types' import { IPC } from '../shared/ipc-channels' import { windowLog } from './logger' import { OfficeSessionContainer, type OfficeSessionRecord } from './office-session-container' +import type { PresentationMountReplacementValidation, PresentationMountUsage } from '../shared/presentation-host' const MAX_OPEN_PRESENTATION_BYTES = 250 * 1024 * 1024 interface EmbeddedPowerPointSurface extends OfficeSessionRecord { + documentCount: number | null loading: boolean openingFilesByPath: Map> } @@ -125,9 +128,30 @@ export class EmbeddedPowerPointManager { } sessionForContents(webContentsId: number): string { + const sessionId = this.ownedSessionForContents(webContentsId) + if (sessionId === null) throw new Error('PowerPoint Session does not own this renderer') + return sessionId + } + + /** Resolve a child renderer without rejecting trusted host-window callers. */ + ownedSessionForContents(webContentsId: number): string | null { + return this.container.forWebContents(webContentsId)?.sessionId ?? null + } + + /** Accept authoritative project inventory only from the Session-owned renderer. */ + reportState(webContentsId: number, value: unknown): void { const surface = this.container.forWebContents(webContentsId) if (!surface) throw new Error('PowerPoint Session does not own this renderer') - return surface.sessionId + if (!value || typeof value !== 'object' || Array.isArray(value)) { + throw new TypeError('Invalid PowerPoint runtime state') + } + const state = value as Partial + if (!Number.isSafeInteger(state.documentCount) || state.documentCount! < 0) { + throw new TypeError('Invalid PowerPoint runtime document count') + } + if (surface.documentCount === state.documentCount) return + surface.documentCount = state.documentCount! + this.publishState() } /** A delayed close belongs to its sender, even if this Session has since reopened. */ @@ -149,6 +173,23 @@ export class EmbeddedPowerPointManager { this.container.closeAll() } + async mountUsage(sessionId: string, mountId: string): Promise { + return this.callWorkspace(sessionId, 'mountUsage', [mountId]) + } + + async validateMountReplacement(sessionId: string, mountId: string, path: string): Promise { + return this.callWorkspace(sessionId, 'validateMountReplacement', [mountId, path]) + } + + async removeMountReferences(sessionId: string, mountId: string): Promise { + return this.callWorkspace(sessionId, 'removeMountReferences', [mountId], true) + } + + refreshSources(sessionId: string): void { + const surface = this.container.get(this.normalizeSessionId(sessionId)) + if (surface && !surface.view.webContents.isDestroyed()) surface.view.webContents.send('office-files:changed', surface.sessionId) + } + /** Keep dedicated PPT renderers aligned with the main App theme, locale, and zoom. */ applySettings(settings: GuiSettings): void { const zoomLevel = clampZoomLevel(settings.zoomLevel) @@ -178,6 +219,7 @@ export class EmbeddedPowerPointManager { sessionId, view, targetId: null, + documentCount: null, loading: true, crashed: false, ready: Promise.resolve(), @@ -186,6 +228,7 @@ export class EmbeddedPowerPointManager { view.webContents.setBackgroundThrottling(false) view.webContents.on('did-start-loading', () => { if (!this.container.owns(surface)) return + surface.documentCount = null surface.loading = true this.publishState() }) @@ -206,7 +249,7 @@ export class EmbeddedPowerPointManager { ): Promise { const content = await readFile(canonicalPath) const value = await this.dispatchToSurface(surface, { - method: 'view_ppt', + method: 'open', params: { target: canonicalPath, file_name: path.basename(canonicalPath), @@ -217,26 +260,25 @@ export class EmbeddedPowerPointManager { throw new Error('PowerPoint renderer returned an invalid file-open result') } const result = value as Record - const identity = result.identity - const meta = result.meta - if (!identity || typeof identity !== 'object' || Array.isArray(identity)) { - throw new Error('PowerPoint renderer returned an invalid file identity') - } - if (!meta || typeof meta !== 'object' || Array.isArray(meta)) { + const deck = result.deck + if (!deck || typeof deck !== 'object' || Array.isArray(deck)) { throw new Error('PowerPoint renderer returned invalid file metadata') } - const identityValue = identity as Record - const metaValue = meta as Record - if (typeof identityValue.document_id !== 'string' || typeof metaValue.total_pages !== 'number') { + const deckValue = deck as Record + if ( + typeof result.document_id !== 'string' + || deckValue.id !== result.document_id + || typeof deckValue.total_pages !== 'number' + ) { throw new Error('PowerPoint renderer returned an incomplete file-open result') } return { - documentId: identityValue.document_id, + documentId: result.document_id, fileName: path.basename(canonicalPath), reused: result.reused === true, - slideCount: metaValue.total_pages, - title: typeof identityValue.name === 'string' - ? identityValue.name + slideCount: deckValue.total_pages, + title: typeof deckValue.title === 'string' && deckValue.title.trim() + ? deckValue.title : path.basename(canonicalPath, '.pptx'), } } @@ -258,6 +300,17 @@ export class EmbeddedPowerPointManager { return response.value } + private async callWorkspace(sessionId: string, method: 'mountUsage' | 'validateMountReplacement' | 'removeMountReferences', args: string[], flush = false): Promise { + if (typeof args[0] !== 'string' || !args[0].trim()) throw new Error('A mount is required') + const id = this.normalizeSessionId(sessionId) + await this.ensureSession(id) + const surface = this.container.get(id)! + const serialized = args.map((value) => JSON.stringify(value)).join(', ') + return surface.ready.then(() => surface.view.webContents.executeJavaScript( + `(async () => { const workspace = window.__bridgicPowerPoint; if (!workspace || workspace.sessionId !== ${JSON.stringify(id)} || typeof workspace.${method} !== 'function') throw new Error('PowerPoint workspace unavailable'); const value = await workspace.${method}(${serialized}); ${flush ? 'await workspace.flush?.();' : ''} return value; })()`, + )) as Promise + } + private infoFor(surface: EmbeddedPowerPointSurface): EmbeddedPowerPointSessionInfo { return { sessionId: surface.sessionId, @@ -265,6 +318,7 @@ export class EmbeddedPowerPointManager { webContentsId: surface.view.webContents.id, loading: surface.loading, crashed: surface.crashed, + documentCount: surface.documentCount, } } diff --git a/desktop/apps/electron/src/main/excel-host.ts b/desktop/apps/electron/src/main/excel-host.ts index 80e2a6c4..5547fbac 100644 --- a/desktop/apps/electron/src/main/excel-host.ts +++ b/desktop/apps/electron/src/main/excel-host.ts @@ -9,6 +9,7 @@ import { pathToFileURL } from 'node:url' import type { EmbeddedBrowserBounds, ExcelHostConfig, + ExcelHostRendererState, ExcelHostSessionInfo, ExcelHostSnapshot, ExcelWorkbookOpenRequest, @@ -37,6 +38,7 @@ const WEB_PREFERENCES: NonNullable createInitialWorkbook: boolean @@ -160,12 +162,19 @@ export class ExcelHost { return results.every((result) => result.status === 'fulfilled') } - setDirty(webContentsId: number, dirty: boolean): void { - if (typeof dirty !== 'boolean') throw new TypeError('Excel dirty state must be a boolean') + reportState(webContentsId: number, value: unknown): void { const record = this.recordForWebContents(webContentsId) if (!record) throw new Error('Excel Session does not own this renderer') - if (record.dirty === dirty) return - record.dirty = dirty + if (!value || typeof value !== 'object' || Array.isArray(value)) { + throw new TypeError('Invalid Excel runtime state') + } + const state = value as Partial + if (!Number.isSafeInteger(state.documentCount) || state.documentCount! < 0 || typeof state.dirty !== 'boolean') { + throw new TypeError('Invalid Excel runtime document count or dirty state') + } + if (record.documentCount === state.documentCount && record.dirty === state.dirty) return + record.documentCount = state.documentCount! + record.dirty = state.dirty this.publishState() } @@ -218,6 +227,7 @@ export class ExcelHost { targetId: null, crashed: false, dirty: false, + documentCount: null, recoveryState: null, workbookOpenRequests: new Map(), createInitialWorkbook, @@ -247,6 +257,7 @@ export class ExcelHost { }) contents.on('render-process-gone', () => { if (!this.container.owns(record) || contents.isDestroyed()) return + record.documentCount = null this.container.invalidate(record) void this.container.reload(record, (current) => ( current.view.webContents.loadURL(this.rendererUrl(current)) @@ -296,6 +307,7 @@ export class ExcelHost { ready: record.targetId !== null && !record.crashed, crashed: record.crashed, dirty: record.dirty, + documentCount: record.documentCount, } } diff --git a/desktop/apps/electron/src/main/handlers/excel-host.ts b/desktop/apps/electron/src/main/handlers/excel-host.ts index 8a81676f..3e953acb 100644 --- a/desktop/apps/electron/src/main/handlers/excel-host.ts +++ b/desktop/apps/electron/src/main/handlers/excel-host.ts @@ -39,8 +39,8 @@ export function registerExcelHostHandlers(excelHost: ExcelHost, browser: Embedde emitToHost, }) - loggedHandle(IPC.excelHost.setDirty, (event, dirty: boolean) => { - excelHost.setDirty(event.sender.id, dirty) + loggedHandle(IPC.excelHost.reportState, (event, state: unknown) => { + excelHost.reportState(event.sender.id, state) }) loggedHandle(IPC.excelHost.getRecoveryState, (event) => { diff --git a/desktop/apps/electron/src/main/handlers/index.ts b/desktop/apps/electron/src/main/handlers/index.ts index 14edd8ee..618667ff 100644 --- a/desktop/apps/electron/src/main/handlers/index.ts +++ b/desktop/apps/electron/src/main/handlers/index.ts @@ -11,6 +11,7 @@ import { registerFsHandlers } from './fs' import { registerFsWatchHandlers } from './fs-watch' import { registerIssueReportHandlers } from './issue-report' import { registerMarketHandlers } from './market' +import { registerMountReferenceHandlers } from './mount-references' import { registerNotifyHandlers } from './notify' import { registerPowerPointHandlers } from './powerpoint' import { registerSettingsHandlers } from './settings' @@ -52,6 +53,13 @@ export function registerAllHandlers(windowManager: WindowManager, quitApp: () => const window = windowManager.getMainWindow() if (window && !window.isDestroyed()) window.webContents.send(channel, value) }) + const powerpoint = windowManager.getEmbeddedPowerPoint() + registerMountReferenceHandlers([{ + usage: (sessionId, mountId) => powerpoint.mountUsage(sessionId, mountId), + validateReplacement: (sessionId, mountId, path) => powerpoint.validateMountReplacement(sessionId, mountId, path), + remove: (sessionId, mountId) => powerpoint.removeMountReferences(sessionId, mountId), + refresh: (sessionId) => powerpoint.refreshSources(sessionId), + }]) registerWordHandlers() registerWordHostHandlers(windowManager.getWordHost(), (channel, value) => { const window = windowManager.getMainWindow() diff --git a/desktop/apps/electron/src/main/handlers/mount-references.ts b/desktop/apps/electron/src/main/handlers/mount-references.ts new file mode 100644 index 00000000..9e7aa55b --- /dev/null +++ b/desktop/apps/electron/src/main/handlers/mount-references.ts @@ -0,0 +1,47 @@ +import { BrowserWindow } from 'electron' +import { IPC } from '../../shared/ipc-channels' +import type { + MountReferenceRebindResult, + MountReferenceSummary, + MountReferenceUsage, + MountReplacementValidation, +} from '../../shared/mount-references' +import { officeWorkspaceRequest } from '../office-workspace-backend' +import { loggedHandle } from './logged-handle' +import { redactLocalPathLogArgs } from './path-log' + +export interface MountReferenceProvider { + usage(sessionId: string, mountId: string): Promise + validateReplacement(sessionId: string, mountId: string, path: string): Promise + remove(sessionId: string, mountId: string): Promise + refresh(sessionId: string): void | Promise +} + +const mountsPath = (id: string) => `/sessions/${encodeURIComponent(id)}/mounts` +const totalUsage = (usages: readonly MountReferenceUsage[]): MountReferenceUsage => usages.reduce((total, usage) => ({ + assetCount: total.assetCount + usage.assetCount, + elementCount: total.elementCount + usage.elementCount, + projectCount: total.projectCount + usage.projectCount, +}), { assetCount: 0, elementCount: 0, projectCount: 0 }) + +export function registerMountReferenceHandlers(providers: readonly MountReferenceProvider[]): void { + loggedHandle(IPC.mountReferences.usage, async (_event, sessionId: string, mountId: string) => { + return totalUsage(await Promise.all(providers.map((provider) => provider.usage(sessionId, mountId)))) + }) + loggedHandle(IPC.mountReferences.remove, async (_event, sessionId: string, mountId: string) => { + return totalUsage(await Promise.all(providers.map((provider) => provider.remove(sessionId, mountId)))) + }) + loggedHandle(IPC.mountReferences.refresh, async (_event, sessionId: string) => { + await Promise.all(providers.map((provider) => provider.refresh(sessionId))) + }) + loggedHandle(IPC.mountReferences.rebind, async (_event, sessionId: string, mountId: string, path: string): Promise => { + if (typeof path !== 'string' || !path.trim()) throw new Error('A replacement path is required') + const validations = await Promise.all(providers.map((provider) => provider.validateReplacement(sessionId, mountId, path))) + const rejected = validations.find((validation): validation is Exclude => !validation.compatible) + if (rejected) return { ok: false, validation: rejected } + const mount = await officeWorkspaceRequest(mountsPath(sessionId), { id: mountId, path }, 'PATCH') as MountReferenceSummary + for (const window of BrowserWindow.getAllWindows()) if (!window.isDestroyed()) window.webContents.send('office-files:changed', sessionId) + await Promise.all(providers.map((provider) => provider.refresh(sessionId))) + return { ok: true, mount } + }, { transformLogArgs: redactLocalPathLogArgs }) +} diff --git a/desktop/apps/electron/src/main/handlers/office-files.ts b/desktop/apps/electron/src/main/handlers/office-files.ts index ecd8a623..7b6986dc 100644 --- a/desktop/apps/electron/src/main/handlers/office-files.ts +++ b/desktop/apps/electron/src/main/handlers/office-files.ts @@ -1,7 +1,7 @@ import { app, BrowserWindow, dialog } from 'electron' import { basename, extname, join } from 'node:path' import { readFile, stat } from 'node:fs/promises' -import type { OfficeCloseDecision, OfficeFileKind, OfficeFileSaveRequest } from '../../shared/office-files' +import type { OfficeCloseDecision, OfficeFileKind, OfficeFileSaveRequest, OfficeRecoveryKind } from '../../shared/office-files' import { createOfficeRecoveryStore, inspectOfficeFile, OFFICE_EXTENSIONS, saveOfficeFile } from '../office-files' import { loggedHandle } from './logged-handle' import { createOfficeWorkspaceFiles } from '../office-workspace-files' @@ -25,6 +25,12 @@ export function registerOfficeFileHandlers(owner: (kind: OfficeFileKind, content if ((await stat(source.path)).size > 150 * 1024 * 1024) throw new Error('Office file exceeds the size limit') return (await readFile(source.path)).toString('base64') }) + loggedHandle('office-files:list-presentation-mounts', (event) => { + return workspace.listPresentationMounts(owner('presentation', event.sender.id)) + }) + loggedHandle('office-files:mount-presentation-source', (event, source: { dataBase64?: string; fileName: string; mimeType: string; path?: string }) => { + return workspace.mountPresentationSource(owner('presentation', event.sender.id), source) + }) const recovery = createOfficeRecoveryStore(join(app.getPath('userData'), 'office-recovery')) loggedHandle('office-files:inspect', (event, kind: OfficeFileKind, path: string) => { owner(kind, event.sender.id) @@ -61,11 +67,13 @@ export function registerOfficeFileHandlers(owner: (kind: OfficeFileKind, content const result = window ? await dialog.showMessageBox(window, options) : await dialog.showMessageBox(options) return (['save', 'discard', 'cancel'] as const)[result.response] ?? 'cancel' }) - loggedHandle('office-files:get-recovery', (event, kind: OfficeFileKind, sessionId: string) => { + loggedHandle('office-files:get-recovery', (event, kind: OfficeRecoveryKind, sessionId: string) => { + if (kind !== 'excel') throw new TypeError('Only Excel uses main-process Office recovery') if (owner(kind, event.sender.id) !== sessionId) throw new Error('Office recovery belongs to another Session') return recovery.read(kind, sessionId) }) - loggedHandle('office-files:set-recovery', (event, kind: OfficeFileKind, sessionId: string, value: string) => { + loggedHandle('office-files:set-recovery', (event, kind: OfficeRecoveryKind, sessionId: string, value: string) => { + if (kind !== 'excel') throw new TypeError('Only Excel uses main-process Office recovery') if (owner(kind, event.sender.id) !== sessionId) throw new Error('Office recovery belongs to another Session') return recovery.write(kind, sessionId, value) }, { transformLogArgs: ([kind, sessionId, value]) => ({ kind, sessionId, bytes: typeof value === 'string' ? value.length : 0 }) }) diff --git a/desktop/apps/electron/src/main/handlers/powerpoint.ts b/desktop/apps/electron/src/main/handlers/powerpoint.ts index 9336227d..dd381642 100644 --- a/desktop/apps/electron/src/main/handlers/powerpoint.ts +++ b/desktop/apps/electron/src/main/handlers/powerpoint.ts @@ -1,3 +1,4 @@ +import { BrowserWindow, dialog, type OpenDialogOptions } from 'electron' import { IPC } from '../../shared/ipc-channels' import type { EmbeddedPowerPointBounds } from '../../shared/types' import type { EmbeddedPowerPointManager } from '../embedded-powerpoint-manager' @@ -51,9 +52,34 @@ export function registerPowerPointHandlers( emitToHost(IPC.events.powerPointExpandedChanged, expanded) }) + loggedHandle(IPC.powerpoint.reportState, (event, state: unknown) => { + powerpoint.reportState(event.sender.id, state) + }) + + loggedHandle(IPC.powerpoint.openDocument, async (event) => { + const sessionId = powerpoint.sessionForContents(event.sender.id) + const options: OpenDialogOptions = { + title: 'Open PowerPoint Presentation', + properties: ['openFile'], + filters: [{ name: 'PowerPoint presentations', extensions: ['pptx'] }], + } + const win = BrowserWindow.getFocusedWindow() ?? BrowserWindow.getAllWindows()[0] + const result = win ? await dialog.showOpenDialog(win, options) : await dialog.showOpenDialog(options) + const path = result.filePaths[0] + if (result.canceled || !path) return + await powerpoint.openFile(sessionId, path) + }, { transformLogArgs: redactLocalPathLogArgs }) + loggedHandle( IPC.powerpoint.openFile, - (_event, sessionId: string, absPath: string) => powerpoint.openFile(sessionId, absPath), + (event, sessionId: string, absPath: string) => { + const ownedSessionId = powerpoint.ownedSessionForContents(event.sender.id) + if (ownedSessionId !== null && ownedSessionId !== String(sessionId ?? '').trim()) { + throw new Error('PowerPoint Session does not own the requested editor') + } + return powerpoint.openFile(ownedSessionId ?? sessionId, absPath) + }, { transformLogArgs: redactLocalPathLogArgs }, ) + } diff --git a/desktop/apps/electron/src/main/handlers/word-host.ts b/desktop/apps/electron/src/main/handlers/word-host.ts index 5c062d8e..e8feda4a 100644 --- a/desktop/apps/electron/src/main/handlers/word-host.ts +++ b/desktop/apps/electron/src/main/handlers/word-host.ts @@ -1,3 +1,5 @@ +import { basename } from 'node:path' +import { BrowserWindow, dialog, type OpenDialogOptions } from 'electron' import { IPC } from '../../shared/ipc-channels' import type { EmbeddedBrowserBounds, WordHostOpenRequest } from '../../shared/types' import type { WordHost } from '../word-host' @@ -23,6 +25,19 @@ export function registerWordHostHandlers(word: WordHost, emitToHost: (channel: s loggedHandle(IPC.wordHost.openFile, (_event, sessionId: string, request: WordHostOpenRequest) => word.openFile(sessionId, request), { transformLogArgs: redactLocalPathLogArgs, }) + loggedHandle(IPC.wordHost.openDocument, async (event) => { + const sessionId = word.sessionForContents(event.sender.id) + const options: OpenDialogOptions = { + title: 'Open Word Document', + properties: ['openFile'], + filters: [{ name: 'Word documents', extensions: ['docx'] }], + } + const win = BrowserWindow.getFocusedWindow() ?? BrowserWindow.getAllWindows()[0] + const result = win ? await dialog.showOpenDialog(win, options) : await dialog.showOpenDialog(options) + const path = result.filePaths[0] + if (result.canceled || !path) return + await word.openFile(sessionId, { id: 'renderer-open', name: basename(path), path, sessionId }) + }, { transformLogArgs: redactLocalPathLogArgs }) loggedHandle(IPC.wordHost.getConfig, (event) => { word.sessionForContents(event.sender.id) return word.getConfig() diff --git a/desktop/apps/electron/src/main/office-files.ts b/desktop/apps/electron/src/main/office-files.ts index b5a4e4a1..657bf746 100644 --- a/desktop/apps/electron/src/main/office-files.ts +++ b/desktop/apps/electron/src/main/office-files.ts @@ -1,7 +1,7 @@ import { createHash, randomUUID } from 'node:crypto' import { mkdir, readFile, realpath, rename, stat, unlink, writeFile } from 'node:fs/promises' import { basename, dirname, extname, isAbsolute, join } from 'node:path' -import type { OfficeFileKind, OfficeFileSaveRequest, OfficeFileSaveResult, OfficeFileSource } from '../shared/office-files' +import type { OfficeFileKind, OfficeFileSaveRequest, OfficeFileSaveResult, OfficeFileSource, OfficeRecoveryKind } from '../shared/office-files' export const OFFICE_EXTENSIONS = { word: '.docx', excel: '.xlsx', presentation: '.pptx' } as const @@ -50,15 +50,15 @@ export async function saveOfficeFile(request: OfficeFileSaveRequest, destination return { ok: true, source: await inspectOfficeFile(request.kind, current.path), fileName: basename(current.path) } } -/** Private recovery files are separate from user documents and survive application restart. */ +/** Excel private recovery files are separate from user documents and survive application restart. */ export function createOfficeRecoveryStore(root: string) { const pending = new Map>() - const pathFor = (kind: OfficeFileKind, sessionId: string) => { - if (!Object.hasOwn(OFFICE_EXTENSIONS, kind) || typeof sessionId !== 'string' || !sessionId) throw new TypeError('Invalid Office recovery owner') + const pathFor = (kind: OfficeRecoveryKind, sessionId: string) => { + if (kind !== 'excel' || typeof sessionId !== 'string' || !sessionId) throw new TypeError('Invalid Office recovery owner') return join(root, kind, `${createHash('sha256').update(sessionId).digest('hex')}.json`) } return { - async read(kind: OfficeFileKind, sessionId: string): Promise { + async read(kind: OfficeRecoveryKind, sessionId: string): Promise { const path = pathFor(kind, sessionId) await pending.get(path) try { return await readFile(path, 'utf8') } catch (error) { @@ -66,7 +66,7 @@ export function createOfficeRecoveryStore(root: string) { throw error } }, - write(kind: OfficeFileKind, sessionId: string, value: string): Promise { + write(kind: OfficeRecoveryKind, sessionId: string, value: string): Promise { if (typeof value !== 'string' || value.length > 400 * 1024 * 1024) return Promise.reject(new TypeError('Invalid Office recovery payload')) const path = pathFor(kind, sessionId) const write = (pending.get(path) ?? Promise.resolve()).catch(() => undefined).then(async () => { diff --git a/desktop/apps/electron/src/main/office-workspace-backend.ts b/desktop/apps/electron/src/main/office-workspace-backend.ts index c0cb3196..906be643 100644 --- a/desktop/apps/electron/src/main/office-workspace-backend.ts +++ b/desktop/apps/electron/src/main/office-workspace-backend.ts @@ -3,11 +3,11 @@ import { pythonClient } from './python-client' import { guiClientId } from './gui-client-id' /** Resolve workspace ownership through the same authenticated Session API as the file panel. */ -export async function officeWorkspaceRequest(path: string, body?: unknown): Promise { +export async function officeWorkspaceRequest(path: string, body?: unknown, method?: 'POST' | 'PATCH'): Promise { const endpoint = pythonClient.snapshot().endpoint if (!endpoint?.token) throw new Error('The Session service is unavailable') const result = await fetch(`${endpoint.baseUrl}${path}`, { - method: body === undefined ? 'GET' : 'POST', + method: body === undefined ? 'GET' : method ?? 'POST', headers: { [AUTH_HEADER_NAME]: `Bearer ${endpoint.token}`, [CLIENT_ID_HEADER]: guiClientId(), [CLIENT_TYPE_HEADER]: 'gui', 'Content-Type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(30_000), diff --git a/desktop/apps/electron/src/main/office-workspace-files.ts b/desktop/apps/electron/src/main/office-workspace-files.ts index cbd885f0..616f9288 100644 --- a/desktop/apps/electron/src/main/office-workspace-files.ts +++ b/desktop/apps/electron/src/main/office-workspace-files.ts @@ -1,11 +1,12 @@ import { createHash } from 'node:crypto' -import { mkdir, open, readFile, realpath, unlink } from 'node:fs/promises' +import { mkdir, open, readFile, realpath, stat, unlink } from 'node:fs/promises' import { basename, dirname, extname, join, relative, isAbsolute } from 'node:path' import type { OfficeFileKind, OfficeFileSaveRequest, OfficeFileSource } from '../shared/office-files' +import type { PresentationMountedSource, PresentationSourceMount } from '../shared/presentation-host' import { inspectOfficeFile, OFFICE_EXTENSIONS, officePath, saveOfficeFile, writeOfficeBytes } from './office-files' -type Mount = { path: string; kind: string; removable?: boolean } -interface WriteReceipt { source: OfficeFileSource; fingerprint: string } +type Mount = PresentationSourceMount +interface WriteReceipt { source: OfficeFileSource; fingerprint: string; protectedSourcePath?: string | null } const fingerprint = (bytes: Uint8Array) => createHash('sha256').update(bytes).digest('hex') const isWithin = (root: string, path: string) => { const rel = relative(root, path) @@ -15,17 +16,18 @@ const isWithin = (root: string, path: string) => { export function createOfficeWorkspaceFiles(request: (path: string, body?: unknown) => Promise, changed: (sessionId: string) => void) { const imports = new Map>() const mountsPath = (id: string) => `/sessions/${encodeURIComponent(id)}/mounts` - const workDir = async (id: string) => { + const workMount = async (id: string) => { const mounts = await request(mountsPath(id)) as Mount[] const work = mounts.find((mount) => mount.kind === 'folder' && mount.removable === false && basename(mount.path) === '.work') if (!work) throw new Error('The Session workspace is unavailable') - return realpath(work.path) + return { mount: work, path: await realpath(work.path) } } - const register = async (id: string, path: string) => { + const workDir = async (id: string) => (await workMount(id)).path + const register = async (id: string, path: string): Promise => { const mount = await request(mountsPath(id), { path }) as Mount - if (!mount || typeof mount.path !== 'string') throw new Error('The imported Office file was not registered') + if (!mount || typeof mount.id !== 'string' || typeof mount.path !== 'string') throw new Error('The imported Office file was not registered') changed(id) - return mount.path + return mount } const prepare = (id: string, kind: OfficeFileKind, path: string): Promise => { officePath(kind, path) @@ -39,13 +41,40 @@ export function createOfficeWorkspaceFiles(request: (path: string, body?: unknow if (!isWithin(work, source.path)) throw new Error('New Office files must be created in the Session workspace') return source } - return inspectOfficeFile(kind, await register(id, source.path)) + return inspectOfficeFile(kind, (await register(id, source.path)).path) })() imports.set(key, pending) void pending.finally(() => { if (imports.get(key) === pending) imports.delete(key) }).catch(() => undefined) } return pending } + const writePresentationSource = async (id: string, input: { dataBase64: string; fileName: string; mimeType: string }): Promise => { + if (!input || typeof input.fileName !== 'string' || !input.fileName.trim() || typeof input.mimeType !== 'string' || !input.mimeType.trim()) { + throw new TypeError('Invalid PowerPoint source') + } + const maximumBytes = 60 * 1024 * 1024 + if (typeof input.dataBase64 !== 'string' + || input.dataBase64.length > Math.ceil(maximumBytes / 3) * 4 + || input.dataBase64.length % 4 !== 0 + || !/^[A-Za-z0-9+/]*={0,2}$/.test(input.dataBase64)) { + throw new TypeError('PowerPoint embedded source data is invalid') + } + const bytes = Buffer.from(input.dataBase64, 'base64') + if (bytes.toString('base64') !== input.dataBase64) throw new TypeError('PowerPoint embedded source data is invalid') + if (bytes.byteLength > maximumBytes) throw new Error('PowerPoint source exceeds the size limit') + const workspace = await workMount(id) + const safeName = basename(input.fileName).replace(/[<>:"/\\|?*\x00-\x1f]/g, '_') || 'asset.bin' + const path = join(workspace.path, `${fingerprint(bytes)}-${safeName}`) + await mkdir(dirname(path), { recursive: true }) + const file = await open(path, 'wx', 0o600).catch((error: NodeJS.ErrnoException) => { + if (error.code === 'EEXIST') return null + throw error + }) + if (file) { + try { await file.writeFile(bytes) } finally { await file.close() } + } + return path + } return { prepare, async save(id: string, input: OfficeFileSaveRequest) { @@ -61,19 +90,33 @@ export function createOfficeWorkspaceFiles(request: (path: string, body?: unknow if (!receipt?.source || typeof receipt.source.path !== 'string' || !isWithin(root, receipt.source.path) || (receipt.source.mtimeMs !== null && !Number.isFinite(receipt.source.mtimeMs)) - || typeof receipt.fingerprint !== 'string' || !/^[a-f0-9]{64}$/.test(receipt.fingerprint)) throw new Error('The Office write receipt is invalid') + || typeof receipt.fingerprint !== 'string' || !/^[a-f0-9]{64}$/.test(receipt.fingerprint) + || (receipt.protectedSourcePath != null && typeof receipt.protectedSourcePath !== 'string')) throw new Error('The Office write receipt is invalid') officePath(input.kind, receipt.source.path) + if (receipt.protectedSourcePath) officePath(input.kind, receipt.protectedSourcePath) return receipt } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null throw error } } - let source = input.source + // A limited importer must never overwrite the original, even for managed files. + // Allocate a sibling on the first edit, then continue saving that editable copy. + let source = input.preserveSource ? undefined : input.source if (source && !isWithin(root, source.path)) source = await prepare(id, input.kind, source.path) let allocated: string | undefined const receipt = !source || (await inspectOfficeFile(input.kind, source.path)).mtimeMs !== source.mtimeMs ? await readReceipt() : null - if (!source && receipt) source = receipt.source + const reusableCopy = receipt && receipt.protectedSourcePath !== undefined && input.source + && (input.source.path === receipt.protectedSourcePath || input.source.path === receipt.source.path) + if (!source && receipt && (!input.preserveSource || reusableCopy)) { + // Once acknowledged, the renderer's source is the copy. Keep its expected + // mtime so external changes remain conflicts rather than being overwritten. + source = input.source?.path === receipt.source.path ? input.source : receipt.source + } + let protectedSourcePath: string | null | undefined + if (input.preserveSource) { + protectedSourcePath = reusableCopy ? receipt!.protectedSourcePath : input.source?.path ?? null + } if (!source) { const extension = OFFICE_EXTENSIONS[input.kind] const name = basename(input.suggestedName).replace(/[<>:"/\\|?*\x00-\x1f]/g, '_') || `Untitled${extension}` @@ -99,7 +142,7 @@ export function createOfficeWorkspaceFiles(request: (path: string, body?: unknow // allocated name without making a duplicate or trusting a stale renderer mtime. try { await mkdir(dirname(receiptPath), { recursive: true }) - await writeOfficeBytes(receiptPath, JSON.stringify({ source, fingerprint: fingerprint(input.bytes) } satisfies WriteReceipt)) + await writeOfficeBytes(receiptPath, JSON.stringify({ source, fingerprint: fingerprint(input.bytes), protectedSourcePath } satisfies WriteReceipt)) } catch (error) { if (allocated) await unlink(allocated).catch(() => undefined) throw error @@ -112,5 +155,23 @@ export function createOfficeWorkspaceFiles(request: (path: string, body?: unknow } return result }, + async listPresentationMounts(id: string): Promise { + return request(mountsPath(id)) as Promise + }, + async mountPresentationSource(id: string, input: { dataBase64?: string; fileName: string; mimeType: string; path?: string }): Promise { + if (!input || typeof input.fileName !== 'string' || !input.fileName.trim() || typeof input.mimeType !== 'string' || !input.mimeType.trim()) { + throw new TypeError('Invalid PowerPoint source') + } + if (input.path) { + const workspace = await workMount(id) + const absolute = isAbsolute(input.path) + const candidate = absolute ? await realpath(input.path) : await realpath(join(workspace.path, input.path)) + if (!absolute && !isWithin(workspace.path, candidate)) throw new Error('A relative PowerPoint source must stay inside the Session workspace') + if (!(await stat(candidate)).isFile()) throw new Error('A PowerPoint source must be a file') + return register(id, candidate) + } + if (typeof input.dataBase64 !== 'string') throw new TypeError('PowerPoint embedded source data is invalid') + return register(id, await writePresentationSource(id, { dataBase64: input.dataBase64, fileName: input.fileName, mimeType: input.mimeType })) + }, } } diff --git a/desktop/apps/electron/src/preload/bootstrap.ts b/desktop/apps/electron/src/preload/bootstrap.ts index 24499be5..92c3baf3 100644 --- a/desktop/apps/electron/src/preload/bootstrap.ts +++ b/desktop/apps/electron/src/preload/bootstrap.ts @@ -113,8 +113,16 @@ const api: ElectronAPI = { ipcRenderer.invoke(IPC.powerpoint.setVisible, visible, focusHost), requestClose: (sessionId) => ipcRenderer.invoke(IPC.powerpoint.requestClose, sessionId), setExpanded: (expanded) => ipcRenderer.invoke(IPC.powerpoint.setExpanded, expanded), + reportState: (state) => ipcRenderer.invoke(IPC.powerpoint.reportState, state), + openDocument: () => ipcRenderer.invoke(IPC.powerpoint.openDocument), openFile: (sessionId, absPath) => ipcRenderer.invoke(IPC.powerpoint.openFile, sessionId, absPath), }, + mountReferences: { + usage: (sessionId, mountId) => ipcRenderer.invoke(IPC.mountReferences.usage, sessionId, mountId), + remove: (sessionId, mountId) => ipcRenderer.invoke(IPC.mountReferences.remove, sessionId, mountId), + rebind: (sessionId, mountId, path) => ipcRenderer.invoke(IPC.mountReferences.rebind, sessionId, mountId, path), + refresh: (sessionId) => ipcRenderer.invoke(IPC.mountReferences.refresh, sessionId), + }, word: { readDocument: (path) => ipcRenderer.invoke(IPC.word.readDocument, path), }, diff --git a/desktop/apps/electron/src/preload/excel-host.ts b/desktop/apps/electron/src/preload/excel-host.ts index 590e6d43..c80b8d85 100644 --- a/desktop/apps/electron/src/preload/excel-host.ts +++ b/desktop/apps/electron/src/preload/excel-host.ts @@ -29,7 +29,7 @@ const api: ExcelHostPreloadAPI = { save: (request) => ipcRenderer.invoke(IPC.excel.save, request), saveAs: (request) => ipcRenderer.invoke(IPC.excel.saveAs, request), requestClose: () => ipcRenderer.invoke(IPC.excelHost.requestClose), - setDirty: (dirty) => ipcRenderer.invoke(IPC.excelHost.setDirty, dirty), + reportState: (state) => ipcRenderer.invoke(IPC.excelHost.reportState, state), getRecoveryState: () => ipcRenderer.invoke(IPC.excelHost.getRecoveryState), setRecoveryState: (state) => ipcRenderer.invoke(IPC.excelHost.setRecoveryState, state), onConfigChanged: (callback) => { diff --git a/desktop/apps/electron/src/preload/office-files.ts b/desktop/apps/electron/src/preload/office-files.ts index c4111014..37d782e0 100644 --- a/desktop/apps/electron/src/preload/office-files.ts +++ b/desktop/apps/electron/src/preload/office-files.ts @@ -10,6 +10,8 @@ export const officeFiles: OfficeFilesAPI = { ipcRenderer.on('office-files:changed', listener) return () => ipcRenderer.removeListener('office-files:changed', listener) }, + listPresentationMounts: () => ipcRenderer.invoke('office-files:list-presentation-mounts'), + mountPresentationSource: (source) => ipcRenderer.invoke('office-files:mount-presentation-source', source), inspect: (kind, path) => ipcRenderer.invoke('office-files:inspect', kind, path), save: (request) => ipcRenderer.invoke('office-files:save', request), confirmClose: (name, locale) => ipcRenderer.invoke('office-files:confirm-close', name, locale), diff --git a/desktop/apps/electron/src/preload/word-host.ts b/desktop/apps/electron/src/preload/word-host.ts index 5d868b5b..0072bb86 100644 --- a/desktop/apps/electron/src/preload/word-host.ts +++ b/desktop/apps/electron/src/preload/word-host.ts @@ -36,6 +36,7 @@ function latestEvent(channel: string) { const api: WordHostPreloadAPI = { getConfig: () => ipcRenderer.invoke(IPC.wordHost.getConfig), + openDocument: () => ipcRenderer.invoke(IPC.wordHost.openDocument), readDocument: (path) => ipcRenderer.invoke(IPC.word.readDocument, path), reportState: (state) => ipcRenderer.invoke(IPC.wordHost.reportState, state), requestClose: () => ipcRenderer.invoke(IPC.wordHost.requestClose), diff --git a/desktop/apps/electron/src/renderer/atoms/__tests__/agent.test.ts b/desktop/apps/electron/src/renderer/atoms/__tests__/agent.test.ts index 2bf0a6af..4264d4e5 100644 --- a/desktop/apps/electron/src/renderer/atoms/__tests__/agent.test.ts +++ b/desktop/apps/electron/src/renderer/atoms/__tests__/agent.test.ts @@ -948,18 +948,14 @@ describe('reducer: tool calls', () => { it('classifies visible PowerPoint actions and reveals their Session surface', () => { const visibleActions = [ - 'view_ppt', - 'update_ppt_design', - 'edit_ppt_page', - 'insert_ppt_element', - 'remove_ppt_element', - 'insert_ppt_page', - 'remove_ppt_page', - 'move_ppt_page', - 'goto_ppt_page', + 'ppt_open', + 'ppt_edit_page', + 'ppt_manage_deck', + 'ppt_inspect', + 'ppt_save', ] expect(visibleActions.every(isPowerPointAgentActionToolName)).toBe(true) - expect(isPowerPointAgentActionToolName('get_ppt_page')).toBe(false) + expect(isPowerPointAgentActionToolName('ppt_read_page')).toBe(false) const store = makeStore() const id = setupSession(store) @@ -976,7 +972,7 @@ describe('reducer: tool calls', () => { type: 'tool_call', messageId: 'powerpoint-write', toolUseId: 'view-deck', - toolName: 'view_ppt', + toolName: 'ppt_open', input: { target: 'quarterly-review' }, }, }) diff --git a/desktop/apps/electron/src/renderer/atoms/__tests__/mounts.test.ts b/desktop/apps/electron/src/renderer/atoms/__tests__/mounts.test.ts index bbb55d77..b0de5f14 100644 --- a/desktop/apps/electron/src/renderer/atoms/__tests__/mounts.test.ts +++ b/desktop/apps/electron/src/renderer/atoms/__tests__/mounts.test.ts @@ -50,6 +50,16 @@ function installDialogResult(result: DialogResult): () => void { return installDialogOpen(mock(async () => result)) } +function installMountReferences(methods: Record): () => void { + const api = (globalThis.window as unknown as { api: { mountReferences?: Record } }).api + const previous = api.mountReferences + api.mountReferences = { ...previous, ...methods } + return () => { + if (previous) api.mountReferences = previous + else delete api.mountReferences + } +} + function mount( id: string, name: string, @@ -408,3 +418,100 @@ describe('pickAndMountAtom', () => { } }) }) + +describe('mount reference safety', () => { + it('confirms referenced slide cleanup after backend deletion succeeds', async () => { + const { loadMountsAtom, mountsFamily, removeMountAtom } = await import('../mounts') + const { confirmRequestAtom, resolveConfirmAtom } = await import('../confirm') + const store = createStore() + const sessionId = 'session_referenced_presentation_mount' + const referenced = mount('mnt_referenced', 'source.png', '/Users/amphi/source.png') + const order: string[] = [] + store.set(backendSnapshotAtom, { + state: BackendState.Ready, + endpoint: { baseUrl: 'http://127.0.0.1:7421', token: 'test-token', version: null, startedAt: null, wsPath: null }, + lastError: null, + } as never) + globalThis.fetch = mock(async (_input: RequestInfo | URL, init?: RequestInit) => { + if (init?.method === 'DELETE') { order.push('delete'); return new Response(null, { status: 204 }) } + return jsonResponse([referenced]) + }) as never + const restoreReferences = installMountReferences({ + usage: mock(async () => { order.push('usage'); return { assetCount: 1, elementCount: 2, projectCount: 1 } }), + remove: mock(async () => { order.push('cleanup'); return { assetCount: 1, elementCount: 2, projectCount: 1 } }), + refresh: mock(async () => { order.push('refresh') }), + }) + try { + await store.set(loadMountsAtom, sessionId) + const pending = store.set(removeMountAtom, { sessionId, mountId: referenced.id }) + while (!store.get(confirmRequestAtom)) await Promise.resolve() + expect(store.get(confirmRequestAtom)?.message).toContain('2') + store.set(resolveConfirmAtom, true) + await pending + expect(order).toEqual(['usage', 'delete', 'refresh', 'cleanup']) + expect(store.get(mountsFamily(sessionId))).toEqual([]) + } finally { + restoreReferences() + } + }) + + it('keeps PowerPoint references and the mount row when backend deletion fails', async () => { + const { loadMountsAtom, mountsFamily, removeMountAtom } = await import('../mounts') + const { confirmRequestAtom, resolveConfirmAtom } = await import('../confirm') + const { toastAtom } = await import('../toast') + const store = createStore() + const sessionId = 'session_failed_presentation_mount_removal' + const referenced = mount('mnt_failed', 'source.png', '/Users/amphi/source.png') + const order: string[] = [] + store.set(backendSnapshotAtom, { + state: BackendState.Ready, + endpoint: { baseUrl: 'http://127.0.0.1:7421', token: 'test-token', version: null, startedAt: null, wsPath: null }, + lastError: null, + } as never) + globalThis.fetch = mock(async (_input: RequestInfo | URL, init?: RequestInit) => { + if (init?.method === 'DELETE') { order.push('delete'); return jsonResponse({ detail: 'disk busy' }, 500) } + return jsonResponse([referenced]) + }) as never + const restoreReferences = installMountReferences({ + usage: mock(async () => { order.push('usage'); return { assetCount: 1, elementCount: 2, projectCount: 1 } }), + remove: mock(async () => { order.push('cleanup'); return { assetCount: 1, elementCount: 2, projectCount: 1 } }), + refresh: mock(async () => { order.push('refresh') }), + }) + try { + await store.set(loadMountsAtom, sessionId) + const pending = store.set(removeMountAtom, { sessionId, mountId: referenced.id }) + while (!store.get(confirmRequestAtom)) await Promise.resolve() + store.set(resolveConfirmAtom, true) + await pending + expect(order).toEqual(['usage', 'delete']) + expect(store.get(mountsFamily(sessionId))).toEqual([referenced]) + expect(store.get(toastAtom)?.message).toBeTruthy() + } finally { + restoreReferences() + } + }) + + it('rebinds a stale mount in place after validating the replacement', async () => { + const { loadMountsAtom, mountsFamily, rebindMountAtom } = await import('../mounts') + const store = createStore() + const sessionId = 'session_relink_presentation_mount' + const stale = { ...mount('mnt_stale', 'old.png', '/Users/amphi/old.png'), exists: false } + const rebound = { ...stale, name: 'new.png', path: '/Users/amphi/new.png', exists: true } + store.set(backendSnapshotAtom, { + state: BackendState.Ready, + endpoint: { baseUrl: 'http://127.0.0.1:7421', token: 'test-token', version: null, startedAt: null, wsPath: null }, + lastError: null, + } as never) + globalThis.fetch = mock(async () => jsonResponse([stale])) as never + const restoreDialog = installDialogResult({ canceled: false, filePaths: [rebound.path] }) + const restoreReferences = installMountReferences({ rebind: mock(async () => ({ ok: true, mount: rebound })) }) + try { + await store.set(loadMountsAtom, sessionId) + expect(await store.set(rebindMountAtom, { sessionId, mount: stale })).toBe(true) + expect(store.get(mountsFamily(sessionId))).toEqual([rebound]) + } finally { + restoreReferences() + restoreDialog() + } + }) +}) diff --git a/desktop/apps/electron/src/renderer/atoms/__tests__/office.test.ts b/desktop/apps/electron/src/renderer/atoms/__tests__/office.test.ts index 16526346..d4d41fd6 100644 --- a/desktop/apps/electron/src/renderer/atoms/__tests__/office.test.ts +++ b/desktop/apps/electron/src/renderer/atoms/__tests__/office.test.ts @@ -75,9 +75,10 @@ describe('Session-scoped Office status projection', () => { store.set(activeSessionIdAtom, 'session-a') store.set(embeddedPowerPointSnapshotAtom, { sessions: [{ sessionId: 'session-a', targetId: 'ppt-a', webContentsId: 1, loading: false, crashed: false, + documentCount: 0, }] }) store.set(excelHostSnapshotAtom, { sessions: [{ - sessionId: 'session-b', targetId: 'excel-b', webContentsId: 2, ready: true, crashed: false, dirty: true, + sessionId: 'session-b', targetId: 'excel-b', webContentsId: 2, ready: true, crashed: false, dirty: true, documentCount: 1, }] }) store.set(setPowerPointNeedsAttentionAtom, { sessionId: 'session-a', needsAttention: true }) let status = store.get(currentOfficeSurfaceStatusesAtom) diff --git a/desktop/apps/electron/src/renderer/atoms/__tests__/presentation.test.ts b/desktop/apps/electron/src/renderer/atoms/__tests__/presentation.test.ts index 8b89e1e6..3240a03d 100644 --- a/desktop/apps/electron/src/renderer/atoms/__tests__/presentation.test.ts +++ b/desktop/apps/electron/src/renderer/atoms/__tests__/presentation.test.ts @@ -4,10 +4,8 @@ import { activeSessionIdAtom } from '../sessions' import { PRESENTATION_PAGE_SIZES, createBlankPresentationSlide, - createBlankPresentationDocument, - createInitialPresentationDocument, - currentPresentationDocumentAtom, - currentPresentationWorkspaceAtom, + createBlankPresentationProject, + createInitialPresentationProject, presentationExpandedAtom, purgePresentationSessionAtom, formatPresentationText, @@ -20,8 +18,8 @@ import { describe('presentation atoms', () => { it('creates documents with an explicit widescreen page size', () => { - expect(createInitialPresentationDocument().pageSize).toEqual(PRESENTATION_PAGE_SIZES.wide) - expect(createBlankPresentationDocument('Blank').pageSize).toEqual(PRESENTATION_PAGE_SIZES.wide) + expect(createInitialPresentationProject().pageSize).toEqual(PRESENTATION_PAGE_SIZES.wide) + expect(createBlankPresentationProject('Blank').pageSize).toEqual(PRESENTATION_PAGE_SIZES.wide) }) it('gives every generated slide an explicit no-transition default', () => { @@ -29,7 +27,7 @@ describe('presentation atoms', () => { expect(blank.transition).toEqual({ effect: 'none', durationMs: 1_000 }) expect(blank.background).toBeUndefined() expect(blank.footer).toBeUndefined() - const initialDocument = createInitialPresentationDocument() + const initialDocument = createInitialPresentationProject() expect(initialDocument.slides.pages.every((slide) => ( slide.transition.effect === 'none' && slide.transition.durationMs === 1_000 ))).toBe(true) @@ -37,7 +35,7 @@ describe('presentation atoms', () => { }) it('starts with one unnamed slide containing ordinary editable text boxes instead of bundled sample content', () => { - const document = createInitialPresentationDocument() + const document = createInitialPresentationProject() expect(document.title).toBe('') expect(document.slides.pages).toHaveLength(1) expect(document.slides.selectedPageId).toBe(document.slides.pages[0]!.id) @@ -55,7 +53,7 @@ describe('presentation atoms', () => { }) it('resolves global theme defaults while preserving page overrides', () => { - const document = createBlankPresentationDocument('Theme defaults') + const document = createBlankPresentationProject('Theme defaults') const slide = document.slides.pages[0]! document.theme = { ...document.theme, @@ -236,67 +234,26 @@ describe('presentation atoms', () => { expect(stripPresentationTextFormatting(formatPresentationText(element), element)).toBe(element.text) }) - it('keeps documents and expanded state independent between Sessions', () => { + it('keeps expanded state independent between Sessions', () => { const store = createStore() store.set(activeSessionIdAtom, 'session-a') - const sessionADocument = { - ...createInitialPresentationDocument(), - title: 'Session A deck', - } - store.set(currentPresentationDocumentAtom, sessionADocument) store.set(presentationExpandedAtom, true) store.set(activeSessionIdAtom, 'session-b') - expect(store.get(currentPresentationDocumentAtom).title).not.toBe('Session A deck') expect(store.get(presentationExpandedAtom)).toBe(false) store.set(activeSessionIdAtom, 'session-a') - expect(store.get(currentPresentationDocumentAtom).title).toBe('Session A deck') expect(store.get(presentationExpandedAtom)).toBe(true) }) - it('removes a deleted Session document and expansion state', () => { + it('removes a deleted Session expansion state', () => { const store = createStore() store.set(activeSessionIdAtom, 'session-delete') - store.set(currentPresentationDocumentAtom, { - ...createInitialPresentationDocument(), - title: 'Delete me', - }) store.set(presentationExpandedAtom, true) store.set(purgePresentationSessionAtom, 'session-delete') - expect(store.get(currentPresentationDocumentAtom).title).not.toBe('Delete me') expect(store.get(presentationExpandedAtom)).toBe(false) }) - it('keeps multiple open presentations independent within one Session', () => { - const store = createStore() - store.set(activeSessionIdAtom, 'session-tabs') - const firstWorkspace = store.get(currentPresentationWorkspaceAtom) - const firstDocument = firstWorkspace.documents[0]! - const secondDocument = createBlankPresentationDocument('Second deck') - - store.set(currentPresentationWorkspaceAtom, { - activeDocumentId: secondDocument.id, - documents: [...firstWorkspace.documents, secondDocument], - }) - store.set(currentPresentationDocumentAtom, { - ...store.get(currentPresentationDocumentAtom), - title: 'Edited second deck', - }) - - const withEditedSecond = store.get(currentPresentationWorkspaceAtom) - store.set(currentPresentationWorkspaceAtom, { - ...withEditedSecond, - activeDocumentId: firstDocument.id, - }) - - expect(store.get(currentPresentationDocumentAtom).id).toBe(firstDocument.id) - expect(store.get(currentPresentationDocumentAtom).title).toBe(firstDocument.title) - expect(store.get(currentPresentationWorkspaceAtom).documents.find((item) => ( - item.id === secondDocument.id - ))?.title).toBe('Edited second deck') - }) - }) diff --git a/desktop/apps/electron/src/renderer/atoms/agent.ts b/desktop/apps/electron/src/renderer/atoms/agent.ts index 358d54f9..816d812c 100644 --- a/desktop/apps/electron/src/renderer/atoms/agent.ts +++ b/desktop/apps/electron/src/renderer/atoms/agent.ts @@ -1041,15 +1041,11 @@ export const currentBrowserAgentActiveAtom = atom((get) => ( /** PowerPoint tools that visibly change the live presentation surface. */ const POWERPOINT_ACTION_TOOL_NAMES = new Set([ - 'view_ppt', - 'update_ppt_design', - 'edit_ppt_page', - 'insert_ppt_element', - 'remove_ppt_element', - 'insert_ppt_page', - 'remove_ppt_page', - 'move_ppt_page', - 'goto_ppt_page', + 'ppt_open', + 'ppt_edit_page', + 'ppt_manage_deck', + 'ppt_inspect', + 'ppt_save', ]) /** Whether a tool is an Agent-controlled PowerPoint operation visible to the user. */ diff --git a/desktop/apps/electron/src/renderer/atoms/mounts.ts b/desktop/apps/electron/src/renderer/atoms/mounts.ts index 54a1ece6..dc1d736a 100644 --- a/desktop/apps/electron/src/renderer/atoms/mounts.ts +++ b/desktop/apps/electron/src/renderer/atoms/mounts.ts @@ -15,6 +15,7 @@ import { atom } from 'jotai' import { atomFamily } from 'jotai-family' import type { DirListResult } from '@shared/dir-tree' +import type { MountReferenceUsage } from '@shared/mount-references' import { graftTree } from '@/lib/fileTree' import type { MountSummary } from '@/lib/amphiClient' import type { PasteItem } from '@/components/composer/pasteClassify' @@ -25,6 +26,9 @@ import { notifySessionWorkbenchActivityAtom, } from './workbench' import { rlog } from '@/lib/logger' +import { i18n } from '@/lib/i18n' +import { requestConfirmAtom } from './confirm' +import { showToastAtom } from './toast' /** Primitive: sessionId → that session's mounts. Not exported (§1.13). */ const _mounts = atom>({}) @@ -318,6 +322,30 @@ export const consumeMentionInsertsAtom = atom(null, (_get, set) => { set(_pendingMentionInserts, []) }) +/** Repoint a stale mount without changing its id, preserving project references. */ +export const rebindMountAtom = atom( + null, + async (get, set, payload: { sessionId: string; mount: MountSummary }): Promise => { + const result = await window.api.dialog.open({ properties: payload.mount.kind === 'folder' ? ['openDirectory'] : ['openFile'] }) + const path = result.filePaths[0] + if (result.canceled || !path) return false + try { + const rebound = await window.api.mountReferences.rebind(payload.sessionId, payload.mount.id, path) + if (!rebound.ok) { + set(showToastAtom, i18n.t('asset.toast.relinkRejected', { name: rebound.validation.assetName })) + return false + } + const current = get(_mounts)[payload.sessionId] ?? [] + set(_mounts, { ...get(_mounts), [payload.sessionId]: current.map((mount) => mount.id === rebound.mount.id ? rebound.mount : mount) }) + return true + } catch (err) { + rlog.warn('[mounts] rebindMount failed', { sessionId: payload.sessionId, mountId: payload.mount.id, err }) + set(showToastAtom, i18n.t('asset.toast.relinkFailed')) + return false + } + }, +) + /** Action: unmount; uploaded attachments are deleted, external sources remain. */ export const removeMountAtom = atom( null, @@ -325,6 +353,24 @@ export const removeMountAtom = atom( const { sessionId, mountId } = payload const client = buildAmphiClient(get) if (!client) return + let usage: MountReferenceUsage + try { + usage = await window.api.mountReferences.usage(sessionId, mountId) + if (usage.assetCount > 0) { + const confirmed = await set(requestConfirmAtom, { + title: i18n.t('asset.mount.removeReferencedTitle'), + message: i18n.t('asset.mount.removeReferencedMessage', { ...usage }), + confirmLabel: i18n.t('asset.mount.removeReferencedConfirm'), + cancelLabel: i18n.t('common.cancel'), + danger: true, + }) + if (!confirmed) return + } + } catch (err) { + rlog.warn('[mounts] inspect mount references failed', { sessionId, mountId, err }) + set(showToastAtom, i18n.t('asset.toast.removeFailed')) + return + } try { await client.removeMount(sessionId, mountId) const current = get(_mounts)[sessionId] ?? [] @@ -334,6 +380,17 @@ export const removeMountAtom = atom( }) } catch (err) { rlog.warn('[mounts] removeMount failed', { sessionId, mountId, err }) + set(showToastAtom, i18n.t('asset.toast.removeFailed')) + return + } + try { await window.api.mountReferences.refresh(sessionId) } + catch (err) { rlog.warn('[mounts] refresh sources after unmount failed', { sessionId, mountId, err }) } + if (usage.assetCount > 0) { + try { await window.api.mountReferences.remove(sessionId, mountId) } + catch (err) { + rlog.warn('[mounts] remove mount references failed', { sessionId, mountId, err }) + set(showToastAtom, i18n.t('asset.toast.removeCleanupFailed')) + } } }, ) diff --git a/desktop/apps/electron/src/renderer/atoms/presentation.ts b/desktop/apps/electron/src/renderer/atoms/presentation.ts index b3a4f81a..7c274697 100644 --- a/desktop/apps/electron/src/renderer/atoms/presentation.ts +++ b/desktop/apps/electron/src/renderer/atoms/presentation.ts @@ -71,17 +71,42 @@ export interface PresentationFileSource { fileName: string mimeType: string path?: string + /** Durable logical reference when runtime bytes came from a containing document. */ + source?: string } -export type PresentationAssetKind = 'image' | 'audio' | 'video' -export type PresentationAssetSource = Omit +export type PresentationAssetKind = 'image' | 'audio' | 'video' | 'text' -/** One project-owned media resource referenced by slide elements. */ +export type PresentationOfficeImageEffect = + | { type: 'backgroundRemoval'; bounds: { top: number; bottom: number; left: number; right: number }; foregroundMarks: Array<{ x1: number; y1: number; x2: number; y2: number }>; backgroundMarks: Array<{ x1: number; y1: number; x2: number; y2: number }> } + | { type: 'brightnessContrast'; bright: number; contrast: number } + | { type: 'colorTemperature'; colorTemp: number } + | { type: 'saturation'; sat: number } + | { type: 'artisticPhotocopy'; detail?: number } + | { type: 'sharpenSoften'; amount: number } + | { type: 'artisticCrisscrossEtching' } + | { type: 'artisticBlur' } + +export interface PresentationImageEffects { + colorChange?: { from: string; to: string; opacity: number } + grayscale?: boolean + biLevelThreshold?: number + /** The Office image layer remains inside the imported PPTX, not in the Files mount list. */ + officeLayer?: { source: string; effects: PresentationOfficeImageEffect[] } +} + +/** One project-owned source resource referenced by slide elements. */ export interface PresentationAsset { id: string kind: PresentationAssetKind + mimeType: string name: string - source: PresentationAssetSource + /** Durable source reference. Runtime URLs are resolved outside PPTProject. */ + source: string + /** Non-destructive Office picture effects attached to this source instance. */ + imageEffects?: PresentationImageEffects + sourceModifiedAt?: number + sourceSize?: number } export interface PresentationTransition { @@ -111,6 +136,46 @@ export const PRESENTATION_SHAPE_TYPES = [ export type PresentationShapeType = (typeof PRESENTATION_SHAPE_TYPES)[number] +export type PresentationCustomShapeCommand = + | { type: 'moveTo'; x: number; y: number } + | { type: 'lineTo'; x: number; y: number } + | { type: 'cubicBezierTo'; x1: number; y1: number; x2: number; y2: number; x: number; y: number } + | { type: 'quadraticBezierTo'; x1: number; y1: number; x: number; y: number } + | { type: 'arcTo'; widthRadius: number; heightRadius: number; startAngle: number; sweepAngle: number } + | { type: 'close' } + +export interface PresentationCustomShapePath { + width: number + height: number + /** OOXML paths may independently opt out of their parent shape fill or stroke. */ + fill: 'normal' | 'none' + stroke: boolean + commands: PresentationCustomShapeCommand[] +} + +export interface PresentationCustomShapeGeometry { + /** Each path owns its source coordinate space, matching DrawingML custom geometry. */ + paths: PresentationCustomShapePath[] +} + +export interface PresentationShapeGradientStop { + offset: number + color: string + opacity: number +} + +export type PresentationShapeGradientFill = + | { type: 'linear'; angle: number; stops: PresentationShapeGradientStop[] } + | { type: 'radial'; path?: string; fillToRect?: { left: number; top: number; right: number; bottom: number }; stops: PresentationShapeGradientStop[] } + +export interface PresentationShapePatternFill { + preset: string + foregroundColor: string + foregroundOpacity: number + backgroundColor: string + backgroundOpacity: number +} + export interface PresentationElementBase { id: string /** Elements sharing a group id behave as one visual object for selection and animation. */ @@ -137,6 +202,8 @@ export interface PresentationElementBase { export interface PresentationTextElement extends PresentationElementBase { type: 'text' + /** Present when this editable text originated from a mounted text asset. */ + sourceAssetId?: string text: string /** Inline style ranges use UTF-16 offsets into text, excluding generated list markers. */ textRuns?: PresentationTextRun[] @@ -204,9 +271,15 @@ export interface PresentationTextParagraph { export interface PresentationShapeElement extends PresentationElementBase { type: PresentationShapeType fill: string + fillOpacity?: number + gradientFill?: PresentationShapeGradientFill + patternFill?: PresentationShapePatternFill borderColor: string borderWidth: number + borderOpacity?: number radius?: number + /** Native per-shape geometry imported from or exported to DrawingML a:custGeom. */ + customGeometry?: PresentationCustomShapeGeometry /** Connector geometry in a 100 x 100 coordinate space. */ connectorPath?: string } @@ -215,7 +288,8 @@ export interface PresentationImageElement extends PresentationElementBase { type: 'image' sourceAssetId: string altText: string - fit: 'contain' | 'cover' + fit: 'contain' | 'cover' | 'stretch' + softEdgeRadius?: number /** Preserve an OOXML picture-filled shape as an editable image crop. */ clipShape?: 'ellipse' /** Normalized source crop fractions copied from OOXML a:srcRect. */ @@ -245,9 +319,36 @@ export interface PresentationVideoElement extends PresentationElementBase { export type PresentationMediaElement = PresentationAudioElement | PresentationVideoElement +export interface PresentationTableCellBorder { + color: string + width: number + type: 'solid' | 'dash' | 'none' +} + +export interface PresentationTableCellStyle { + fill?: string + textColor?: string + borderColor?: string + borders?: Partial> + fontSize?: number + fontFamily?: string + bold?: boolean + align?: 'left' | 'center' | 'right' + verticalAlign?: 'top' | 'middle' | 'bottom' + padding?: { left: number; right: number; top: number; bottom: number } + /** UTF-16 ranges into the corresponding cells[row][column] string. */ + textRuns?: PresentationTextRun[] + colSpan?: number + rowSpan?: number + covered?: boolean +} + export interface PresentationTableElement extends PresentationElementBase { type: 'table' cells: string[][] + columnWidths?: number[] + rowHeights?: number[] + cellStyles?: PresentationTableCellStyle[][] headerRow: boolean headerFill: string headerTextColor?: string @@ -573,12 +674,7 @@ export function selectPresentationPage(slides: PresentationSlides, selectedPageI return { ...slides, selectedPageId } } -/** - * The authoritative, serializable PowerPoint model. - * - * File handles and save bookkeeping deliberately live on PresentationDocument, - * while all deck content lives here. - */ +/** The authoritative, serializable PowerPoint model. */ export interface PresentationProject { schemaVersion: 1 version: 1 @@ -590,19 +686,6 @@ export interface PresentationProject { slides: PresentationSlides } -/** Renderer host metadata attached to a project without becoming deck content. */ -export interface PresentationDocument extends PresentationProject { - sourceProtected?: boolean - source?: import('../../shared/office-files').OfficeFileSource - savedRevision?: number - revision: number -} - -export interface PresentationWorkspace { - activeDocumentId: string - documents: PresentationDocument[] -} - export interface PresentationAgentChange { changeId: number elementIds: string[] @@ -610,9 +693,6 @@ export interface PresentationAgentChange { slideId: string } -/** One renderer-local visual transition requested by an Agent domain command. */ -export const presentationAgentChangeAtom = atom(null) - type SessionStateUpdate = T | ((current: T) => T) let generatedId = 0 @@ -632,9 +712,9 @@ export function createBlankPresentationSlide(name: string): PresentationSlide { } } -export function createInitialPresentationDocument(): PresentationDocument { - const document = createBlankPresentationDocument('') - const slide = document.slides.pages[0]! +export function createInitialPresentationProject(): PresentationProject { + const project = createBlankPresentationProject('') + const slide = project.slides.pages[0]! const createTextBox = ( kind: 'body' | 'subtitle' | 'title', geometry: Pick, @@ -653,7 +733,7 @@ export function createInitialPresentationDocument(): PresentationDocument { rotation: 0, text, fontSize, - fontFamily: isTitle ? document.theme.titleFontFamily : document.theme.bodyFontFamily, + fontFamily: isTitle ? project.theme.titleFontFamily : project.theme.bodyFontFamily, fontWeight: isTitle ? 700 : 400, italic: false, underline: false, @@ -669,19 +749,18 @@ export function createInitialPresentationDocument(): PresentationDocument { } slide.layout = 'title' slide.elements = [ - createTextBox('title', { x: 120, y: 105, width: document.pageSize.width - 240, height: 90 }), - createTextBox('subtitle', { x: 160, y: 220, width: document.pageSize.width - 320, height: 60 }), - createTextBox('body', { x: 120, y: 320, width: document.pageSize.width - 240, height: Math.max(180, document.pageSize.height - 425) }), + createTextBox('title', { x: 120, y: 105, width: project.pageSize.width - 240, height: 90 }), + createTextBox('subtitle', { x: 160, y: 220, width: project.pageSize.width - 320, height: 60 }), + createTextBox('body', { x: 120, y: 320, width: project.pageSize.width - 240, height: Math.max(180, project.pageSize.height - 425) }), ] - return document + return project } -export function createBlankPresentationDocument(title: string, slideName = 'Slide 1'): PresentationDocument { +export function createBlankPresentationProject(title: string, slideName = 'Slide 1'): PresentationProject { const slide = createBlankPresentationSlide(slideName) return { schemaVersion: 1, version: 1, - revision: 1, id: createPresentationId('presentation'), theme: { ...DEFAULT_PRESENTATION_MASTER, @@ -699,17 +778,6 @@ export function createBlankPresentationDocument(title: string, slideName = 'Slid } } -export function createInitialPresentationWorkspace(): PresentationWorkspace { - const document = createInitialPresentationDocument() - return { - activeDocumentId: document.id, - documents: [document], - } -} - -const fallbackPresentationWorkspace = createInitialPresentationWorkspace() -const fallbackPresentationDocument = fallbackPresentationWorkspace.documents[0]! -const presentationWorkspacesBySessionAtom = atom>(new Map()) const expandedPresentationSessionsAtom = atom>(new Set()) /** Dedicated PowerPoint renderers pin their exact Session independently of main navigation. */ export const powerPointSessionIdOverrideAtom = atom(null) @@ -717,52 +785,6 @@ export const presentationSessionIdAtom = atom((get) => ( get(powerPointSessionIdOverrideAtom) ?? get(viewedSessionIdAtom) )) -/** Explicit Session ownership for commands that can outlive a navigation change. */ -export const presentationWorkspaceFamily = atomFamily((sessionId: string) => atom( - (get) => get(presentationWorkspacesBySessionAtom).get(sessionId) ?? fallbackPresentationWorkspace, - (get, set, update: SessionStateUpdate) => { - const current = get(presentationWorkspacesBySessionAtom).get(sessionId) ?? fallbackPresentationWorkspace - const next = typeof update === 'function' ? update(current) : update - const workspaces = new Map(get(presentationWorkspacesBySessionAtom)) - workspaces.set(sessionId, next) - set(presentationWorkspacesBySessionAtom, workspaces) - }, -)) - -/** Every open presentation tab owned by the viewed Session. */ -export const currentPresentationWorkspaceAtom = atom( - (get) => { - const sessionId = get(presentationSessionIdAtom) - return sessionId ? get(presentationWorkspaceFamily(sessionId)) : fallbackPresentationWorkspace - }, - (get, set, update: SessionStateUpdate) => { - const sessionId = get(presentationSessionIdAtom) - if (sessionId) set(presentationWorkspaceFamily(sessionId), update) - }, -) - -/** The active presentation tab's editable document. */ -export const currentPresentationDocumentAtom = atom( - (get) => { - const workspace = get(currentPresentationWorkspaceAtom) - return workspace.documents.find((document) => document.id === workspace.activeDocumentId) - ?? workspace.documents[0] - ?? fallbackPresentationDocument - }, - (get, set, update: SessionStateUpdate) => { - const workspace = get(currentPresentationWorkspaceAtom) - const current = get(currentPresentationDocumentAtom) - const next = typeof update === 'function' ? update(current) : update - const hasActiveDocument = workspace.documents.some((document) => document.id === current.id) - set(currentPresentationWorkspaceAtom, { - activeDocumentId: next.id, - documents: hasActiveDocument - ? workspace.documents.map((document) => document.id === current.id ? next : document) - : [...workspace.documents, next], - }) - }, -) - /** Whether the viewed Session's presentation owns the work area. */ export const presentationExpandedAtom = atom( (get) => { @@ -784,14 +806,7 @@ export const presentationExpandedAtom = atom( /** Drop presentation state when its owning Session is deleted. */ export const purgePresentationSessionAtom = atom(null, (get, set, sessionId: string) => { - presentationWorkspaceFamily.remove(sessionId) presentationPaneViewFamily.remove(sessionId) - const workspaces = get(presentationWorkspacesBySessionAtom) - if (workspaces.has(sessionId)) { - const nextWorkspaces = new Map(workspaces) - nextWorkspaces.delete(sessionId) - set(presentationWorkspacesBySessionAtom, nextWorkspaces) - } const expandedSessions = get(expandedPresentationSessionsAtom) if (expandedSessions.has(sessionId)) { const nextExpandedSessions = new Set(expandedSessions) diff --git a/desktop/apps/electron/src/renderer/components/amphi/FileTreeView.tsx b/desktop/apps/electron/src/renderer/components/amphi/FileTreeView.tsx index d3dbb739..59aabfa5 100644 --- a/desktop/apps/electron/src/renderer/components/amphi/FileTreeView.tsx +++ b/desktop/apps/electron/src/renderer/components/amphi/FileTreeView.tsx @@ -20,7 +20,7 @@ import { useTranslation } from 'react-i18next' import type { MouseEvent } from 'react' import type { DirTreeNode } from '@shared/dir-tree' import { cn } from '@/lib/cn' -import { isDocxFileName } from '@/lib/fileTypes' +import { isOfficePreviewFileName } from '@/lib/fileTypes' import { extColor, formatSize } from '@/lib/fileTree' import { Icons } from './Icons' import { RowActionMenu } from './RowActionMenu' @@ -131,7 +131,7 @@ function TreeNodeRow({ const pickable = !isFolder && onPickFile !== undefined // File rows are openable only in the Files panel; the @ picker keeps its own selection behaviour. const openable = !isFolder && onOpen !== undefined - const opensOnClick = openable && (isDocxFileName(node.name) || openOnSingleClick?.(node)) + const opensOnClick = openable && (isOfficePreviewFileName(node.name) || openOnSingleClick?.(node)) const handleRowClick = (event: MouseEvent): void => { if (expandable) onToggle(node) diff --git a/desktop/apps/electron/src/renderer/components/amphi/MountRow.tsx b/desktop/apps/electron/src/renderer/components/amphi/MountRow.tsx index 901039c3..badcf032 100644 --- a/desktop/apps/electron/src/renderer/components/amphi/MountRow.tsx +++ b/desktop/apps/electron/src/renderer/components/amphi/MountRow.tsx @@ -15,7 +15,7 @@ import { useAtomValue, useSetAtom } from 'jotai' import { useTranslation } from 'react-i18next' import type { TFunction } from 'i18next' import { cn } from '@/lib/cn' -import { isDocxFileName } from '@/lib/fileTypes' +import { isOfficePreviewFileName } from '@/lib/fileTypes' import { extColor, findNode, formatSize, pruneExpanded } from '@/lib/fileTree' import { APP_PRODUCT_NAME } from '@shared/app-meta' import type { DirListResult, DirTreeNode } from '@shared/dir-tree' @@ -55,6 +55,7 @@ export interface MountRowProps { onOpenInFileManager: () => void /** Absent for system-owned roots such as the Session `.work` directory. */ onRemove?: () => void + onRelink?: () => void onMentionRoot: () => void onMentionChild: (node: DirTreeNode) => void /** Child-row ⋯ menu (the single-open state lives in the panel, keyed by relPath; no "remove" — child items are not mounts). */ @@ -80,6 +81,7 @@ export function MountRow({ onCopyPath, onOpenInFileManager, onRemove, + onRelink, onMentionRoot, onMentionChild, childMenuFor, @@ -108,7 +110,7 @@ export function MountRow({ const expandable = m.kind === 'folder' && m.exists // In-app file owners open on one click; other files retain the established double-click behaviour. const rootOpenable = m.kind === 'file' && m.exists - const rootOpensOnSingleClick = rootOpenable && (openOnSingleClick(m.name) || isDocxFileName(m.name)) + const rootOpensOnSingleClick = rootOpenable && (isOfficePreviewFileName(m.name) || openOnSingleClick(m.name)) const toggleRoot = (): void => { if (!expandable) return if (!open) { @@ -236,6 +238,7 @@ export function MountRow({ items={[ { label: t('asset.common.copyPath'), onSelect: onCopyPath }, { label: t('asset.common.revealInFileManager'), onSelect: onOpenInFileManager }, + ...(onRelink ? [{ label: t('asset.mount.relink'), onSelect: onRelink }] : []), ...(onRemove ? [{ label: ( diff --git a/desktop/apps/electron/src/renderer/components/amphi/SessionAssets.tsx b/desktop/apps/electron/src/renderer/components/amphi/SessionAssets.tsx index e8d41054..b419d041 100644 --- a/desktop/apps/electron/src/renderer/components/amphi/SessionAssets.tsx +++ b/desktop/apps/electron/src/renderer/components/amphi/SessionAssets.tsx @@ -39,10 +39,12 @@ import { showToastAtom } from '@/atoms/toast' import { mountsFamily, pickAndMountAtom, + rebindMountAtom, removeMountAtom, requestMentionInsertAtom, } from '@/atoms/mounts' -import { isPowerPointFileTarget, requestSessionFileOpenAtom } from '@/atoms/fileOpen' +import { requestSessionFileOpenAtom } from '@/atoms/fileOpen' +import { isOfficePreviewFileName } from '@/lib/fileTypes' import type { DirTreeNode } from '@shared/dir-tree' import type { MountSummary } from '@/lib/amphiClient' @@ -123,6 +125,7 @@ export function SessionAssetsPanel({ const mounts = useAtomValue(mountsFamily(sessionId ?? '')) const pickAndMount = useSetAtom(pickAndMountAtom) const removeMount = useSetAtom(removeMountAtom) + const rebindMount = useSetAtom(rebindMountAtom) const requestMentionInsert = useSetAtom(requestMentionInsertAtom) const requestSessionFileOpen = useSetAtom(requestSessionFileOpenAtom) const showToast = useSetAtom(showToastAtom) @@ -173,6 +176,11 @@ export function SessionAssetsPanel({ if (sessionId) void removeMount({ sessionId, mountId: m.id }) } + const relink = (m: MountSummary) => { + setMenuFor(null) + if (sessionId) void rebindMount({ sessionId, mount: m }) + } + return (
@@ -225,6 +233,7 @@ export function SessionAssetsPanel({ onCopyPath={copyAbsPath} onReveal={revealAbsPath} onRemove={remove} + onRelink={relink} onMentionRoot={addToChat} onMentionChild={addChildToChat} onOpen={requestSessionFileOpen} @@ -242,6 +251,7 @@ interface MountListProps { onCopyPath: (abs: string) => void onReveal: (abs: string) => void onRemove: (m: MountSummary) => void + onRelink: (m: MountSummary) => void onMentionRoot: (m: MountSummary) => void onMentionChild: (m: MountSummary, node: DirTreeNode) => void onOpen: (req: { path: string; name: string }) => void @@ -256,6 +266,7 @@ function MountList({ onCopyPath, onReveal, onRemove, + onRelink, onMentionRoot, onMentionChild, onOpen, @@ -282,6 +293,7 @@ function MountList({ onCopyPath={() => onCopyPath(m.path)} onOpenInFileManager={() => onReveal(m.path)} onRemove={m.removable === false ? undefined : () => onRemove(m)} + onRelink={!m.exists && m.removable !== false ? () => onRelink(m) : undefined} onMentionRoot={() => onMentionRoot(m)} onMentionChild={(node) => onMentionChild(m, node)} childMenuFor={menuFor?.startsWith(`${m.id}:`) ? menuFor.slice(m.id.length + 1) : null} @@ -293,7 +305,7 @@ function MountList({ onRevealChild={(node) => onReveal(`${m.path}/${node.relPath}`)} onOpenRoot={() => onOpen({ path: m.path, name: m.name })} onOpenChild={(node) => onOpen({ path: `${m.path}/${node.relPath}`, name: node.name })} - openOnSingleClick={(name) => isPowerPointFileTarget({ name })} + openOnSingleClick={isOfficePreviewFileName} /> ))}
diff --git a/desktop/apps/electron/src/renderer/components/amphi/__tests__/FileTreeView.test.tsx b/desktop/apps/electron/src/renderer/components/amphi/__tests__/FileTreeView.test.tsx index 6d430790..81f03d85 100644 --- a/desktop/apps/electron/src/renderer/components/amphi/__tests__/FileTreeView.test.tsx +++ b/desktop/apps/electron/src/renderer/components/amphi/__tests__/FileTreeView.test.tsx @@ -1,6 +1,7 @@ import { afterAll, describe, expect, it, mock } from 'bun:test' import { GlobalRegistrator } from '@happy-dom/global-registrator' import type { DirTreeNode } from '@shared/dir-tree' +import type { MountSummary } from '@/lib/amphiClient' GlobalRegistrator.register() ;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true @@ -8,6 +9,8 @@ GlobalRegistrator.register() const { act } = await import('react') const { createRoot } = await import('react-dom/client') const { FileTreeView } = await import('../FileTreeView') +const { MountRow } = await import('../MountRow') +const { Provider, createStore } = await import('jotai') afterAll(async () => { await GlobalRegistrator.unregister() @@ -19,6 +22,59 @@ const nodes: DirTreeNode[] = [ ] describe('FileTreeView in-app file owners', () => { + it('opens mounted Excel files once on a single click even with the old PPT-only policy', async () => { + const onOpenRoot = mock(() => undefined) + const mount: MountSummary = { id: 'excel-click', name: 'Book.XLSX', path: '/qa/Book.XLSX', kind: 'file', exists: true, size_bytes: 10, item_count: null, created_at: '' } + const host = document.createElement('div') + document.body.appendChild(host) + const root = createRoot(host) + const noop = () => undefined + try { + await act(async () => root.render( name.endsWith('.pptx')} + />)) + const row = host.querySelector('.group')! + await act(async () => row.dispatchEvent(new MouseEvent('click', { bubbles: true, detail: 1 }))) + expect(onOpenRoot).toHaveBeenCalledTimes(1) + await act(async () => { + row.dispatchEvent(new MouseEvent('click', { bubbles: true, detail: 2 })) + row.dispatchEvent(new MouseEvent('dblclick', { bubbles: true, detail: 2 })) + }) + expect(onOpenRoot).toHaveBeenCalledTimes(1) + } finally { + await act(async () => root.unmount()) + host.remove() + } + }) + + it('opens every supported Office format once on a single click without a custom policy', async () => { + const onOpen = mock((_node: DirTreeNode) => undefined) + const files: DirTreeNode[] = ['Book.XLSX', 'Report.docx', 'Slides.pptx', 'Legacy.xls'].map((name) => ({ name, relPath: name, kind: 'file', sizeBytes: 10 })) + const host = document.createElement('div') + document.body.appendChild(host) + const root = createRoot(host) + try { + await act(async () => root.render( undefined} onOpen={onOpen} />)) + for (const [index, file] of files.entries()) { + const row = host.querySelector(`[data-file-tree-path="${file.relPath}"]`)! + await act(async () => row.dispatchEvent(new MouseEvent('click', { bubbles: true, detail: 1 }))) + expect(onOpen).toHaveBeenCalledTimes(index < 3 ? index + 1 : index) + await act(async () => { + row.dispatchEvent(new MouseEvent('click', { bubbles: true, detail: 2 })) + row.dispatchEvent(new MouseEvent('dblclick', { bubbles: true, detail: 2 })) + }) + expect(onOpen).toHaveBeenCalledTimes(index + 1) + expect(onOpen).toHaveBeenLastCalledWith(file) + } + } finally { + await act(async () => root.unmount()) + host.remove() + } + }) + it('opens claimed PPTX files once on click and leaves ordinary files on double-click', async () => { const onOpen = mock((_node: DirTreeNode) => undefined) const host = document.createElement('div') diff --git a/desktop/apps/electron/src/renderer/components/amphi/__tests__/MessageBubble.test.tsx b/desktop/apps/electron/src/renderer/components/amphi/__tests__/MessageBubble.test.tsx index a4f417c6..e237085d 100644 --- a/desktop/apps/electron/src/renderer/components/amphi/__tests__/MessageBubble.test.tsx +++ b/desktop/apps/electron/src/renderer/components/amphi/__tests__/MessageBubble.test.tsx @@ -505,13 +505,13 @@ describe('Pipeline', () => { content: '', toolCalls: [{ toolUseId: 'powerpoint-update', - name: 'edit_ppt_page', + name: 'ppt_edit_page', input: { page_id: 'page-1', ref: 'title', replacement: 'Updated' }, }], blocks: [{ type: 'tool', toolUseId: 'powerpoint-update', - name: 'edit_ppt_page', + name: 'ppt_edit_page', input: { page_id: 'page-1', ref: 'title', replacement: 'Updated' }, }], startedAt: Date.now(), diff --git a/desktop/apps/electron/src/renderer/components/app/ExcelWorkbenchPanel.tsx b/desktop/apps/electron/src/renderer/components/app/ExcelWorkbenchPanel.tsx index 08998b16..bbd1250a 100644 --- a/desktop/apps/electron/src/renderer/components/app/ExcelWorkbenchPanel.tsx +++ b/desktop/apps/electron/src/renderer/components/app/ExcelWorkbenchPanel.tsx @@ -29,7 +29,7 @@ const excelSurfacePolicy: NativeOfficeSurfacePolicy = { onError: (error) => rlog.warn('[excel-host] native surface sync failed', error), } -/** Renderer chrome around one Session-owned native Excel WebContentsView. */ +/** Main-window viewport for one Session-owned native Excel WebContentsView. */ export function ExcelWorkbenchPanel({ active = true }: { active?: boolean }) { const { t, i18n } = useTranslation() const sessionId = useAtomValue(viewedSessionIdAtom) @@ -122,29 +122,32 @@ export function ExcelWorkbenchPanel({ active = true }: { active?: boolean }) { if (hostSession?.crashed) status = t('excel.hostCrashed') else if (error) status = t('excel.hostFailed') else if (hostSession?.ready) status = t('excel.hostReady') + const showShellHeader = !nativeVisible || (hostSession.documentCount ?? 0) > 0 return (
- - { - void window.api.excelHost.closeSession(sessionId).catch((error) => { - rlog.warn('[excel-host] panel close failed', error) - }) - }} - onToggleExpanded={() => setExpanded((value) => !value)} - testIdPrefix="excel" - /> - + {showShellHeader ? ( + + { + void window.api.excelHost.closeSession(sessionId).catch((error) => { + rlog.warn('[excel-host] panel close failed', error) + }) + }} + onToggleExpanded={() => setExpanded((value) => !value)} + testIdPrefix="excel" + /> + + ) : null}
{!nativeVisible ? ( diff --git a/desktop/apps/electron/src/renderer/components/app/OfficeLaunchEmptyState.tsx b/desktop/apps/electron/src/renderer/components/app/OfficeLaunchEmptyState.tsx index 18e720ae..8941d813 100644 --- a/desktop/apps/electron/src/renderer/components/app/OfficeLaunchEmptyState.tsx +++ b/desktop/apps/electron/src/renderer/components/app/OfficeLaunchEmptyState.tsx @@ -3,31 +3,88 @@ import { useTranslation } from 'react-i18next' import { Icons } from '@/components/amphi/Icons' import { OfficeAppHeader } from './OfficeWorkbenchChrome' -export function OfficeLaunchEmptyState({ kind, onCreate, onOpen }: { kind: 'excel' | 'presentation'; onCreate: () => Promise; onOpen?: () => void }) { +type OfficeLaunchKind = 'excel' | 'presentation' | 'word' +type LaunchOperation = 'create' | 'open' + +const launchConfig = { + excel: { + title: 'Excel', + prefix: 'excel', + icon: Icons.spreadsheet, + iconClassName: 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400', + titleKey: 'excel.emptyTitle', + descriptionKey: 'excel.emptyDescription', + createLabelKey: 'excel.newWorkbook', + createTestId: 'excel-create-workbook', + }, + presentation: { + title: 'PPT', + prefix: 'powerpoint', + icon: Icons.presentation, + iconClassName: 'bg-orange-500/10 text-orange-600 dark:text-orange-400', + titleKey: 'session.presentation.launchTitle', + descriptionKey: 'session.presentation.launchDetail', + createLabelKey: 'session.presentation.launchButton.create', + createTestId: 'powerpoint-create-session', + }, + word: { + title: 'Word', + prefix: 'word', + icon: Icons.wordDocument, + iconClassName: 'bg-blue-500/10 text-blue-600 dark:text-blue-400', + titleKey: 'word.emptyTitle', + descriptionKey: 'word.emptyDescription', + createLabelKey: 'word.newDocument', + createTestId: 'word-create-document', + }, +} as const + +export function OfficeLaunchEmptyState({ errorMessage = null, failure = null, kind, onCreate, onOpen }: { + kind: OfficeLaunchKind + onCreate: () => unknown | Promise + onOpen: () => unknown | Promise + errorMessage?: string | null + failure?: LaunchOperation | null +}) { const { t } = useTranslation() - const [creating, setCreating] = useState(false) - const [failed, setFailed] = useState(false) - const presentation = kind === 'presentation' - const title = presentation ? 'PPT' : 'Excel' - const icon = presentation ? Icons.presentation(20) : Icons.spreadsheet(20) - const prefix = presentation ? 'powerpoint' : 'excel' - const createLabel = presentation ? 'session.presentation.launchButton.create' : 'excel.newWorkbook' - return
- + const [pending, setPending] = useState(null) + const [failed, setFailed] = useState(null) + const config = launchConfig[kind] + const visibleFailure = failure ?? failed + const run = (operation: LaunchOperation, action: () => unknown | Promise) => { + if (pending) return + setPending(operation) + setFailed(null) + void Promise.resolve().then(action).catch(() => setFailed(operation)).finally(() => setPending(null)) + } + return
+
-
{icon}
-
{t(presentation ? 'session.presentation.launchTitle' : 'excel.emptyTitle')}
-
{t(presentation ? 'session.presentation.launchDetail' : 'excel.emptyDescription')}
+
{config.icon(20)}
+
{t(config.titleKey)}
+
{t(config.descriptionKey)}
- - {onOpen ? : null} + +
- {failed ?
{t('office.createFailed')}
: null} + {errorMessage || visibleFailure ? ( +
+ {errorMessage ?? t(visibleFailure === 'create' ? 'office.createFailed' : 'office.openFailed')} +
+ ) : null}
diff --git a/desktop/apps/electron/src/renderer/components/app/PresentationAnimationPlayer.tsx b/desktop/apps/electron/src/renderer/components/app/PresentationAnimationPlayer.tsx index 9169483a..9df17488 100644 --- a/desktop/apps/electron/src/renderer/components/app/PresentationAnimationPlayer.tsx +++ b/desktop/apps/electron/src/renderer/components/app/PresentationAnimationPlayer.tsx @@ -31,6 +31,7 @@ export interface PresentationAnimationPlayerProps { onComplete?: () => void onActivateHyperlink?: (hyperlink: PresentationHyperlink) => void suppressMediaPlayback?: boolean + sources?: Readonly> runKey: string | number pageSize?: PresentationPageSize slide: PresentationSlide @@ -56,7 +57,7 @@ function applyFinalKeyframe(node: HTMLSpanElement, keyframes: Keyframe[]): void if (final.clipPath !== undefined) node.style.clipPath = String(final.clipPath) } -function PresentationAnimationPart({ assets, elements, pageSize, part, runKey }: { assets: readonly PresentationAsset[]; elements: readonly PresentationElement[]; pageSize: PresentationPageSize; part: PresentationAnimationPartSpec; runKey: string | number }) { +function PresentationAnimationPart({ assets, elements, pageSize, part, runKey, sources }: { assets: readonly PresentationAsset[]; elements: readonly PresentationElement[]; pageSize: PresentationPageSize; part: PresentationAnimationPartSpec; runKey: string | number; sources?: Readonly> }) { const layerRef = useRef(null) useLayoutEffect(() => { @@ -84,7 +85,7 @@ function PresentationAnimationPart({ assets, elements, pageSize, part, runKey }: > {elements.map((element) => ( - + ))} @@ -92,7 +93,7 @@ function PresentationAnimationPart({ assets, elements, pageSize, part, runKey }: } /** PowerPoint-style element animation preview rendered independently from the editable Fabric canvas. */ -export function PresentationAnimationPlayer({ assets = [], baseHiddenElementIds, completedTargetIds, className, elementIds, onComplete, onActivateHyperlink, suppressMediaPlayback = true, pageSize = PRESENTATION_PAGE_SIZES.wide, runKey, slide, slideNumber, theme, width }: PresentationAnimationPlayerProps) { +export function PresentationAnimationPlayer({ assets = [], baseHiddenElementIds, completedTargetIds, className, elementIds, onComplete, onActivateHyperlink, suppressMediaPlayback = true, sources, pageSize = PRESENTATION_PAGE_SIZES.wide, runKey, slide, slideNumber, theme, width }: PresentationAnimationPlayerProps) { const animationStates = useMemo(() => completedTargetIds ? getPresentationAnimationDisplayStates(slide.elements, completedTargetIds) : undefined, [completedTargetIds, slide.elements]) const requestedIds = useMemo(() => elementIds ? new Set(elementIds) : null, [elementIds]) const elements = useMemo(() => { @@ -125,12 +126,12 @@ export function PresentationAnimationPlayer({ assets = [], baseHiddenElementIds, const members = slide.elements.slice(index, end) for (const member of members) replacements.set(member.id, null) replacements.set(element.id, parts.map(part => ( - + ))) index = end - 1 } return replacements - }, [assets, pageSize, runKey, slide.elements, timeline]) + }, [assets, pageSize, runKey, slide.elements, sources, timeline]) const onCompleteRef = useRef(onComplete) const totalDuration = timeline.reduce((maximum, entry) => Math.max(maximum, entry.endsAt), 0) @@ -166,6 +167,7 @@ export function PresentationAnimationPlayer({ assets = [], baseHiddenElementIds, slideNumber={slideNumber} theme={theme} suppressMediaPlayback={suppressMediaPlayback} + sources={sources} onActivateHyperlink={onActivateHyperlink} width={width} pageSize={pageSize} diff --git a/desktop/apps/electron/src/renderer/components/app/PresentationRibbon.tsx b/desktop/apps/electron/src/renderer/components/app/PresentationRibbon.tsx index 25001e82..75bf01ac 100644 --- a/desktop/apps/electron/src/renderer/components/app/PresentationRibbon.tsx +++ b/desktop/apps/electron/src/renderer/components/app/PresentationRibbon.tsx @@ -435,8 +435,11 @@ export function PresentationRibbon({ sourceType: 'shape', patch: { fill: selectedElement.fill, + fillOpacity: selectedElement.fillOpacity, + gradientFill: selectedElement.gradientFill, borderColor: selectedElement.borderColor, borderWidth: selectedElement.borderWidth, + borderOpacity: selectedElement.borderOpacity, radius: selectedElement.radius, shadow: selectedElement.shadow, }, @@ -468,8 +471,12 @@ export function PresentationRibbon({ if (!isPresentationShapeElement(selectedElement)) return onUpdateElement({ fill: '#8B7CFF', + fillOpacity: undefined, + gradientFill: undefined, + patternFill: undefined, borderColor: '#6957D9', borderWidth: 0, + borderOpacity: undefined, shadow: false, }) } @@ -973,7 +980,7 @@ function InsertControls({ onAddShape, onAddSlide, onAddText }: { const { t } = useTranslation() return (
- + onAddText('body')} testId="presentation-add-text" />
@@ -1122,7 +1129,7 @@ function ObjectControls({ inspectorOpen, selectedElement, onMoveElement, onToggl onMoveElement('front')}> onMoveElement('back')}> shadowSupported && onUpdateElement({ shadow: !selectedElement?.shadow })}> - } onChange={(fill) => onUpdateElement({ fill })} /> + } onChange={(fill) => onUpdateElement({ fill, fillOpacity: undefined, gradientFill: undefined, patternFill: undefined })} /> } onChange={(borderColor) => onUpdateElement({ borderColor, borderWidth: Math.max(1, shape?.borderWidth ?? 0) })} /> 0} onClick={() => onUpdateElement({ borderWidth: (shape?.borderWidth ?? 0) >= 4 ? 0 : Math.max(1, (shape?.borderWidth ?? 0) + 1) })}>▱ onMoveElement('front')}> @@ -1446,7 +1453,7 @@ function ShapeRibbon({ canRedo, canUndo, formatPainterActive, layersOpen, onAddS
- onUpdateElement({ fill })} /> + onUpdateElement({ fill, fillOpacity: undefined, gradientFill: undefined, patternFill: undefined })} /> onUpdateElement({ borderColor, borderWidth: Math.max(1, shape?.borderWidth ?? 0) })} /> shadowSupported && selectedElement && onUpdateElement({ shadow: !selectedElement.shadow })} /> diff --git a/desktop/apps/electron/src/renderer/components/app/PresentationSlidePreview.tsx b/desktop/apps/electron/src/renderer/components/app/PresentationSlidePreview.tsx index 27f6c54b..b7aec739 100644 --- a/desktop/apps/electron/src/renderer/components/app/PresentationSlidePreview.tsx +++ b/desktop/apps/electron/src/renderer/components/app/PresentationSlidePreview.tsx @@ -22,6 +22,7 @@ import { type PresentationTextStyle, } from '@/atoms/presentation' import { presentationElementSource } from '@/presentation/project' +import { presentationTableCellAppearance, presentationTableCellSegments, presentationTableGrid } from '@/lib/presentationTable' import { cn } from '@/lib/cn' import type { PresentationAnimationDisplayState, PresentationAnimationScale, PresentationColorAnimation } from '@/lib/presentationAnimationPreview' import { @@ -33,7 +34,13 @@ import { isPresentationTextElement, supportsPresentationElementHyperlink, } from '@/lib/presentationInsert' -import { getPresentationShapePath, getPresentationShapeDefinition, isPresentationLineShape } from '@/lib/presentationShapes' +import { + getPresentationShapePath, + getPresentationShapeDefinition, + isPresentationLineShape, + presentationCustomShapePathData, + presentationLinearGradientCoordinates, +} from '@/lib/presentationShapes' import { PRESENTATION_TEXT_LINE_METRICS, presentationRenderingFontFamily, @@ -166,6 +173,7 @@ interface PresentationSlidePreviewProps { theme?: PresentationTheme width: number selected: boolean + sources?: Readonly> presentation?: boolean suppressMediaPlayback?: boolean onActivateHyperlink?: (hyperlink: PresentationHyperlink) => void @@ -184,6 +192,7 @@ export function PresentationSlidePreview({ theme = DEFAULT_PRESENTATION_MASTER, width, selected, + sources = {}, presentation = false, suppressMediaPlayback = false, onActivateHyperlink, @@ -233,6 +242,7 @@ export function PresentationSlidePreview({ aria-hidden={interactive ? undefined : 'true'} ref={previewRef} data-testid="presentation-slide-preview" + data-presentation-page-id={slide.id} > {elementReplacements?.get(element.id)} {visible && ( - + )} {visible && interactive && element.hyperlink && supportsPresentationElementHyperlink(element) ? ( > suppressMediaPlayback: boolean }) { const element = animationState?.element ?? sourceElement @@ -501,7 +512,7 @@ export function PresentationElementPreview({ assets = [], element: sourceElement } if (isPresentationShapeElement(element)) return if (isPresentationImageElement(element)) { - const source = presentationElementSource({ assets: [...assets] }, element) + const source = presentationElementSource({ assets: [...assets] }, element, sources) if (!source) return null const crop = element.crop if (crop) { @@ -536,7 +547,7 @@ export function PresentationElementPreview({ assets = [], element: sourceElement src={source.dataUrl} style={{ ...elementStyle(element, scale), - objectFit: element.fit, + objectFit: element.fit === 'stretch' ? 'fill' : element.fit, borderRadius: element.clipShape === 'ellipse' ? '50%' : undefined, filter: element.shadow ? 'drop-shadow(5px 6px 6px rgba(20, 20, 32, 0.22))' : undefined, }} @@ -544,7 +555,7 @@ export function PresentationElementPreview({ assets = [], element: sourceElement ) } if (isPresentationMediaElement(element)) { - const source = presentationElementSource({ assets: [...assets] }, element) + const source = presentationElementSource({ assets: [...assets] }, element, sources) if (!source) return null if (element.type === 'video' && interactive && !suppressMediaPlayback) { return @@ -593,8 +604,40 @@ function presentationVerticalAlignment(alignment: PresentationTextElement['verti function SlideShapePreview({ element, scale }: { scale?: PresentationAnimationScale; element: PresentationShapeElement }) { const definition = getPresentationShapeDefinition(element.type) const strokeOnly = definition.strokeOnly || isPresentationLineShape(element.type) + const gradientId = `presentation-shape-gradient-${element.id.replace(/[^\w-]/g, '-')}` + const patternId = `presentation-shape-pattern-${element.id.replace(/[^\w-]/g, '-')}` + const preset = element.patternFill?.preset + let patternPath: string | undefined + if (preset === 'lgGrid') patternPath = 'M 0 0 H 2 M 0 0 V 2' + else if (preset?.endsWith('DnDiag')) patternPath = 'M -2 0 L 2 4 M 0 -2 L 4 2 M 2 -2 L 6 2' + else if (preset?.endsWith('UpDiag')) patternPath = 'M -2 2 L 2 -2 M 0 4 L 4 0 M 2 4 L 6 0' + let shapeFill = element.fill + if (element.gradientFill) shapeFill = `url(#${gradientId})` + if (patternPath) shapeFill = `url(#${patternId})` + let patternStrokeWidth = 0.45 + if (preset?.startsWith('dk')) patternStrokeWidth = 0.8 + else if (preset?.startsWith('lt')) patternStrokeWidth = 0.2 + const linearGradient = element.gradientFill?.type === 'linear' + ? presentationLinearGradientCoordinates(element.gradientFill.angle) + : null let shape: React.ReactNode - if (element.type === 'rect' || element.type === 'roundRect') shape = ( + if (element.customGeometry) shape = element.customGeometry.paths.map((path, index) => ( + + )) + else if (element.type === 'rect' || element.type === 'roundRect') shape = ( ) else if (element.type === 'ellipse') shape = ( - + ) else shape = ( + {element.gradientFill || (element.patternFill && patternPath) ? ( + + {element.patternFill && patternPath ? ( + + + + + ) : null} + {element.gradientFill?.type === 'linear' && linearGradient ? ( + + {element.gradientFill.stops.map((stop, index) => )} + + ) : null} + {element.gradientFill?.type === 'radial' ? ( + + {element.gradientFill.stops.map((stop, index) => )} + + ) : null} + + ) : null} {shape} ) } function PresentationTablePreview({ element, scale }: { scale?: PresentationAnimationScale; element: PresentationTableElement }) { - const columns = Math.max(1, ...element.cells.map((row) => row.length)) - const cellHeight = element.height / Math.max(1, element.cells.length) + const grid = presentationTableGrid(element) return ( + {grid.columnWidths.map((width, index) => )} {element.cells.map((row, rowIndex) => ( - - {Array.from({ length: columns }, (_, columnIndex) => ( - + {Array.from({ length: grid.columns }, (_, columnIndex) => { + const cell = presentationTableCellAppearance(element, rowIndex, columnIndex) + if (cell.covered) return null + const cellHeight = grid.rowHeights.slice(rowIndex, rowIndex + cell.rowSpan).reduce((sum, size) => sum + size, 0) + let justifyContent = 'safe center' + if (cell.verticalAlign === 'top') justifyContent = 'flex-start' + if (cell.verticalAlign === 'bottom') justifyContent = 'flex-end' + const border = (edge: keyof typeof cell.borders) => { + const value = cell.borders[edge] + return value.type === 'none' || value.width === 0 ? 'none' : `${value.width}px ${value.type === 'dash' ? 'dashed' : 'solid'} ${value.color}` + } + return ( + - ))} + + ) + })} ))} diff --git a/desktop/apps/electron/src/renderer/components/app/PresentationWorkbenchPanel.tsx b/desktop/apps/electron/src/renderer/components/app/PresentationWorkbenchPanel.tsx index e32dfe64..08d45f34 100644 --- a/desktop/apps/electron/src/renderer/components/app/PresentationWorkbenchPanel.tsx +++ b/desktop/apps/electron/src/renderer/components/app/PresentationWorkbenchPanel.tsx @@ -1,5 +1,5 @@ import { OfficeSaveActions } from './OfficeSaveActions' -import { isPresentationDirty } from '@/lib/presentationWorkspaceRuntime' +import { isPresentationProjectDirty } from '@/lib/presentationFileController' import { presentationChartValueTicks, presentationChartHoleSize, presentationChartValue, presentationChartLineSegments, presentationLineLabelY, presentationPieLabels } from '@/lib/presentationCharts' import { useCallback, @@ -8,17 +8,20 @@ import { useMemo, useRef, useState, + useSyncExternalStore, type ChangeEvent, type FormEvent, type ReactElement, type ReactNode, } from 'react' -import { useAtom, useAtomValue, useSetAtom, useStore } from 'jotai' +import { useAtom, useSetAtom } from 'jotai' import { useTranslation } from 'react-i18next' import type { Canvas as FabricCanvas, FabricImage, FabricObject, + Gradient as FabricGradient, + Pattern as FabricPattern, Group as FabricGroup, Point as FabricPoint, TextStyle, @@ -38,17 +41,12 @@ import { import { createBlankPresentationSlide, createPresentationId, - currentPresentationDocumentAtom, - currentPresentationWorkspaceAtom, formatPresentationText, getPresentationPageSize, layoutPresentationVerticalText, presentationSlideBackground, presentationSlideFooter, - presentationAgentChangeAtom, presentationExpandedAtom, - presentationSessionIdAtom, - presentationWorkspaceFamily, replacePresentationPages, selectPresentationPage, stripPresentationTextFormatting, @@ -56,7 +54,7 @@ import { type PresentationAsset, type PresentationChartElement, type PresentationComment, - type PresentationDocument, + type PresentationProject, type PresentationElement, type PresentationFileSource, type PresentationHyperlink, @@ -79,10 +77,10 @@ import { showToastAtom } from '@/atoms/toast' import { Tooltip } from '@/components/amphi/Tooltip' import { cn } from '@/lib/cn' import { rlog } from '@/lib/logger' -import { presentationThemeTextColors, resizePresentationDocument } from '@/lib/presentationDesign' +import { presentationThemeTextColors, resizePresentationProject } from '@/lib/presentationDesign' +import { presentationTableCellAppearance, presentationTableCellSegments, presentationTableCellsPatch, presentationTableGrid } from '@/lib/presentationTable' import { clearPresentationHyperlinksToPages, - createPresentationAsset, detachPresentationCommentsFromElements, duplicatePresentationSlide, mergePresentationAssets, @@ -151,14 +149,21 @@ import { supportsPresentationElementShadow, } from '@/lib/presentationInsert' import { normalizePresentationTransition } from '@/lib/presentationTransitions' -import { createPresentationWorkspaceRuntime, type PresentationWorkspaceRuntime } from '@/lib/presentationWorkspaceRuntime' import { createOfficeEditorBinding, type OfficeEditorBinding, type OfficeEditorLease } from '@/lib/office/officeEditorBinding' import { bindPresentationNativeEdit, createPresentationEditorDriver, type PresentationEditingObject } from '@/lib/presentationEditorDriver' +import { + PRESENTATION_HISTORY_MAX_BYTES, + estimatePresentationProjectBytes, +} from '@/presentation/history' +import type { PresentationStore } from '@/presentation/store' import { getPresentationShapePath, getPresentationShapeDefinition, getPresentationShapeSize, isPresentationLineShape, + presentationColorWithOpacity, + presentationCustomShapePathData, + presentationLinearGradientCoordinates, } from '@/lib/presentationShapes' import { PresentationInsertDialogs, @@ -188,11 +193,9 @@ import { export interface PresentationWorkbenchPanelProps { active: boolean - workspaceRuntime?: PresentationWorkspaceRuntime + presentationStore: PresentationStore onClose?: () => void onExpandedChange?: (expanded: boolean) => void - onSave?: (documentId: string, saveAs: boolean) => Promise - saveError?: string | null } interface SlideshowTransitionRun { @@ -222,73 +225,8 @@ interface SlideshowTransitionView extends SlideshowTransitionRun { transition: PresentationTransition } -export const PRESENTATION_HISTORY_MAX_ENTRIES = 50 -export const PRESENTATION_HISTORY_MAX_BYTES = 192 * 1024 * 1024 - -export interface PresentationHistoryEntry { - document: PresentationDocument - estimatedBytes: number -} - -/** Estimate retained JS heap without serializing large embedded data URLs. */ -export function estimatePresentationDocumentBytes(document: PresentationDocument): number { - const seen = new Set() - let bytes = 0 - - const visit = (value: unknown) => { - if (value === null || value === undefined) { - bytes += 4 - return - } - if (typeof value === 'string') { - // UTF-16 is deliberately conservative; data URLs are ASCII but can still be - // promoted internally, and the budget should remain safe across runtimes. - bytes += value.length * 2 - return - } - if (typeof value === 'number' || typeof value === 'boolean') { - bytes += 8 - return - } - if (typeof value !== 'object' || seen.has(value)) return - seen.add(value) - bytes += Array.isArray(value) ? 24 : 32 - if (Array.isArray(value)) { - for (const item of value) visit(item) - return - } - for (const [key, item] of Object.entries(value)) { - bytes += key.length * 2 - visit(item) - } - } - - visit(document) - return bytes -} - -function cloneDocument(document: PresentationDocument): PresentationDocument { - // structuredClone would duplicate every Base64 payload for every undo step. - // Strip the immutable payloads while cloning the mutable model, then reattach - // the original strings by index so snapshots cannot mutate one another. - const payloads = document.assets.map((asset) => asset.source.dataUrl) - const payloadFreeDocument: PresentationDocument = { - ...document, - assets: document.assets.map((asset) => ({ ...asset, source: { ...asset.source, dataUrl: '' } })), - } - const cloned = structuredClone(payloadFreeDocument) - cloned.assets.forEach((asset, index) => { asset.source.dataUrl = payloads[index] ?? '' }) - return cloned -} - -export function createPresentationHistoryEntry(document: PresentationDocument, maxBytes = PRESENTATION_HISTORY_MAX_BYTES): PresentationHistoryEntry | null { - const estimatedBytes = estimatePresentationDocumentBytes(document) - if (estimatedBytes > maxBytes) return null - return { document: cloneDocument(document), estimatedBytes } -} - export function canAppendPresentationFileElement( - document: PresentationDocument, + document: PresentationProject, element: PresentationImageElement | PresentationMediaElement, asset: PresentationAsset, maxBytes = PRESENTATION_HISTORY_MAX_BYTES, @@ -302,7 +240,7 @@ export function canAppendPresentationFileElement( ? { ...item, elements: [...item.elements, element] } : item)), } - return estimatePresentationDocumentBytes(nextDocument) <= maxBytes + return estimatePresentationProjectBytes(nextDocument) <= maxBytes } export function resolvePresentationNumberFieldValue(draft: string, min: number | undefined, fallback: number): number { @@ -311,32 +249,6 @@ export function resolvePresentationNumberFieldValue(draft: string, min: number | return Math.round(min === undefined ? parsed : Math.max(min, parsed)) } -/** Keep the newest contiguous history segment within both entry and byte limits. */ -export function trimPresentationHistoryEntries(entries: readonly PresentationHistoryEntry[], maxEntries = PRESENTATION_HISTORY_MAX_ENTRIES, maxBytes = PRESENTATION_HISTORY_MAX_BYTES): PresentationHistoryEntry[] { - const kept: PresentationHistoryEntry[] = [] - let retainedBytes = 0 - for (let index = entries.length - 1; index >= 0 && kept.length < Math.max(0, maxEntries); index -= 1) { - const entry = entries[index]! - if (entry.estimatedBytes > maxBytes - retainedBytes) break - kept.unshift(entry) - retainedBytes += entry.estimatedBytes - } - return kept -} - -function trimPresentationHistoryPair(past: PresentationHistoryEntry[], future: PresentationHistoryEntry[]): void { - let entryCount = past.length + future.length - let retainedBytes = [...past, ...future].reduce((sum, entry) => sum + entry.estimatedBytes, 0) - while (entryCount > PRESENTATION_HISTORY_MAX_ENTRIES || retainedBytes > PRESENTATION_HISTORY_MAX_BYTES) { - // Prefer discarding the oldest undo state. Once none remain, discard the - // farthest redo state (future[0]); the nearest redo lives at the end. - const removed = past.length > 0 ? past.shift() : future.shift() - if (!removed) break - entryCount -= 1 - retainedBytes -= removed.estimatedBytes - } -} - export function isPresentationRotationLocked(element: PresentationElement): boolean { return !supportsPresentationElementRotation(element) } @@ -1026,55 +938,99 @@ function createFixedGraphicGroup(fabric: FabricModule, element: PresentationTabl } function createTableFabricObject(fabric: FabricModule, element: PresentationTableElement): FabricObject { - const rows = Math.max(1, element.cells.length) - const columns = Math.max(1, ...element.cells.map((row) => row.length)) - const cellWidth = element.width / columns - const cellHeight = element.height / rows - const objects: FabricObject[] = [] - for (let rowIndex = 0; rowIndex < rows; rowIndex += 1) { - for (let columnIndex = 0; columnIndex < columns; columnIndex += 1) { - const header = element.headerRow && rowIndex === 0 - objects.push(new fabric.Rect({ + const grid = presentationTableGrid(element) + const fills: FabricObject[] = [] + const borders: FabricObject[] = [] + const texts: FabricObject[] = [] + for (let rowIndex = 0; rowIndex < grid.rows; rowIndex += 1) { + for (let columnIndex = 0; columnIndex < grid.columns; columnIndex += 1) { + const style = presentationTableCellAppearance(element, rowIndex, columnIndex) + if (style.covered) continue + const cellX = grid.columnOffsets[columnIndex]! + const cellY = grid.rowOffsets[rowIndex]! + const cellWidth = grid.columnWidths.slice(columnIndex, columnIndex + style.colSpan).reduce((sum, width) => sum + width, 0) + const cellHeight = grid.rowHeights.slice(rowIndex, rowIndex + style.rowSpan).reduce((sum, height) => sum + height, 0) + const contentWidth = Math.max(0, cellWidth - style.padding.left - style.padding.right) + const contentHeight = Math.max(0, cellHeight - style.padding.top - style.padding.bottom) + fills.push(new fabric.Rect({ originX: 'left', originY: 'top', - left: columnIndex * cellWidth, - top: rowIndex * cellHeight, - width: cellWidth - 1, - height: cellHeight - 1, - strokeWidth: 1, - fill: header ? element.headerFill : element.bodyFill, - stroke: element.borderColor, + left: cellX, + top: cellY, + width: cellWidth, + height: cellHeight, + strokeWidth: 0, + fill: style.fill, })) - const text = new fabric.Textbox(element.cells[rowIndex]?.[columnIndex] ?? '', { + for (const edge of ['top', 'right', 'bottom', 'left'] as const) { + const border = style.borders[edge] + if (border.type === 'none' || border.width === 0) continue + const inset = border.width / 2 + let points: [number, number, number, number] + if (edge === 'top') points = [cellX, cellY + inset, cellX + cellWidth, cellY + inset] + else if (edge === 'right') points = [cellX + cellWidth - inset, cellY, cellX + cellWidth - inset, cellY + cellHeight] + else if (edge === 'bottom') points = [cellX, cellY + cellHeight - inset, cellX + cellWidth, cellY + cellHeight - inset] + else points = [cellX + inset, cellY, cellX + inset, cellY + cellHeight] + borders.push(new fabric.Line(points, { + stroke: border.color, strokeWidth: border.width, + ...(border.type === 'dash' ? { strokeDashArray: [4 * border.width, 2 * border.width] } : {}), + })) + } + const cellText = element.cells[rowIndex]?.[columnIndex] ?? '' + const textStyles: TextStyle = {} + let textLine = 0 + let character = 0 + for (const segment of presentationTableCellSegments(element, rowIndex, columnIndex)) { + for (const glyph of fabric.Text.prototype.graphemeSplit(segment.text)) { + if (glyph === '\n') { textLine += 1; character = 0; continue } + if (Object.keys(segment.style).length > 0) { + textStyles[textLine] ??= {} + textStyles[textLine]![character] = { + ...(segment.style.color ? { fill: segment.style.color } : {}), + ...(segment.style.fontSize ? { fontSize: segment.style.fontSize } : {}), + ...(segment.style.fontFamily ? { fontFamily: presentationRenderingFontFamily(segment.style.fontFamily, glyph) } : {}), + ...(segment.style.fontWeight ? { fontWeight: segment.style.fontWeight } : {}), + ...(segment.style.italic !== undefined ? { fontStyle: segment.style.italic ? 'italic' : 'normal' } : {}), + ...(segment.style.underline !== undefined ? { underline: segment.style.underline } : {}), + ...(segment.style.strikethrough !== undefined ? { linethrough: segment.style.strikethrough } : {}), + } + } + character += 1 + } + } + const text = new fabric.Textbox(cellText, { originX: 'left', originY: 'center', strokeWidth: 0, - left: (columnIndex * cellWidth) + 10, - top: (rowIndex + 0.5) * cellHeight, - width: Math.max(12, cellWidth - 20), - height: Math.max(12, cellHeight - 8), - fill: header ? element.headerTextColor ?? '#FFFFFF' : element.textColor, - fontFamily: presentationRenderingFontFamily('Aptos', element.cells[rowIndex]?.[columnIndex] ?? ''), + left: cellX + style.padding.left, + top: cellY + cellHeight / 2, + width: Math.max(1, contentWidth), + height: Math.max(1, contentHeight), + fill: style.textColor, + fontFamily: presentationRenderingFontFamily(style.fontFamily, element.cells[rowIndex]?.[columnIndex] ?? ''), splitByGrapheme: shouldSplitPresentationTextByGrapheme(element.cells[rowIndex]?.[columnIndex] ?? ''), - fontSize: element.fontSize, - fontWeight: header ? 600 : 400, - textAlign: 'left', + fontSize: style.fontSize, + fontWeight: style.bold ? 600 : 400, + textAlign: style.align, + styles: textStyles, }) - const contentHeight = Math.max(0, cellHeight - 8) + let textOffset = 0 + if (style.verticalAlign === 'middle') textOffset = Math.max(0, (contentHeight - text.height) / 2) + if (style.verticalAlign === 'bottom') textOffset = Math.max(0, contentHeight - text.height) // Clip each cell independently; overflowing text starts at the top of its own row. text.set({ - top: rowIndex * cellHeight + 4 + Math.max(contentHeight, text.height) / 2, + top: cellY + style.padding.top + textOffset + text.height / 2, clipPath: new fabric.Rect({ - width: Math.max(0, cellWidth - 20), height: contentHeight, - left: (cellWidth - 20 - text.width) / 2, + width: contentWidth, height: contentHeight, + left: (contentWidth - text.width) / 2, top: Math.min(0, (contentHeight - text.height) / 2), originX: 'center', originY: 'center', strokeWidth: 0, }), }) - objects.push(text) + texts.push(text) } } - return createFixedGraphicGroup(fabric, element, objects) + return createFixedGraphicGroup(fabric, element, [...fills, ...borders, ...texts]) } function createChartFabricObject(fabric: FabricModule, element: Extract): FabricObject { @@ -1341,9 +1297,9 @@ function createShapeFabricObject(fabric: FabricModule, element: PresentationShap const shadow = element.shadow ? new fabric.Shadow({ color: 'rgba(20, 20, 32, 0.22)', blur: 12, offsetX: 6, offsetY: 6 }) : undefined - const frameShape = (shape: FabricObject) => { + const frameShape = (shape: FabricObject | FabricObject[]) => { const frame = new fabric.Rect({ left: 0, top: 0, width: element.width, height: element.height, originX: 'center', originY: 'center', fill: 'transparent', strokeWidth: 0 }) - return new fabric.Group([frame, shape], { + return new fabric.Group([frame, ...(Array.isArray(shape) ? shape : [shape])], { left: element.x, top: element.y, width: element.width, height: element.height, originX: 'left', originY: 'top', angle: element.rotation, flipX: element.flipHorizontal, flipY: element.flipVertical, @@ -1353,9 +1309,88 @@ function createShapeFabricObject(fabric: FabricModule, element: PresentationShap layoutManager: new fabric.LayoutManager(new fabric.FixedLayout()), }) } + const linearGradient = element.gradientFill?.type === 'linear' + ? presentationLinearGradientCoordinates(element.gradientFill.angle) + : null + let shapeFill: string | FabricGradient<'linear'> | FabricGradient<'radial'> | FabricPattern = presentationColorWithOpacity(element.fill, element.fillOpacity) + if (element.gradientFill?.type === 'linear' && linearGradient) { + shapeFill = new fabric.Gradient<'linear'>({ + type: 'linear', gradientUnits: 'percentage', coords: linearGradient, + colorStops: element.gradientFill.stops.map(stop => ({ ...stop, opacity: stop.opacity * (element.fillOpacity ?? 1) })), + }) + } else if (element.gradientFill?.type === 'radial') { + shapeFill = new fabric.Gradient<'radial'>({ + type: 'radial', gradientUnits: 'percentage', + coords: { x1: 0.5, y1: 0.5, r1: 0, x2: 0.5, y2: 0.5, r2: 0.71 }, + colorStops: element.gradientFill.stops.map(stop => ({ ...stop, opacity: stop.opacity * (element.fillOpacity ?? 1) })), + }) + } else if (element.patternFill) { + const { patternFill } = element + const canvas = document.createElement('canvas') + canvas.width = 8 + canvas.height = 8 + const context = canvas.getContext('2d') + if (context) { + context.globalAlpha = patternFill.backgroundOpacity * (element.fillOpacity ?? 1) + context.fillStyle = patternFill.backgroundColor + context.fillRect(0, 0, 8, 8) + context.globalAlpha = patternFill.foregroundOpacity * (element.fillOpacity ?? 1) + context.strokeStyle = patternFill.foregroundColor + let lineWidth = 1.2 + if (patternFill.preset.startsWith('dk')) lineWidth = 2.5 + else if (patternFill.preset.startsWith('lt')) lineWidth = 0.6 + context.lineWidth = lineWidth + context.beginPath() + if (patternFill.preset === 'lgGrid') { + context.moveTo(0, 0) + context.lineTo(8, 0) + context.moveTo(0, 0) + context.lineTo(0, 8) + } else if (patternFill.preset.endsWith('DnDiag')) { + context.moveTo(-8, 0) + context.lineTo(8, 16) + context.moveTo(0, -8) + context.lineTo(16, 8) + context.moveTo(8, -8) + context.lineTo(24, 8) + } else if (patternFill.preset.endsWith('UpDiag')) { + context.moveTo(-8, 8) + context.lineTo(8, -8) + context.moveTo(0, 16) + context.lineTo(16, 0) + context.moveTo(8, 16) + context.lineTo(24, 0) + } + context.stroke() + shapeFill = new fabric.Pattern({ source: canvas, repeat: 'repeat' }) + } + } + const shapeStroke = presentationColorWithOpacity(element.borderColor, element.borderOpacity) const shapeStyle = { left: 0, top: 0, originX: 'center', originY: 'center', - fill: element.fill, stroke: element.borderColor, strokeWidth: element.borderWidth, + fill: shapeFill, stroke: shapeStroke, strokeWidth: element.borderWidth, } as const + if (element.customGeometry) { + return frameShape(element.customGeometry.paths.map((customPath) => { + const path = new fabric.Path(presentationCustomShapePathData(customPath), { + originX: 'center', + originY: 'center', + fill: customPath.fill === 'none' ? 'transparent' : shapeFill, + fillRule: 'evenodd', + stroke: customPath.stroke ? shapeStroke : 'transparent', + strokeWidth: element.borderWidth, + strokeLineCap: 'round', + strokeLineJoin: 'round', + strokeUniform: true, + }) + path.set({ + left: (path.pathOffset.x - customPath.width / 2) * element.width / customPath.width, + top: (path.pathOffset.y - customPath.height / 2) * element.height / customPath.height, + scaleX: element.width / customPath.width, + scaleY: element.height / customPath.height, + }) + return path + })) + } if (element.type === 'ellipse') { return frameShape(new fabric.Ellipse({ ...shapeStyle, rx: element.width / 2, ry: element.height / 2 })) } @@ -1368,9 +1403,9 @@ function createShapeFabricObject(fabric: FabricModule, element: PresentationShap const path = new fabric.Path(getPresentationShapePath(element), { originX: 'center', originY: 'center', - fill: strokeOnly ? 'transparent' : element.fill, + fill: strokeOnly ? 'transparent' : shapeFill, fillRule: 'evenodd', - stroke: element.borderColor, + stroke: shapeStroke, strokeWidth: strokeOnly ? Math.max(3, element.borderWidth) : element.borderWidth, strokeLineCap: 'round', strokeLineJoin: 'round', @@ -1758,6 +1793,8 @@ export async function createPresentationFabricObject( scaleX: element.width / cropWidth, scaleY: element.height / cropHeight, }) + } else if (element.fit === 'stretch') { + image.set({ left: 0, top: 0, scaleX: element.width / naturalWidth, scaleY: element.height / naturalHeight }) } else if (element.fit === 'cover') { const scale = Math.max(element.width / naturalWidth, element.height / naturalHeight) const cropWidth = element.width / scale @@ -1841,25 +1878,18 @@ function createFooterFabricObjects(fabric: FabricModule, theme: PresentationMast } /** A focused PowerPoint-style editor embedded in the Session workbench. */ -export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, workspaceRuntime, onSave, saveError }: PresentationWorkbenchPanelProps) { +export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, presentationStore }: PresentationWorkbenchPanelProps) { const { t } = useTranslation() - const sessionId = useAtomValue(presentationSessionIdAtom) - const agentChange = useAtomValue(presentationAgentChangeAtom) - const workspace = useAtomValue(currentPresentationWorkspaceAtom) - const document = useAtomValue(currentPresentationDocumentAtom) - const store = useStore() - const presentationRuntime = useMemo(() => { - if (workspaceRuntime) return workspaceRuntime - const workspaceAtom = presentationWorkspaceFamily(sessionId ?? '') - return createPresentationWorkspaceRuntime({ - sessionId: sessionId ?? '', - read: () => store.get(workspaceAtom), - write: (next) => store.set(workspaceAtom, next), - }) - }, [sessionId, store, workspaceRuntime]) - useEffect(() => store.sub(presentationWorkspaceFamily(sessionId ?? ''), () => { - presentationRuntime.runtime.publish() - }), [presentationRuntime, sessionId, store]) + const sessionId = presentationStore.sessionId + const presentationSnapshot = useSyncExternalStore( + presentationStore.subscribe, + presentationStore.getSnapshot, + presentationStore.getSnapshot, + ) + const agentChange = presentationSnapshot.agentChange + const document = presentationSnapshot.project! + const documentMetadata = presentationSnapshot.projectMetadata[document.id]! + const documentRevision = documentMetadata.revision const pageSize = getPresentationPageSize(document) const [expanded, setExpanded] = useAtom(presentationExpandedAtom) const setRightCollapsed = useSetAtom(setRightPanelCollapsedAtom) @@ -1867,6 +1897,10 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, const showToast = useSetAtom(showToastAtom) const [selectedElementId, setSelectedElementId] = useState(null) const [canvasGeneration, setCanvasGeneration] = useState(0) + const [canvasRenderState, setCanvasRenderState] = useState<{ + key: string | null + status: 'error' | 'loading' | 'ready' + }>({ key: null, status: 'loading' }) const [canvasScale, setCanvasScale] = useState(0.4) const [compact, setCompact] = useState(true) const [ribbonCollapsed, setRibbonCollapsed] = useState(false) @@ -1887,7 +1921,7 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, const [slideshowTransition, setSlideshowTransition] = useState(null) const [animationPreviewRun, setAnimationPreviewRun] = useState(null) const [transitionPreviewRun, setTransitionPreviewRun] = useState(null) - const [historyStatus, setHistoryStatus] = useState({ canUndo: false, canRedo: false }) + const historyStatus = { canUndo: presentationSnapshot.canUndo, canRedo: presentationSnapshot.canRedo } const [insertDialog, setInsertDialog] = useState(null) const [masterDialogOpen, setMasterDialogOpen] = useState(false) const rootRef = useRef(null) @@ -1901,8 +1935,8 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, const mediaRuntimeRef = useRef(null) const objectIdsRef = useRef(new WeakMap()) const documentRef = useRef(document) - const editorBindingRef = useRef | null>(null) - const nativeCommitRef = useRef<(next: PresentationDocument) => void>(() => undefined) + const editorBindingRef = useRef | null>(null) + const nativeCommitRef = useRef<(next: PresentationProject) => void>(() => undefined) const flushNativeEditRef = useRef<(() => void) | null>(null) const pendingCanvasEditRef = useRef<(() => void) | null>(null) const pageSizeRef = useRef(pageSize) @@ -1917,8 +1951,6 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, }) const suppressCanvasSelectionRef = useRef(false) const canvasSelectionFrameRef = useRef(null) - const pastRef = useRef([]) - const futureRef = useRef([]) const animationRunIdRef = useRef(0) const transitionRunIdRef = useRef(0) const consumedAgentChangeIdRef = useRef(0) @@ -1931,6 +1963,12 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, const currentSlide = document.slides.pages.find((slide) => slide.id === document.slides.selectedPageId) ?? document.slides.pages[0] + const currentCanvasRenderKey = currentSlide + ? JSON.stringify([document.id, documentRevision, currentSlide.id, canvasGeneration, agentChange?.changeId ?? 0]) + : null + const currentCanvasRenderStatus = canvasRenderState.key === currentCanvasRenderKey + ? canvasRenderState.status + : 'loading' const currentSlideBackground = currentSlide ? presentationSlideBackground(document.theme, currentSlide) : document.theme.background @@ -1945,30 +1983,17 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, : [] const selectedText = selectedElement && isPresentationTextElement(selectedElement) ? selectedElement : null - const commitDocument = useCallback((next: PresentationDocument, recordHistory = true) => { + const commitDocument = useCallback((next: PresentationProject, recordHistory = true) => { const current = documentRef.current - let versionedNext: PresentationDocument + let versionedNext: PresentationProject try { - versionedNext = presentationRuntime.commitDocument(current, next) + versionedNext = presentationStore.commitProject(current, next, true, recordHistory) } catch (error) { showToast(error instanceof Error ? error.message : String(error)) return } - if (recordHistory) { - const entry = createPresentationHistoryEntry(current) - // An oversized state is an undo barrier. Keeping older entries would make - // Undo skip the latest change and restore an unrelated document state. - pastRef.current = entry - ? trimPresentationHistoryEntries([...pastRef.current, entry]) - : [] - futureRef.current = [] - } documentRef.current = versionedNext - setHistoryStatus({ - canUndo: pastRef.current.length > 0, - canRedo: futureRef.current.length > 0, - }) - }, [presentationRuntime, showToast]) + }, [presentationStore, showToast]) const replaceCurrentSlide = useCallback((nextSlide: PresentationSlide) => { const current = documentRef.current @@ -2042,7 +2067,15 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, } if (isPresentationShapeElement(element) && element.fill !== 'transparent') { const accent = colors[index % colors.length] ?? element.fill - return { ...element, fill: accent, borderColor: accent } + return { + ...element, + fill: accent, + fillOpacity: undefined, + gradientFill: undefined, + patternFill: undefined, + borderColor: accent, + borderOpacity: undefined, + } } return element }), @@ -2170,8 +2203,6 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, }, [syncFabricObject, syncFabricObjects]) useEffect(() => { - pastRef.current = [] - futureRef.current = [] isolatedElementIdRef.current = null selectedElementIdRef.current = null const timer = window.setTimeout(() => { @@ -2181,7 +2212,6 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, setTransitionPreviewRun(null) setInsertDialog(null) setSelectedElementId(null) - setHistoryStatus({ canUndo: false, canRedo: false }) }, 0) return () => window.clearTimeout(timer) }, [document.id, sessionId]) @@ -2303,10 +2333,10 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, useEffect(() => { if (!active || !canvasElementRef.current) return - const binding = createOfficeEditorBinding({ + const binding = createOfficeEditorBinding({ appKind: 'presentation', sessionId: sessionId ?? '', documentId: documentRef.current.id, onChange: (next, identity) => { - if (identity.documentId !== presentationRuntime.runtime.getSnapshot().activeDocumentId) return + if (identity.documentId !== presentationStore.runtime.getSnapshot().activeDocumentId) return nativeCommitRef.current(next) }, }) @@ -2474,7 +2504,7 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, setInsertDialog({ kind: element.type, elementId: element.id }) }) const driver = createPresentationEditorDriver({ - readSnapshot: () => store.get(presentationWorkspaceFamily(sessionId ?? '')).documents + readSnapshot: () => presentationStore.getSnapshot().projects .find((item) => item.id === binding.capture().identity.documentId) ?? null, readEditingObject: () => canvas.getActiveObject() as (FabricObject & PresentationEditingObject) | null, flushPendingEdit: () => { @@ -2509,7 +2539,7 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, }) if (!binding.attach(driver)) return flushNativeEditRef.current = () => { void driver.flush(binding.capture()) } - unregisterEditor = presentationRuntime.bindEditor(binding) + unregisterEditor = presentationStore.bindEditor(binding) setCanvasGeneration((value) => value + 1) }) return () => { @@ -2517,7 +2547,7 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, binding.dispose() if (editorBindingRef.current === binding) editorBindingRef.current = null } - }, [activateFabricElement, active, presentationRuntime, sessionId, store]) + }, [activateFabricElement, active, presentationStore, sessionId]) useEffect(() => { const canvas = canvasRef.current @@ -2526,6 +2556,19 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, if (!active || !canvas || !fabric || !mediaRuntime || !currentSlide) return const lease = editorBindingRef.current?.capture() let cancelled = false + const renderKey = JSON.stringify([document.id, documentRevision, currentSlide.id, canvasGeneration, agentChange?.changeId ?? 0]) + let pendingElements = currentSlide.elements.length + let renderFailed = false + const finishElement = () => { + pendingElements -= 1 + if (!cancelled && !renderFailed && pendingElements === 0) { + setCanvasRenderState({ key: renderKey, status: 'ready' }) + } + } + const failRender = () => { + renderFailed = true + if (!cancelled) setCanvasRenderState({ key: renderKey, status: 'error' }) + } const revealFrameIds = new Set() const visibleAgentChange = agentChange && agentChange.slideId === currentSlide.id @@ -2543,7 +2586,10 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, revealFrameIds.add(frameId) } const animateAgentObject = (object: FabricObject, element: PresentationElement, index: number) => { - if (!visibleAgentChange || reducedMotion || !revealedElementIds.has(element.id)) return + if (!visibleAgentChange || reducedMotion || !revealedElementIds.has(element.id)) { + finishElement() + return + } const delayMs = Math.min(240, index * 32) const targetOpacity = element.opacity ?? 1 if ( @@ -2569,7 +2615,11 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, object.setCoords() canvas.requestRenderAll() if (progress < 1) scheduleRevealFrame(tick) - else object.set({ text: fullText }) + else { + object.set({ text: fullText }) + canvas.requestRenderAll() + finishElement() + } } scheduleRevealFrame(tick) return @@ -2588,7 +2638,11 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, object.set({ opacity: targetOpacity * eased }) canvas.requestRenderAll() if (progress < 1) scheduleRevealFrame(tick) - else object.set({ opacity: targetOpacity }) + else { + object.set({ opacity: targetOpacity }) + canvas.requestRenderAll() + finishElement() + } } scheduleRevealFrame(tick) } @@ -2608,10 +2662,15 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, const slideNumber = documentRef.current.slides.pages.findIndex((slide) => slide.id === currentSlide.id) + 1 createFooterFabricObjects(fabric, document.theme, currentSlide, Math.max(1, slideNumber), pageSize).forEach((object) => canvas.add(object)) canvas.requestRenderAll() + if (pendingElements === 0) { + scheduleRevealFrame(() => { + if (!cancelled) setCanvasRenderState({ key: renderKey, status: 'ready' }) + }) + } currentSlide.elements.forEach((element, index) => { const source = isPresentationImageElement(element) || isPresentationMediaElement(element) - ? presentationElementSource(documentRef.current, element) + ? presentationElementSource(documentRef.current, element, presentationSnapshot.sources) : undefined void createPresentationFabricObject( fabric, @@ -2621,7 +2680,7 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, }) : () => undefined, source, ).then((object) => { - if (cancelled || !lease?.isCurrent() || canvasRef.current !== canvas) return + if (cancelled || (lease && !lease.isCurrent()) || canvasRef.current !== canvas) return let hoverCursor = 'move' if (isPresentationMediaElement(element)) hoverCursor = 'default' else if (element.hyperlink && supportsPresentationElementHyperlink(element)) hoverCursor = 'pointer' @@ -2655,6 +2714,7 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, canvas.requestRenderAll() }).catch((error: unknown) => { if (cancelled || canvasRef.current !== canvas) return + failRender() rlog.warn('[presentation] canvas element render failed', { elementId: element.id, elementType: element.type, @@ -2668,27 +2728,17 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, for (const frameId of revealFrameIds) window.cancelAnimationFrame(frameId) if (mediaRuntimeRef.current === mediaRuntime) mediaRuntime.reset() } - }, [activateFabricElement, active, agentChange, canvasGeneration, currentSlide, currentSlideBackground, document.theme, pageSize]) + }, [activateFabricElement, active, agentChange, canvasGeneration, currentSlide, currentSlideBackground, document.id, documentRevision, document.theme, pageSize, presentationSnapshot.sources]) const undo = useCallback(() => { - const previous = pastRef.current.pop() - if (!previous) return - const current = createPresentationHistoryEntry(documentRef.current) - if (current) futureRef.current.push(current) - else futureRef.current = [] - trimPresentationHistoryPair(pastRef.current, futureRef.current) - commitDocument(previous.document, false) - }, [commitDocument]) + const previous = presentationStore.undo() + if (previous) documentRef.current = previous + }, [presentationStore]) const redo = useCallback(() => { - const next = futureRef.current.pop() - if (!next) return - const current = createPresentationHistoryEntry(documentRef.current) - if (current) pastRef.current.push(current) - else pastRef.current = [] - trimPresentationHistoryPair(pastRef.current, futureRef.current) - commitDocument(next.document, false) - }, [commitDocument]) + const next = presentationStore.redo() + if (next) documentRef.current = next + }, [presentationStore]) const deleteSelectedElement = useCallback(() => { const elementId = selectedElementIdRef.current @@ -2804,7 +2854,7 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, if (current.slides.selectedPageId === slideId) return const selected = { ...current, slides: selectPresentationPage(current.slides, slideId) } try { - documentRef.current = presentationRuntime.commitDocument(current, selected, false) + documentRef.current = presentationStore.commitProject(current, selected, false, false) } catch (error) { showToast(error instanceof Error ? error.message : String(error)) } @@ -2812,12 +2862,13 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, const [saving, setSaving] = useState(false) const savePresentation = useCallback((saveAs: boolean) => { - if (!onSave) return setSaving(true) - void onSave(document.id, saveAs).catch((error) => showToast(String(error))).finally(() => setSaving(false)) - }, [document.id, onSave, showToast]) + void presentationStore.save(document.id, saveAs).catch((error) => showToast(String(error))).finally(() => setSaving(false)) + }, [document.id, presentationStore, showToast]) + const retryPresentationWorkspace = useCallback(() => { + void presentationStore.retryPersistence().catch((error) => showToast(error instanceof Error ? error.message : String(error))) + }, [presentationStore, showToast]) useEffect(() => { - if (!onSave) return const key = (event: KeyboardEvent) => { if (!(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== 's') return event.preventDefault() @@ -2825,33 +2876,34 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, } window.addEventListener('keydown', key) return () => window.removeEventListener('keydown', key) - }, [onSave, savePresentation]) + }, [savePresentation]) - const selectPresentationDocument = (documentId: string) => { - void presentationRuntime.activateDocument(documentId).then((result) => { - if (!result.ok) showToast(result.error.message) - }) + const selectPresentationProject = (documentId: string) => { + void presentationStore.selectProject(documentId).catch((error) => showToast(error instanceof Error ? error.message : String(error))) } - const createPresentationDocument = () => { - void presentationRuntime.createDocument().then((result) => { - if (!result.ok) showToast(result.error.message) - }) + const createPresentationProject = () => { + void presentationStore.createProject().catch((error) => showToast(error instanceof Error ? error.message : String(error))) } - const closePresentationDocument = (documentId: string) => { - void presentationRuntime.closeDocument(documentId).then((result) => { - if (!result.ok) showToast(result.error.message) - else if (result.value.closeSurface) { + const closePresentationProject = (documentId: string) => { + if (presentationSnapshot.projects.length === 1) { + setExpanded(false) + if (onClose) onClose() + else setRightCollapsed(true) + return + } + void presentationStore.closeProject(documentId).then((result) => { + if (result.closeSurface) { setExpanded(false) if (onClose) onClose() else setRightCollapsed(true) } - }) + }).catch((error) => showToast(error instanceof Error ? error.message : String(error))) } const closePresentationPanel = () => { - void presentationRuntime.flushEditor().then(() => { + void presentationStore.flushEditor().then(() => { setExpanded(false) if (onClose) onClose() else setRightCollapsed(true) @@ -3084,13 +3136,21 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, showToast(t('session.common.cancelled')) return } - const asset = createPresentationAsset(kind, source, element.sourceAssetId) + const mountedAsset = await presentationStore.mountFileSource( + kind, + source, + window.api?.shell?.getPathForFile?.(file) || undefined, + file.size, + file.lastModified, + ) + const asset = { ...mountedAsset, id: element.sourceAssetId } if (!canAppendPresentationFileElement(documentRef.current, element, asset)) { showToast(t('session.presentation.insertDialog.totalFileSizeTooLarge')) return } appendElement(element, asset) - } catch { + } catch (error) { + rlog.warn('[presentation] file insertion failed', { kind, error }) showToast(t('session.presentation.insertDialog.fileReadError')) } } @@ -3114,7 +3174,7 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, if (value.kind === 'table') { if (existing && isPresentationTableElement(existing)) { - patchElement(existing.id, { cells: value.cells.map((row) => [...row]) } as Partial) + patchElement(existing.id, presentationTableCellsPatch(existing, value.cells)) } else { appendElement(createPresentationTableElement(value.cells)) } @@ -3318,7 +3378,7 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, const changePageSize = (preset: PresentationPageSizePreset) => { const current = documentRef.current - commitDocument(resizePresentationDocument(current, preset)) + commitDocument(resizePresentationProject(current, preset)) } const applyCurrentTransitionToAll = () => { @@ -3492,7 +3552,7 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, const previewWidth = compact ? 78 : 126 const sessionTarget = sessionId ? sessionId.slice(0, 8).toUpperCase() : '—' - const documentFileName = (item: PresentationDocument) => { + const documentFileName = (item: PresentationProject) => { const title = item.title.trim() || t('session.presentation.untitled') return title.toLowerCase().endsWith('.pptx') ? title : `${title}.pptx` } @@ -3590,21 +3650,22 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, : undefined} - activeId={workspace.activeDocumentId} + actions={presentationSnapshot.persistenceError ? undefined : } + activeId={presentationSnapshot.activeProjectId} icon={} label={t('session.presentation.documentTabs')} newIcon={} newLabel={t('session.presentation.newPresentation')} - onClose={closePresentationDocument} - onCreate={createPresentationDocument} - onSelect={selectPresentationDocument} - tabs={workspace.documents.map((item) => { - const fileName = item.source?.path.split(/[\\/]/).at(-1) || documentFileName(item) + onClose={closePresentationProject} + onCreate={createPresentationProject} + onSelect={selectPresentationProject} + tabs={presentationSnapshot.projects.map((item) => { + const metadata = presentationSnapshot.projectMetadata[item.id]! + const fileName = metadata.source?.path.split(/[\\/]/).at(-1) || documentFileName(item) return { id: item.id, label: fileName, - dirtyLabel: isPresentationDirty(item) ? t('office.unsaved') : undefined, + dirtyLabel: isPresentationProjectDirty(metadata) ? t('office.unsaved') : undefined, closeLabel: t('session.presentation.closeDocument', { name: fileName }), } })} @@ -3612,7 +3673,13 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, tooltipOptions={{ appearance: 'presentation', delayMs: 0 }} /> - {document.sourceProtected ?
{t('office.importedCopyNotice')}
: null} + {presentationSnapshot.persistenceError ? ( +
+ {t('office.checkpointFailed')} + +
+ ) : null} + {documentMetadata.sourceProtected ?
{t('office.importedCopyNotice')}
: null} {index + 1} - + ))} @@ -3723,6 +3790,10 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange,
@@ -3773,6 +3844,7 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange,
setAnimationPreviewRun((run) => run?.runKey === animationPreviewRun.runKey ? null : run)} @@ -3789,9 +3861,9 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange,
+ ? : } - current={} + current={} transition={transitionPreviewRun.transition} runKey={transitionPreviewRun.runKey} onComplete={() => setTransitionPreviewRun((run) => run?.runKey === transitionPreviewRun.runKey ? null : run)} @@ -3916,6 +3988,7 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, {slideshowOpen && slideshowSlide ? ( undefined }: { ) } -function SlideshowOverlay({ assets, current, onActivateHyperlink, onClose, onNext, onPrevious, onTransitionComplete, pageSize, slide, theme, total, transitionRun }: { +function SlideshowOverlay({ assets, current, onActivateHyperlink, onClose, onNext, onPrevious, onTransitionComplete, pageSize, slide, sources, theme, total, transitionRun }: { assets: readonly PresentationAsset[] current: number onActivateHyperlink: (hyperlink: PresentationHyperlink, completedTargetIds: ReadonlySet) => void @@ -4034,6 +4107,7 @@ function SlideshowOverlay({ assets, current, onActivateHyperlink, onClose, onNex onTransitionComplete: () => void pageSize: PresentationPageSize slide: PresentationSlide + sources: Readonly> theme: PresentationMaster total: number transitionRun: SlideshowTransitionView | null @@ -4137,6 +4211,7 @@ function SlideshowOverlay({ assets, current, onActivateHyperlink, onClose, onNex previous={( )} - current={} + current={} transition={transitionRun.transition} runKey={transitionRun.runKey} direction={transitionRun.direction} @@ -4163,6 +4238,7 @@ function SlideshowOverlay({ assets, current, onActivateHyperlink, onClose, onNex slideshowContent = ( onElementChange({ fill: value })} + onChange={(value) => onElementChange({ fill: value, gradientFill: undefined, patternFill: undefined })} /> ) : null} {isPresentationTextElement(selectedElement) ? ( @@ -4613,6 +4689,7 @@ function PresentationInspector({ > +
00 + +

First line

Second line

${text}

`) + const box = (await importSheetTextBoxes(archive, new Map([[1, { path: 'xl/worksheets/sheet1.xml' }]]))).get(1)![0]! + const svg = new DOMParser().parseFromString(Buffer.from(box.source.split(',')[1]!, 'base64').toString(), 'text/xml') + const lines = Array.from(svg.getElementsByTagName('text')) + expect(lines.slice(0, 3).map((line) => line.textContent)).toEqual(['First line', '', 'Second line']) + expect(lines.length).toBeGreaterThan(5) + expect(lines.slice(3).map((line) => line.textContent).join('').replace(/\s/g, '')).toBe(text.replace(/\s/g, '')) + expect(lines.every((line, index) => !index || Number(line.getAttribute('y')) > Number(lines[index - 1]!.getAttribute('y')))).toBe(true) + expect(Number(lines.at(-1)!.getAttribute('y'))).toBeLessThan(300) + archive.file('xl/drawings/drawing1.xml', (await archive.file('xl/drawings/drawing1.xml')!.async('text')).replace('wrap="square"', 'wrap="none"')) + const unwrapped = (await importSheetTextBoxes(archive, new Map([[1, { path: 'xl/worksheets/sheet1.xml' }]]))).get(1)![0]! + const unwrappedSvg = new DOMParser().parseFromString(Buffer.from(unwrapped.source.split(',')[1]!, 'base64').toString(), 'text/xml') + expect(Array.from(unwrappedSvg.getElementsByTagName('text')).map((line) => line.textContent)).toEqual(['First line', '', 'Second line', text]) +}) + +it('previews native text boxes with their anchors and XML-escaped text without loading external parts', async () => { + const archive = new JSZip() + archive.file('xl/worksheets/_rels/sheet1.xml.rels', ` + + + `) + archive.file('xl/drawings/drawing1.xml', ` + 295250319050 + 5080 + + R&D <计划> + `) + const boxes = await importSheetTextBoxes(archive, new Map([[7, { path: 'xl/worksheets/sheet1.xml' }]])) + const box = boxes.get(7)![0]! + expect(boxes.size).toBe(1) + expect(boxes.get(7)).toHaveLength(1) + expect(box.from).toEqual({ column: 2, row: 3, columnOffset: 10, rowOffset: 2 }) + expect(box.to).toEqual({ column: 5, row: 8, columnOffset: 0, rowOffset: 0 }) + const svg = Buffer.from(box.source.split(',')[1]!, 'base64').toString('utf8') + expect(svg).toContain('width="200"') + expect(svg).toContain('font-size="20"') + expect(svg).toContain('font-weight="bold"') + expect(svg).toContain('R&D <计划>') +}) + +it('previews one-cell text boxes with native size, theme background and paragraph alignment', async () => { + const archive = new JSZip() + archive.file('xl/worksheets/_rels/sheet1.xml.rels', '') + archive.file('xl/theme/theme1.xml', ' ') + archive.file('xl/drawings/drawing1.xml', ` + 395251519050 + +

Caption

+ `) + const box = (await importSheetTextBoxes(archive, new Map([[1, { path: 'xl/worksheets/sheet1.xml' }]]))).get(1)![0]! + expect(box.from).toEqual({ column: 3, row: 15, columnOffset: 1, rowOffset: 2 }) + expect(box.to).toEqual({ column: 3, row: 15, columnOffset: 201, rowOffset: 52 }) + const svg = Buffer.from(box.source.split(',')[1]!, 'base64').toString('utf8') + expect(svg).toContain('fill="#d6e0eb"') + expect(svg).toContain('text-anchor="middle"') + expect(svg).toContain('Caption') +}) diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/excelWorkbook.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/excelWorkbook.test.ts index de390740..bcfb5fac 100644 --- a/desktop/apps/electron/src/renderer/lib/__tests__/excelWorkbook.test.ts +++ b/desktop/apps/electron/src/renderer/lib/__tests__/excelWorkbook.test.ts @@ -14,6 +14,74 @@ import { } from '../excelWorkbook' describe('Excel workbook conversion', () => { + it('keeps native image stacking order through repeated save and reopen cycles', async () => { + const source = new Workbook() + const sheet = source.addWorksheet('Stacked images') + for (const offset of [0, 95250]) { + const image = source.addImage({ extension: 'png', base64: 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Y9ZQmcAAAAASUVORK5CYII=' }) + sheet.addImage(image, { tl: { nativeCol: 0, nativeRow: 0, nativeColOff: offset, nativeRowOff: 0 }, br: { nativeCol: 3, nativeRow: 3, nativeColOff: offset, nativeRowOff: 0 } } as never) + } + let snapshot = await importXlsx(new Uint8Array(await source.xlsx.writeBuffer()), LocaleType.EN_US) + const resource = snapshot.resources!.find((entry) => entry.name === 'SHEET_DRAWING_PLUGIN')! + const drawings = JSON.parse(resource.data) + const imported = drawings[snapshot.sheetOrder[0]!] + imported.order.reverse() + imported.order.push('removed-image', imported.order[0]) + resource.data = JSON.stringify(drawings) + for (let cycle = 0; cycle < 2; cycle++) { + const bytes = await exportXlsx(snapshot) + const office = new Workbook() + await office.xlsx.load(bytes.slice().buffer) + expect(office.worksheets[0]!.getImages().map((image) => image.range.tl.nativeColOff / 9525)).toEqual([10, 0]) + snapshot = await importXlsx(bytes, LocaleType.EN_US) + } + }) + it('preserves native image offsets across custom row and column dimensions and repeated exports', async () => { + const source = new Workbook() + const sheet = source.addWorksheet('Images') + sheet.getColumn(3).width = 30 + sheet.getRow(4).height = 45 + const id = source.addImage({ extension: 'png', base64: 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Y9ZQmcAAAAASUVORK5CYII=' }) + sheet.addImage(id, { + tl: { nativeCol: 2, nativeRow: 3, nativeColOff: 95250, nativeRowOff: 190500 }, + br: { nativeCol: 5, nativeRow: 8, nativeColOff: 47625, nativeRowOff: 28575 }, + } as never) + let snapshot = await importXlsx(new Uint8Array(await source.xlsx.writeBuffer()), LocaleType.EN_US) + for (let cycle = 0; cycle < 2; cycle++) { + const resource = JSON.parse(snapshot.resources!.find((entry) => entry.name === 'SHEET_DRAWING_PLUGIN')!.data)[snapshot.sheetOrder[0]!] + expect(resource.data[resource.order[0]].sheetTransform).toEqual({ + from: { column: 2, row: 3, columnOffset: 10, rowOffset: 20 }, + to: { column: 5, row: 8, columnOffset: 5, rowOffset: 3 }, + }) + snapshot = await importXlsx(await exportXlsx(snapshot), LocaleType.EN_US) + } + }) + it('opens table icon filters without changing original bytes or losing cells', async () => { + const source = new Workbook() + source.addWorksheet('Data').addTable({ name: 'DataTable', ref: 'A1', headerRow: true, columns: [{ name: 'Value', filterButton: true }], rows: [[10], [20]] }) + const archive = await JSZip.loadAsync(await source.xlsx.writeBuffer()) + const table = archive.file('xl/tables/table1.xml')! + archive.file(table.name, (await table.async('text')).replace(/]*\/>/, '')) + const bytes = await archive.generateAsync({ type: 'uint8array' }) + const original = bytes.slice() + const snapshot = await importXlsx(bytes, LocaleType.EN_US) + const sheet = snapshot.sheets[snapshot.sheetOrder[0]!]! + expect(sheet.cellData![1]![0]!.v).toBe(10) + expect(sheet.cellData![2]![0]!.v).toBe(20) + expect(unsupportedWorkbookFeatures(snapshot)).toContain('active filter criteria') + expect(bytes).toEqual(original) + }) + + it('loads one-cell image anchors into the drawing plugin data and display order', async () => { + const source = new Workbook() + const sheet = source.addWorksheet('Images') + const id = source.addImage({ extension: 'png', base64: 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Y9ZQmcAAAAASUVORK5CYII=' }) + sheet.addImage(id, { tl: { col: 2, row: 3 }, ext: { width: 120, height: 80 } }) + const snapshot = await importXlsx(new Uint8Array(await source.xlsx.writeBuffer()), LocaleType.EN_US) + const resource = JSON.parse(snapshot.resources!.find((entry) => entry.name === 'SHEET_DRAWING_PLUGIN')!.data)[snapshot.sheetOrder[0]!] + expect(resource.order).toHaveLength(1) + expect(resource.data[resource.order[0]].sheetTransform.to).toMatchObject({ column: 2, row: 3, columnOffset: 120, rowOffset: 80 }) + }) it('keeps formulas, formatting and frozen panes through repeated save and reopen cycles', async () => { let workbook = createEmptyWorkbook(LocaleType.EN_US, 'Repeated edits') const sheet = workbook.sheets[workbook.sheetOrder[0]!]! @@ -319,8 +387,9 @@ describe('Excel workbook conversion', () => { const imported = await importXlsx(new Uint8Array(await source.xlsx.writeBuffer()), LocaleType.EN_US) const sheetId = imported.sheetOrder[0]! const drawingResource = imported.resources?.find((resource) => resource.name === 'SHEET_DRAWING_PLUGIN') - const drawings = JSON.parse(drawingResource?.data ?? '{}') as Record> - const drawingId = Object.keys(drawings[sheetId] ?? {})[0]! + const drawings = JSON.parse(drawingResource?.data ?? '{}') as Record; order: string[] }> + const drawingId = drawings[sheetId]!.order[0]! + expect(drawings[sheetId]!.data[drawingId]).toBeDefined() const liveAnalysis = { version: 1, bindings: [{ @@ -336,10 +405,11 @@ describe('Excel workbook conversion', () => { expect(officeWorkbook.worksheets.some((worksheet) => worksheet.state === 'veryHidden')).toBeTrue() const restored = await importXlsx(bytes, LocaleType.EN_US) - const restoredDrawings = JSON.parse(restored.resources?.find((resource) => resource.name === 'SHEET_DRAWING_PLUGIN')?.data ?? '{}') as Record> + const restoredDrawings = JSON.parse(restored.resources?.find((resource) => resource.name === 'SHEET_DRAWING_PLUGIN')?.data ?? '{}') as Record; order: string[] }> expect(restored.sheetOrder[0]).toBe(sheetId) expect(restored.sheets[sheetId]?.name).toBe(name) - expect(Object.keys(restoredDrawings[sheetId] ?? {})).toContain(drawingId) + expect(restoredDrawings[sheetId]!.order).toContain(drawingId) + expect(Object.keys(restoredDrawings[sheetId]!.data)).toContain(drawingId) expect(restored.custom?.[EXCEL_LIVE_ANALYSIS_CUSTOM_KEY]).toEqual(liveAnalysis) expect(Object.values(restored.sheets).some((worksheet) => worksheet?.name?.startsWith('__BRIDGIC_INTERNAL__'))).toBeFalse() }) diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/excelWorkbookImport.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/excelWorkbookImport.test.ts index d6f25f10..214ae1e4 100644 --- a/desktop/apps/electron/src/renderer/lib/__tests__/excelWorkbookImport.test.ts +++ b/desktop/apps/electron/src/renderer/lib/__tests__/excelWorkbookImport.test.ts @@ -1,6 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, mock } from 'bun:test' import { LocaleType, type IWorkbookData } from '@univerjs/core' import { importExcelWorkbook, type ExcelImportWorkerResponse } from '../excelWorkbookImport' +import { unsupportedWorkbookFeatures } from '../excelWorkbook' const originalWorker = globalThis.Worker let workers: ImportWorker[] = [] @@ -26,6 +27,18 @@ beforeEach(() => { afterEach(() => { globalThis.Worker = originalWorker }) describe('background workbook import', () => { + it('keeps readable cells and supported images when an embedded image cannot be previewed', async () => { + const png = 'data:image/png;base64,AAAA' + const resource = { name: 'SHEET_DRAWING_PLUGIN', data: JSON.stringify({ sheet: { + data: { good: { source: png }, bad: { source: 'data:image/tiff;base64,AAAA' } }, order: ['good', 'bad'], + } }) } + const snapshot = { id: 'imported', sheets: {}, sheetOrder: [], resources: [resource] } as unknown as IWorkbookData + const result = importExcelWorkbook(new Uint8Array(), LocaleType.EN_US) + workers[0]!.reply({ type: 'complete', snapshot }) + expect(await result).toBe(snapshot) + expect(JSON.parse(resource.data).sheet).toEqual({ data: { good: { source: png } }, order: ['good'] }) + expect(unsupportedWorkbookFeatures(snapshot)).toContain('unrenderable embedded images') + }) it('transfers a copy of the input, reports progress, and releases the worker on success', async () => { const input = new Uint8Array([1, 2, 3]) const onProgress = mock(() => {}) diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/i18n-coverage.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/i18n-coverage.test.ts index f21a4ea0..4bbd5ad0 100644 --- a/desktop/apps/electron/src/renderer/lib/__tests__/i18n-coverage.test.ts +++ b/desktop/apps/electron/src/renderer/lib/__tests__/i18n-coverage.test.ts @@ -133,7 +133,7 @@ const NAMESPACES = new Set(Object.keys(zh)) * ~80 of them would rot, and `tool.verb.getSchedule` shipped missing while one existed. */ const KEY_LIKE = /['"]([a-z][A-Za-z0-9]*(?:\.[A-Za-z0-9_]+)+)['"]/g /** Filenames share the `word.word` shape and collide with namespaces like `workflow`. */ -const FILENAME = /\.(?:html|md|json|ts|tsx|js|jsx|css|png|svg|txt|ya?ml|py|sh|lock|log|exe|nsh|zip)$/ +const FILENAME = /\.(?:html|md|json|xml|ts|tsx|js|jsx|css|png|svg|txt|ya?ml|py|sh|lock|log|exe|nsh|zip|bin)$/ /** `t('some.key', { …count… })` — the only calls i18next resolves through the * `_one`/`_other` plural family instead of the bare path. */ diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/officeImages.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/officeImages.test.ts index 923da52b..f24404ef 100644 --- a/desktop/apps/electron/src/renderer/lib/__tests__/officeImages.test.ts +++ b/desktop/apps/electron/src/renderer/lib/__tests__/officeImages.test.ts @@ -5,7 +5,9 @@ import { LocaleType } from '@univerjs/core' import JSZip from 'jszip' GlobalRegistrator.register() -const { prepareOfficeImage } = await import('../office/officeImage') +const { prepareOfficeImage, normalizeLegacyEmfHeader } = await import('../office/officeImage') +const { prepareWordHtmlImages } = await import('../wordImages') +const { i18n } = await import('../i18n') const { createWordWorkspace, createWordDomainStore, isWordDocumentDirty, reduceWordCommand } = await import('../wordDomain') const { exportWordDocx } = await import('../wordDocxExport') const { importDocxToHtml } = await import('../wordDocxImport') @@ -43,6 +45,25 @@ afterEach(() => { }) afterAll(() => GlobalRegistrator.unregister()) +it('removes a legacy EMF description without confusing its text with OpenGL header fields', () => { + const source = new Uint8Array(136) + const view = new DataView(source.buffer) + view.setUint32(4, 116, true) + view.setUint32(48, 136, true) + view.setUint32(60, 13, true) + view.setUint32(64, 88, true) + view.setUint32(96, 12345, true) + source[116] = 14 + const normalized = normalizeLegacyEmfHeader(source) + const header = new DataView(normalized.buffer) + expect(normalized.length).toBe(108) + expect(header.getUint32(4, true)).toBe(88) + expect(header.getUint32(48, true)).toBe(108) + expect(header.getUint32(60, true)).toBe(0) + expect(normalized[88]).toBe(14) + expect(view.getUint32(96, true)).toBe(12345) +}) + it('converts BMP and WebP to PNG while retaining supported image payloads', async () => { for (const [mime, payload] of [['bmp', BMP], ['webp', WEBP]]) { expect(await prepareOfficeImage(`data:image/${mime};base64,${payload}`, 'word')).toEqual({ extension: 'png', base64: PNG, dataUrl: pngSource }) @@ -55,6 +76,31 @@ it('converts BMP and WebP to PNG while retaining supported image payloads', asyn expect(decoded).toHaveLength(2) }) +it('shows a warning placeholder for an unsupported imported image while explicit edits stay strict', async () => { + const html = `

BeforediagramAfter

` + const warnings: string[] = [] + const preview = await prepareWordHtmlImages(html, (message) => warnings.push(message)) + expect(preview).toContain('Before') + expect(preview).toContain('After') + expect(preview).toContain('[图片未能预览:diagram]') + expect(preview).toContain(pngSource) + expect(warnings).toHaveLength(1) + await expect(prepareWordHtmlImages(html)).rejects.toThrow('Use an embedded') +}) + +it('localizes an unavailable imported image using the active UI language', async () => { + const previousLanguage = i18n.language + try { + await i18n.changeLanguage('en') + const withAlt = await prepareWordHtmlImages('diagram', () => undefined) + const withoutAlt = await prepareWordHtmlImages('', () => undefined) + expect(withAlt).toContain('[Image could not be previewed: diagram]') + expect(withoutAlt).toContain('[Image could not be previewed]') + } finally { + await i18n.changeLanguage(previousLanguage) + } +}) + async function workbookWithImage(source: string) { const workbook = new Workbook() const sheet = workbook.addWorksheet('Images') @@ -63,7 +109,7 @@ async function workbookWithImage(source: string) { const snapshot = await importXlsx(new Uint8Array(await workbook.xlsx.writeBuffer()), LocaleType.EN_US) const resource = snapshot.resources!.find((item) => item.name === 'SHEET_DRAWING_PLUGIN')! const drawings = JSON.parse(resource.data) - const drawing = Object.values(drawings[snapshot.sheetOrder[0]!])[0] as { source: string } + const drawing = Object.values(drawings[snapshot.sheetOrder[0]!].data)[0] as { source: string } drawing.source = source resource.data = JSON.stringify(drawings) return snapshot diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/officeSurfaceStatus.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/officeSurfaceStatus.test.ts index 78caa8ff..0573a19b 100644 --- a/desktop/apps/electron/src/renderer/lib/__tests__/officeSurfaceStatus.test.ts +++ b/desktop/apps/electron/src/renderer/lib/__tests__/officeSurfaceStatus.test.ts @@ -15,9 +15,11 @@ const input = { } const ppt = { sessionId: 'session-a', targetId: 'ppt-a', webContentsId: 1, loading: false, crashed: false, + documentCount: null, } const excel = { sessionId: 'session-a', targetId: 'excel-a', webContentsId: 2, ready: true, crashed: false, dirty: false, + documentCount: null, } const word = { @@ -56,13 +58,24 @@ describe('Office shell status compatibility contract', () => { expect(hasOfficeBackgroundContent(crashed)).toBe(true) }) - it('retains native background markers without fabricating PPT or Excel document counts', () => { + it('does not treat an empty or pending PPT or Excel target as background content', () => { const statuses = projectOfficeSurfaceStatuses({ ...input, powerPointSession: ppt, excelSession: excel }) - for (const kind of ['presentation', 'excel'] as const) { - expect(hasOfficeBackgroundContent(statuses[kind])).toBe(true) - expect(statuses[kind].documentCount).toBeNull() - expect(statuses[kind].runtimeState).toBe('ready') - } + expect(statuses.presentation.documentInventory).toBe('pending') + expect(statuses.presentation.documentCount).toBeNull() + expect(hasOfficeBackgroundContent(statuses.presentation)).toBe(false) + const empty = projectOfficeSurfaceStatuses({ ...input, powerPointSession: { ...ppt, documentCount: 0 } }).presentation + expect(empty.documentInventory).toBe('ready') + expect(hasOfficeBackgroundContent(empty)).toBe(false) + const populated = projectOfficeSurfaceStatuses({ ...input, powerPointSession: { ...ppt, documentCount: 1 } }).presentation + expect(hasOfficeBackgroundContent(populated)).toBe(true) + + expect(hasOfficeBackgroundContent(statuses.excel)).toBe(false) + expect(statuses.excel.documentCount).toBeNull() + expect(statuses.excel.documentInventory).toBe('pending') + const emptyExcel = projectOfficeSurfaceStatuses({ ...input, excelSession: { ...excel, documentCount: 0 } }).excel + expect(hasOfficeBackgroundContent(emptyExcel)).toBe(false) + const populatedExcel = projectOfficeSurfaceStatuses({ ...input, excelSession: { ...excel, documentCount: 1 } }).excel + expect(hasOfficeBackgroundContent(populatedExcel)).toBe(true) }) it('rejects native inventories owned by a different Session', () => { @@ -93,8 +106,8 @@ describe('Office shell status compatibility contract', () => { it('keeps failed native targets discoverable and gives crash state priority over loading', () => { const statuses = projectOfficeSurfaceStatuses({ ...input, - powerPointSession: { ...ppt, loading: true, crashed: true }, - excelSession: { ...excel, crashed: true }, + powerPointSession: { ...ppt, loading: true, crashed: true, documentCount: 1 }, + excelSession: { ...excel, crashed: true, documentCount: 1 }, }) for (const kind of ['presentation', 'excel'] as const) { expect(statuses[kind].runtimeState).toBe('crashed') diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/powerPointProtocol.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/powerPointProtocol.test.ts index 7a56ef71..c80d5013 100644 --- a/desktop/apps/electron/src/renderer/lib/__tests__/powerPointProtocol.test.ts +++ b/desktop/apps/electron/src/renderer/lib/__tests__/powerPointProtocol.test.ts @@ -1,467 +1,332 @@ import { describe, expect, it } from 'bun:test' import { - createBlankPresentationDocument, + createBlankPresentationProject, createBlankPresentationSlide, - presentationSlideBackground, - presentationSlideFooter, - type PresentationWorkspace, } from '@/atoms/presentation' import { createPresentationAsset } from '@/presentation/project' -import { executePowerPointRequest } from '../powerPointProtocol' -import { presentationTextStyleAt } from '../presentationText' +import { executePowerPointRequest, type PowerPointProjectCollection } from '../powerPointProtocol' -function workspace(): PresentationWorkspace { - const document = createBlankPresentationDocument('Quarterly review') - return { activeDocumentId: document.id, documents: [document] } +function workspace(): PowerPointProjectCollection { + const document = createBlankPresentationProject('Quarterly review') + return { activeProjectId: document.id, projects: [document] } +} + +async function readDeck(state: PowerPointProjectCollection) { + const document = state.projects[0]! + return executePowerPointRequest(state, { method: 'read_deck', params: { document_id: document.id, include_theme: true } }) +} + +async function readPage(state: PowerPointProjectCollection, pageId: string, format = 'compact') { + const document = state.projects[0]! + return executePowerPointRequest(state, { method: 'read_page', params: { document_id: document.id, page_id: pageId, format } }) } describe('PowerPoint renderer protocol', () => { - it('invalidates cached media revisions for payload changes and rejects stale edits', async () => { - const initial = workspace() - const document = initial.documents[0]! - const slide = document.slides.pages[0]! - const source = { dataUrl: 'data:image/png;base64,YQ==', fileName: 'image.png', mimeType: 'image/png' } - const asset = createPresentationAsset('image', source) - document.assets = [asset] - slide.elements = [{ id: 'image', type: 'image', sourceAssetId: asset.id, altText: '', fit: 'contain', x: 0, y: 0, width: 20, height: 20, rotation: 0 }] - const revision = async () => { - const read = await executePowerPointRequest(initial, { method: 'get_ppt_page', params: { page_id: slide.id } }) - return (read.result as { page: { revision: string } }).page.revision - } - const first = await revision() - expect(await revision()).toBe(first) - asset.source.dataUrl = 'data:image/png;base64,Yg==' - const second = await revision() - expect(second).not.toBe(first) - expect(await revision()).toBe(second) - await expect(executePowerPointRequest(initial, { method: 'remove_ppt_element', params: { page_id: slide.id, ref: 'image', expected_revision: first } })).rejects.toThrow('changed after it was read') - expect(slide.elements).toHaveLength(1) - asset.source.dataUrl = 'data:image/png;base64,YQ==' - expect(await revision()).toBe(first) - slide.elements[0]!.x = 10 - expect(await revision()).not.toBe(first) + it('opens a new target and reuses the exact Session document', async () => { + const opened = await executePowerPointRequest(workspace(), { + method: 'open', params: { target: '/workspace/roadmap.pptx', file_name: 'roadmap.pptx' }, + }) + expect(opened.target).toBe('/workspace/roadmap.pptx') + expect(opened.result).toMatchObject({ + revision: expect.any(String), + deck: { id: expect.any(String), file_name: 'roadmap.pptx', total_pages: 1, pages: [{ index: 0, has_content: false }] }, + reused: false, + }) + const reopened = await executePowerPointRequest(opened.projects!, { + method: 'open', params: { target: '/workspace/roadmap.pptx', file_name: 'roadmap.pptx' }, + }, { currentTarget: opened.target! }) + expect(reopened.projects).toBeUndefined() + expect(reopened.result).toMatchObject({ reused: true }) }) - it('respects explicit Agent run sizes alongside base formatting and retains numbering through later edits', async () => { - const initial = workspace() - const slide = initial.documents[0]!.slides.pages[0]! - slide.elements = [{ id: 'rich', type: 'text', text: '标题 English', x: 20, y: 20, width: 600, height: 120, rotation: 0, - fontSize: 40, fontFamily: 'Arial', fontWeight: 700, color: '#111111', align: 'left', - textRuns: [{ start: 3, end: 10, style: { fontSize: 20, fontWeight: 400, color: '#0088CC' } }], - }] - const read = await executePowerPointRequest(initial, { method: 'get_ppt_page', params: { page_id: slide.id } }) - const page = (read.result as { page: { markdown: string; revision: string } }).page - const runs = JSON.stringify([{ start: 3, end: 10, style: { fontSize: 40, fontWeight: 400, color: '#0088CC', opacity: 0.25 } }]).replaceAll('"', '"') - const paragraphs = JSON.stringify([{ start: 0, end: 10, style: { listStyle: 'number', listStartAt: 9, listNumberFormat: 'romanUcPeriod' } }]).replaceAll('"', '"') - const replacement = page.markdown.match(//)![0] - .replace('fontSize="40"', 'fontSize="80"').replace(/textRuns="[^"]*"/, `textRuns="${runs}" paragraphs="${paragraphs}"`) - const result = await executePowerPointRequest(initial, { method: 'edit_ppt_page', params: { - page_id: slide.id, ref: 'rich', expected_revision: page.revision, replacement, - } }) - const text = result.workspace?.documents[0]?.slides.pages[0]?.elements[0] - if (text?.type !== 'text') throw new Error(JSON.stringify(result.result)) - expect(presentationTextStyleAt(text, 3)).toMatchObject({ fontSize: 40, fontWeight: 400, color: '#0088CC' }) - expect(text.paragraphs?.[0]?.style.listStartAt).toBe(9) - expect(text.paragraphs?.[0]?.style.listNumberFormat).toBe('romanUcPeriod') - expect(presentationTextStyleAt(text, 3).opacity).toBe(0.25) - const updated = await executePowerPointRequest(result.workspace!, { method: 'get_ppt_page', params: { page_id: slide.id } }) - expect((updated.result as { page: { markdown: string } }).page.markdown).toContain('listStartAt":9') + it('reports the requested document file name independently of the active tab', async () => { + const first = createBlankPresentationProject('First') + const second = createBlankPresentationProject('Second') + const initial = { activeProjectId: second.id, projects: [first, second] } + const result = await executePowerPointRequest(initial, { + method: 'read_deck', params: { document_id: first.id }, + }, { currentTarget: '/workspace/second.pptx', fileNameOf: (projectId) => projectId === first.id ? 'first.pptx' : 'second.pptx' }) + expect(result.result).toMatchObject({ deck: { id: first.id, file_name: 'first.pptx' } }) + expect(result.projects?.activeProjectId).toBe(first.id) }) - it('keeps middle run and paragraph formatting when the Agent changes several separated words', async () => { + + it('offers compact Markdown and an exact structured model without using Markdown for edits', async () => { const initial = workspace() - const slide = initial.documents[0]!.slides.pages[0]! + const slide = initial.projects[0]!.slides.pages[0]! slide.elements = [{ - id: 'rich', type: 'text', text: '标题 English 结尾\n正文', x: 20, y: 20, width: 500, height: 200, rotation: 0, - fontSize: 40, fontFamily: 'Arial', fontWeight: 700, color: '#111111', align: 'left', lineSpacing: 48, - textRuns: [{ start: 3, end: 10, style: { fontSize: 20, fontWeight: 400, color: '#0088CC' } }], - paragraphs: [{ start: 0, end: 13, style: { align: 'center', lineSpacing: 48 } }, - { start: 14, end: 16, style: { align: 'right', lineSpacing: 28, spaceBefore: 12 } }], + id: 'title', type: 'text', text: 'Before', x: 37, y: 91, width: 620, height: 110, rotation: 4, + fontSize: 44, fontFamily: 'Arial', fontWeight: 700, color: '#112233', align: 'center', }] - const read = await executePowerPointRequest(initial, { method: 'get_ppt_page', params: { page_id: slide.id } }) - const page = (read.result as { page: { markdown: string; revision: string } }).page - expect(page.markdown).toContain('paragraphs=') - for (const omitAttributes of [false, true]) { - let replacement = page.markdown.match(//)![0].replace('标题', '新标题').replace('结尾', '新结尾').replace('正文', '新正文') - if (omitAttributes) replacement = replacement.replace(/ (textRuns|paragraphs)="[^"]*"/g, '') - const edited = await executePowerPointRequest(initial, { method: 'edit_ppt_page', params: { - page_id: slide.id, ref: 'rich', expected_revision: page.revision, replacement, - } }) - const text = edited.workspace?.documents[0]?.slides.pages[0]?.elements[0] - if (text?.type !== 'text') throw new Error(JSON.stringify(edited.result)) - expect(presentationTextStyleAt(text, 4)).toMatchObject({ fontSize: 20, fontWeight: 400, color: '#0088CC' }) - expect(text.paragraphs).toEqual([ - { start: 0, end: 15, style: expect.objectContaining({ align: 'center', lineSpacing: 48 }) }, - { start: 16, end: 19, style: expect.objectContaining({ align: 'right', lineSpacing: 28, spaceBefore: 12 }) }, - ]) - } + slide.comments = [{ id: 'review', author: 'Reviewer', createdAt: new Date(0).toISOString(), resolved: false, text: 'Tighten this', elementId: 'title' }] + const compact = await readPage(initial, slide.id) + expect((compact.result as { page: { markdown: string } }).page.markdown).toContain('') + const model = await readPage(initial, slide.id, 'model') + expect(model.result).toMatchObject({ page: { model: { + comments: [{ id: 'review', text: 'Tighten this', elementId: 'title' }], + elements: [{ id: 'title', x: 37, fontSize: 44 }], + } } }) }) - it('retains authored blank-line size when the Agent edits the surrounding text', async () => { + it('patches native elements while preserving every omitted property', async () => { const initial = workspace() - const slide = initial.documents[0]!.slides.pages[0]! - slide.elements = [{ id: 'blank-lines', type: 'text', text: 'Before\n\nAfter', x: 0, y: 0, width: 600, height: 400, rotation: 0, - fontSize: 32, fontFamily: 'Arial', fontWeight: 400, color: '#111111', align: 'left', - paragraphs: [{ start: 0, end: 6, style: {} }, { start: 7, end: 7, style: {}, endStyle: { fontSize: 128 } }, { start: 8, end: 13, style: {} }], + const document = initial.projects[0]! + const slide = document.slides.pages[0]! + slide.elements = [{ + id: 'title', type: 'text', text: 'Before', x: 37, y: 91, width: 620, height: 110, rotation: 4, + fontSize: 44, fontFamily: 'Arial', fontWeight: 700, color: '#112233', align: 'center', + textInsets: { left: 5, top: 6, right: 7, bottom: 8 }, }] - const read = await executePowerPointRequest(initial, { method: 'get_ppt_page', params: { page_id: slide.id } }) - const page = (read.result as { page: { markdown: string; revision: string } }).page - for (const omitAttributes of [false, true]) { - let replacement = page.markdown.match(//)![0].replace('Before', 'New Before').replace('After', 'New After') - if (omitAttributes) replacement = replacement.replace(/ paragraphs="[^"]*"/g, '') - const edited = await executePowerPointRequest(initial, { method: 'edit_ppt_page', params: { page_id: slide.id, ref: 'blank-lines', expected_revision: page.revision, replacement } }) - expect(edited.workspace?.documents[0]?.slides.pages[0]?.elements[0]).toMatchObject({ text: 'New Before\n\nNew After', - paragraphs: [{ start: 0, end: 10 }, { start: 11, end: 11, endStyle: { fontSize: 128 } }, { start: 12, end: 21 }], - }) - } - }) - - it('rejects malformed paragraph partitions and styles without mutating the document', async () => { - const initial = workspace() - const slide = initial.documents[0]!.slides.pages[0]! - const read = await executePowerPointRequest(initial, { method: 'get_ppt_page', params: { page_id: slide.id } }) - for (const paragraphs of [[], [{ start: 1, end: 4, style: {} }], [{ start: 0, end: 99, style: {} }], - [{ start: 0, end: 4, style: { lineSpacing: -1 } }], [{ start: 0, end: 4, style: { align: 'invalid' } }], - [{ start: 0, end: 1, style: {} }, { start: 2, end: 4, style: {} }], - ...[null, { fontSize: -1 }, { opacity: 2 }, { fontFamily: 12 }].map(endStyle => [{ start: 0, end: 4, style: {}, endStyle }]), - ...[0, -1, 1.5, 32768, '5'].map(listStartAt => [{ start: 0, end: 4, style: { listStartAt } }])]) { - const serialized = JSON.stringify(paragraphs).replaceAll('"', '"') - const result = await executePowerPointRequest(initial, { method: 'insert_ppt_element', params: { - page_id: slide.id, expected_revision: (read.result as { page: { revision: string } }).page.revision, - element: `Text`, - } }) - expect(result.result).toMatchObject({ status: 'invalid' }) - expect(result.workspace).toBeUndefined() - } - expect(slide.elements).toEqual([]) + const read = await readPage(initial, slide.id) + const revision = (read.result as { revision: string }).revision + const updated = await executePowerPointRequest(initial, { method: 'edit_page', params: { + document_id: document.id, page_id: slide.id, expected_revision: revision, + operations: [{ type: 'patch', id: 'title', element_type: 'text', patch: { text: 'After', x: 55 } }], + } }) + expect(updated.projects!.projects[0]!.slides.pages[0]!.elements[0]).toMatchObject({ + id: 'title', text: 'After', x: 55, y: 91, width: 620, fontSize: 44, + textInsets: { left: 5, top: 6, right: 7, bottom: 8 }, + }) }) - it('preserves rich text through agent moves, source edits and explicit frame formatting', async () => { + it('keeps an explicit fill opacity when an Agent replaces a gradient fill', async () => { const initial = workspace() - const slide = initial.documents[0]!.slides.pages[0]! + const document = initial.projects[0]! + const slide = document.slides.pages[0]! slide.elements = [{ - id: 'rich-text', type: 'text', text: '标题 English', x: 20, y: 100, width: 400, height: 100, rotation: 0, - fontSize: 40, fontFamily: 'Arial', fontWeight: 700, color: '#111111', align: 'left', lineSpacing: 48, - textRuns: [{ start: 3, end: 10, style: { fontSize: 20, fontWeight: 400, color: '#0088CC' } }], + id: 'accent', type: 'rect', x: 10, y: 10, width: 100, height: 60, rotation: 0, + fill: '#FF0000', borderColor: 'transparent', borderWidth: 0, + gradientFill: { type: 'linear', angle: 0, stops: [ + { offset: 0, color: '#FF0000', opacity: 1 }, + { offset: 1, color: '#0000FF', opacity: 1 }, + ] }, }] - const readPage = async (state: PresentationWorkspace) => { - const read = await executePowerPointRequest(state, { method: 'get_ppt_page', params: { page_id: slide.id } }) - return (read.result as { page: { markdown: string; revision: string } }).page - } - const change = async (state: PresentationWorkspace, transform: (markdown: string) => string) => { - const page = await readPage(state) - const element = page.markdown.match(//)![0] - const result = await executePowerPointRequest(state, { method: 'edit_ppt_page', params: { - page_id: slide.id, ref: 'rich-text', expected_revision: page.revision, replacement: transform(element), - } }) - expect(result.workspace).toBeDefined() - return result.workspace! - } - expect((await readPage(initial)).markdown).toContain('textRuns=') - const moved = await change(initial, markdown => markdown.replace('x="20"', 'x="35"')) - const movedText = moved.documents[0]!.slides.pages[0]!.elements[0]! - expect(movedText).toMatchObject({ x: 35, lineSpacing: 48 }) - if (movedText.type !== 'text') throw new Error('Expected text') - expect(presentationTextStyleAt(movedText, 3)).toMatchObject({ fontSize: 20, color: '#0088CC', fontWeight: 400 }) - const edited = await change(moved, markdown => markdown.replace('标题 English', '新标题 English')) - const editedText = edited.documents[0]!.slides.pages[0]!.elements[0]! - if (editedText.type !== 'text') throw new Error('Expected text') - expect(presentationTextStyleAt(editedText, 4)).toMatchObject({ fontSize: 20, color: '#0088CC', fontWeight: 400 }) - const colored = await change(edited, markdown => markdown.replace('color="#111111"', 'color="#FF0000"')) - const coloredText = colored.documents[0]!.slides.pages[0]!.elements[0]! - if (coloredText.type !== 'text') throw new Error('Expected text') - expect(presentationTextStyleAt(coloredText, 4)).toMatchObject({ fontSize: 20, color: '#FF0000' }) - expect(slide.elements[0]).toMatchObject({ text: '标题 English', x: 20 }) - }) - - it('rejects invalid inline style ranges without changing the document', async () => { - const initial = workspace() - const slide = initial.documents[0]!.slides.pages[0]! - const read = await executePowerPointRequest(initial, { method: 'get_ppt_page', params: { page_id: slide.id } }) - for (const textRuns of [ - [{ start: 0, end: 99, style: { fontSize: 20 } }], - [{ start: 0, end: 1, style: { fontSize: -1 } }], - [{ start: 0, end: 1, style: { unexpected: true } }], - ]) { - const serialized = JSON.stringify(textRuns).replaceAll('"', '"') - const result = await executePowerPointRequest(initial, { method: 'insert_ppt_element', params: { - page_id: slide.id, expected_revision: (read.result as { page: { revision: string } }).page.revision, - element: `Text`, - } }) - expect(result.result).toMatchObject({ status: 'invalid' }) - expect(result.workspace).toBeUndefined() - } - expect(slide.elements).toEqual([]) - }) - - it('opens a new target with metadata and one blank page summary', async () => { - const opened = await executePowerPointRequest(workspace(), { - method: 'view_ppt', - params: { target: '/workspace/roadmap.pptx', file_name: 'roadmap.pptx' }, - }) - - expect(opened.target).toBe('/workspace/roadmap.pptx') - expect(opened.persist).toBeTrue() - expect(opened.result).toMatchObject({ - identity: { document_id: expect.any(String), file_name: 'roadmap.pptx' }, - meta: { total_pages: 1, current_position: 1 }, - pages: [{ index: 0, has_content: false }], - reused: false, - }) - - const reopened = await executePowerPointRequest(opened.workspace!, { - method: 'view_ppt', - params: { target: '/workspace/roadmap.pptx', file_name: 'roadmap.pptx' }, - }, { currentTarget: opened.target!, fileName: 'roadmap.pptx' }) - expect(reopened.workspace).toBeUndefined() - expect(reopened.result).toMatchObject({ reused: true }) + const read = await readPage(initial, slide.id) + const updated = await executePowerPointRequest(initial, { method: 'edit_page', params: { + document_id: document.id, page_id: slide.id, + expected_revision: (read.result as { revision: string }).revision, + operations: [{ type: 'patch', id: 'accent', element_type: 'rect', patch: { fill: '#00FF00', fillOpacity: 0.35 } }], + } }) + expect(updated.projects!.projects[0]!.slides.pages[0]!.elements[0]).toMatchObject({ fill: '#00FF00', fillOpacity: 0.35 }) + expect(updated.projects!.projects[0]!.slides.pages[0]!.elements[0]).not.toHaveProperty('gradientFill') }) - it('reads refs and atomically inserts one native element', async () => { + it('replaces an imported pattern when an Agent applies a solid shape fill', async () => { const initial = workspace() - const slideId = initial.documents[0]!.slides.selectedPageId - const read = await executePowerPointRequest(initial, { - method: 'get_ppt_page', - params: { page_id: slideId }, - }) - const revision = (read.result as { page: { revision: string } }).page.revision - expect((read.result as { page: { refs: string[] } }).page.refs).toEqual([]) - const applied = await executePowerPointRequest(initial, { - method: 'insert_ppt_element', - params: { - page_id: slideId, - expected_revision: revision, - element: 'Revenue grew 24%', - assets: {}, + const document = initial.projects[0]! + const slide = document.slides.pages[0]! + slide.elements = [{ + id: 'card', type: 'rect', x: 10, y: 10, width: 100, height: 60, rotation: 0, + fill: '#FFFFFF', borderColor: 'transparent', borderWidth: 0, + patternFill: { + preset: 'wdUpDiag', foregroundColor: '#F8FCFE', foregroundOpacity: 1, + backgroundColor: '#FFFFFF', backgroundOpacity: 1, }, - }) - - const document = applied.workspace!.documents[0]! - expect(document.slides.pages[0]!.elements[0]).toMatchObject({ - type: 'text', - text: 'Revenue grew 24%', - }) - expect(document.revision).toBe(initial.documents[0]!.revision + 1) - expect(document.slides.selectedPageId).toBe(slideId) - expect(applied.agentChange).toEqual({ - elementIds: [expect.any(String)], - kind: 'content', - slideId, - }) - const result = applied.result as { element_ref: string; page: { markdown: string; refs: string[] } } - expect(result.page.refs).toEqual([result.element_ref]) - expect(result.page.markdown).toContain(`ref="${result.element_ref}"`) - expect(initial.documents[0]!.slides.pages[0]!.elements).toEqual([]) + }] + const read = await readPage(initial, slide.id) + const updated = await executePowerPointRequest(initial, { method: 'edit_page', params: { + document_id: document.id, page_id: slide.id, + expected_revision: (read.result as { revision: string }).revision, + operations: [{ type: 'patch', id: 'card', element_type: 'rect', patch: { fill: '#00FF00' } }], + } }) + expect(updated.projects!.projects[0]!.slides.pages[0]!.elements[0]).toMatchObject({ fill: '#00FF00' }) + expect(updated.projects!.projects[0]!.slides.pages[0]!.elements[0]).not.toHaveProperty('patternFill') }) - it('edits one referenced element without replacing its identity or siblings', async () => { + it('adds, patches, and removes comments atomically', async () => { const initial = workspace() - const slideId = initial.documents[0]!.slides.selectedPageId - initial.documents[0]!.slides.pages[0]!.elements = [ - { - id: 'stable', type: 'text', text: 'Same', x: 20, y: 20, width: 200, height: 60, - rotation: 0, fontSize: 24, fontFamily: 'Aptos', fontWeight: 400, color: '#111111', align: 'left', - }, - { - id: 'changed', type: 'text', text: 'Before', x: 20, y: 100, width: 200, height: 60, - rotation: 0, fontSize: 24, fontFamily: 'Aptos', fontWeight: 400, color: '#111111', align: 'left', - }, - ] - const read = await executePowerPointRequest(initial, { - method: 'get_ppt_page', params: { page_id: slideId }, - }) - const revision = (read.result as { page: { revision: string } }).page.revision - const applied = await executePowerPointRequest(initial, { - method: 'edit_ppt_page', - params: { - page_id: slideId, - expected_revision: revision, - ref: 'changed', - replacement: 'After', - assets: {}, - }, - }) - - expect(applied.agentChange?.elementIds).toEqual(['changed']) - expect(applied.workspace!.documents[0]!.slides.pages[0]!.elements).toEqual([ - initial.documents[0]!.slides.pages[0]!.elements[0], - expect.objectContaining({ id: 'changed', text: 'After' }), + const document = initial.projects[0]! + const slide = document.slides.pages[0]! + slide.elements = [{ + id: 'title', type: 'text', text: 'Title', x: 37, y: 91, width: 620, height: 110, rotation: 0, + fontSize: 44, fontFamily: 'Arial', fontWeight: 700, color: '#112233', align: 'center', + }] + slide.comments = [{ id: 'obsolete', author: 'Reviewer', createdAt: new Date(0).toISOString(), resolved: false, text: 'Remove me' }] + const read = await readPage(initial, slide.id) + const updated = await executePowerPointRequest(initial, { method: 'edit_page', params: { + document_id: document.id, + page_id: slide.id, + expected_revision: (read.result as { revision: string }).revision, + operations: [ + { type: 'add-comment', comment: { id: 'review', text: 'Tighten this', elementId: 'title' } }, + { type: 'patch-comment', id: 'review', patch: { text: 'Looks good', resolved: true, elementId: null } }, + { type: 'remove-comment', id: 'obsolete' }, + ], + } }) + expect(updated.projects!.projects[0]!.slides.pages[0]!.comments).toEqual([ + expect.objectContaining({ id: 'review', author: 'Agent', resolved: true, text: 'Looks good' }), ]) + expect(updated.projects!.projects[0]!.slides.pages[0]!.comments![0]).not.toHaveProperty('elementId') }) - it('removes one referenced element and rejects an invented ref', async () => { + it('rejects an element patch whose declared type does not match the live element', async () => { const initial = workspace() - const slide = initial.documents[0]!.slides.pages[0]! + const document = initial.projects[0]! + const slide = document.slides.pages[0]! slide.elements = [{ - id: 'obsolete', type: 'text', text: 'Remove me', x: 20, y: 20, width: 200, height: 60, - rotation: 0, fontSize: 24, fontFamily: 'Aptos', fontWeight: 400, color: '#111111', align: 'left', - }] - slide.comments = [{ - id: 'comment', author: 'Reviewer', createdAt: new Date(0).toISOString(), resolved: false, - text: 'Keep this review note', elementId: 'obsolete', + id: 'title', type: 'text', text: 'Title', x: 37, y: 91, width: 620, height: 110, rotation: 0, + fontSize: 44, fontFamily: 'Arial', fontWeight: 700, color: '#112233', align: 'center', }] - const read = await executePowerPointRequest(initial, { - method: 'get_ppt_page', params: { page_id: slide.id }, - }) - const revision = (read.result as { page: { revision: string } }).page.revision - const removed = await executePowerPointRequest(initial, { - method: 'remove_ppt_element', - params: { page_id: slide.id, ref: 'obsolete', expected_revision: revision }, - }) - - expect(removed.workspace!.documents[0]!.slides.pages[0]!.elements).toEqual([]) - expect(removed.workspace!.documents[0]!.slides.pages[0]!.comments?.[0]).not.toHaveProperty('elementId') - expect((removed.result as { element_ref: string }).element_ref).toBe('obsolete') - await expect(executePowerPointRequest(initial, { - method: 'remove_ppt_element', - params: { page_id: slide.id, ref: 'invented', expected_revision: revision }, - })).rejects.toThrow('Unknown PowerPoint element ref') + const read = await readPage(initial, slide.id) + await expect(executePowerPointRequest(initial, { method: 'edit_page', params: { + document_id: document.id, + page_id: slide.id, + expected_revision: (read.result as { revision: string }).revision, + operations: [{ type: 'patch', id: 'title', element_type: 'image', patch: { altText: 'Nope' } }], + } })).rejects.toThrow('title is text, not image') + await expect(executePowerPointRequest(initial, { method: 'edit_page', params: { + document_id: document.id, + page_id: slide.id, + expected_revision: (read.result as { revision: string }).revision, + operations: [{ type: 'patch', id: 'title', element_type: 'text', patch: { fill: '#FF0000' } }], + } })).rejects.toThrow('Unsupported patch.patch property: fill') }) - it('clears links to a page when the Agent removes that page', async () => { + it('applies deck design, insertion, movement, and deletion as one transaction', async () => { const initial = workspace() - const document = initial.documents[0]! - const first = document.slides.pages[0]! - const second = createBlankPresentationSlide('Second') - first.elements = [{ - id: 'link', type: 'rect', x: 0, y: 0, width: 10, height: 10, rotation: 0, - fill: '#FFFFFF', borderColor: '#000000', borderWidth: 0, - hyperlink: { type: 'slide', slideId: second.id }, - }] - document.slides = { - pages: [first, second], - slideOrder: [first.id, second.id], - selectedPageId: first.id, - } - const overview = await executePowerPointRequest(initial, { - method: 'view_ppt', params: { target: '/workspace/review.pptx', file_name: 'review.pptx' }, - }, { currentTarget: '/workspace/review.pptx', fileName: 'review.pptx' }) - const page = await executePowerPointRequest(initial, { method: 'get_ppt_page', params: { page_id: second.id } }) - const removed = await executePowerPointRequest(initial, { - method: 'remove_ppt_page', - params: { - page_id: second.id, - expected_revision: (page.result as { page: { revision: string } }).page.revision, - expected_deck_revision: (overview.result as { deck_revision: string }).deck_revision, - }, - }) - - expect(removed.workspace!.documents[0]!.slides.pages).toHaveLength(1) - expect(removed.workspace!.documents[0]!.slides.pages[0]!.elements[0]).not.toHaveProperty('hyperlink') + const document = initial.projects[0]! + const cover = document.slides.pages[0]! + cover.id = 'cover' + const obsolete = createBlankPresentationSlide('Obsolete') + obsolete.id = 'obsolete' + document.slides = { pages: [cover, obsolete], slideOrder: ['cover', 'obsolete'], selectedPageId: 'cover' } + const read = await readDeck(initial) + const revision = (read.result as { revision: string }).revision + const result = await executePowerPointRequest(initial, { method: 'manage_deck', params: { + document_id: document.id, + expected_revision: revision, + operations: [ + { type: 'set-design', patch: { title: 'Updated deck', theme: 'midnight' } }, + { type: 'insert-page', page: { id: 'evidence', name: 'Evidence' }, after: 'cover' }, + { type: 'remove-page', pageId: 'obsolete' }, + ], + } }) + const next = result.projects!.projects[0]! + expect(next.title).toBe('Updated deck') + expect(next.theme.background).toBe('#17182B') + expect(next.slides.pages.map((page) => page.id)).toEqual(['cover', 'evidence']) + expect(result.result).toMatchObject({ status: 'ready', changed_page_ids: expect.arrayContaining(['cover', 'obsolete', 'evidence']) }) }) - it('updates document-wide design with a private document revision', async () => { + it('merges a partial deck transition with the selected page transition', async () => { const initial = workspace() - const overview = await executePowerPointRequest(initial, { - method: 'view_ppt', - params: { target: '/workspace/review.pptx', file_name: 'review.pptx' }, - }, { currentTarget: '/workspace/review.pptx', fileName: 'review.pptx' }) - const revision = (overview.result as { document_revision: string }).document_revision - const applied = await executePowerPointRequest(initial, { - method: 'update_ppt_design', - params: { - expected_document_revision: revision, - design: { - theme: 'midnight', - page_size: 'standard', - footer: { show_slide_number: true }, - transition: { effect: 'fade', duration_ms: 650, through_black: true }, - }, - }, - }) - - const document = applied.workspace!.documents[0]! - expect(document.theme).toMatchObject({ - background: '#17182B', - bodyFontFamily: 'Aptos', - footer: { showSlideNumber: true }, - titleFontFamily: 'Aptos Display', - }) - expect(document.pageSize.preset).toBe('standard') - expect(document.slides.pages[0]).toMatchObject({ - transition: { effect: 'fade', durationMs: 650, throughBlack: true }, + const document = initial.projects[0]! + const slide = document.slides.pages[0]! + slide.transition = { effect: 'reveal', durationMs: 750, direction: 'left', throughBlack: true } + const read = await readDeck(initial) + const result = await executePowerPointRequest(initial, { method: 'manage_deck', params: { + document_id: document.id, + expected_revision: (read.result as { revision: string }).revision, + operations: [{ type: 'set-design', patch: { transition: { durationMs: 1250 } } }], + } }) + expect(result.projects!.projects[0]!.slides.pages[0]!.transition).toEqual({ + effect: 'reveal', durationMs: 1250, direction: 'left', throughBlack: true, }) - expect(document.slides.pages[0]).not.toHaveProperty('background') - expect(document.slides.pages[0]).not.toHaveProperty('footer') - expect(presentationSlideBackground(document.theme, document.slides.pages[0]!)).toBe('#17182B') - expect(presentationSlideFooter(document.theme, document.slides.pages[0]!).showSlideNumber).toBe(true) - expect(applied.agentChange).toMatchObject({ kind: 'design', slideId: document.slides.selectedPageId }) - expect(applied.persist).toBeTrue() }) - it('rejects a stale document-wide design change', async () => { + it('does not publish a partial workspace when any operation is invalid', async () => { const initial = workspace() - await expect(executePowerPointRequest(initial, { - method: 'update_ppt_design', - params: { expected_document_revision: 'stale', design: { theme: 'paper' } }, - })).rejects.toEqual(expect.objectContaining({ code: 'document_changed' })) + const original = structuredClone(initial) + const document = initial.projects[0]! + const slide = document.slides.pages[0]! + const read = await readPage(initial, slide.id) + await expect(executePowerPointRequest(initial, { method: 'edit_page', params: { + document_id: document.id, + page_id: slide.id, + expected_revision: (read.result as { revision: string }).revision, + operations: [ + { type: 'add', element: { id: 'valid', type: 'text', text: 'Valid' } }, + { type: 'add', element: { id: 'broken', type: 'not-a-shape' } }, + ], + } })).rejects.toThrow('Unsupported PowerPoint element type') + expect(initial).toEqual(original) }) - it('rejects a stale page token without publishing a workspace', async () => { + it('rejects stale page and deck revisions before applying commands', async () => { const initial = workspace() - const slideId = initial.documents[0]!.slides.selectedPageId - await expect(executePowerPointRequest(initial, { - method: 'insert_ppt_element', - params: { - page_id: slideId, - expected_revision: 'stale', - element: 'Changed', - }, - })).rejects.toEqual(expect.objectContaining({ code: 'page_changed' })) - expect(initial.documents[0]!.slides.pages[0]!.elements).toEqual([]) + const document = initial.projects[0]! + const slide = document.slides.pages[0]! + await expect(executePowerPointRequest(initial, { method: 'edit_page', params: { + document_id: document.id, page_id: slide.id, expected_revision: 'stale', + operations: [{ type: 'set-page', patch: { name: 'Nope' } }], + } })).rejects.toEqual(expect.objectContaining({ code: 'page_changed' })) + await expect(executePowerPointRequest(initial, { method: 'manage_deck', params: { + document_id: document.id, expected_revision: 'stale', + operations: [{ type: 'set-design', patch: { title: 'Nope' } }], + } })).rejects.toEqual(expect.objectContaining({ code: 'document_changed' })) }) - it('returns compiler diagnostics without mutating the page', async () => { + it('supports validation without publishing or incrementing a revision', async () => { const initial = workspace() - const slideId = initial.documents[0]!.slides.selectedPageId - const read = await executePowerPointRequest(initial, { - method: 'get_ppt_page', params: { page_id: slideId }, - }) - const revision = (read.result as { page: { revision: string } }).page.revision - const invalid = await executePowerPointRequest(initial, { - method: 'insert_ppt_element', - params: { - page_id: slideId, - expected_revision: revision, - element: '# Not a Ppt element', - }, - }) - expect(invalid.workspace).toBeUndefined() - expect(invalid.result).toMatchObject({ status: 'invalid' }) - expect(initial.documents[0]!.slides.pages[0]!.elements).toEqual([]) + const document = initial.projects[0]! + const slide = document.slides.pages[0]! + const read = await readPage(initial, slide.id) + const revision = (read.result as { revision: string }).revision + const result = await executePowerPointRequest(initial, { method: 'edit_page', params: { + document_id: document.id, page_id: slide.id, expected_revision: revision, + operations: [{ type: 'set-page', patch: { name: 'Validated' } }], validate_only: true, + } }) + expect(result.projects).toBeUndefined() + expect(result.result).toMatchObject({ status: 'validated' }) + expect(document.slides.pages[0]!.name).not.toBe('Validated') }) - it('returns a workspace path for embedded assets without exposing it in Markdown', async () => { + it('clears optional properties and detaches comments through explicit commands', async () => { const initial = workspace() - const document = initial.documents[0]! + const document = initial.projects[0]! const slide = document.slides.pages[0]! + slide.background = '#123456' + slide.elements = [{ id: 'remove', type: 'text', text: 'Remove', x: 20, y: 20, width: 200, height: 60, + rotation: 0, fontSize: 24, fontFamily: 'Aptos', fontWeight: 400, color: '#111111', align: 'left' }] + slide.comments = [{ id: 'comment', author: 'Reviewer', createdAt: new Date(0).toISOString(), resolved: false, text: 'Keep', elementId: 'remove' }] + const read = await readPage(initial, slide.id) + const result = await executePowerPointRequest(initial, { method: 'edit_page', params: { + document_id: document.id, page_id: slide.id, expected_revision: (read.result as { revision: string }).revision, + operations: [{ type: 'set-page', patch: { background: null } }, { type: 'remove', id: 'remove' }], + } }) + const next = result.projects!.projects[0]!.slides.pages[0]! + expect(next.background).toBeUndefined() + expect(next.elements).toEqual([]) + expect(next.comments?.[0]).not.toHaveProperty('elementId') + }) + + it('selects an exact live page for rendering and returns embedded assets safely', async () => { + const initial = workspace() + const document = initial.projects[0]! + const first = document.slides.pages[0]! + const second = createBlankPresentationSlide('Second') + document.slides = { pages: [first, second], slideOrder: [first.id, second.id], selectedPageId: first.id } document.assets = [createPresentationAsset('image', { dataUrl: 'data:image/png;base64,cG5n', fileName: 'hero.png', mimeType: 'image/png', }, 'hero-asset')] - const hero = { - id: 'hero', - type: 'image' as const, - sourceAssetId: 'hero-asset', - altText: 'Hero', - fit: 'cover' as const, - x: 20, - y: 20, - width: 320, - height: 180, - rotation: 0, - } - slide.elements = [hero, { ...hero, id: 'hero-copy', x: 360 }] + second.elements = [{ id: 'hero', type: 'image', sourceAssetId: 'hero-asset', altText: 'Hero', fit: 'cover', x: 20, y: 20, width: 320, height: 180, rotation: 0 }] + const rendered = await executePowerPointRequest(initial, { method: 'inspect', params: { document_id: document.id, kind: 'render', page_id: second.id } }) + expect(rendered.result).toMatchObject({ document_revision: 1, page_id: second.id, index: 1, revision: expect.any(String) }) + expect(rendered.projects!.projects[0]!.slides.selectedPageId).toBe(second.id) + const read = await readPage(initial, second.id, 'both') + expect(read.result).toMatchObject({ assets: [{ path: '.ppt-assets/hero-asset-hero.png', data_url: 'data:image/png;base64,cG5n' }] }) + expect(read.result).toMatchObject({ page: { model: { elements: [{ id: 'hero', src: '.ppt-assets/hero-asset-hero.png' }] } } }) + expect(JSON.stringify(read.result)).not.toContain('sourceAssetId') + }) - const read = await executePowerPointRequest(initial, { - method: 'get_ppt_page', params: { page_id: slide.id }, - }) - const result = read.result as { assets: Array>; page: { markdown: string } } - expect(result.assets).toHaveLength(1) - expect(result.assets[0]).toMatchObject({ - path: '.ppt-assets/hero-asset-hero.png', - data_url: 'data:image/png;base64,cG5n', + it('projects source-backed text through the same asset contract as media', async () => { + const initial = workspace() + const document = initial.projects[0]! + const slide = document.slides.pages[0]! + document.assets = [createPresentationAsset('text', { + dataUrl: 'data:text/plain;base64,SGVsbG8=', fileName: 'speaker-notes.txt', mimeType: 'text/plain', + }, 'text-asset')] + slide.elements = [{ + id: 'source-text', type: 'text', sourceAssetId: 'text-asset', text: 'Hello', x: 20, y: 20, + width: 320, height: 80, rotation: 0, fontSize: 24, fontFamily: 'Aptos', fontWeight: 400, + color: '#111111', align: 'left', + }] + + const read = await readPage(initial, slide.id, 'both') + expect(read.result).toMatchObject({ + assets: [{ path: '.ppt-assets/text-asset-speaker-notes.txt', data_url: 'data:text/plain;base64,SGVsbG8=' }], + page: { model: { elements: [{ id: 'source-text', src: '.ppt-assets/text-asset-speaker-notes.txt', text: 'Hello' }] } }, }) - expect(result.page.markdown).toContain('src="@existing/hero"') - expect(result.page.markdown).toContain('src="@existing/hero-copy"') - expect(result.page.markdown).not.toContain('base64') + expect((read.result as { page: { markdown: string } }).page.markdown).toContain('') + expect(JSON.stringify(read.result)).not.toContain('sourceAssetId') }) }) diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/presentationDesign.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/presentationDesign.test.ts index bbefca58..5c8b7414 100644 --- a/desktop/apps/electron/src/renderer/lib/__tests__/presentationDesign.test.ts +++ b/desktop/apps/electron/src/renderer/lib/__tests__/presentationDesign.test.ts @@ -1,16 +1,31 @@ import { describe, expect, it } from 'bun:test' import { - createBlankPresentationDocument, + createBlankPresentationProject, createBlankPresentationSlide, presentationSlideBackground, presentationSlideFooter, replacePresentationPages, } from '@/atoms/presentation' -import { applyPresentationDesign } from '../presentationDesign' +import { applyPresentationDesign, resizePresentationProject } from '../presentationDesign' +import { createPresentationTableElement } from '../presentationInsert' describe('presentation design defaults', () => { + it('scales table cell text runs when changing slide aspect ratio', () => { + const document = createBlankPresentationProject('Rich table resize') + const table = createPresentationTableElement([['Title']]) + table.fontSize = 20 + table.cellStyles = [[{ fontSize: 24, textRuns: [{ start: 0, end: 5, style: { fontSize: 28 } }] }]] + document.slides.pages[0]!.elements = [table] + const resized = resizePresentationProject(document, 'standard') + const result = resized.slides.pages[0]!.elements[0] + if (result?.type !== 'table') throw new Error('Missing resized table') + expect(result.fontSize).toBe(15) + expect(result.cellStyles?.[0]?.[0]?.fontSize).toBe(18) + expect(result.cellStyles?.[0]?.[0]?.textRuns?.[0]?.style.fontSize).toBe(21) + }) + it('updates global theme defaults without copying over page overrides', () => { - const document = createBlankPresentationDocument('Theme defaults') + const document = createBlankPresentationProject('Theme defaults') const inherited = document.slides.pages[0]! const overridden = { ...createBlankPresentationSlide('Override'), diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/presentationEditorDriver.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/presentationEditorDriver.test.ts index d2f037d9..1278ca9d 100644 --- a/desktop/apps/electron/src/renderer/lib/__tests__/presentationEditorDriver.test.ts +++ b/desktop/apps/electron/src/renderer/lib/__tests__/presentationEditorDriver.test.ts @@ -1,10 +1,10 @@ import { describe, expect, it } from 'bun:test' -import { createBlankPresentationDocument, createBlankPresentationSlide, selectPresentationPage } from '@/atoms/presentation' +import { createBlankPresentationProject, createBlankPresentationSlide, selectPresentationPage } from '@/atoms/presentation' import { createOfficeEditorBinding } from '../office/officeEditorBinding' import { bindPresentationNativeEdit, createPresentationEditorDriver, type PresentationEditingObject } from '../presentationEditorDriver' function setup() { - let document = createBlankPresentationDocument('Native edit') + let document = createBlankPresentationProject('Native edit') let editing: PresentationEditingObject | null = null let pending: (() => void) | null = null let disposed = 0 @@ -41,7 +41,7 @@ describe('PowerPoint native editor driver', () => { const active = { isEditing: true, exitEditing: () => { events.push('text') active.isEditing = false - binding.publishChange({ ...read(), title: 'Committed native text', revision: read().revision + 1 }) + binding.publishChange({ ...read(), title: 'Committed native text' }) } } edit(active) defer(() => { events.push('transform') }) diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/presentationFileController.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/presentationFileController.test.ts index 06e74975..2bdbeb7e 100644 --- a/desktop/apps/electron/src/renderer/lib/__tests__/presentationFileController.test.ts +++ b/desktop/apps/electron/src/renderer/lib/__tests__/presentationFileController.test.ts @@ -1,186 +1,51 @@ import { describe, expect, it, mock } from 'bun:test' -import { createBlankPresentationDocument, type PresentationWorkspace } from '@/atoms/presentation' -import { createPresentationEditorDriver } from '../presentationEditorDriver' -import { createOfficeEditorBinding } from '../office/officeEditorBinding' -import { createPresentationFileController } from '../presentationFileController' -import { isPresentationDirty } from '../presentationWorkspaceRuntime' +import { createBlankPresentationProject } from '@/atoms/presentation' +import type { PresentationWorkspace } from '@/presentation/workspace' import type { OfficeFilesAPI } from '../../../shared/office-files' +import { createPresentationFileController } from '../presentationFileController' -function setup(automatic = false, onSaveStatus?: (status: 'saving' | 'saved' | 'error', error?: string) => void) { - const document = { ...createBlankPresentationDocument('Report'), source: { path: '/Report.pptx', mtimeMs: 42 }, savedRevision: 1 } - let workspace: PresentationWorkspace = { activeDocumentId: document.id, documents: [document] } - let recovery: string | null = null +function setup() { + const project = createBlankPresentationProject('Deck') + let workspace: PresentationWorkspace = { + schemaVersion: 1, + activeProjectId: project.id, + projects: [project], + projectMetadata: { [project.id]: { revision: 2 } }, + } + const save = mock(async () => ({ ok: true as const, fileName: 'Deck.pptx', source: { path: '/Deck.pptx', mtimeMs: 2 } })) const files: OfficeFilesAPI = { - inspect: async (_kind, path) => ({ path, mtimeMs: 42 }), - save: mock(async () => ({ ok: true as const, fileName: 'Report.pptx', source: { path: '/Report.pptx', mtimeMs: 43 } })), - confirmClose: mock(async () => 'cancel' as const), - getRecovery: async () => recovery, - setRecovery: async (_kind, _session, value) => { recovery = value }, + confirmClose: async () => 'cancel', getRecovery: async () => null, + inspect: async (_kind, path) => ({ path, mtimeMs: null }), save, setRecovery: async () => undefined, } - const controller = createPresentationFileController({ automatic, onSaveStatus, sessionId: 'session-a', files, read: () => workspace, write: (value) => { workspace = value; controller.schedule() }, encode: async () => new Uint8Array([1]), flushEditor: async () => undefined, locale: () => 'en' }) - return { controller, files, read: () => workspace, edit: () => { workspace = { ...workspace, documents: [{ ...workspace.documents[0]!, revision: workspace.documents[0]!.revision + 1 }] } } } -} - -describe('PowerPoint explicit saving', () => { - it('uses Save as when Save is chosen while closing a protected imported file', async () => { - const { controller, files, read, edit } = setup() - await controller.restore() - read().documents[0]!.sourceProtected = true - edit() - files.confirmClose = async () => 'save' - expect(await controller.beforeClose(read().activeDocumentId)).toBe(true) - expect(files.save).toHaveBeenCalledWith(expect.objectContaining({ saveAs: true, preserveSource: true })) - controller.recovery.dispose() - }) - - it('requires a distinct Save as for a converted source and clears protection only after saving', async () => { - const { controller, files, read, edit } = setup() - await controller.restore() - read().documents[0]!.sourceProtected = true - edit() - await expect(controller.save(read().activeDocumentId)).rejects.toThrow() - expect(files.save).not.toHaveBeenCalled() - files.save = mock(async () => ({ ok: false as const, reason: 'source-protected' as const })) - await expect(controller.save(read().activeDocumentId, true)).rejects.toThrow() - expect(read().documents[0]!.sourceProtected).toBe(true) - files.save = mock(async () => ({ ok: true as const, source: { path: '/Copy.pptx', mtimeMs: 43 }, fileName: 'Copy.pptx' })) - expect(await controller.save(read().activeDocumentId, true)).toBe(true) - expect(files.save).toHaveBeenCalledWith(expect.objectContaining({ preserveSource: true })) - expect(read().documents[0]!.sourceProtected).toBe(false) - controller.recovery.dispose() + const controller = createPresentationFileController({ + files, read: () => workspace, encode: async () => new Uint8Array([1, 2, 3]), flushEditor: async () => undefined, managed: false, + commitExport: (projectId, _fileName, source, exportedRevision) => { + workspace = { ...workspace, projectMetadata: { ...workspace.projectMetadata, + [projectId]: { revision: 2, savedRevision: exportedRevision, source, sourceProtected: false } } } + }, }) + return { controller, project, save, workspace: () => workspace } +} - it('checkpoints edits without writing the source, then saves only on an explicit request', async () => { - const { controller, files, read, edit } = setup() - await controller.restore() - edit() - controller.schedule() - await controller.flush() - expect(files.save).not.toHaveBeenCalled() - expect(isPresentationDirty(read().documents[0]!)).toBe(true) - expect(await controller.save(read().activeDocumentId)).toBe(true) - expect(files.save).toHaveBeenCalledTimes(1) - expect(isPresentationDirty(read().documents[0]!)).toBe(false) - controller.recovery.dispose() - }) - it('does not clear newer edits made during saving', async () => { - const { controller, files, read, edit } = setup() - await controller.restore() - edit() - files.save = async () => { edit(); return { ok: true, source: { path: '/Report.pptx', mtimeMs: 43 }, fileName: 'Report.pptx' } } - expect(await controller.save(read().activeDocumentId)).toBe(false) - expect(isPresentationDirty(read().documents[0]!)).toBe(true) - controller.recovery.dispose() - }) - it('canceled closing keeps the draft and never saves implicitly', async () => { - const { controller, files, read, edit } = setup() - await controller.restore() - edit() - expect(await controller.beforeClose(read().activeDocumentId)).toBe(false) - expect(files.save).not.toHaveBeenCalled() - controller.recovery.dispose() +describe('presentation file controller', () => { + it('exports PPTX only on an explicit save request', async () => { + const { controller, project, save, workspace } = setup() + expect(await controller.save(project.id)).toBe(true) + expect(save).toHaveBeenCalledTimes(1) + expect(workspace().projectMetadata[project.id]).toMatchObject({ savedRevision: 2, source: { path: '/Deck.pptx' } }) }) -}) -it('retries a failed PPT recovery write after the source is saved and clears the failure only on success', async () => { - const status = mock(() => undefined) - const { controller, files, read, edit } = setup(true, status) - let fail = true - let checkpoint: string | null = null - files.setRecovery = mock(async (_kind, _session, value) => { - if (fail) throw new Error('Recovery unavailable') - checkpoint = value + it('does not rewrite a clean project', async () => { + const { controller, project, save, workspace } = setup() + workspace().projectMetadata[project.id] = { revision: 2, savedRevision: 2, source: { path: '/Deck.pptx', mtimeMs: 2 } } + expect(await controller.save(project.id)).toBe(true) + expect(save).not.toHaveBeenCalled() }) - try { - await controller.restore() - edit() - controller.schedule() - await expect(controller.autoSave.flush()).rejects.toThrow('Recovery unavailable') - expect(isPresentationDirty(read().documents[0]!)).toBe(false) - expect(files.save).toHaveBeenCalledTimes(1) - await expect(controller.save(read().activeDocumentId)).rejects.toThrow('Recovery unavailable') - expect(status).toHaveBeenLastCalledWith('error', 'Recovery unavailable') - fail = false - expect(await controller.save(read().activeDocumentId)).toBe(true) - expect(JSON.parse(checkpoint!)).toEqual(read()) - expect(files.save).toHaveBeenCalledTimes(1) - expect(status).toHaveBeenLastCalledWith('saved') - expect(controller.recovery.getSnapshot().status).toBe('saved') - } finally { controller.autoSave.dispose(); controller.recovery.dispose() } -}) - -it('keeps PPT edits made during a clean-file recovery retry pending', async () => { - const status = mock(() => undefined) - const { controller, files, read, edit } = setup(true, status) - try { - await controller.restore() - files.setRecovery = async () => { edit() } - expect(await controller.save(read().activeDocumentId)).toBe(false) - expect(isPresentationDirty(read().documents[0]!)).toBe(true) - expect(files.save).not.toHaveBeenCalled() - expect(status).toHaveBeenLastCalledWith('saving') - } finally { controller.autoSave.dispose(); controller.recovery.dispose() } -}) - - -it('automatically saves PPT edits and retains a failed write for retry without a discard dialog', async () => { - const { controller, files, read, edit } = setup(true) - await controller.restore() - read().documents[0]!.sourceProtected = true - edit() - controller.schedule() - await controller.autoSave.flush() - expect(files.save).toHaveBeenCalledWith(expect.objectContaining({ managed: true, documentId: read().activeDocumentId })) - expect(isPresentationDirty(read().documents[0]!)).toBe(false) - files.save = async () => { throw new Error('disk full') } - edit() - controller.schedule() - await expect(controller.autoSave.flush()).rejects.toThrow('disk full') - await expect(controller.beforeClose(read().activeDocumentId)).rejects.toThrow('disk full') - expect(isPresentationDirty(read().documents[0]!)).toBe(true) - expect(files.confirmClose).not.toHaveBeenCalled() - files.save = async () => ({ ok: true, fileName: 'Report.pptx', source: { path: '/Report.pptx', mtimeMs: 44 } }) - await controller.autoSave.flush() - expect(isPresentationDirty(read().documents[0]!)).toBe(false) - controller.autoSave.dispose() - controller.recovery.dispose() -}) - -it('background PPT saves leave active text and IME input intact, while close commits the final text', async () => { - const document = { ...createBlankPresentationDocument('Report'), source: { path: '/Report.pptx', mtimeMs: 42 }, savedRevision: 0 } - let workspace: PresentationWorkspace = { activeDocumentId: document.id, documents: [document] } - const writes: string[] = [] - let exits = 0 - const editing = { - isEditing: true, inCompositionMode: true, - exitEditing() { - exits++ - editing.isEditing = false - workspace = { ...workspace, documents: workspace.documents.map((item) => ({ ...item, revision: item.revision + 1, title: 'Completed text' })) } - }, - } - const binding = createOfficeEditorBinding({ appKind: 'presentation', sessionId: 's', documentId: document.id }) - binding.attach(createPresentationEditorDriver({ readSnapshot: () => workspace.documents[0]!, readEditingObject: () => editing, flushPendingEdit: () => undefined, dispose: () => undefined })) - const controller = createPresentationFileController({ - sessionId: 's', automatic: true, read: () => workspace, write: (next) => { workspace = next }, - flushEditor: binding.flush, encode: async (item) => new TextEncoder().encode(item.title), locale: () => 'en', - files: { - inspect: async () => document.source, - save: async (request) => { writes.push(new TextDecoder().decode(request.bytes)); return { ok: true, source: document.source, fileName: 'Report.pptx' } }, - getRecovery: async () => null, setRecovery: async () => undefined, confirmClose: async () => 'cancel', - }, + it('protects imported files from implicit overwrite', async () => { + const { controller, project, save, workspace } = setup() + workspace().projectMetadata[project.id] = { revision: 2, savedRevision: 1, source: { path: '/Imported.pptx', mtimeMs: 1 }, sourceProtected: true } + await expect(controller.save(project.id)).rejects.toThrow() + expect(save).not.toHaveBeenCalled() }) - try { - await controller.restore() - await controller.autoSave.flush() - expect(writes).toEqual(['Report']) - expect(editing.isEditing).toBe(true) - expect(exits).toBe(0) - await expect(controller.beforeClose(document.id)).rejects.toThrow('Finish composing') - editing.inCompositionMode = false - expect(await controller.beforeClose(document.id)).toBe(true) - expect(exits).toBe(1) - expect(writes).toEqual(['Report', 'Completed text']) - } finally { controller.autoSave.dispose(); controller.recovery.dispose(); binding.dispose() } }) diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/presentationMarkdown.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/presentationMarkdown.test.ts index ab6bff98..52092c85 100644 --- a/desktop/apps/electron/src/renderer/lib/__tests__/presentationMarkdown.test.ts +++ b/desktop/apps/electron/src/renderer/lib/__tests__/presentationMarkdown.test.ts @@ -1,469 +1,74 @@ import { describe, expect, it } from 'bun:test' -import { createBlankPresentationDocument, presentationSlideBackground } from '@/atoms/presentation' -import { - compilePresentationElementMarkdown, - compilePresentationMarkdown, - compilePresentationSlideMarkdown, - decompilePresentationSlideMarkdown, - inspectPresentationMarkdownAssets, -} from '../presentationMarkdown' +import { createBlankPresentationProject } from '@/atoms/presentation' +import { createPresentationAsset } from '@/presentation/project' +import { decompilePresentationSlideMarkdown } from '../presentationMarkdown' -describe('presentation Markdown compiler', () => { - it('inherits document-wide typography and palette for later semantic pages', () => { - const document = createBlankPresentationDocument('Designed deck') - document.theme = { - ...document.theme, - accentColors: ['#CC5500', '#118844'], - background: '#17182B', - bodyFontFamily: 'Arial', - titleFontFamily: 'Georgia', - } - const compiled = compilePresentationSlideMarkdown(`--- -id: designed ---- - -# A designed title - -Supporting evidence - -`, { document }).slide - - expect(compiled.elements[0]).toMatchObject({ color: '#FFFFFF', fontFamily: 'Georgia' }) - expect(compiled.background).toBeUndefined() - expect(presentationSlideBackground(document.theme, compiled)).toBe('#17182B') - expect(compiled.elements[1]).toMatchObject({ color: '#C7C8D8', fontFamily: 'Arial' }) - expect(compiled.elements[2]).toMatchObject({ fill: '#CC5500', borderColor: '#CC5500' }) - }) - - it('uses a page background override when deriving editable text and table colors', () => { - const document = createBlankPresentationDocument('Mixed-background deck') - document.theme = { ...document.theme, background: '#FFFFFF', accentColors: ['#CC5500'] } - const slide = compilePresentationSlideMarkdown(`--- -id: dark-page -background: '#17182B' ---- - -# Visible title - -| Metric | Value | -| --- | ---: | -| ARR | 42 |`, { document }).slide - - expect(slide.elements[0]).toMatchObject({ type: 'text', color: '#FFFFFF' }) - expect(slide.elements[1]).toMatchObject({ - type: 'table', - headerFill: '#CC5500', - bodyFill: '#17182B', - textColor: '#FFFFFF', - }) - - const fragmentSlide = { ...document.slides.pages[0]!, background: '#17182B' } - const fragment = compilePresentationElementMarkdown('Supporting evidence', { - document, - slide: fragmentSlide, - }).element - expect(fragment).toMatchObject({ type: 'text', color: '#C7C8D8' }) - }) - - it('keeps inherited page styling out of canonical slide Markdown', () => { - const document = createBlankPresentationDocument('Inherited page') - document.theme = { - ...document.theme, - background: '#17182B', - footer: { text: 'Global footer', showDate: false, showSlideNumber: true }, - } +describe('PowerPoint compact Markdown projection', () => { + it('keeps stable refs and authored text while omitting routine native layout', () => { + const document = createBlankPresentationProject('Review') const slide = document.slides.pages[0]! + slide.name = 'Executive summary' + slide.elements = [{ + id: 'title', type: 'text', text: 'Revenue\nup 20%', x: 37, y: 91, width: 620, height: 110, rotation: 4, + fontSize: 44, fontFamily: 'Arial', fontWeight: 700, color: '#112233', align: 'center', + }] const markdown = decompilePresentationSlideMarkdown(slide, document) - const roundTripped = compilePresentationSlideMarkdown(markdown, { document }).slide - - expect(markdown).not.toContain('background:') - expect(markdown).not.toContain('footer:') - expect(roundTripped.background).toBeUndefined() - expect(roundTripped.footer).toBeUndefined() - expect(presentationSlideBackground(document.theme, roundTripped)).toBe('#17182B') - }) - - it('uses a deck theme immediately while compiling its first inherited page', () => { - const compiled = compilePresentationMarkdown(`--- -title: Dark deck -theme: - background: '#17182B' - titleFontFamily: Georgia - bodyFontFamily: Arial ---- - -# Visible title - -Visible body`).document - const slide = compiled.slides.pages[0]! - - expect(slide.background).toBeUndefined() - expect(slide.elements[0]).toMatchObject({ color: '#FFFFFF', fontFamily: 'Georgia' }) - expect(slide.elements[1]).toMatchObject({ color: '#C7C8D8', fontFamily: 'Arial' }) - }) - - it('compiles Slidev framing, YAML, Markdown blocks, slots, tables, and notes', () => { - const markdown = `--- -title: Product review -pageSize: wide -id: cover -name: Cover -layout: title ---- - -# Product review {#title} - -One native presentation model. - ---- -id: metrics -name: Metrics -layout: two-cols ---- - -::left:: - -- ARR grew 42% -- NRR reached 118% - -::right:: - -| Quarter | ARR | -| --- | ---: | -| Q3 | 25 | - -` - const compiled = compilePresentationMarkdown(markdown).document - - expect(compiled.title).toBe('Product review') - expect(compiled.slides.pages.map((slide) => slide.id)).toEqual(['cover', 'metrics']) - expect(compiled.slides.pages[0]!.elements[0]).toMatchObject({ id: 'title', type: 'text', text: 'Product review' }) - expect(compiled.slides.pages[1]!.layout).toBe('twoContent') - expect(compiled.slides.pages[1]!.elements.map((element) => element.type)).toEqual(['text', 'table']) - expect(compiled.slides.pages[1]!.elements[0]!.x).toBeLessThan(compiled.pageSize.width / 2) - expect(compiled.slides.pages[1]!.elements[1]!.x).toBeGreaterThan(compiled.pageSize.width / 2) - expect(compiled.slides.pages[1]!.notes).toBe('Pause on retention.') - }) - - it('does not split slides on delimiters inside YAML literals, fences, comments, or native components', () => { - const markdown = `--- -title: |- - A title - --- -id: one ---- - -\`\`\`md ---- - -\`\`\` - - - - ---- -` - const compiled = compilePresentationMarkdown(markdown).document - - expect(compiled.slides.pages).toHaveLength(1) - expect(compiled.slides.pages[0]!.elements).toHaveLength(2) - expect(compiled.slides.pages[0]!.elements[0]).toHaveProperty('text', '---\n') - expect(compiled.slides.pages[0]!.elements[1]).toMatchObject({ id: 'rule', text: '---' }) - expect(inspectPresentationMarkdownAssets(markdown)).toEqual([]) + expect(markdown).toContain('id: slide-') + expect(markdown).toContain('name: Executive summary') + expect(markdown).toContain('') + expect(markdown).toContain('Revenue up 20%') + expect(markdown).not.toContain('x="37"') + expect(markdown).not.toContain('fontSize="44"') }) - it('honors fence length and multiline self-closing components while framing slides', () => { - const fenced = `--- -id: fenced ---- - -~~~~md ---- -~~~ ---- -~~~~` - const fencedDocument = compilePresentationMarkdown(fenced).document - expect(fencedDocument.slides.pages).toHaveLength(1) - expect(fencedDocument.slides.pages[0]!.elements[0]).toHaveProperty('text', '---\n~~~\n---') - - const multilineComponent = `--- -id: first ---- - - - ---- -id: second ---- - -# Second` - const componentDocument = compilePresentationMarkdown(multilineComponent).document - expect(componentDocument.slides.pages.map((slide) => slide.id)).toEqual(['first', 'second']) - expect(componentDocument.slides.pages[0]!.elements[0]).toMatchObject({ id: 'shape', type: 'rect' }) - }) - - it('compiles adjacent native components emitted in one HTML token', () => { - const markdown = `--- -id: adjacent ---- - - -Summary` - - const document = compilePresentationMarkdown(markdown).document - expect(document.slides.pages[0]!.elements).toHaveLength(2) - expect(document.slides.pages[0]!.elements.map((element) => element.id)).toEqual(['panel', 'label']) - }) - - it('round-trips every native element family through canonical Markdown without base64', () => { - const existing = createBlankPresentationDocument('Imported deck') - existing.assets = [ - { id: 'image-asset', kind: 'image', name: 'image.png', source: { dataUrl: 'data:image/png;base64,aW1hZ2U=', fileName: 'image.png', mimeType: 'image/png' } }, - { id: 'audio-asset', kind: 'audio', name: 'audio.mp3', source: { dataUrl: 'data:audio/mpeg;base64,YXVkaW8=', fileName: 'audio.mp3', mimeType: 'audio/mpeg' } }, - { id: 'video-asset', kind: 'video', name: 'video.mp4', source: { dataUrl: 'data:video/mp4;base64,dmlkZW8=', fileName: 'video.mp4', mimeType: 'video/mp4' } }, + it('uses workspace paths for linked media and opaque refs for embedded media', () => { + const document = createBlankPresentationProject('Media') + const slide = document.slides.pages[0]! + document.assets = [ + createPresentationAsset('image', { + assetId: 'linked', dataUrl: 'data:image/png;base64,cG5n', fileName: 'linked.png', mimeType: 'image/png', path: 'assets/linked.png', + }), + createPresentationAsset('image', { + assetId: 'embedded', dataUrl: 'data:image/png;base64,cG5n', fileName: 'embedded.png', mimeType: 'image/png', + }), ] - const slide = existing.slides.pages[0]! - slide.id = 'imported' - slide.name = 'Imported' - existing.slides.selectedPageId = slide.id - slide.notes = 'Speaker note' slide.elements = [ - { - id: 'text', - type: 'text', - text: ' Revenue & ', - x: 20, - y: 20, - width: 300, - height: 80, - rotation: 4, - flipHorizontal: true, - fontSize: 30, - fontFamily: 'Inter', - fontWeight: 700, - color: '#112233', - align: 'center', - textDirection: 'eastAsianVertical', - animation: 'fade', - animationStart: 'afterPrevious', - }, - { - id: 'shape', - type: 'roundRect', - x: 30, - y: 120, - width: 220, - height: 100, - rotation: 0, - fill: '#FF0000', - borderColor: '#000000', - borderWidth: 2, - }, - { - id: 'image', - type: 'image', - sourceAssetId: 'image-asset', - altText: 'Hero', - fit: 'cover', - clipShape: 'ellipse', - x: 280, - y: 120, - width: 300, - height: 180, - rotation: 0, - flipVertical: true, - }, - { - id: 'audio', - type: 'audio', - sourceAssetId: 'audio-asset', - autoplay: false, - loop: true, - muted: false, - x: 20, - y: 320, - width: 240, - height: 80, - rotation: 0, - }, - { - id: 'video', - type: 'video', - sourceAssetId: 'video-asset', - autoplay: false, - loop: false, - muted: true, - x: 280, - y: 320, - width: 300, - height: 180, - rotation: 0, - }, - { - id: 'table', - type: 'table', - cells: [['Name', 'Value'], ['A|B', 'Line 1\nLine 2']], - headerRow: true, - headerFill: '#EEEEEE', - bodyFill: '#FFFFFF', - textColor: '#111111', - borderColor: '#999999', - fontSize: 18, - x: 610, - y: 20, - width: 400, - height: 180, - rotation: 0, - }, - { - id: 'chart', - type: 'chart', - chartType: 'line', - categories: ['Q1', 'Q2'], - series: [{ name: 'ARR', values: [12, 18] }], - showLegend: true, - colors: ['#5B67F1'], - x: 610, - y: 230, - width: 500, - height: 300, - rotation: 0, - }, + { id: 'linked-image', type: 'image', sourceAssetId: 'linked', altText: 'Linked', fit: 'cover', x: 0, y: 0, width: 100, height: 100, rotation: 0 }, + { id: 'embedded-image', type: 'image', sourceAssetId: 'embedded', altText: 'Embedded', fit: 'contain', x: 100, y: 0, width: 100, height: 100, rotation: 0 }, ] - - const markdown = decompilePresentationSlideMarkdown(slide, existing) - expect(markdown).toContain(' element.type)).toEqual( - existing.slides.pages[0]!.elements.map((element) => element.type), - ) - expect(roundTripped.slides.pages[0]!.elements[0]).toMatchObject({ - id: 'text', - text: ' Revenue & ', - animation: 'fade', - animationStart: 'afterPrevious', - flipHorizontal: true, - textDirection: 'eastAsianVertical', - }) - expect(roundTripped.slides.pages[0]!.elements[2]).toMatchObject({ id: 'image', flipVertical: true, clipShape: 'ellipse' }) - expect(roundTripped.slides.pages[0]!.elements[5]).toMatchObject({ - id: 'table', - cells: [['Name', 'Value'], ['A|B', 'Line 1\nLine 2']], - }) - expect(roundTripped.slides.pages[0]!.elements[6]).toMatchObject({ - id: 'chart', - categories: ['Q1', 'Q2'], - series: [{ name: 'ARR', values: [12, 18] }], - }) + it('projects tables, charts, notes, and non-default page metadata', () => { + const document = createBlankPresentationProject('Data') + const slide = document.slides.pages[0]! + slide.background = '#123456' + slide.notes = 'Explain the growth assumptions.' + slide.footer = { text: 'Confidential', showDate: false, showSlideNumber: true } + slide.transition = { effect: 'fade', durationMs: 500 } + slide.elements = [ + { id: 'table', type: 'table', x: 0, y: 0, width: 500, height: 200, rotation: 0, cells: [['A', 'B'], ['1', '2']], headerRow: true, headerFill: '#000000', bodyFill: '#FFFFFF', textColor: '#111111', borderColor: '#CCCCCC', fontSize: 18 }, + { id: 'chart', type: 'chart', x: 0, y: 220, width: 500, height: 300, rotation: 0, chartType: 'column', categories: ['A'], series: [{ name: 'Revenue', values: [10] }], showLegend: false, colors: ['#123456'], title: 'Growth' }, + ] + const markdown = decompilePresentationSlideMarkdown(slide, document) + expect(markdown).toContain("background: '#123456'") + expect(markdown).toContain('effect: fade') + expect(markdown).toContain('') + expect(markdown).toContain('| A | B |') + expect(markdown).toContain('') + expect(markdown).toContain('') }) - it('compiles a single editable fragment while preserving or assigning its ref', () => { - const document = createBlankPresentationDocument('Element edits') + it('fails loudly when a media element refers to a missing asset', () => { + const document = createBlankPresentationProject('Broken') const slide = document.slides.pages[0]! slide.elements = [{ - id: 'title', type: 'text', text: 'Before', x: 20, y: 20, width: 300, height: 60, - rotation: 0, fontSize: 30, fontFamily: 'Aptos', fontWeight: 700, color: '#111111', align: 'left', + id: 'hero', type: 'image', sourceAssetId: 'missing', altText: 'Hero', fit: 'cover', + x: 0, y: 0, width: 100, height: 100, rotation: 0, }] - - const edited = compilePresentationElementMarkdown( - 'After', - { document, elementId: 'title', slide }, - ).element - const inserted = compilePresentationElementMarkdown( - '', - { document, slide }, - ).element - - expect(edited).toMatchObject({ id: 'title', text: 'After' }) - expect(inserted.id).not.toBe('title') - expect(() => compilePresentationElementMarkdown('Duplicate', { - document, - slide, - })).toThrow('must not provide id or ref') - }) - - it('uses one parser for local asset discovery and compilation', () => { - const markdown = `--- -id: media ---- - -![Hero](assets/hero.png) - -` - const textWithImageSyntax = [markdown, '![Not media](ignored.png)'].join('\n\n') - expect(inspectPresentationMarkdownAssets(textWithImageSyntax)).toEqual(['assets/hero.png', 'media/voice.mp3']) - expect(() => compilePresentationMarkdown(markdown)).toThrow('asset was not registered') - - const document = compilePresentationMarkdown(markdown, { - assets: { - 'assets/hero.png': { - assetId: 'asset-image', - dataUrl: 'bridgic-resource://hero', - fileName: 'hero.png', - mimeType: 'image/png', - path: 'assets/hero.png', - }, - 'media/voice.mp3': { - assetId: 'asset-audio', - dataUrl: 'bridgic-resource://voice', - fileName: 'voice.mp3', - mimeType: 'audio/mpeg', - path: 'media/voice.mp3', - }, - }, - }).document - expect(document.slides.pages[0]!.elements.map((element) => element.type)).toEqual(['image', 'audio']) - expect(inspectPresentationMarkdownAssets('')).toEqual([ - 'assets/detail.png', - ]) - expect(inspectPresentationMarkdownAssets('')).toEqual([]) - }) - - it('rejects duplicate refs, unknown component attributes, and arbitrary executable Vue', () => { - expect(() => compilePresentationMarkdown(`--- -id: duplicate ---- - -# One {#same} - -# Two {#same}`)).toThrow('Duplicate element ref') - expect(() => compilePresentationMarkdown(`--- -id: typo ---- - -Title`)).toThrow('Unsupported PptText attribute: widht') - expect(() => compilePresentationMarkdown(`--- -id: unsafe ---- - -`)).toThrow('Unsupported HTML or Vue block') - }) - - it('accepts style blocks as inert input and reports that they were not executed', () => { - const compiled = compilePresentationMarkdown(`--- -id: styled ---- - - - -# Native title`) - expect(compiled.document.slides.pages[0]!.elements).toHaveLength(1) - expect(compiled.diagnostics[0]).toContain('accepted but ignored') + expect(() => decompilePresentationSlideMarkdown(slide, document)).toThrow('has no source asset') }) }) diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/presentationPersistence.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/presentationPersistence.test.ts deleted file mode 100644 index 92a21d5d..00000000 --- a/desktop/apps/electron/src/renderer/lib/__tests__/presentationPersistence.test.ts +++ /dev/null @@ -1,234 +0,0 @@ -import { describe, expect, it } from 'bun:test' -import { createBlankPresentationDocument, type PresentationWorkspace } from '@/atoms/presentation' -import { createPresentationPersistence } from '../presentationPersistence' -import { createPresentationWorkspaceRuntime } from '../presentationWorkspaceRuntime' - -function workspace(title: string, revision = 1): PresentationWorkspace { - const document = { ...createBlankPresentationDocument(title), revision } - return { activeDocumentId: document.id, documents: [document] } -} - -function changed(state: PresentationWorkspace, title: string): PresentationWorkspace { - return { ...state, documents: state.documents.map((document) => ({ ...document, title, revision: document.revision + 1 })) } -} - -function deferred() { - let resolve!: () => void - let reject!: (error: unknown) => void - const promise = new Promise((yes, no) => { resolve = yes; reject = no }) - return { promise, resolve, reject } -} - -describe('presentation source persistence', () => { - it('declares source-file storage and does not write unbound or newly created UI tabs', async () => { - const writes: string[] = [] - const persistence = createPresentationPersistence({ sessionId: 'session-a', encode: async () => new Uint8Array(), write: async (path) => { writes.push(path) } }) - const first = workspace('Source') - await persistence.persist(first) - persistence.bindTarget('/tmp/source.pptx', first, true) - const blank = workspace('Untitled') - const tabs = { activeDocumentId: blank.activeDocumentId, documents: [...first.documents, ...blank.documents] } - await persistence.persist(tabs) - expect(writes).toEqual([]) - expect(persistence.targetFor(tabs)).toBeNull() - expect(persistence.targetFor(first)).toBe('/tmp/source.pptx') - expect(persistence.getSnapshot().policy).toEqual({ appKind: 'presentation', sessionId: 'session-a', kind: 'source', storage: 'source-file', automatic: true }) - }) - - it('returns the same actual write receipt to autosave and a matching protocol checkpoint', async () => { - const gate = deferred() - let writes = 0 - const persistence = createPresentationPersistence({ sessionId: 's', encode: async () => new Uint8Array(), write: async () => { writes += 1; await gate.promise } }) - const state = workspace('Source') - persistence.bindTarget('/tmp/source.pptx', state, false) - const autosave = persistence.persist(state) - const protocol = persistence.persist(state) - expect(protocol).toBe(autosave) - let settled = false - void protocol.then(() => { settled = true }) - await Promise.resolve() - await Promise.resolve() - expect(writes).toBe(1) - expect(settled).toBe(false) - gate.resolve() - await protocol - expect(settled).toBe(true) - await persistence.persist(state) - expect(writes).toBe(1) - }) - - it('keeps same-target revision writes ordered and waits for each receipt', async () => { - const firstGate = deferred() - const written: number[] = [] - const persistence = createPresentationPersistence({ - sessionId: 's', encode: async (document) => new Uint8Array([document.revision]), - write: async (_path, bytes) => { written.push(bytes[0]!); if (bytes[0] === 1) await firstGate.promise }, - }) - const state = workspace('First') - persistence.bindTarget('/tmp/source.pptx', state, false) - const first = persistence.persist(state) - const second = persistence.persist(changed(state, 'Second')) - await Promise.resolve() - await Promise.resolve() - expect(written).toEqual([1]) - firstGate.resolve() - await Promise.all([first, second]) - expect(written).toEqual([1, 2]) - }) - - it('lets a newer queued write settle after an older autosave fails', async () => { - const gate = deferred() - const written: number[] = [] - const persistence = createPresentationPersistence({ - sessionId: 's', encode: async (document) => new Uint8Array([document.revision]), - write: async (_path, bytes) => { written.push(bytes[0]!); if (bytes[0] === 1) await gate.promise }, - }) - const state = workspace('First') - persistence.bindTarget('/tmp/source.pptx', state, false) - const first = persistence.persist(state) - const firstOutcome = first.then(() => 'saved', () => 'failed') - const second = persistence.persist(changed(state, 'Second')) - gate.reject(new Error('First write failed')) - expect(await firstOutcome).toBe('failed') - await second - await persistence.flush() - expect(written).toEqual([1, 2]) - expect(persistence.getSnapshot().status).toBe('saved') - }) - - it('retains the latest failed write for an explicit retry and does not write bytes on encoding failure', async () => { - let encodes = 0 - let writes = 0 - const persistence = createPresentationPersistence({ - sessionId: 's', encode: async () => { if (++encodes === 1) throw new Error('Encoding failed'); return new Uint8Array() }, - write: async () => { writes += 1 }, - }) - const state = workspace('First') - persistence.bindTarget('/tmp/source.pptx', state, false) - await expect(persistence.persist(state)).rejects.toThrow('Encoding failed') - expect(writes).toBe(0) - await persistence.flush() - expect(writes).toBe(1) - expect(encodes).toBe(2) - expect(persistence.getSnapshot().status).toBe('saved') - }) - - it.each(['complete', 'fail'] as const)('keeps a previous target %s from changing a newly imported target baseline', async (outcome) => { - const gate = deferred() - const writes: string[] = [] - const persistence = createPresentationPersistence({ - sessionId: 's', encode: async () => new Uint8Array(), - write: async (target) => { writes.push(target); if (target === '/tmp/first.pptx') await gate.promise }, - }) - const first = workspace('First') - persistence.bindTarget('/tmp/first.pptx', first, false) - const pending = persistence.persist(first) - const completed = pending.then(() => undefined, () => undefined) - const second = workspace('Second') - persistence.bindTarget('/tmp/second.pptx', second, true) - const secondStatus = persistence.getSnapshot() - if (outcome === 'complete') gate.resolve() - else gate.reject(new Error('Old destination unavailable')) - await completed - await persistence.persist(second) - expect(persistence.getSnapshot()).toBe(secondStatus) - expect(persistence.getSnapshot().status).toBe('saved') - expect(writes).toEqual(['/tmp/first.pptx']) - }) - - it('continues a different target while an older destination is still saving', async () => { - const gate = deferred() - const writes: string[] = [] - const persistence = createPresentationPersistence({ sessionId: 's', encode: async () => new Uint8Array(), write: async (target) => { writes.push(target); if (target === '/tmp/first.pptx') await gate.promise } }) - const first = workspace('First') - persistence.bindTarget('/tmp/first.pptx', first, false) - const pending = persistence.persist(first) - const second = workspace('Second') - persistence.bindTarget('/tmp/second.pptx', second, false) - await persistence.persist(second) - expect(writes).toEqual(['/tmp/first.pptx', '/tmp/second.pptx']) - gate.resolve() - await pending - }) - - it('includes native edits made during a close checkpoint before acknowledging the close', async () => { - const gate = deferred() - const written: number[] = [] - const persistence = createPresentationPersistence({ sessionId: 's', encode: async (document) => new Uint8Array([document.revision]), write: async (_path, bytes) => { written.push(bytes[0]!); if (bytes[0] === 1) await gate.promise } }) - let state = workspace('First') - persistence.bindTarget('/tmp/source.pptx', state, false) - let closed = false - const checkpoint = persistence.checkpoint(() => state).then(() => { closed = true }) - state = changed(state, 'Typed while saving') - expect(closed).toBe(false) - gate.resolve() - await checkpoint - expect(written).toEqual([1, 2]) - expect(closed).toBe(true) - }) - - it('rejects a failed close checkpoint so its caller can preserve the editor', async () => { - const persistence = createPresentationPersistence({ sessionId: 's', encode: async () => new Uint8Array(), write: async () => { throw new Error('Disk unavailable') } }) - const state = workspace('First') - persistence.bindTarget('/tmp/source.pptx', state, false) - let closed = false - await expect(persistence.checkpoint(() => state).then(() => { closed = true })).rejects.toThrow('Disk unavailable') - expect(closed).toBe(false) - }) - - it('returns view_ppt to its existing source document after the user selects an unbound tab', async () => { - let writes = 0 - const persistence = createPresentationPersistence({ sessionId: 's', encode: async () => new Uint8Array(), write: async () => { writes += 1 } }) - const source = workspace('Source') - const blank = workspace('New UI tab') - persistence.bindTarget('/tmp/source.pptx', source, true) - let state = { activeDocumentId: blank.activeDocumentId, documents: [...source.documents, ...blank.documents] } - const controller = createPresentationWorkspaceRuntime({ sessionId: 's', read: () => state, write: (next) => { state = next } }) - const result = await controller.dispatchProtocol( - { method: 'view_ppt', params: { target: '/tmp/source.pptx', file_name: 'source.pptx', content_base64: 'Not reread for a reused document' } }, - () => ({ currentTarget: persistence.targetFor(state), fileName: 'source.pptx' }), - async () => undefined, - (request) => persistence.prepareProtocol(request, () => state, (next) => { state = next }), - ) - expect(result).toMatchObject({ ok: true, value: { reused: true, identity: { document_id: source.activeDocumentId } } }) - expect(state.activeDocumentId).toBe(source.activeDocumentId) - expect(state.documents).toHaveLength(2) - expect(writes).toBe(0) - }) - - it('rejects source mutations before they can modify an unbound UI tab', async () => { - const persistence = createPresentationPersistence({ sessionId: 's', encode: async () => new Uint8Array(), write: async () => undefined }) - const state = workspace('Unbound') - let commits = 0 - const controller = createPresentationWorkspaceRuntime({ sessionId: 's', read: () => state, write: () => { commits += 1 } }) - const result = await controller.dispatchProtocol( - { method: 'insert_ppt_page', params: { markdown: 'Must not be applied' } }, - () => ({ currentTarget: null, fileName: 'Unbound.pptx' }), - async () => { commits += 1 }, - (request) => persistence.prepareProtocol(request, () => state, () => { commits += 1 }), - ) - expect(result).toMatchObject({ ok: false, code: 'document_changed' }) - expect(commits).toBe(0) - expect(state.documents[0]!.slides.pages).toHaveLength(1) - }) - - it('requires fresh source bytes when reopening a replaced document with pending writes', async () => { - const gate = deferred() - const persistence = createPresentationPersistence({ sessionId: 's', encode: async () => new Uint8Array(), write: async () => gate.promise }) - const first = workspace('First') - persistence.bindTarget('/tmp/first.pptx', first, false) - const pending = persistence.persist(first) - const second = workspace('Second') - persistence.bindTarget('/tmp/second.pptx', second, true) - const request = { method: 'view_ppt' as const, params: { target: '/tmp/first.pptx', file_name: 'first.pptx', content_base64: 'Previously read bytes' } } - let writesToWorkspace = 0 - const preparation = persistence.prepareProtocol(request, () => second, () => { writesToWorkspace += 1 }) - gate.resolve() - await pending - await expect(preparation).rejects.toMatchObject({ code: 'document_changed' }) - expect(persistence.targetFor(second)).toBe('/tmp/second.pptx') - expect(writesToWorkspace).toBe(0) - await persistence.prepareProtocol(request, () => second, () => { writesToWorkspace += 1 }) - expect(writesToWorkspace).toBe(0) - }) -}) diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/presentationPptx.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/presentationPptx.test.ts index eeddeb46..1b869c25 100644 --- a/desktop/apps/electron/src/renderer/lib/__tests__/presentationPptx.test.ts +++ b/desktop/apps/electron/src/renderer/lib/__tests__/presentationPptx.test.ts @@ -4,23 +4,23 @@ import { DOMParser } from '@xmldom/xmldom' import { PRESENTATION_PAGE_SIZES, createBlankPresentationSlide, - createInitialPresentationDocument as createEmptyPresentationDocument, + createInitialPresentationProject as createEmptyPresentationProject, type PresentationAsset, type PresentationAssetKind, type PresentationElement, type PresentationFileSource, type PresentationTransition, } from '@/atoms/presentation' -import { createPresentationTestDocument as createInitialPresentationDocument } from '@/test-fixtures/presentation' +import { createPresentationTestDocument as createInitialPresentationProject } from '@/test-fixtures/presentation' import { createPresentationPptx } from '../presentationPptx' function presentationAsset(id: string, kind: PresentationAssetKind, source: PresentationFileSource): PresentationAsset { - return { id, kind, name: source.fileName, source } + return { id, kind, mimeType: source.mimeType, name: source.fileName, source: source.dataUrl } } describe('createPresentationPptx', () => { async function exportTransitionSlides(transitions: PresentationTransition[]): Promise { - const document = createInitialPresentationDocument() + const document = createInitialPresentationProject() document.slides.pages = transitions.map((transition, index) => ({ ...createBlankPresentationSlide(`Transition ${index + 1}`), id: `transition-slide-${index + 1}`, @@ -37,7 +37,7 @@ describe('createPresentationPptx', () => { } it('does not export empty text boxes as slide content', async () => { - const document = createEmptyPresentationDocument() + const document = createEmptyPresentationProject() document.slides.pages[0]!.elements = [{ id: 'empty-title-placeholder', type: 'text', @@ -62,7 +62,7 @@ describe('createPresentationPptx', () => { }) it('exports inherited theme background and footer without page copies', async () => { - const document = createEmptyPresentationDocument() + const document = createEmptyPresentationProject() document.theme = { ...document.theme, background: '#112233', @@ -80,7 +80,7 @@ describe('createPresentationPptx', () => { }) it('exports every slide into a valid PowerPoint Open XML archive', async () => { - const document = createInitialPresentationDocument() + const document = createInitialPresentationProject() const title = document.slides.pages[0]?.elements.find((element) => element.type === 'text') if (document.slides.pages[0]) { document.slides.pages[0].notes = 'Speaker note exported from Bridgic.' @@ -154,7 +154,7 @@ describe('createPresentationPptx', () => { }) it('exports the document page size instead of forcing widescreen', async () => { - const document = createInitialPresentationDocument() + const document = createInitialPresentationProject() document.pageSize = PRESENTATION_PAGE_SIZES.standard const archive = await JSZip.loadAsync(await createPresentationPptx(document)) @@ -164,7 +164,7 @@ describe('createPresentationPptx', () => { }) it('exports element animations as native PowerPoint timing targeted by object id', async () => { - const document = createInitialPresentationDocument() + const document = createInitialPresentationProject() const slide = document.slides.pages[0]! const title = slide.elements.find((element) => element.type === 'text')! title.animation = 'fade' @@ -295,7 +295,7 @@ describe('createPresentationPptx', () => { }) it('exports grouped card members in one synchronized native animation step', async () => { - const document = createInitialPresentationDocument() + const document = createInitialPresentationProject() const slide = document.slides.pages[0]! slide.elements = [ { @@ -370,7 +370,7 @@ describe('createPresentationPptx', () => { }) it('preserves after-previous steps when a with-previous effect follows them', async () => { - const document = createInitialPresentationDocument() + const document = createInitialPresentationProject() const slide = document.slides.pages[0]! const animatedShape = (id: string, animationStart: 'onClick' | 'withPrevious' | 'afterPrevious', animation: 'fade' | 'appear' | 'disappear', duration: number, x: number): PresentationElement => ({ id, @@ -411,7 +411,7 @@ describe('createPresentationPptx', () => { }) it('exports hyperlinks, embedded media, editable tables and charts, and slide footers', async () => { - const document = createInitialPresentationDocument() + const document = createInitialPresentationProject() const sourceSlide = document.slides.pages[0]! const targetSlide = document.slides.pages[1]! const pngDataUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Y9Z5QAAAABJRU5ErkJggg==' @@ -678,7 +678,7 @@ describe('createPresentationPptx', () => { }) it('canonicalizes QuickTime content types without relying on audio or transitions', async () => { - const document = createInitialPresentationDocument() + const document = createInitialPresentationProject() document.assets.push(presentationAsset('quicktime-only-asset', 'video', { dataUrl: 'data:video/quicktime;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDE=', fileName: 'quicktime-only.mov', @@ -707,7 +707,7 @@ describe('createPresentationPptx', () => { }) it('skips malformed legacy elements and dangling hyperlinks without failing export', async () => { - const document = createInitialPresentationDocument() + const document = createInitialPresentationProject() document.assets.push( presentationAsset('broken-image-asset', 'image', { dataUrl: 'not-a-data-url', fileName: 'broken.png', mimeType: 'image/png' }), presentationAsset('mismatched-image-asset', 'image', { diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/presentationPptxDisplay.test.tsx b/desktop/apps/electron/src/renderer/lib/__tests__/presentationPptxDisplay.test.tsx index c9403eed..501f5d7c 100644 --- a/desktop/apps/electron/src/renderer/lib/__tests__/presentationPptxDisplay.test.tsx +++ b/desktop/apps/electron/src/renderer/lib/__tests__/presentationPptxDisplay.test.tsx @@ -5,10 +5,10 @@ import { PresentationSlidePreview } from '../../components/app/PresentationSlide import { importPresentationPptx } from '../presentationPptxImport' import { createPresentationPptx } from '../presentationPptx' import { presentationTextStyleAt, presentationTextDisplaySegments } from '../presentationText' -import { createBlankPresentationDocument, layoutPresentationVerticalText } from '../../atoms/presentation' +import { createBlankPresentationProject, layoutPresentationVerticalText, type PresentationProject } from '../../atoms/presentation' import { DOMParser, XMLSerializer } from '@xmldom/xmldom' -import { compilePresentationSlideMarkdown, decompilePresentationSlideMarkdown } from '../presentationMarkdown' -import { presentationElementSource } from '@/presentation/project' +import { editPresentationPage } from '@/presentation/agentCommands' +import { materializePresentationProjectSources, presentationPptxSourceUrls } from '@/presentation/sources' const ns = 'xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"' const emu = (px: number) => Math.round(px * 9525) @@ -21,12 +21,16 @@ function textBody(direction = '', runs = '标题 Hea return `${runs}` } -async function readFixture(tree: string, height = 6858000, width = 12192000, extraFiles: Record = {}, slideAttributes = '') { +async function fixtureBytes(tree: string, height = 6858000, width = 12192000, extraFiles: Record = {}, slideAttributes = '') { const zip = new JSZip() zip.file('ppt/presentation.xml', ``) zip.file('ppt/slides/slide1.xml', `${tree}`) for (const [path, content] of Object.entries(extraFiles)) zip.file(path, content) - return importPresentationPptx(await zip.generateAsync({ type: 'uint8array' })) + return zip.generateAsync({ type: 'uint8array' }) +} + +async function readFixture(tree: string, height = 6858000, width = 12192000, extraFiles: Record = {}, slideAttributes = '') { + return importPresentationPptx(await fixtureBytes(tree, height, width, extraFiles, slideAttributes)) } function preview(model: Awaited>) { @@ -39,9 +43,63 @@ function firstText(model: Awaited>) { return text } +function agentEdit(model: PresentationProject): PresentationProject { + const page = model.slides.pages[0]! + const element = page.elements[0]! + return editPresentationPage(model, page.id, [{ type: 'patch', id: element.id, element_type: element.type, patch: { x: element.x } }]).project +} + describe('PowerPoint display fidelity', () => { + it('previews mixed colors and emphasis inside one table cell', () => { + const model = createBlankPresentationProject('Rich table') + model.slides.pages[0]!.elements = [{ + id: 'table', type: 'table', x: 80, y: 80, width: 500, height: 180, rotation: 0, + cells: [['Red Blue']], + cellStyles: [[{ textRuns: [ + { start: 0, end: 4, style: { color: '#FF0000', fontWeight: 700 } }, + { start: 4, end: 8, style: { color: '#0000FF', italic: true } }, + ] }]], + headerRow: false, headerFill: '#FFFFFF', bodyFill: '#FFFFFF', textColor: '#000000', borderColor: '#333333', fontSize: 20, + }] + const markup = preview(model) + expect(markup).toContain('color:#FF0000;font-weight:700') + expect(markup).toContain('color:#0000FF;font-style:italic') + expect(markup).toContain('Red ') + expect(markup).toContain('Blue') + }) + + it('previews imported table cell spans, grid dimensions and individual cell colors', () => { + const model = createBlankPresentationProject('Table grid') + model.slides.pages[0]!.elements = [{ + id: 'table', type: 'table', x: 100, y: 100, width: 600, height: 240, rotation: 0, + cells: [['Merged', '', 'Right'], ['A', 'B', 'C']], + columnWidths: [1, 2, 3], rowHeights: [1, 2], + cellStyles: [[{ colSpan: 2, fill: '#FF0000', textColor: '#FFFFFF' }, { covered: true }, { fill: '#00FF00' }], [{}, {}, {}]], + headerRow: false, headerFill: '#FFFFFF', bodyFill: '#FFFFFF', textColor: '#000000', borderColor: '#333333', fontSize: 16, + }] + const markup = preview(model) + expect(markup).toContain('colSpan="2"') + expect(markup).toContain('background-color:#FF0000') + expect(markup).toContain('background-color:#00FF00') + expect(markup).toContain('width:100px') + expect(markup).toContain('width:200px') + expect(markup).toContain('width:300px') + }) + + it('previews an imported patterned shape from its editable pattern data', async () => { + const tree = shape(1, 100).replace( + '', + '', + ) + const model = await readFixture(tree) + const markup = preview(model) + expect(markup).toContain(' { - const model = createBlankPresentationDocument('Theme preview') + const model = createBlankPresentationProject('Theme preview') model.theme = { ...model.theme, background: '#17182B', @@ -57,7 +115,7 @@ describe('PowerPoint display fidelity', () => { }) it.each([0, 1, 2])('keeps category/value indices when chart point %s is absent', async (missingIndex) => { - const model = createBlankPresentationDocument('Sparse data') + const model = createBlankPresentationProject('Sparse data') model.slides.pages[0]!.elements = [{ id: 'chart', type: 'chart', chartType: 'column', x: 100, y: 100, width: 800, height: 400, rotation: 0, categories: ['Jan', 'Feb', 'Mar'], series: [{ name: 'North', values: [10, 20, 30] }, { name: 'South', values: [40, 50, 60] }], colors: ['#2266EE', '#00AA88'], showLegend: true }] const zip = await JSZip.loadAsync(await createPresentationPptx(model)) @@ -83,7 +141,7 @@ describe('PowerPoint display fidelity', () => { }) it.each(['', ''])('retains sparse indices without relying on an ordered or complete cache (%s)', async (count) => { - const model = createBlankPresentationDocument('Unordered cache') + const model = createBlankPresentationProject('Unordered cache') model.slides.pages[0]!.elements = [{ id: 'chart', type: 'chart', chartType: 'line', x: 100, y: 100, width: 800, height: 400, rotation: 0, categories: ['Jan', 'Feb', 'Mar'], series: [{ name: 'Sales', values: [10, 20, 30] }], colors: ['#2266EE'], showLegend: true }] const zip = await JSZip.loadAsync(await createPresentationPptx(model)) @@ -103,7 +161,7 @@ describe('PowerPoint display fidelity', () => { expect(original.connectorPath).toStartWith('M 0 0 L 100 100') expect(original.connectorPath!.match(/ M /g)?.length).toBe(ends === 'both' ? 2 : 1) for (let round = 0; round < 2; round++) { - model.slides.pages = [compilePresentationSlideMarkdown(decompilePresentationSlideMarkdown(model.slides.pages[0]!), { document: model }).slide] + model = agentEdit(model) model = await importPresentationPptx(await createPresentationPptx(model)) const arrow = model.slides.pages[0]!.elements[0]! if (!('connectorPath' in arrow)) throw new Error('Lost arrow geometry') @@ -127,7 +185,7 @@ describe('PowerPoint display fidelity', () => { if (headerRow) expect(table).toMatchObject({ headerTextColor: '#000000', headerFill: '#FFFFFF' }) const markup = new DOMParser().parseFromString(preview(model), 'text/html') expect(markup.getElementsByTagName('td')[0]!.getAttribute('style')).toContain('color:#000000') - const edited = compilePresentationSlideMarkdown(decompilePresentationSlideMarkdown(model.slides.pages[0]!), { document: model }).slide + const edited = agentEdit(model).slides.pages[0]! expect(edited.elements[0]).toMatchObject({ headerRow, ...(headerRow ? { headerTextColor: '#000000' } : {}) }) model.slides.pages = [edited] const bytes = await createPresentationPptx(model) @@ -138,7 +196,7 @@ describe('PowerPoint display fidelity', () => { }) it('retains the existing white-on-accent default header separately from black body text', async () => { - const model = createBlankPresentationDocument('Header colors') + const model = createBlankPresentationProject('Header colors') model.slides.pages[0]!.elements = [{ id: 'table', type: 'table', x: 80, y: 80, width: 600, height: 300, rotation: 0, cells: [['Header', 'Value'], ['Body', '10']], headerRow: true, headerFill: '#6957D9', bodyFill: '#FFFFFF', textColor: '#000000', borderColor: '#D8D9E0', fontSize: 24 }] const reopened = await importPresentationPptx(await createPresentationPptx(model)) @@ -146,7 +204,7 @@ describe('PowerPoint display fidelity', () => { }) it.each(['pie', 'doughnut'] as const)('retains per-category %s colors through repeated exports', async (chartType) => { - let model = createBlankPresentationDocument('Category colors') + let model = createBlankPresentationProject('Category colors') model.slides.pages[0]!.elements = [{ id: 'pie', type: 'chart', chartType, x: 100, y: 100, width: 800, height: 400, rotation: 0, categories: ['A', 'B', 'C'], series: [{ name: 'Total', values: [50, 0, 20] }], colors: ['#FF0000', '#00AA00', '#0000FF'], showLegend: true }] for (let round = 0; round < 2; round++) { @@ -158,7 +216,7 @@ describe('PowerPoint display fidelity', () => { }) it.each(['pie', 'doughnut'] as const)('matches sparse, unordered %s point overrides by index and retains single-series fallback', async (chartType) => { - const model = createBlankPresentationDocument('Point overrides') + const model = createBlankPresentationProject('Point overrides') model.slides.pages[0]!.elements = [{ id: 'pie', type: 'chart', chartType, x: 100, y: 100, width: 800, height: 400, rotation: 0, categories: ['A', 'B', 'C'], series: [{ name: 'Total', values: [50, 30, 20] }], colors: ['#FF0000', '#00AA00', '#0000FF'], showLegend: true }] const zip = await JSZip.loadAsync(await createPresentationPptx(model)) @@ -178,12 +236,15 @@ describe('PowerPoint display fidelity', () => { 'ppt/slides/_rels/slide1.xml.rels': '', } const tree = `` - let model = await readFixture(tree, undefined, undefined, files) + let bytes = await fixtureBytes(tree, undefined, undefined, files) + let model = await importPresentationPptx(bytes) for (let round = 0; round < 2; round++) { const image = model.slides.pages[0]!.elements[0]! expect(image).toMatchObject({ type: 'image', crop: { left: 0.5, top: 0.1, right: 0.05, bottom: 0.15 }, opacity: 0.5, flipHorizontal: true }) if (clipShape === 'ellipse') expect(image).toMatchObject({ clipShape: 'ellipse' }) - model = await importPresentationPptx(await createPresentationPptx(model)) + const sources = await presentationPptxSourceUrls(model, Buffer.from(bytes).toString('base64')) + bytes = await createPresentationPptx(await materializePresentationProjectSources(model, sources)) + model = await importPresentationPptx(bytes) } }) @@ -213,27 +274,22 @@ describe('PowerPoint display fidelity', () => { }) it('exports CSS-pixel stroke widths in DrawingML point units', async () => { - const model = createBlankPresentationDocument('Stroke units') + const model = createBlankPresentationProject('Stroke units') model.slides.pages[0]!.elements = [{ id: 'outline', type: 'rect', x: 100, y: 100, width: 400, height: 300, rotation: 0, fill: 'transparent', borderColor: '#000000', borderWidth: 4 }] const xml = await (await JSZip.loadAsync(await createPresentationPptx(model))).file('ppt/slides/slide1.xml')!.async('text') expect(new DOMParser().parseFromString(xml, 'text/xml').getElementsByTagName('a:ln')[0]!.getAttribute('w')).toBe('38100') }) - it.each([0, 45, 90])('pads SVG strokes without moving the authored shape at %s degrees', async (rotation) => { + it.each([0, 45, 90])('keeps native translucent strokes on the authored shape at %s degrees', async (rotation) => { const tree = shape(1, 100).replace('', ``) .replace('', '') const project = await readFixture(tree) - const image = project.slides.pages[0]!.elements[0]! - if (image.type !== 'image') throw new Error('Expected an SVG shape') - const svg = new DOMParser().parseFromString(atob(presentationElementSource(project, image)!.dataUrl.split(',')[1]!), 'image/svg+xml').documentElement - expect(svg.getAttribute('viewBox')).toBe('-64 -64 228 178') - expect(svg.getElementsByTagName('rect')[0]!.getAttribute('stroke-width')).toBe('32') - expect(image.flipHorizontal).toBe(true) + const element = project.slides.pages[0]!.elements[0]! + expect(element).toMatchObject({ type: 'rect', borderWidth: 32, borderOpacity: 0.5, flipHorizontal: true }) const angle = rotation * Math.PI / 180 - // Rotation is stored about the top-left corner; the padded frame must keep the original center. - expect(image.x + image.width / 2 * Math.cos(angle) - image.height / 2 * Math.sin(angle)).toBeCloseTo(150) - expect(image.y + image.width / 2 * Math.sin(angle) + image.height / 2 * Math.cos(angle)).toBeCloseTo(125) + expect(element.x + element.width / 2 * Math.cos(angle) - element.height / 2 * Math.sin(angle)).toBeCloseTo(150) + expect(element.y + element.width / 2 * Math.sin(angle) + element.height / 2 * Math.cos(angle)).toBeCloseTo(125) }) it('preserves leading, consecutive and trailing blank paragraph formatting through Agent edits and PPTX export', async () => { @@ -242,7 +298,7 @@ describe('PowerPoint display fidelity', () => { let model = await readFixture(shape(1, 100, `${paragraphs}`)) const text = firstText(model) expect(text.paragraphs?.map(paragraph => paragraph.endStyle?.fontSize)).toEqual([64, undefined, 128, 16, undefined, 80]) - const slide = compilePresentationSlideMarkdown(decompilePresentationSlideMarkdown(model.slides.pages[0]!), { document: model }).slide + const slide = agentEdit(model).slides.pages[0]! expect(slide.elements.find(element => element.type === 'text')).toMatchObject({ paragraphs: text.paragraphs }) model.slides.pages = [slide] for (let round = 0; round < 2; round++) { @@ -257,7 +313,7 @@ describe('PowerPoint display fidelity', () => { it.each(['rect', 'line'] as const)('exports whole-object opacity on %s outlines as well as fills', async (type) => { for (const opacity of [0, 0.2, 0.65]) { - const model = createBlankPresentationDocument('Faded outline') + const model = createBlankPresentationProject('Faded outline') model.slides.pages[0]!.elements = [{ id: 'faded', type, x: 100, y: 100, width: 500, height: type === 'line' ? 1 : 300, rotation: 0, fill: 'transparent', borderColor: '#000000', borderWidth: 8, opacity }] const bytes = await createPresentationPptx(model) @@ -271,7 +327,7 @@ describe('PowerPoint display fidelity', () => { }) it('keeps outline interiors transparent and their borders visible through export and reopening', async () => { - let model = createBlankPresentationDocument('Outline') + let model = createBlankPresentationProject('Outline') model.slides.pages[0]!.background = '#152945' model.slides.pages[0]!.elements = [{ id: 'outline', type: 'rect', x: 80, y: 80, width: 500, height: 300, rotation: 0, fill: 'transparent', borderColor: '#FFCC00', borderWidth: 3 }] @@ -283,7 +339,7 @@ describe('PowerPoint display fidelity', () => { }) it('keeps matching fill and border opacity editable through repeated exports', async () => { - let model = createBlankPresentationDocument('Faded filled shape') + let model = createBlankPresentationProject('Faded filled shape') model.slides.pages[0]!.elements = [{ id: 'faded', type: 'rect', x: 100, y: 100, width: 400, height: 200, rotation: 0, fill: '#FF0000', borderColor: '#000000', borderWidth: 8, opacity: 0.25 }] for (let count = 0; count < 2; count++) { @@ -342,7 +398,7 @@ describe('PowerPoint display fidelity', () => { }) it.each([0, 1])('keeps borderless ellipses borderless through repeated export/import with width=%s', async (borderWidth) => { - let model = createBlankPresentationDocument('Borderless') + let model = createBlankPresentationProject('Borderless') model.slides.pages[0]!.elements = [{ id: 'circle', type: 'ellipse', x: 40, y: 40, width: 200, height: 100, rotation: 0, fill: '#745ADD', borderColor: 'transparent', borderWidth }] for (let count = 0; count < 2; count++) { @@ -351,28 +407,35 @@ describe('PowerPoint display fidelity', () => { } }) - it.each([false, true])('honors explicit no-fill strokes over theme line references, including SVG shapes=%s', async (svg) => { + it.each([false, true])('honors explicit no-fill strokes over theme line references, including gradient shapes=%s', async (gradient) => { let tree = shape(1, 100).replace('', ``) - if (svg) tree = tree.replace('', '') - const project = await readFixture(tree) + if (gradient) tree = tree.replace('', '') + let project = await readFixture(tree) const element = project.slides.pages[0]!.elements[0]! - if (svg) { - if (element.type !== 'image') throw new Error('Expected SVG image') - expect(atob(presentationElementSource(project, element)!.dataUrl.split(',')[1]!)).toContain('stroke-width="0"') - } else expect(element).toMatchObject({ borderColor: 'transparent', borderWidth: 0 }) + expect(element).toMatchObject({ type: 'rect', borderColor: 'transparent', borderWidth: 0 }) + if (gradient && element.type === 'rect') { + const expected = { + type: 'linear' as const, angle: 90, stops: [ + { offset: 0, color: '#FF0000', opacity: 1 }, + { offset: 1, color: '#0000FF', opacity: 1 }, + ], + } + expect(element.gradientFill).toEqual(expected) + project = await importPresentationPptx(await createPresentationPptx(project)) + expect(project.slides.pages[0]!.elements[0]).toMatchObject({ type: 'rect', gradientFill: expected }) + } }) it('preserves partially transparent strokes without fading the fill', async () => { const tree = shape(1, 100).replace('', '') - const project = await readFixture(tree) - const element = project.slides.pages[0]!.elements[0]! - if (element.type !== 'image') throw new Error('Expected SVG image') - const svg = atob(presentationElementSource(project, element)!.dataUrl.split(',')[1]!) - expect(svg).toContain('stroke-opacity="0.25"') - expect(svg).toContain('fill-opacity="1"') + let project = await readFixture(tree) + expect(project.slides.pages[0]!.elements[0]).toMatchObject({ type: 'rect', fill: '#FF0000', borderColor: '#000000', borderOpacity: 0.25 }) + expect(preview(project)).toContain('stroke-opacity="0.25"') + project = await importPresentationPptx(await createPresentationPptx(project)) + expect(project.slides.pages[0]!.elements[0]).toMatchObject({ type: 'rect', fill: '#FF0000', borderColor: '#000000', borderOpacity: 0.25 }) }) it('writes legal rich-text paragraphs, including soft breaks, blank paragraphs, and hyperlink relationships', async () => { - const model = createBlankPresentationDocument('Rich text') + const model = createBlankPresentationProject('Rich text') model.slides.pages[0]!.elements = [{ id: 'rich', type: 'text', text: 'First\nSecond\n\nThird', x: 40, y: 40, width: 500, height: 250, rotation: 0, fontSize: 32, fontFamily: 'Arial', fontWeight: 400, color: '#111111', align: 'left', @@ -428,6 +491,62 @@ describe('PowerPoint display fidelity', () => { expect(presentationTextStyleAt(text, 9).fontFamily).toBe('Courier New') }) + it('applies theme tint to an editable shape instead of using its unmodified scheme color', async () => { + const theme = `` + const style = '' + const tree = shape(1, 100, style).replace('', '') + const model = await readFixture(tree, undefined, undefined, { 'ppt/theme/theme1.xml': theme }) + expect(model.slides.pages[0]!.elements[0]).toMatchObject({ fill: '#9BB1CF' }) + }) + + it('resolves a grouped shape fill through the master color map', async () => { + const rel = (type: string, target: string) => `` + const extras = { + 'ppt/slides/_rels/slide1.xml.rels': rel('slideLayout', '../slideLayouts/slideLayout1.xml'), + 'ppt/slideLayouts/slideLayout1.xml': ``, + 'ppt/slideLayouts/_rels/slideLayout1.xml.rels': rel('slideMaster', '../slideMasters/slideMaster1.xml'), + 'ppt/slideMasters/slideMaster1.xml': ``, + 'ppt/slideMasters/_rels/slideMaster1.xml.rels': rel('theme', '../theme/theme1.xml'), + 'ppt/theme/theme1.xml': ``, + } + const child = shape(1, 100).replace('', '') + const tree = `${child}` + const model = await readFixture(tree, undefined, undefined, extras) + expect(model.slides.pages[0]!.elements[0]).toMatchObject({ type: 'rect', fill: '#4B778B' }) + expect(preview(model)).toContain('fill="#4B778B"') + const reopened = await importPresentationPptx(await createPresentationPptx(model)) + expect(reopened.slides.pages[0]!.elements[0]).toMatchObject({ fill: '#4B778B' }) + }) + + it('keeps an OLE object picture fallback visible as an editable image', async () => { + const tree = `` + const extras = { + 'ppt/slides/_rels/slide1.xml.rels': '', + 'ppt/media/preview.svg': '', + } + const bytes = await fixtureBytes(tree, undefined, undefined, extras) + const model = await importPresentationPptx(bytes) + expect(model.slides.pages[0]!.elements[0]).toMatchObject({ type: 'image', x: 100, y: 80, width: 400, height: 300, fit: 'stretch' }) + const sources = await presentationPptxSourceUrls(model, Buffer.from(bytes).toString('base64')) + const markup = renderToStaticMarkup() + expect(markup).toContain('data:image/svg+xml;base64,') + const reopened = await importPresentationPptx(await createPresentationPptx(await materializePresentationProjectSources(model, sources))) + expect(reopened.slides.pages[0]!.elements[0]).toMatchObject({ type: 'image', x: 100, y: 80 }) + }) + + it('lets a shape font reference override an inherited master default color', async () => { + const rel = (type: string, target: string) => `` + const extras = { + 'ppt/slides/_rels/slide1.xml.rels': rel('slideLayout', '../slideLayouts/slideLayout1.xml'), + 'ppt/slideLayouts/slideLayout1.xml': ``, + 'ppt/slideLayouts/_rels/slideLayout1.xml.rels': rel('slideMaster', '../slideMasters/slideMaster1.xml'), + 'ppt/slideMasters/slideMaster1.xml': ``, + } + const body = `${textBody('', '1')}` + const text = firstText(await readFixture(shape(1, 100, body), undefined, undefined, extras)) + expect(text.color).toBe('#FFFFFF') + }) + it.each(['0', 'false', '1'] as const)('honors showMasterSp="%s" on slides and layouts', async (flag) => { const rel = (type: string, target: string) => `` const extras = (layoutFlag: string) => ({ @@ -443,7 +562,7 @@ describe('PowerPoint display fidelity', () => { }) it('draws ellipse and round-rectangle previews at the same bounds and radii as the canvas', () => { - const model = createBlankPresentationDocument('Shapes') + const model = createBlankPresentationProject('Shapes') model.slides.pages[0]!.elements = ['ellipse', 'roundRect'].map((type, index) => ({ id: type, type: type as 'ellipse' | 'roundRect', x: index * 300, y: 0, width: 200, height: 100, rotation: 0, fill: '#FF0000', borderColor: 'transparent', borderWidth: 0, @@ -456,6 +575,30 @@ describe('PowerPoint display fidelity', () => { expect(Number(rounded.getAttribute('ry')) / 100 * 100).toBeCloseTo(12) }) + it('renders every native custom-geometry path without converting the shape to an image', () => { + const model = createBlankPresentationProject('Custom shape') + model.slides.pages[0]!.elements = [{ + id: 'custom', type: 'rect', x: 0, y: 0, width: 200, height: 100, rotation: 0, + fill: '#FF0000', borderColor: '#0000FF', borderWidth: 2, + customGeometry: { paths: [ + { width: 200, height: 100, fill: 'normal', stroke: true, commands: [ + { type: 'moveTo', x: 0, y: 0 }, { type: 'lineTo', x: 200, y: 100 }, + ] }, + { width: 20, height: 10, fill: 'none', stroke: false, commands: [ + { type: 'moveTo', x: 0, y: 10 }, { type: 'lineTo', x: 20, y: 0 }, + ] }, + ] }, + }] + + const xml = new DOMParser().parseFromString(preview(model), 'text/xml') + const paths = Array.from(xml.getElementsByTagName('path')) + expect(paths).toHaveLength(2) + expect(paths[0]!.getAttribute('d')).toBe('M 0 0 L 200 100') + expect(paths[0]!.getAttribute('transform')).toBe('scale(0.5 1)') + expect(paths[1]!.getAttribute('fill')).toBe('none') + expect(paths[1]!.getAttribute('stroke')).toBe('none') + }) + it('applies auto-fit font scale and subtracts percentage line-spacing reduction', async () => { const body = 'HeadingBody' const model = await readFixture(shape(1, 100, body)) @@ -543,8 +686,9 @@ describe('PowerPoint display fidelity', () => { model.assets.push({ id: 'asymmetric-image-asset', kind: 'image', + mimeType: 'image/png', name: 'image.png', - source: { dataUrl: 'data:image/png;base64,AA==', fileName: 'image.png', mimeType: 'image/png' }, + source: 'data:image/png;base64,AA==', }) model.slides.pages[0]!.elements = [{ ...base, type: 'image', flipHorizontal: true, flipVertical: true, fit: 'cover', sourceAssetId: 'asymmetric-image-asset', altText: 'asymmetric image', @@ -555,6 +699,8 @@ describe('PowerPoint display fidelity', () => { if (image.type !== 'image') throw new Error('Missing image') delete image.crop expect(preview(model)).toContain('translate(100px, 50px) scale(-1, -1)') + image.fit = 'stretch' + expect(preview(model)).toContain('object-fit:fill') }) it.each([['vert', 90], ['vert270', -90]] as const)('lays out %s text in a rotated inner frame', async (direction, angle) => { diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/presentationPptxImages.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/presentationPptxImages.test.ts index 1669e831..ba3acd16 100644 --- a/desktop/apps/electron/src/renderer/lib/__tests__/presentationPptxImages.test.ts +++ b/desktop/apps/electron/src/renderer/lib/__tests__/presentationPptxImages.test.ts @@ -1,9 +1,10 @@ import { describe, expect, it } from 'bun:test' import JSZip from 'jszip' import { DOMParser } from '@xmldom/xmldom' -import { createBlankPresentationDocument, createBlankPresentationSlide, type PresentationFileSource, type PresentationImageElement } from '@/atoms/presentation' +import { createBlankPresentationProject, createBlankPresentationSlide, type PresentationFileSource, type PresentationImageElement } from '@/atoms/presentation' import { createPresentationPptx } from '../presentationPptx' import { importPresentationPptx } from '../presentationPptxImport' +import { materializePresentationProjectSources, presentationPptxSourceUrls } from '@/presentation/sources' const pixel: PresentationFileSource = { dataUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Y9Z9N8AAAAASUVORK5CYII=', @@ -11,9 +12,9 @@ const pixel: PresentationFileSource = { mimeType: 'image/png', } -function picture(document: ReturnType, id: string, source = pixel): PresentationImageElement { +function picture(document: ReturnType, id: string, source = pixel): PresentationImageElement { const sourceAssetId = `${id}-asset` - document.assets.push({ id: sourceAssetId, kind: 'image', name: source.fileName, source }) + document.assets.push({ id: sourceAssetId, kind: 'image', mimeType: source.mimeType, name: source.fileName, source: source.dataUrl }) return { id, type: 'image', sourceAssetId, altText: id, fit: 'contain', x: 10, y: 20, width: 200, height: 100, rotation: 0 } } @@ -28,7 +29,7 @@ async function imageRelationships(archive: JSZip, slideNumber: number) { describe('PPTX shared image export', () => { it('deduplicates payloads across slides while keeping distinct images, frames, crops and links', async () => { const differentPixel = { ...pixel, dataUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLttAAAAABJRU5ErkJggg==' } - const document = createBlankPresentationDocument('Shared images') + const document = createBlankPresentationProject('Shared images') const first = document.slides.pages[0]! const second = createBlankPresentationSlide('Second') document.slides.pages.push(second) @@ -73,7 +74,7 @@ describe('PPTX shared image export', () => { }) it('keeps repeated save and reopen cycles compact after editing an imported deck', async () => { - const document = createBlankPresentationDocument('Shared backgrounds') + const document = createBlankPresentationProject('Shared backgrounds') document.slides.pages = Array.from({ length: 30 }, (_, index) => ({ ...createBlankPresentationSlide(`Page ${index + 1}`), elements: [picture(document, `image-${index}`)] })) document.slides.selectedPageId = document.slides.pages[0]!.id let bytes = await createPresentationPptx(document) @@ -82,7 +83,8 @@ describe('PPTX shared image export', () => { const imported = await importPresentationPptx(bytes, 'shared.pptx') imported.slides.pages[29]!.notes = `Edit ${cycle}` imported.slides.pages[29]!.elements[0]!.x = 120 + cycle - bytes = await createPresentationPptx(imported) + const sources = await presentationPptxSourceUrls(imported, Buffer.from(bytes).toString('base64')) + bytes = await createPresentationPptx(await materializePresentationProjectSources(imported, sources)) const archive = await JSZip.loadAsync(bytes) const media = Object.keys(archive.files).filter((name) => name.startsWith('ppt/media/') && !name.endsWith('/')) expect(media).toHaveLength(1) @@ -99,7 +101,7 @@ describe('PPTX shared image export', () => { const svg = (color: string): PresentationFileSource => ({ dataUrl: `data:image/svg+xml;base64,${btoa(``)}`, fileName: 'shape.svg', mimeType: 'image/svg+xml' }) const red = svg('red') const blue = svg('blue') - const document = createBlankPresentationDocument('SVG sharing') + const document = createBlankPresentationProject('SVG sharing') document.slides.pages[0]!.elements = [picture(document, 'red', red), picture(document, 'blue', blue)] document.slides.pages.push({ ...createBlankPresentationSlide('Scaled SVG'), elements: [{ ...picture(document, 'scaled-red', { ...red }), width: 400, height: 300 }] }) const archive = await JSZip.loadAsync(await createPresentationPptx(document)) diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/presentationPptxImport.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/presentationPptxImport.test.ts index 96a37514..0f15f021 100644 --- a/desktop/apps/electron/src/renderer/lib/__tests__/presentationPptxImport.test.ts +++ b/desktop/apps/electron/src/renderer/lib/__tests__/presentationPptxImport.test.ts @@ -1,19 +1,154 @@ import { describe, expect, it } from 'bun:test' +import { DOMParser } from '@xmldom/xmldom' import JSZip from 'jszip' -import { PRESENTATION_PAGE_SIZES, type PresentationDocument, type PresentationFileSource } from '@/atoms/presentation' -import { createPresentationTestDocument as createInitialPresentationDocument } from '@/test-fixtures/presentation' +import { PRESENTATION_PAGE_SIZES, type PresentationProject, type PresentationFileSource } from '@/atoms/presentation' +import { createPresentationTestDocument as createInitialPresentationProject } from '@/test-fixtures/presentation' import { createPresentationPptx } from '../presentationPptx' import { normalizePresentationProject, presentationElementSource } from '@/presentation/project' -import { validatePresentationDocument } from '@/presentation/model/reducer' +import { validatePresentationProject } from '@/presentation/model/reducer' +import { materializePresentationProjectSources, presentationPptxSourceUrls } from '@/presentation/sources' -function addImageAsset(document: PresentationDocument, id: string, source: PresentationFileSource): void { - document.assets.push({ id, kind: 'image', name: source.fileName, source }) +function addImageAsset(document: PresentationProject, id: string, source: PresentationFileSource): void { + document.assets.push({ id, kind: 'image', mimeType: source.mimeType, name: source.fileName, source: source.dataUrl }) } describe('importPresentationPptx', () => { + it('inherits placeholder frames through empty layouts and matches master placeholders by type rather than index', async () => { + const { importPresentationPptx } = await import('../presentationPptxImport') + const source = createInitialPresentationProject() + source.slides.pages[0]!.elements = [] + const archive = await JSZip.loadAsync(await createPresentationPptx(source)) + const placeholder = (id: number, type: string, index: number, properties: string, text = '') => `${properties}${text}` + for (const [path, shapes] of [ + ['ppt/slideMasters/slideMaster1.xml', placeholder(2, 'title', 31, '') + placeholder(3, 'body', 42, '')], + ['ppt/slideLayouts/slideLayout1.xml', placeholder(2, 'title', 0, '') + placeholder(3, 'body', 1, '')], + ['ppt/slides/slide1.xml', placeholder(2, 'title', 0, '', 'Title') + placeholder(3, '', 1, '', 'Body')], + ] as const) { + const xml = await archive.file(path)!.async('text') + archive.file(path, xml.replace('', `${shapes}`)) + } + const imported = await importPresentationPptx(await archive.generateAsync({ type: 'uint8array' })) + const title = imported.slides.pages[0]!.elements.find((element) => element.type === 'text' && element.text === 'Title')! + const body = imported.slides.pages[0]!.elements.find((element) => element.type === 'text' && element.text === 'Body')! + expect(title.width).toBeGreaterThan(imported.pageSize!.width * 0.5) + expect(body.width).toBe(title.width) + expect(body.y).toBeGreaterThan(title.y + title.height) + expect(body.x).toBeGreaterThan(title.x) + }) + it('keeps an explicitly non-bold table header non-bold after native PPTX export', async () => { + const { importPresentationPptx } = await import('../presentationPptxImport') + const source = createInitialPresentationProject() + source.slides.pages[0]!.elements = [{ + id: 'plain-header-table', type: 'table', x: 80, y: 80, width: 400, height: 160, rotation: 0, + cells: [['Plain heading'], ['Body'], ['']], cellStyles: [[{ bold: false }], [{}], [{ bold: false, textColor: '#FF0000' }]], + headerRow: true, headerFill: '#FFFFFF', bodyFill: '#FFFFFF', textColor: '#000000', borderColor: '#333333', fontSize: 20, + }] + const bytes = await createPresentationPptx(source) + const xml = await (await JSZip.loadAsync(bytes)).file('ppt/slides/slide1.xml')!.async('text') + expect(xml).toMatch(/]*b="0"[^>]*>/) + const imported = await importPresentationPptx(bytes) + const table = imported.slides.pages[0]!.elements[0] + if (table?.type !== 'table') throw new Error('Missing imported table') + expect(table.cellStyles?.[0]?.[0]?.bold).toBe(false) + expect(table.cellStyles?.[2]?.[0]).toMatchObject({ bold: false, textColor: '#FF0000' }) + expect(validatePresentationProject(imported)).toBe(imported) + }) + + it('preserves independent table cell borders through native PPTX export and import', async () => { + const { importPresentationPptx } = await import('../presentationPptxImport') + const source = createInitialPresentationProject() + source.slides.pages[0]!.elements = [{ + id: 'border-table', type: 'table', x: 80, y: 80, width: 400, height: 160, rotation: 0, + cells: [['Border']], cellStyles: [[{ borders: { + top: { color: '#FF0000', width: 4, type: 'solid' }, + right: { color: '#0000FF', width: 2, type: 'dash' }, + bottom: { color: '#00AA00', width: 1, type: 'solid' }, + left: { color: 'transparent', width: 0, type: 'none' }, + } }]], + headerRow: false, headerFill: '#FFFFFF', bodyFill: '#FFFFFF', textColor: '#000000', borderColor: '#333333', fontSize: 20, + }] + const bytes = await createPresentationPptx(source) + const xml = await (await JSZip.loadAsync(bytes)).file('ppt/slides/slide1.xml')!.async('text') + expect(xml).toContain('FF0000') + expect(xml).toContain('0000FF') + expect(xml).toContain('00AA00') + const imported = await importPresentationPptx(bytes) + const table = imported.slides.pages[0]!.elements[0] + if (table?.type !== 'table') throw new Error('Missing imported table') + const borders = table.cellStyles?.[0]?.[0]?.borders + expect(borders?.top).toMatchObject({ color: '#FF0000', width: 4, type: 'solid' }) + expect(borders?.right).toMatchObject({ color: '#0000FF', width: 2, type: 'dash' }) + expect(borders?.bottom).toMatchObject({ color: '#00AA00', width: 1, type: 'solid' }) + expect(borders?.left).toMatchObject({ width: 0, type: 'none' }) + expect(validatePresentationProject(imported)).toBe(imported) + }) + + it('keeps mixed formatting within an editable table cell through native PPTX round trips', async () => { + const { importPresentationPptx } = await import('../presentationPptxImport') + const source = createInitialPresentationProject() + source.slides.pages[0]!.elements = [{ + id: 'rich-table', type: 'table', x: 80, y: 80, width: 500, height: 180, rotation: 0, + cells: [['Red Blue']], + cellStyles: [[{ textRuns: [ + { start: 0, end: 4, style: { color: '#FF0000', fontWeight: 700, fontSize: 24 } }, + { start: 4, end: 8, style: { color: '#0000FF', italic: true, fontSize: 16 } }, + ] }]], + headerRow: false, headerFill: '#FFFFFF', bodyFill: '#FFFFFF', textColor: '#000000', borderColor: '#333333', fontSize: 20, + }] + const bytes = await createPresentationPptx(source) + const xml = await (await JSZip.loadAsync(bytes)).file('ppt/slides/slide1.xml')!.async('text') + expect(xml).toContain('val="FF0000"') + expect(xml).toContain('val="0000FF"') + const imported = await importPresentationPptx(bytes) + const table = imported.slides.pages[0]!.elements[0] + if (table?.type !== 'table') throw new Error('Missing imported table') + expect(table.cells).toEqual([['Red Blue']]) + expect(table.cellStyles?.[0]?.[0]?.textRuns).toMatchObject([ + { start: 0, end: 4, style: { color: '#FF0000', fontWeight: 700 } }, + { start: 4, end: 8, style: { color: '#0000FF', italic: true } }, + ]) + expect(validatePresentationProject(imported)).toBe(imported) + }) + + it('keeps uneven table grids, merged cells and individual cell formatting editable across export and import', async () => { + const { importPresentationPptx } = await import('../presentationPptxImport') + const source = createInitialPresentationProject() + source.slides.pages[0]!.elements = [{ + id: 'complex-table', type: 'table', x: 100, y: 100, width: 600, height: 300, rotation: 0, + cells: [['Merged', '', 'Top'], ['', '', 'Middle'], ['A', 'B', 'C']], + columnWidths: [1, 2, 3], rowHeights: [1, 2, 3], + cellStyles: [ + [{ colSpan: 2, rowSpan: 2, fill: '#FF0000', textColor: '#FFFFFF', fontSize: 28, bold: true, align: 'center', + padding: { left: 2, right: 4, top: 6, bottom: 8 } }, { covered: true }, { fill: '#00FF00' }], + [{ covered: true }, { covered: true }, { fill: '#0000FF' }], + [{ fill: '#FFFF00' }, { fill: '#00FFFF' }, { fill: '#FF00FF' }], + ], + headerRow: false, headerFill: '#FFFFFF', bodyFill: '#FFFFFF', textColor: '#000000', borderColor: '#333333', fontSize: 16, + }] + const bytes = await createPresentationPptx(source) + const archive = await JSZip.loadAsync(bytes) + const slideXml = await archive.file('ppt/slides/slide1.xml')!.async('text') + expect(slideXml).toContain('gridSpan="2"') + expect(slideXml).toContain('rowSpan="2"') + const imported = await importPresentationPptx(bytes) + const table = imported.slides.pages[0]!.elements[0] + expect(table).toMatchObject({ type: 'table', cells: [['Merged', '', 'Top'], ['', '', 'Middle'], ['A', 'B', 'C']] }) + if (table?.type !== 'table') throw new Error('Missing imported table') + if (!table.columnWidths || !table.rowHeights) throw new Error('Missing imported table grid') + expect(table.columnWidths[1]! / table.columnWidths[0]!).toBeCloseTo(2, 2) + expect(table.rowHeights[2]! / table.rowHeights[0]!).toBeCloseTo(3, 2) + expect(table.cellStyles?.[0]?.[0]).toMatchObject({ colSpan: 2, rowSpan: 2, fill: '#FF0000', textColor: '#FFFFFF', bold: true, align: 'center' }) + expect(table.cellStyles?.[0]?.[0]?.padding?.left).toBeCloseTo(2, 1) + expect(table.cellStyles?.[0]?.[0]?.padding?.bottom).toBeCloseTo(8, 1) + expect(table.cellStyles?.[0]?.[1]).toMatchObject({ covered: true }) + expect(table.cellStyles?.[1]?.[0]).toMatchObject({ covered: true }) + expect(table.cellStyles?.[2]?.[1]).toMatchObject({ fill: '#00FFFF' }) + expect(validatePresentationProject(imported)).toBe(imported) + }) + it('preserves the editable master and footer through repeated save and reopen cycles', async () => { const { importPresentationPptx } = await import('../presentationPptxImport') - const source = normalizePresentationProject(createInitialPresentationDocument()) + const source = normalizePresentationProject(createInitialPresentationProject()) source.theme.footer = { text: 'Confidential', showDate: true, showSlideNumber: true } source.theme.bodyFontFamily = 'Arial' source.theme.titleFontFamily = 'Georgia' @@ -22,26 +157,26 @@ describe('importPresentationPptx', () => { document = await importPresentationPptx(await createPresentationPptx(document), 'Report.pptx', { restoreEditorModel: true }) expect(document.theme).toEqual(source.theme) expect(document.slides.pages).toEqual(source.slides.pages) - expect(document.sourceProtected).toBe(false) + expect(document).not.toHaveProperty('sourceProtected') document.slides.pages[0]!.notes = `Edited note ${cycle}` source.slides.pages[0]!.notes = `Edited note ${cycle}` } }) - it('invalidates its embedded model after an external edit and protects that source', async () => { + it('invalidates its embedded model after an external edit without adding host metadata', async () => { const { importPresentationPptx } = await import('../presentationPptxImport') - const source = createInitialPresentationDocument() + const source = createInitialPresentationProject() const archive = await JSZip.loadAsync(await createPresentationPptx(source)) const slide = archive.file('ppt/slides/slide1.xml')! archive.file(slide.name, (await slide.async('string')).replace(/[^<]*<\/a:t>/, 'Externally corrected')) const imported = await importPresentationPptx(await archive.generateAsync({ type: 'uint8array' }), 'Report.pptx', { restoreEditorModel: true }) expect(JSON.stringify(imported.slides.pages)).toContain('Externally corrected') - expect(imported.sourceProtected).toBe(true) + expect(imported).not.toHaveProperty('sourceProtected') }) it('falls back to native PPTX content when a matching embedded model is invalid', async () => { const { importPresentationPptx } = await import('../presentationPptxImport') - const source = createInitialPresentationDocument() + const source = createInitialPresentationProject() const archive = await JSZip.loadAsync(await createPresentationPptx(source)) const modelFile = archive.file('bridgic/editor-model.json')! const envelope = JSON.parse(await modelFile.async('string')) as Record @@ -57,7 +192,7 @@ describe('importPresentationPptx', () => { ) expect(imported.slides.pages.length).toBeGreaterThan(0) expect(JSON.stringify(imported.slides.pages)).toContain('Primary message') - expect(imported.sourceProtected).toBe(true) + expect(imported).not.toHaveProperty('sourceProtected') expect(warnings[0]?.[0]).toContain('Ignoring an invalid embedded editor model') } finally { console.warn = originalWarn @@ -66,7 +201,7 @@ describe('importPresentationPptx', () => { it('shares a master image across slides and preserves sharing through worker transfer', async () => { const { importPresentationPptx } = await import('../presentationPptxImport') - const source = createInitialPresentationDocument() + const source = createInitialPresentationProject() const second = structuredClone(source.slides.pages[0]!) second.id = 'second-slide' source.slides.pages = [source.slides.pages[0]!, second] @@ -81,19 +216,21 @@ describe('importPresentationPptx', () => { const rels = archive.file('ppt/slideMasters/_rels/slideMaster1.xml.rels')! archive.file(rels.name, (await rels.async('text')).replace('', '')) archive.file('ppt/media/shared.png', new Uint8Array([137, 80, 78, 71])) - const imported = structuredClone(await importPresentationPptx(await archive.generateAsync({ type: 'uint8array' }))) + const bytes = await archive.generateAsync({ type: 'uint8array' }) + const imported = structuredClone(await importPresentationPptx(bytes)) + const sources = await presentationPptxSourceUrls(imported, Buffer.from(bytes).toString('base64')) const images = imported.slides.pages.map((slide) => slide.elements[0]!) expect(images).toHaveLength(2) expect(images.every((element) => element.type === 'image')).toBe(true) if (images[0]!.type !== 'image' || images[1]!.type !== 'image') throw new Error('Missing background') expect(images[0]!.sourceAssetId).toBe(images[1]!.sourceAssetId) - expect(presentationElementSource(imported, images[0]!)!.dataUrl).toBe('data:image/png;base64,iVBORw==') + expect(presentationElementSource(imported, images[0]!, sources)!.dataUrl).toBe('data:image/png;base64,iVBORw==') expect(images[0]!.id).not.toBe(images[1]!.id) }) it('preserves slide, layout and master background images behind foreground elements', async () => { const { importPresentationPptx } = await import('../presentationPptxImport') - const bytes = await createPresentationPptx(createInitialPresentationDocument()) + const bytes = await createPresentationPptx(createInitialPresentationProject()) const owners = ['slides/slide1.xml', 'slideLayouts/slideLayout1.xml', 'slideMasters/slideMaster1.xml'] for (const owner of owners) { const archive = await JSZip.loadAsync(bytes) @@ -109,18 +246,42 @@ describe('importPresentationPptx', () => { archive.file(rels.name, (await rels.async('text')).replace('', '')) archive.file('ppt/media/template-background.png', new Uint8Array([137, 80, 78, 71])) - const imported = await importPresentationPptx(await archive.generateAsync({ type: 'uint8array' })) + const modifiedBytes = await archive.generateAsync({ type: 'uint8array' }) + const imported = await importPresentationPptx(modifiedBytes) + const sources = await presentationPptxSourceUrls(imported, Buffer.from(modifiedBytes).toString('base64')) const first = imported.slides.pages[0]!.elements[0]! expect(first.type).toBe('image') if (first.type !== 'image') throw new Error('Background missing') - expect(presentationElementSource(imported, first)!.fileName).toBe('template-background.png') + expect(presentationElementSource(imported, first, sources)!.fileName).toBe('template-background.png') expect([first.x, first.y, first.width, first.height]).toEqual([0, 0, imported.pageSize.width, imported.pageSize.height]) expect(imported.slides.pages[0]!.elements.slice(1).some(element => element.type === 'text')).toBe(true) } }) + it('imports a master gradient background as an editable shape behind slide content', async () => { + const { importPresentationPptx } = await import('../presentationPptxImport') + const archive = await JSZip.loadAsync(await createPresentationPptx(createInitialPresentationProject())) + for (const part of ['slides/slide1.xml', 'slideLayouts/slideLayout1.xml', 'slideMasters/slideMaster1.xml']) { + const file = archive.file(`ppt/${part}`)! + archive.file(file.name, (await file.async('text')).replace(/.*?<\/p:bg>/s, '')) + } + const master = archive.file('ppt/slideMasters/slideMaster1.xml')! + const background = '' + archive.file(master.name, (await master.async('text')).replace(/(]*>)/, `$1${background}`)) + const imported = await importPresentationPptx(await archive.generateAsync({ type: 'uint8array' })) + const first = imported.slides.pages[0]!.elements[0]! + expect(first).toMatchObject({ + type: 'rect', x: 0, y: 0, width: imported.pageSize.width, height: imported.pageSize.height, + gradientFill: { type: 'radial', path: 'circle', fillToRect: { left: 0.5, top: 0.5, right: 0.5, bottom: 0.5 } }, + }) + if (first.type !== 'rect' || !first.gradientFill) throw new Error('Gradient background missing') + first.gradientFill.stops[1]!.color = '#E9DDCC' + const reopened = await importPresentationPptx(await createPresentationPptx(imported)) + expect(reopened.slides.pages[0]!.elements[0]).toMatchObject({ gradientFill: first.gradientFill }) + }) + it('round-trips editable slides, geometry, notes and page size', async () => { - const source = createInitialPresentationDocument() + const source = createInitialPresentationProject() source.theme.accentColors = ['#123456', '#ABCDEF', '#CC5500', '#118844', '#663399', '#DDCC22'] source.theme.background = '#112233' source.theme.bodyFontFamily = 'Arial' @@ -152,7 +313,7 @@ describe('importPresentationPptx', () => { }) it('imports only the requested source slides for lightweight template previews', async () => { - const source = createInitialPresentationDocument() + const source = createInitialPresentationProject() const first = source.slides.pages[0]! const second = structuredClone(first) second.id = 'preview-slide-2' @@ -174,7 +335,7 @@ describe('importPresentationPptx', () => { }) it('cleans omitted page links and assets when restoring a page subset', async () => { - const source = createInitialPresentationDocument() + const source = createInitialPresentationProject() const [first, second] = source.slides.pages const firstText = first!.elements.find((element) => element.type === 'text')! firstText.hyperlink = { type: 'slide', slideId: second!.id } @@ -203,11 +364,11 @@ describe('importPresentationPptx', () => { expect(imported.slides.pages).toHaveLength(1) expect(imported.slides.pages[0]!.elements.find((element) => element.id === firstText.id)).not.toHaveProperty('hyperlink') expect(imported.assets.map((asset) => asset.id)).toEqual(['retained-asset']) - expect(validatePresentationDocument(imported)).toBe(imported) + expect(validatePresentationProject(imported)).toBe(imported) }) it('preserves mixed shape-picture z-order, source crop and text-box layout', async () => { - const source = createInitialPresentationDocument() + const source = createInitialPresentationProject() const slide = source.slides.pages[0]! source.slides.pages = [slide] source.slides.selectedPageId = slide.id @@ -283,7 +444,7 @@ describe('importPresentationPptx', () => { }) it('keeps color-keyed pictures visible and preserves picture mirroring', async () => { - const source = createInitialPresentationDocument() + const source = createInitialPresentationProject() const slide = source.slides.pages[0]! source.slides.pages = [slide] source.slides.selectedPageId = slide.id @@ -327,8 +488,85 @@ describe('importPresentationPptx', () => { } }) + it('keeps an imported picture stretched to its non-square frame', async () => { + const source = createInitialPresentationProject() + const slide = source.slides.pages[0]! + source.slides.pages = [slide] + source.slides.selectedPageId = slide.id + addImageAsset(source, 'square-picture', { + dataUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Y9Z9N8AAAAASUVORK5CYII=', + fileName: 'square.png', mimeType: 'image/png', + }) + slide.elements = [{ + id: 'stretched-picture', type: 'image', sourceAssetId: 'square-picture', + x: 20, y: 30, width: 200, height: 100, rotation: 0, altText: '', fit: 'stretch', + }] + const { importPresentationPptx } = await import('../presentationPptxImport') + const bytes = await createPresentationPptx(source) + const imported = await importPresentationPptx(bytes, 'stretched.pptx') + expect(imported.slides.pages[0]!.elements.find(element => element.type === 'image')).toMatchObject({ + type: 'image', fit: 'stretch', width: 200, height: 100, + }) + const urls = await presentationPptxSourceUrls(imported, Buffer.from(bytes).toString('base64')) + const reopened = await importPresentationPptx( + await createPresentationPptx(await materializePresentationProjectSources(imported, urls)), + 'stretched-round-trip.pptx', + ) + expect(reopened.slides.pages[0]!.elements.find(element => element.type === 'image')).toMatchObject({ type: 'image', fit: 'stretch' }) + }) + + it('keeps an editable patterned shape through native PPTX import and export', async () => { + const source = createInitialPresentationProject() + const slide = source.slides.pages[0]! + source.slides.pages = [slide] + source.slides.selectedPageId = slide.id + const patternFill = { + preset: 'wdUpDiag', foregroundColor: '#F8FCFE', foregroundOpacity: 1, + backgroundColor: '#FFFFFF', backgroundOpacity: 1, + } + slide.elements = [{ + id: 'patterned-card', type: 'roundRect', x: 40, y: 50, width: 700, height: 360, rotation: 0, + fill: '#FFFFFF', borderColor: 'transparent', borderWidth: 0, + patternFill, + }] + const { importPresentationPptx } = await import('../presentationPptxImport') + const bytes = await createPresentationPptx(source) + const imported = await importPresentationPptx(bytes, 'patterned.pptx') + expect(imported.slides.pages[0]!.elements[0]).toMatchObject({ + type: 'roundRect', fill: '#FFFFFF', patternFill, + }) + const reopenedBytes = await createPresentationPptx(imported) + const reopenedXml = await (await JSZip.loadAsync(reopenedBytes)).file('ppt/slides/slide1.xml')!.async('text') + expect(reopenedXml).toContain('') + expect((await importPresentationPptx(reopenedBytes, 'patterned-again.pptx')).slides.pages[0]!.elements[0]).toMatchObject({ + type: 'roundRect', patternFill, + }) + }) + + it('preserves an Office radial gradient path and fill rectangle', async () => { + const source = createInitialPresentationProject() + const slide = source.slides.pages[0]! + source.slides.pages = [slide] + source.slides.selectedPageId = slide.id + slide.elements = [{ + id: 'radial-card', type: 'ellipse', x: 30, y: 40, width: 300, height: 300, rotation: 0, + fill: '#FFFFFF', borderColor: 'transparent', borderWidth: 0, + gradientFill: { type: 'radial', path: 'circle', fillToRect: { left: 0.5, top: 0.5, right: 0.5, bottom: 0.5 }, stops: [ + { offset: 0, color: '#FFFFFF', opacity: 1 }, { offset: 1, color: '#004950', opacity: 1 }, + ] }, + }] + const { importPresentationPptx } = await import('../presentationPptxImport') + const exported = await createPresentationPptx(source) + const imported = await importPresentationPptx(exported, 'radial.pptx') + expect(imported.slides.pages[0]!.elements[0]).toMatchObject({ + type: 'ellipse', gradientFill: { type: 'radial', path: 'circle', fillToRect: { left: 0.5, top: 0.5, right: 0.5, bottom: 0.5 } }, + }) + const roundTrip = await JSZip.loadAsync(await createPresentationPptx(imported)) + expect(await roundTrip.file('ppt/slides/slide1.xml')!.async('text')).toContain('') + }) + it('imports an ellipse shape with a picture fill as a clipped image instead of its theme fallback color', async () => { - const source = createInitialPresentationDocument() + const source = createInitialPresentationProject() const slide = source.slides.pages[0]! source.slides.pages = [slide] source.slides.selectedPageId = slide.id @@ -362,29 +600,83 @@ describe('importPresentationPptx', () => { archive.file('ppt/slides/slide1.xml', slideXml.replace(picture!, pictureFilledEllipse)) const { importPresentationPptx } = await import('../presentationPptxImport') - const imported = await importPresentationPptx( - await archive.generateAsync({ type: 'uint8array' }), - 'picture-filled-shape.pptx', - ) + const bytes = await archive.generateAsync({ type: 'uint8array' }) + const imported = await importPresentationPptx(bytes, 'picture-filled-shape.pptx') + const sources = await presentationPptxSourceUrls(imported, Buffer.from(bytes).toString('base64')) const image = imported.slides.pages[0]!.elements[0] expect(image?.type).toBe('image') if (image?.type === 'image') { expect(image.clipShape).toBe('ellipse') - expect(presentationElementSource(imported, image)!.mimeType).toBe('image/png') - expect(presentationElementSource(imported, image)!.dataUrl).toStartWith('data:image/png;base64,') + expect(presentationElementSource(imported, image, sources)!.mimeType).toBe('image/png') + expect(presentationElementSource(imported, image, sources)!.dataUrl).toStartWith('data:image/png;base64,') expect(image.altText).toBe('landscape') } const reimported = await importPresentationPptx( - await createPresentationPptx(imported), + await createPresentationPptx(await materializePresentationProjectSources(imported, sources)), 'picture-filled-shape-round-trip.pptx', ) expect(reimported.slides.pages[0]!.elements[0]).toMatchObject({ type: 'image', clipShape: 'ellipse' }) }) + it('keeps imported picture effects and their embedded Office layer through export', async () => { + const source = createInitialPresentationProject() + const slide = source.slides.pages[0]! + source.slides.pages = [slide] + source.slides.selectedPageId = slide.id + addImageAsset(source, 'picture-asset', { + dataUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Y9Z9N8AAAAASUVORK5CYII=', + fileName: 'picture.png', mimeType: 'image/png', + }) + slide.elements = [{ id: 'picture', type: 'image', sourceAssetId: 'picture-asset', + x: 30, y: 40, width: 200, height: 150, rotation: 0, altText: '', fit: 'contain' }] + const archive = await JSZip.loadAsync(await createPresentationPptx(source)) + const slideFile = archive.file('ppt/slides/slide1.xml')! + const effect = '' + + '' + archive.file(slideFile.name, (await slideFile.async('text')).replace(/<\/a:blip>/, `${effect}`)) + const relationships = archive.file('ppt/slides/_rels/slide1.xml.rels')! + archive.file(relationships.name, (await relationships.async('text')).replace('', + '')) + archive.file('ppt/media/layer.wdp', new Uint8Array([0x49, 0x49, 0x42, 0x43])) + const bytes = await archive.generateAsync({ type: 'uint8array' }) + const { importPresentationPptx } = await import('../presentationPptxImport') + const imported = await importPresentationPptx(bytes, 'effects.pptx') + const asset = imported.assets.find(value => value.imageEffects)! + expect(asset).toBeDefined() + expect(asset.imageEffects).toMatchObject({ + colorChange: { from: '#FFFFFF', to: '#FFFFFF', opacity: 0 }, + officeLayer: { effects: [ + { type: 'backgroundRemoval', bounds: { top: 10, bottom: 90000, left: 20, right: 80000 }, + foregroundMarks: [{ x1: 1, y1: 2, x2: 3, y2: 4 }], backgroundMarks: [{ x1: 5, y1: 6, x2: 7, y2: 8 }] }, + { type: 'brightnessContrast', bright: 20000, contrast: -20000 }, + { type: 'colorTemperature', colorTemp: 4700 }, + ] }, + }) + expect(asset.imageEffects?.officeLayer?.source).toStartWith(`bridgic-pptx:${imported.id}/`) + const image = imported.slides.pages[0]!.elements.find(value => value.type === 'image')! + image.x += 20 + const brightness = asset.imageEffects?.officeLayer?.effects.find(value => value.type === 'brightnessContrast') + if (brightness?.type !== 'brightnessContrast') throw new Error('Brightness adjustment missing') + brightness.bright = 30000 + const urls = await presentationPptxSourceUrls(imported, Buffer.from(bytes).toString('base64')) + const exported = await createPresentationPptx(await materializePresentationProjectSources(imported, urls)) + const output = await JSZip.loadAsync(exported) + const outputXml = await output.file('ppt/slides/slide1.xml')!.async('text') + expect(outputXml).toContain('') + expect(outputXml).toContain('') + expect(outputXml).toContain('') + expect(outputXml).toContain('') + expect(Object.keys(output.files).some(path => path.endsWith('.wdp'))).toBe(true) + const reopened = await importPresentationPptx(exported, 'effects-export.pptx') + expect(reopened.assets.some(value => value.imageEffects?.officeLayer?.effects.length === 3)).toBe(true) + expect(reopened.slides.pages[0]!.elements.find(value => value.type === 'image')?.x).toBeCloseTo(image.x) + }) + it('imports East Asian vertical text and DrawingML preset colors', async () => { - const source = createInitialPresentationDocument() + const source = createInitialPresentationProject() const slide = source.slides.pages[0]! source.slides.pages = [slide] source.slides.selectedPageId = slide.id @@ -426,7 +718,7 @@ describe('importPresentationPptx', () => { }) it('prefers the East Asian run font for CJK text', async () => { - const source = createInitialPresentationDocument() + const source = createInitialPresentationProject() const slide = source.slides.pages[0]! source.slides.pages = [slide] source.slides.selectedPageId = slide.id @@ -463,8 +755,8 @@ describe('importPresentationPptx', () => { if (text?.type === 'text') expect(text.fontFamily).toBe('East Asian Font') }) - it('keeps custom geometry as a fidelity-preserving SVG object', async () => { - const source = createInitialPresentationDocument() + it('keeps custom geometry as a native editable shape through import and export', async () => { + const source = createInitialPresentationProject() const slide = source.slides.pages[0]! source.slides.pages = [slide] source.slides.selectedPageId = slide.id @@ -489,15 +781,37 @@ describe('importPresentationPptx', () => { const imported = await importPresentationPptx(await archive.generateAsync({ type: 'uint8array' }), 'custom-shape.pptx') const customShape = imported.slides.pages[0]!.elements[0] - expect(customShape?.type).toBe('image') - if (customShape?.type === 'image') { - expect(presentationElementSource(imported, customShape)!.mimeType).toBe('image/svg+xml') - expect(presentationElementSource(imported, customShape)!.dataUrl).toStartWith('data:image/svg+xml;base64,') - } + expect(customShape?.type).toBe('rect') + if (customShape?.type !== 'rect') throw new Error('Missing custom shape') + expect(customShape.customGeometry).toEqual({ + paths: [{ + width: 100, + height: 100, + fill: 'normal', + stroke: true, + commands: [ + { type: 'moveTo', x: 0, y: 0 }, + { type: 'lineTo', x: 100, y: 0 }, + { type: 'lineTo', x: 100, y: 8 }, + { type: 'lineTo', x: 0, y: 8 }, + { type: 'close' }, + ], + }], + }) + expect(imported.assets).toHaveLength(0) + + const exported = await JSZip.loadAsync(await createPresentationPptx(imported)) + const exportedSlide = new DOMParser().parseFromString(await exported.file('ppt/slides/slide1.xml')!.async('text'), 'text/xml') + const exportedShape = Array.from(exportedSlide.getElementsByTagName('p:sp')) + .find(shape => shape.getElementsByTagName('p:cNvPr')[0]?.getAttribute('name') === customShape.id) + expect(exportedShape?.getElementsByTagName('a:custGeom')).toHaveLength(1) + expect(Array.from(exportedShape!.getElementsByTagName('a:pt')).map(point => [point.getAttribute('x'), point.getAttribute('y')])).toEqual([ + ['0', '0'], ['100', '0'], ['100', '8'], ['0', '8'], + ]) }) it('imports an Office SVG extension when the picture has no raster fallback relationship', async () => { - const source = createInitialPresentationDocument() + const source = createInitialPresentationProject() const slide = source.slides.pages[0]! source.slides.pages = [slide] source.slides.selectedPageId = slide.id @@ -527,18 +841,20 @@ describe('importPresentationPptx', () => { expect(extensionOnly).toContain('svgBlip') archive.file('ppt/slides/slide1.xml', extensionOnly) const { importPresentationPptx } = await import('../presentationPptxImport') - const imported = await importPresentationPptx(await archive.generateAsync({ type: 'uint8array' }), 'svg-extension.pptx') + const bytes = await archive.generateAsync({ type: 'uint8array' }) + const imported = await importPresentationPptx(bytes, 'svg-extension.pptx') + const sources = await presentationPptxSourceUrls(imported, Buffer.from(bytes).toString('base64')) const image = imported.slides.pages[0]!.elements.find((element) => element.type === 'image') expect(image?.type).toBe('image') if (image?.type === 'image') { - expect(presentationElementSource(imported, image)!.mimeType).toBe('image/svg+xml') + expect(presentationElementSource(imported, image, sources)!.mimeType).toBe('image/svg+xml') expect(image.opacity).toBeCloseTo(0.1, 4) } }) it('imports common editable tables and charts', async () => { - const source = createInitialPresentationDocument() + const source = createInitialPresentationProject() const slide = source.slides.pages[0]! source.slides.pages = [slide] source.slides.selectedPageId = slide.id diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/presentationTable.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/presentationTable.test.ts new file mode 100644 index 00000000..2f5335f9 --- /dev/null +++ b/desktop/apps/electron/src/renderer/lib/__tests__/presentationTable.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from 'bun:test' +import { createPresentationTableElement } from '../presentationInsert' +import { presentationTableCellAppearance, presentationTableCellsPatch } from '../presentationTable' +import { resizePresentationProject } from '../presentationDesign' +import { createBlankPresentationProject } from '@/atoms/presentation' +import { editPresentationPage } from '@/presentation/agentCommands' + +describe('presentation table cell editing', () => { + it('keeps a transparent legacy border invisible on every side', () => { + const table = createPresentationTableElement([['Value']]) + table.borderColor = 'transparent' + expect(presentationTableCellAppearance(table, 0, 0).borders).toEqual({ + top: { color: 'transparent', width: 0, type: 'none' }, + right: { color: 'transparent', width: 0, type: 'none' }, + bottom: { color: 'transparent', width: 0, type: 'none' }, + left: { color: 'transparent', width: 0, type: 'none' }, + }) + }) + + it('keeps and scales an imported partial cell border when the page is resized', () => { + const project = createBlankPresentationProject('Border scale') + const table = createPresentationTableElement([['Value']]) + table.cellStyles = [[{ borders: { top: { color: '#FF0000', width: 4, type: 'solid' } } }]] + project.slides.pages[0]!.elements = [table] + const resized = resizePresentationProject(project, 'standard').slides.pages[0]!.elements[0] + if (resized?.type !== 'table') throw new Error('Missing resized table') + expect(resized.cellStyles?.[0]?.[0]?.borders).toEqual({ top: { color: '#FF0000', width: 3, type: 'solid' } }) + }) + + it('keeps formatting on unchanged cells and clears stale run ranges on edited text', () => { + const table = createPresentationTableElement([['Original', 'Keep']]) + table.cellStyles = [[ + { fill: '#FF0000', textRuns: [{ start: 0, end: 8, style: { color: '#FFFFFF' } }] }, + { fill: '#00FF00', textRuns: [{ start: 0, end: 4, style: { color: '#000000' } }] }, + ]] + const patch = presentationTableCellsPatch(table, [['Changed', 'Keep']]) + expect(patch.cells).toEqual([['Changed', 'Keep']]) + expect(patch.cellStyles?.[0]?.[0]).toEqual({ fill: '#FF0000' }) + expect(patch.cellStyles?.[0]?.[1]).toEqual(table.cellStyles[0]![1]!) + expect(table.cellStyles[0]![0]!.textRuns).toHaveLength(1) + }) + + it('lets Agent patches edit the table grid without retaining invalid text runs', () => { + const project = createBlankPresentationProject('Agent table') + const table = createPresentationTableElement([['Original']]) + table.cellStyles = [[{ textRuns: [{ start: 0, end: 8, style: { color: '#FF0000' } }] }]] + project.slides.pages[0]!.elements = [table] + const updated = editPresentationPage(project, project.slides.pages[0]!.id, [{ + type: 'patch', id: table.id, element_type: 'table', patch: { cells: [['New']], columnWidths: [1] }, + }]).project.slides.pages[0]!.elements[0] + if (updated?.type !== 'table') throw new Error('Missing edited table') + expect(updated.cells).toEqual([['New']]) + expect(updated.cellStyles?.[0]?.[0]?.textRuns).toBeUndefined() + expect(updated.columnWidths).toEqual([1]) + }) +}) diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/presentationWorkspaceRuntime.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/presentationWorkspaceRuntime.test.ts deleted file mode 100644 index b3448384..00000000 --- a/desktop/apps/electron/src/renderer/lib/__tests__/presentationWorkspaceRuntime.test.ts +++ /dev/null @@ -1,277 +0,0 @@ -import { describe, expect, it } from 'bun:test' -import { createStore } from 'jotai' -import { - createBlankPresentationDocument, - createBlankPresentationSlide, - presentationWorkspaceFamily, - replacePresentationPages, - selectPresentationPage, - type PresentationDocument, - type PresentationWorkspace, -} from '@/atoms/presentation' -import { activeSessionIdAtom } from '@/atoms/sessions' -import { createPresentationWorkspaceRuntime } from '../presentationWorkspaceRuntime' -import { createOfficeEditorBinding } from '../office/officeEditorBinding' -import type { PowerPointDispatchResult, PowerPointRequest } from '../powerPointProtocol' - -function setup() { - const first = createBlankPresentationDocument('First') - let workspace: PresentationWorkspace = { activeDocumentId: first.id, documents: [first] } - const controller = createPresentationWorkspaceRuntime({ - sessionId: 'session-a', - read: () => workspace, - write: (next) => { workspace = next }, - }) - const apply = async (dispatched: PowerPointDispatchResult) => { - if (dispatched.workspace) workspace = dispatched.workspace - } - const context = () => ({ currentTarget: null, fileName: 'First.pptx' }) - return { first, controller, apply, context, read: () => workspace } -} - -describe('presentation workspace runtime', () => { - it('imports concurrent opens of the same file once and preserves its edited document on another click', async () => { - let target: string | null = null - let imports = 0 - let finish!: () => void - const gate = new Promise((resolve) => { finish = resolve }) - const initial = createBlankPresentationDocument('Initial') - let workspace: PresentationWorkspace = { activeDocumentId: initial.id, documents: [initial] } - const context = () => ({ - currentTarget: target, fileName: 'Deck.pptx', - importPptx: async () => { imports++; await gate; return createBlankPresentationDocument('Imported deck') }, - }) - const apply = async (result: PowerPointDispatchResult) => { - if (result.target) target = result.target - if (result.workspace) workspace = result.workspace - } - const runtime = createPresentationWorkspaceRuntime({ sessionId: 'session-a', read: () => workspace, write: (next) => { workspace = next } }) - const request = { method: 'view_ppt', params: { target: '/tmp/Deck.pptx', file_name: 'Deck.pptx', content_base64: 'AQ==' } } as const - const first = runtime.dispatchProtocol(request, context, apply) - const second = runtime.dispatchProtocol(request, context, apply) - finish() - expect(await first).toMatchObject({ ok: true, value: { reused: false } }) - expect(await second).toMatchObject({ ok: true, value: { reused: true } }) - expect(imports).toBe(1) - expect(workspace.documents).toHaveLength(1) - const document = workspace.documents[0]! - runtime.commitDocument(document, { ...document, title: 'User edits' }) - expect(await runtime.dispatchProtocol(request, context, apply)).toMatchObject({ ok: true, value: { reused: true } }) - expect(workspace.documents[0]!.id).toBe(document.id) - expect(workspace.documents[0]!.title).toBe('User edits') - expect(imports).toBe(1) - }) - - it('reconciles native edits before an Agent page read without changing the v5 response', async () => { - const { controller, first, read, context, apply } = setup() - const binding = createOfficeEditorBinding({ appKind: 'presentation', sessionId: 'session-a', documentId: first.id }) - binding.attach({ - readSnapshot: () => read().documents[0]!, - flush: () => { - const current = read().documents[0]! - controller.commitDocument(current, { ...current, slides: replacePresentationPages(current.slides, current.slides.pages.map((slide) => ({ ...slide, notes: 'Uncommitted native text' }))) }) - }, - dispose: () => undefined, - }) - controller.bindEditor(binding) - const result = await controller.dispatchProtocol({ method: 'get_ppt_page', params: { page_id: first.slides.selectedPageId } }, context, apply) - expect(result).toMatchObject({ ok: true, value: { page: { has_content: true } } }) - expect(read().documents[0]!.slides.pages[0]!.notes).toBe('Uncommitted native text') - }) - - it('flushes the original native document before creating a new tab', async () => { - const { controller, first, read } = setup() - const binding = createOfficeEditorBinding({ appKind: 'presentation', sessionId: 'session-a', documentId: first.id }) - binding.attach({ readSnapshot: () => read().documents[0]!, flush: () => { - const current = read().documents[0]! - controller.commitDocument(current, { ...current, title: 'Native text kept before switching' }) - }, dispose: () => undefined }) - controller.bindEditor(binding) - const result = await controller.createDocument() - expect(result.ok).toBe(true) - expect(read().documents[0]!.title).toBe('Native text kept before switching') - expect(read().activeDocumentId).not.toBe(first.id) - }) - - it('keeps the current workspace when native composition prevents a tab change or close', async () => { - const { controller, first, read } = setup() - let composing = true - const binding = createOfficeEditorBinding({ appKind: 'presentation', sessionId: 'session-a', documentId: first.id }) - binding.attach({ readSnapshot: () => first, flush: () => { if (composing) throw new Error('Finish composing') }, dispose: () => undefined }) - controller.bindEditor(binding) - const previous = read() - expect(await controller.createDocument()).toMatchObject({ ok: false, error: { message: 'Finish composing' } }) - expect(await controller.closeDocument(first.id)).toMatchObject({ ok: false, error: { message: 'Finish composing' } }) - expect(read()).toBe(previous) - composing = false - expect((await controller.createDocument()).ok).toBe(true) - }) - - it.each(['create', 'activate', 'close', 'protocol'] as const)('does not apply %s after the workspace was disposed during native flush', async (operation) => { - const { controller, first, read, context, apply } = setup() - let release!: () => void - let flushing = false - const gate = new Promise((resolve) => { release = resolve }) - const binding = createOfficeEditorBinding({ appKind: 'presentation', sessionId: 'session-a', documentId: first.id }) - binding.attach({ readSnapshot: () => first, flush: async () => { flushing = true; await gate }, dispose: () => undefined }) - controller.bindEditor(binding) - const before = read() - const operations = { - create: () => controller.createDocument(), - activate: () => controller.activateDocument(first.id), - close: () => controller.closeDocument(first.id), - protocol: () => controller.dispatchProtocol({ method: 'view_ppt', params: { target: '/tmp/after-close.pptx', file_name: 'after-close.pptx' } }, context, apply), - } - const pending = operations[operation]() - await Promise.resolve() - expect(flushing).toBe(true) - controller.runtime.dispose() - release() - expect(await pending).toMatchObject({ ok: false }) - expect(read()).toBe(before) - }) - - it('rejects editor bindings owned by another Session', () => { - const { controller, first } = setup() - const binding = createOfficeEditorBinding({ appKind: 'presentation', sessionId: 'another-session', documentId: first.id }) - expect(() => controller.bindEditor(binding)).toThrow('another Session') - }) - - it('projects blank document identity and honest capabilities without owning another model', () => { - const { controller, first } = setup() - expect(controller.runtime.getSnapshot()).toMatchObject({ - appKind: 'presentation', sessionId: 'session-a', activeDocumentId: first.id, - documents: [{ id: first.id, title: 'First', revision: 1, dirty: true }], - }) - expect(controller.runtime.supports('document.create')).toBe(true) - expect(controller.runtime.supports('powerpoint.edit_ppt_page')).toBe(true) - expect(controller.runtime.supports('document.save')).toBe(true) - expect(controller.runtime.supports('document.undo')).toBe(false) - }) - - it('keeps native editing synchronous and rejects stale document commits', () => { - const { controller, first, read } = setup() - const revisions: number[] = [] - controller.runtime.subscribe((snapshot) => { revisions.push(snapshot.documents[0]!.revision) }) - const changed = controller.commitDocument(first, { ...first, title: 'Typed' }) - expect(read().documents[0]).toBe(changed) - expect(changed.revision).toBe(2) - expect(revisions).toEqual([2]) - expect(() => controller.commitDocument(first, { ...first, title: 'Stale' })).toThrow() - expect(read().documents[0]!.title).toBe('Typed') - }) - - it('does not count selecting a slide as a content revision', () => { - const { controller, first, read } = setup() - const nextSlide = createBlankPresentationSlide('Second') - const withSlide = controller.commitDocument(first, { ...first, slides: replacePresentationPages(first.slides, [...first.slides.pages, nextSlide]) }) - const selected = controller.commitDocument(withSlide, { ...withSlide, slides: selectPresentationPage(withSlide.slides, nextSlide.id) }, false) - expect(selected.revision).toBe(withSlide.revision) - expect(read().documents[0]!.slides.selectedPageId).toBe(nextSlide.id) - }) - - it('routes create, activate and close through the existing workspace and preserves final-tab close', async () => { - const { controller, first, read } = setup() - const created = await controller.createDocument() - if (!created.ok) throw new Error(created.error.message) - expect(read().documents).toHaveLength(2) - expect(read().activeDocumentId).toBe(created.value) - expect((await controller.activateDocument(first.id)).ok).toBe(true) - expect(read().activeDocumentId).toBe(first.id) - expect(await controller.closeDocument(first.id)).toEqual({ ok: true, value: { closeSurface: false } }) - expect(read().activeDocumentId).toBe(created.value) - const before = read() - expect(await controller.closeDocument(created.value)).toEqual({ ok: true, value: { closeSurface: true } }) - expect(read()).toBe(before) - expect(await controller.closeDocument('missing')).toMatchObject({ ok: false, error: { code: 'document_not_found' } }) - }) - - it('orders UI tab commands after an Agent command and its persistence acknowledgement', async () => { - const { controller, context, apply, read } = setup() - let release: () => void = () => undefined - const gate = new Promise((resolve) => { release = resolve }) - let saving = false - const opened = controller.dispatchProtocol({ - method: 'view_ppt', params: { target: '/tmp/queued.pptx', file_name: 'Queued.pptx' }, - }, context, async (dispatched) => { - await apply(dispatched) - saving = true - await gate - }) - const created = controller.createDocument() - await Promise.resolve() - await Promise.resolve() - expect(saving).toBe(true) - expect(read().documents).toHaveLength(1) - expect(read().documents[0]!.title).toBe('Queued') - release() - expect((await opened).ok).toBe(true) - expect((await created).ok).toBe(true) - expect(read().documents).toHaveLength(2) - }) - - it('preserves native edits made while an Agent command prepares its workspace', async () => { - const { controller, first, context, apply, read } = setup() - const pending = controller.dispatchProtocol({ - method: 'view_ppt', params: { target: '/tmp/open.pptx', file_name: 'Opened.pptx' }, - }, context, apply) - controller.commitDocument(first, { ...first, title: 'User edit' }) - expect(await pending).toMatchObject({ ok: false, code: 'document_changed' }) - expect(read().documents[0]!.title).toBe('User edit') - expect((await controller.createDocument()).ok).toBe(true) - }) - - it('keeps protocol v5 revision errors and compiler diagnostics unchanged', async () => { - const { controller, first, context, apply } = setup() - const stale = await controller.dispatchProtocol({ - method: 'insert_ppt_element', - params: { page_id: first.slides.selectedPageId, expected_revision: 'stale', element: 'Text' }, - }, context, apply) - expect(stale).toMatchObject({ ok: false, code: 'page_changed', error: expect.any(String) }) - const readPage = await controller.dispatchProtocol({ method: 'get_ppt_page', params: { page_id: first.slides.selectedPageId } }, context, apply) - if (!readPage.ok) throw new Error(readPage.error) - const revision = (readPage.value as { page: { revision: string } }).page.revision - const invalid = await controller.dispatchProtocol({ - method: 'insert_ppt_element', - params: { page_id: first.slides.selectedPageId, expected_revision: revision, element: '# Invalid element' }, - }, context, apply) - expect(invalid).toMatchObject({ ok: true, value: { status: 'invalid' } }) - expect(await controller.dispatchProtocol({ method: 'invented' } as unknown as PowerPointRequest, context, apply)) - .toEqual({ ok: false, error: 'Unsupported PowerPoint method: invented' }) - }) - - it('preserves a committed model on persistence failure and allows following commands', async () => { - const { controller, context, apply, read } = setup() - const failed = await controller.dispatchProtocol({ - method: 'view_ppt', params: { target: '/tmp/failure.pptx', file_name: 'Committed.pptx' }, - }, context, async (dispatched) => { - await apply(dispatched) - throw new Error('Disk unavailable') - }) - expect(failed).toEqual({ ok: false, error: 'Disk unavailable' }) - expect(read().documents[0]!.title).toBe('Committed') - expect((await controller.createDocument()).ok).toBe(true) - }) - - it('keeps queued work bound to its Session when main navigation changes', async () => { - const store = createStore() - store.set(activeSessionIdAtom, 'session-a') - const atom = presentationWorkspaceFamily('session-a') - const controller = createPresentationWorkspaceRuntime({ - sessionId: 'session-a', read: () => store.get(atom), write: (workspace) => store.set(atom, workspace), - }) - let release: () => void = () => undefined - const gate = new Promise((resolve) => { release = resolve }) - const blocking = controller.runtime.execute({ sessionId: 'session-a', capability: 'document.create' }, () => gate) - const pending = controller.createDocument() - store.set(activeSessionIdAtom, 'session-b') - const sessionB = store.get(presentationWorkspaceFamily('session-b')) - release() - await blocking - expect((await pending).ok).toBe(true) - expect(store.get(atom).documents).toHaveLength(2) - expect(store.get(presentationWorkspaceFamily('session-b'))).toBe(sessionB) - const other = store.get(atom).documents[0] as PresentationDocument - expect(() => controller.commitDocument(other, { ...other, title: 'Wrong active document' })).toThrow() - }) -}) diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/rendererRoots.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/rendererRoots.test.ts new file mode 100644 index 00000000..d3b448cd --- /dev/null +++ b/desktop/apps/electron/src/renderer/lib/__tests__/rendererRoots.test.ts @@ -0,0 +1,10 @@ +import { describe, expect, it } from 'bun:test' +import { readFileSync } from 'node:fs' + +describe('standalone renderer roots', () => { + it('gives every Office entry root the full viewport height', () => { + const css = readFileSync(new URL('../../index.css', import.meta.url), 'utf8') + + expect(css).toMatch(/html,\s*body,\s*#root,\s*#excel-root,\s*#word-root\s*\{[^}]*height:\s*100%/s) + }) +}) diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/tool-display.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/tool-display.test.ts index 7131a2ba..824e638c 100644 --- a/desktop/apps/electron/src/renderer/lib/__tests__/tool-display.test.ts +++ b/desktop/apps/electron/src/renderer/lib/__tests__/tool-display.test.ts @@ -191,26 +191,27 @@ describe('toolLabel — 已登记工具族(spec 驱动)', () => { // Preserve unmapped enum values instead of dropping them. expect(toolLabel('generic', 'browser_scroll', { direction: 'sideways' }).subject).toBe('sideways') }) - it('PPT 工具显示页面级动作和稳定页 id', () => { - expect(toolLabel('generic', 'view_ppt', { target: 'decks/review.pptx' })).toEqual({ + it('PPT 工具显示精简事务和渲染动作', () => { + expect(toolLabel('generic', 'ppt_open', { target: 'decks/review.pptx' })).toEqual({ verb: '打开 PPT', subject: 'review.pptx', subjectFull: 'decks/review.pptx', }) - expect(toolLabel('generic', 'edit_ppt_page', { page_id: 'page-2', ref: 'title' })).toEqual({ + expect(toolLabel('generic', 'ppt_edit_page', { document_id: 'deck', page_id: 'page-2', operations: [] })).toEqual({ verb: '编辑 PPT 页', subject: 'page-2', subjectMono: true, }) - expect(toolMeta('generic', 'edit_ppt_page', { page_id: 'page-2', ref: 'title' }, '').detail).toBe('title') - expect(toolLabel('generic', 'update_ppt_design', { theme: 'midnight' })).toEqual({ - verb: '更新 PPT 设计', - subject: 'midnight', + expect(toolLabel('generic', 'ppt_inspect', { document_id: 'deck', query: { kind: 'render', page_ids: ['page-2'] } })).toEqual({ + verb: '渲染 PPT', + subject: 'deck', + subjectMono: true, + }) + expect(toolLabel('generic', 'ppt_save', { document_id: 'deck' })).toEqual({ + verb: '保存 PPT', + subject: 'deck', + subjectFull: 'deck', }) - expect(toolMeta('generic', 'move_ppt_page', { - page_id: 'page-2', - target_page_id: 'page-4', - }, '').detail).toBe('page-4') }) it('无参工具只显示动词', () => { expect(toolLabel('generic', 'workspace_status', {})).toEqual({ verb: '查看工作区状态', subject: '' }) diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/wordDocxImport.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/wordDocxImport.test.ts index 8acb1fec..653e5b2e 100644 --- a/desktop/apps/electron/src/renderer/lib/__tests__/wordDocxImport.test.ts +++ b/desktop/apps/electron/src/renderer/lib/__tests__/wordDocxImport.test.ts @@ -1,9 +1,61 @@ import { describe, expect, it } from 'bun:test' import { resolve } from 'node:path' +import JSZip from 'jszip' import { importDocxToHtml } from '../wordDocxImport' describe('importDocxToHtml', () => { + it('retains simple and complex page fields even without cached results', async () => { + const fixture = resolve(import.meta.dir, '../../../../../../node_modules/mammoth/test/test-data/single-paragraph.docx') + const archive = await JSZip.loadAsync(await Bun.file(fixture).arrayBuffer()) + archive.file('word/document.xml', '') + archive.file('word/_rels/document.xml.rels', '') + archive.file('word/footer.xml', ' of NUMPAGES ') + const imported = await importDocxToHtml(await archive.generateAsync({ type: 'uint8array' })) + expect(imported.layout?.headerFooter.footerHtml).toBe('

1 of 1

') + expect(imported.warnings).toEqual([]) + }) + + it.each(['', '0', 'false', 'off'] as const)('imports all header/footer variants and respects OOXML on/off values (%s)', async (value) => { + const fixture = resolve(import.meta.dir, '../../../../../../node_modules/mammoth/test/test-data/single-paragraph.docx') + const archive = await JSZip.loadAsync(await Bun.file(fixture).arrayBuffer()) + const parts = (['header', 'footer'] as const).flatMap((kind) => (['default', 'first', 'even'] as const).map((variant) => ({ kind, variant, id: `${kind}-${variant}` }))) + const flag = value ? ` w:val="${value}"` : '' + archive.file('word/document.xml', `${parts.map(({ kind, variant, id }) => ``).join('')}`) + archive.file('word/_rels/document.xml.rels', `${parts.map(({ kind, id }) => ``).join('')}`) + for (const { kind, id } of parts) archive.file(`word/${id}.xml`, `${id}`) + archive.file('word/config/settings.xml', ``) + const result = await importDocxToHtml(await archive.generateAsync({ type: 'uint8array' })) + expect(result.layout!.headerFooter).toMatchObject({ headerHtml: '

header-default

', footerHtml: '

footer-default

', differentFirstPage: value === '', pageNumberStart: 4 }) + expect(result.layout!.evenAndOddHeaders).toBe(value === '') + expect(result.layout!.headerFooterVariants).toEqual(parts.flatMap(({ kind, variant, id }) => variant === 'default' ? [] : [{ kind, variant, html: `

${id}

` }])) + expect(result.warnings).toEqual([]) + }) + + it.each([ + ['letter', 'portrait', 12240, 15840], ['letter', 'landscape', 15840, 12240], + ['a4', 'portrait', 11906, 16838], ['a4', 'landscape', 16838, 11906], + ] as const)('detects %s paper in %s orientation from both native dimensions', async (paper, orientation, width, height) => { + const fixture = resolve(import.meta.dir, '../../../../../../node_modules/mammoth/test/test-data/single-paragraph.docx') + const archive = await JSZip.loadAsync(await Bun.file(fixture).arrayBuffer()) + archive.file('word/document.xml', ``) + const result = await importDocxToHtml(await archive.generateAsync({ type: 'uint8array' })) + expect(result.layout?.page).toMatchObject({ size: paper, orientation }) + }) + + it('imports native header/footer relationships even when the main body is empty', async () => { + const fixture = resolve(import.meta.dir, '../../../../../../node_modules/mammoth/test/test-data/single-paragraph.docx') + const archive = await JSZip.loadAsync(await Bun.file(fixture).arrayBuffer()) + archive.file('word/document.xml', '') + archive.file('word/_rels/document.xml.rels', '') + archive.file('word/header1.xml', 'Report header') + archive.file('word/footer1.xml', 'Report footer') + const result = await importDocxToHtml(await archive.generateAsync({ type: 'uint8array' })) + expect(result.layout?.headerFooter.headerHtml).toContain('Report header') + expect(result.layout?.headerFooter.footerHtml).toContain('Report footer') + expect(result.layout?.page).toEqual({ size: 'letter', orientation: 'portrait', margins: 'narrow' }) + expect(result.sourceProtected).toBe(true) + }) it('converts DOCX OOXML bytes into semantic HTML', async () => { const fixture = resolve(import.meta.dir, '../../../../../../node_modules/mammoth/test/test-data/single-paragraph.docx') const bytes = new Uint8Array(await Bun.file(fixture).arrayBuffer()) diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/wordDomain.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/wordDomain.test.ts index 28dc3c2d..0268e260 100644 --- a/desktop/apps/electron/src/renderer/lib/__tests__/wordDomain.test.ts +++ b/desktop/apps/electron/src/renderer/lib/__tests__/wordDomain.test.ts @@ -19,6 +19,30 @@ afterAll(async () => { }) describe('Word renderer domain', () => { + it('keeps unchanged and untargeted native header/footer content intact', async () => { + const store = createWordDomainStore(createWordWorkspace('rich-parts', 'Report'), { defaultTitle: 'Report' }) + try { + await store.dispatch({ type: 'document.headerFooter.update', settings: { headerHtml: '

Brand

', footerHtml: '

Confidential

' } }) + const initial = store.getSnapshot() + expect((await store.dispatch({ type: 'document.headerFooter.update', settings: { headerHtml: '

Brand

' } })).ok).toBe(true) + expect(store.getSnapshot()).toBe(initial) + const document = initial.documents[0]! + const native = structuredClone(document.snapshot) + const header = native.headers![native.documentStyle.defaultHeaderId!]!.body + header.textRuns![0]!.ts!.cl = { rgb: '#123456' } + store.commitEditorSnapshot(document.id, native) + expect((await store.dispatch({ type: 'document.headerFooter.update', settings: { footerHtml: '

Updated footer

' } })).ok).toBe(true) + const updated = store.getSnapshot().documents[0]! + expect(updated.snapshot.headers).toEqual(native.headers) + expect(updated.snapshot.body).toEqual(native.body) + expect(updated.snapshot.footers![updated.snapshot.documentStyle.defaultFooterId!]!.body.dataStream).toContain('Updated footer') + const beforeNumbering = updated.snapshot + await store.dispatch({ type: 'document.headerFooter.update', settings: { pageNumberStart: 3, showPageNumbers: true } }) + expect(store.getSnapshot().documents[0]!.snapshot.headers).toEqual(beforeNumbering.headers) + expect(store.getSnapshot().documents[0]!.snapshot.footers).toEqual(beforeNumbering.footers) + } finally { store.dispose() } + }) + it('isolates one workspace to its Session and manages internal document tabs', async () => { const initial = createWordWorkspace('session-word', 'Untitled document') const store = createWordDomainStore(initial, { defaultTitle: 'Untitled document' }) diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/wordEditorAdapter.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/wordEditorAdapter.test.ts index 6baf0b3f..8021984c 100644 --- a/desktop/apps/electron/src/renderer/lib/__tests__/wordEditorAdapter.test.ts +++ b/desktop/apps/electron/src/renderer/lib/__tests__/wordEditorAdapter.test.ts @@ -1,6 +1,7 @@ import { afterAll, describe, expect, it, mock } from 'bun:test' import { GlobalRegistrator } from '@happy-dom/global-registrator' -import type { IDocumentData } from '@univerjs/core' +import { Univer, UniverInstanceType, type DocumentDataModel, type IDocumentData } from '@univerjs/core' +import { UniverDocsHyperLinkPlugin } from '@univerjs/docs-hyper-link' import type { WordEditorNativeEngine } from '../wordEditorAdapter' GlobalRegistrator.register() @@ -88,6 +89,52 @@ function createFixture(options: { beforeReplace?: () => Promise; failSu } describe('Word editor engine binding', () => { + it('reopens canonical hyperlink URLs without letting a stale native resource replace them', async () => { + const fixture = createFixture() + await fixture.store.dispatch({ type: 'document.headerFooter.update', settings: { headerHtml: '

Website

' } }) + const snapshot = structuredClone(fixture.store.getSnapshot().documents[0]!.snapshot) + const header = snapshot.headers![snapshot.documentStyle.defaultHeaderId!]!.body + snapshot.resources = [ + { name: 'DOC_HYPER_LINK_PLUGIN', data: JSON.stringify({ links: [{ id: header.customRanges![0]!.rangeId, payload: 'https://example.com/old' }] }) }, + { name: 'OTHER_PLUGIN', data: '{}' }, + ] + fixture.store.commitEditorSnapshot(fixture.document.id, snapshot) + const before = fixture.store.getSnapshot() + const univer = new Univer() + univer.registerPlugin(UniverDocsHyperLinkPlugin) + let loaded!: DocumentDataModel + const adapter = createWordEditorAdapter({ + container: window.document.createElement('div'), documentId: fixture.document.id, + language: 'en', snapshot: before.documents[0]!.snapshot, store: fixture.store, zoom: 100, + mountNative: (input) => { + expect(input.snapshot.resources).toEqual([{ name: 'OTHER_PLUGIN', data: '{}' }]) + loaded = univer.createUnit(UniverInstanceType.UNIVER_DOC, input.snapshot) + fixture.native.document.getSnapshot = () => loaded.getSnapshot() + return fixture.native + }, + }) + try { + expect(loaded.getSnapshot().headers![snapshot.documentStyle.defaultHeaderId!]!.body.customRanges![0]!.properties?.url).toBe('https://example.com/new') + await adapter.flush() + expect(fixture.store.getSnapshot()).toBe(before) + expect(before.documents[0]!.snapshot.resources).toEqual(snapshot.resources) + } finally { adapter.dispose(); fixture.store.dispose(); univer.dispose() } + }) + + it('does not publish renderer normalization as an edit on open, flush or close', async () => { + const fixture = createFixture() + const adapter = fixture.mount() + const before = fixture.store.getSnapshot().documents[0]! + fixture.native.document.getSnapshot().settings = { zoomRatio: 0.5 } + fixture.native.document.getSnapshot().drawings!['layout-only'] = { drawingId: 'layout-only' } as NonNullable[string] + fixture.emit('drawing.operation.set-drawing-selected') + fixture.emit('doc.operation.set-selections') + await adapter.flush() + adapter.dispose() + expect(fixture.store.getSnapshot().documents[0]!.snapshot).toEqual(before.snapshot) + expect(fixture.store.getSnapshot().documents[0]!.contentVersion).toBe(before.contentVersion) + fixture.store.dispose() + }) it('commits in-place native image changes without aliasing mounted or replaced domain snapshots', async () => { const fixture = createFixture({ retainNativeInput: true }) const adapter = fixture.mount() diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/wordHeaderFooter.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/wordHeaderFooter.test.ts new file mode 100644 index 00000000..b0f8c8c4 --- /dev/null +++ b/desktop/apps/electron/src/renderer/lib/__tests__/wordHeaderFooter.test.ts @@ -0,0 +1,354 @@ +import { afterAll, describe, expect, it } from 'bun:test' +import { GlobalRegistrator } from '@happy-dom/global-registrator' +import { BooleanNumber, CustomRangeType, ListGlyphType, PRESET_LIST_TYPE, PresetListType, type IDocumentData } from '@univerjs/core' +import JSZip from 'jszip' + +GlobalRegistrator.register() +const { createWordHeaderFooterDraft, mergeWordHeaderFooterDraft, wordHeaderFooterContentSignature } = await import('../wordHeaderFooter') +const { createWordDomainStore, createWordWorkspace } = await import('../wordDomain') +const { createUniverDocumentSnapshot, htmlToUniverSnapshot, normalizeUniverDocumentSnapshot } = await import('../wordUniverModel') +const { exportWordDocx } = await import('../wordDocxExport') +const { importDocxToHtml } = await import('../wordDocxImport') +afterAll(async () => GlobalRegistrator.unregister()) + +const page = { size: 'a4', orientation: 'portrait', margins: 'normal' } as const +const settings = { headerHtml: '

Old header

', footerHtml: '

Old footer

', showPageNumbers: false, differentFirstPage: false, pageNumberStart: 1 } +const png = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl6T4cAAAAASUVORK5CYII=' + +function richSnapshot(): IDocumentData { + const snapshot = createUniverDocumentSnapshot('report', 'Report', page, settings, '

Body text

') + const rich = htmlToUniverSnapshot(`

Company website

  1. Custom list
-
-
- {row[columnIndex] ?? ''} +
+
+
+ {presentationTableCellSegments(element, rowIndex, columnIndex).map((segment, index) => ( + {segment.text} + ))} +
- -
Cell text
`, snapshot.id, snapshot.title!) + snapshot.headers!['bridgic-word-header']!.body = rich.body! + Object.assign(snapshot.drawings!, rich.drawings) + Object.assign(snapshot.tableSource!, rich.tableSource) + Object.assign(snapshot.lists!, rich.lists) + snapshot.drawingsOrder!.push(...rich.drawingsOrder!) + snapshot.headerFooterDrawingsOrder = rich.drawingsOrder + for (const paragraph of rich.body!.paragraphs!) paragraph.paragraphStyle = { + indentStart: { v: 48 }, indentEnd: { v: 24 }, indentFirstLine: { v: 12 }, hanging: { v: 6 }, + tabStops: [{ offset: 90, alignment: 0 }], lineSpacing: 1.5, spaceAbove: { v: 12 }, spaceBelow: { v: 18 }, + keepNext: BooleanNumber.TRUE, + } + rich.body!.textRuns![0]!.ts = { ...rich.body!.textRuns![0]!.ts, fs: 18, sc: 3, sa: 80, ff: 'Arial', cl: { rgb: '#aa0000' } } + const startIndex = rich.body!.dataStream.indexOf('website') + rich.body!.customRanges = [{ rangeId: 'native-link', rangeType: CustomRangeType.HYPERLINK, startIndex, endIndex: startIndex + 6, properties: { url: 'https://example.com/?q=one&lang=en' } }] + rich.body!.customDecorations = [{ id: 'decoration', startIndex: 1, endIndex: 8, type: 0 }] + const list = Object.values(rich.lists!)[0]! + list.nestingLevel[0]!.startNumber = 7 + list.nestingLevel[0]!.glyphFormat = '%1)' + const table = Object.values(rich.tableSource!)[0]! + table.tableColumns[0]!.size.width.v = 480 + table.tableRows[0]!.tableCells[0]!.backgroundColor = { rgb: '#eeeeee' } + table.tableRows[0]!.tableCells[0]!.margin = { top: { v: 8 }, bottom: { v: 6 }, start: { v: 10 }, end: { v: 10 } } + const drawing = Object.values(rich.drawings!)[0]! + drawing.docTransform.angle = 15 + drawing.distL = 11 + drawing.behindDoc = BooleanNumber.TRUE + drawing.transform = { ...drawing.transform, angle: 15 } + snapshot.headers!['first'] = { headerId: 'first', body: htmlToUniverSnapshot('

First header

', snapshot.id, '').body! } + snapshot.headers!['even'] = { headerId: 'even', body: htmlToUniverSnapshot('

Even header

', snapshot.id, '').body! } + snapshot.footers!['first-footer'] = { footerId: 'first-footer', body: htmlToUniverSnapshot('

First footer

', snapshot.id, '').body! } + snapshot.documentStyle.firstPageHeaderId = 'first' + snapshot.documentStyle.evenPageHeaderId = 'even' + snapshot.documentStyle.firstPageFooterId = 'first-footer' + snapshot.resources = [{ name: 'OTHER_PLUGIN', data: 'leave unchanged' }] + return snapshot +} + +describe('Native Word header/footer drafts', () => { + it.each(['headerHtml', 'footerHtml'] as const)('adds, clears and adds %s again from a real blank document through save/reopen', async (field) => { + const store = createWordDomainStore(createWordWorkspace(`blank-${field}`, 'Report'), { defaultTitle: 'Report' }) + try { + const part = field === 'headerHtml' ? 'headers' : 'footers' + const key = field === 'headerHtml' ? 'defaultHeaderId' : 'defaultFooterId' + expect(store.getSnapshot().documents[0]!.snapshot.documentStyle[key]).toBe('') + for (const text of ['First addition', '', 'Second addition']) { + const current = store.getSnapshot().documents[0]! + const draft = createWordHeaderFooterDraft(current.snapshot, field) + expect(draft.segmentId).not.toBe('') + const merged = mergeWordHeaderFooterDraft(current.snapshot, draft, htmlToUniverSnapshot(`

${text}

`, draft.snapshot.id, '')) + expect(store.commitEditorSnapshot(current.id, merged)).toBe(true) + const document = store.getSnapshot().documents[0]! + const imported = await importDocxToHtml(await exportWordDocx(document)) + const snapshot = imported.document!.snapshot + expect(snapshot.documentStyle[key]).toBe(draft.segmentId) + expect(snapshot[part]![draft.segmentId]!.body.dataStream).toBe(`${text}\r\n`) + expect(Object.keys(snapshot[part]!)).toEqual([draft.segmentId]) + } + } finally { store.dispose() } + }) + + it.each(['headerHtml', 'footerHtml'] as const)('recovers an existing %s stored under an empty ID', (field) => { + const snapshot = createWordWorkspace('empty-id-recovery', 'Report').documents[0]!.snapshot + const part = field === 'headerHtml' ? 'headers' : 'footers' + snapshot[part]![''] = field === 'headerHtml' + ? { headerId: '', body: htmlToUniverSnapshot('

Previous draft

', snapshot.id, '').body! } + : { footerId: '', body: htmlToUniverSnapshot('

Previous draft

', snapshot.id, '').body! } + const draft = createWordHeaderFooterDraft(snapshot, field) + expect(draft.snapshot.body!.dataStream).toBe('Previous draft\r\n') + const merged = mergeWordHeaderFooterDraft(snapshot, draft, draft.snapshot) + expect(Object.keys(merged[part]!)).toEqual([draft.segmentId]) + expect(draft.segmentId).not.toBe('') + }) + + it.each(['headerHtml', 'footerHtml'] as const)('does not fill a deliberately blank section while editing an existing %s', (field) => { + const snapshot = richSnapshot() + const key = field === 'headerHtml' ? 'defaultHeaderId' : 'defaultFooterId' + snapshot.body!.sectionBreaks!.at(-1)![key] = '' + const draft = createWordHeaderFooterDraft(snapshot, field) + const edited = htmlToUniverSnapshot('

Updated default

', draft.snapshot.id, '') + expect(mergeWordHeaderFooterDraft(snapshot, draft, edited).body!.sectionBreaks!.at(-1)![key]).toBe('') + }) + + it.each(['headerHtml', 'footerHtml'] as const)('preserves all native %s properties through editing, save and reopening', async (field) => { + const snapshot = richSnapshot() + if (field === 'footerHtml') snapshot.footers!['bridgic-word-footer']!.body = structuredClone(snapshot.headers!['bridgic-word-header']!.body) + const part = field === 'headerHtml' ? 'headers' : 'footers' + const other = field === 'headerHtml' ? 'footers' : 'headers' + const draft = createWordHeaderFooterDraft(snapshot, field) + expect(draft.snapshot.body).toEqual(snapshot[part]![draft.segmentId]!.body) + expect(draft.snapshot.headers).toEqual({}) + expect(draft.snapshot.footers).toEqual({}) + expect(draft.snapshot.resources).toBeUndefined() + expect(draft.snapshot.documentStyle.defaultHeaderId).toBeUndefined() + const edited = structuredClone(draft.snapshot) + edited.body!.dataStream = edited.body!.dataStream.replace('Company', 'Updated') + const merged = mergeWordHeaderFooterDraft(snapshot, draft, edited) + expect(merged[part]![draft.segmentId]!.body).toEqual({ ...snapshot[part]![draft.segmentId]!.body, dataStream: edited.body!.dataStream }) + expect(merged[other]).toEqual(snapshot[other]) + expect(merged.body).toEqual(snapshot.body) + expect(merged.documentStyle).toEqual(snapshot.documentStyle) + for (const key of ['drawings', 'tableSource', 'lists', 'drawingsOrder', 'headerFooterDrawingsOrder', 'resources'] as const) expect(merged[key]).toEqual(snapshot[key]) + const store = createWordDomainStore(createWordWorkspace('header-round-trip', 'Report'), { defaultTitle: 'Report' }) + await store.dispatch({ type: 'document.headerFooter.update', settings }) + const current = store.getSnapshot().documents[0]! + merged.id = current.id + store.commitEditorSnapshot(current.id, merged) + const document = store.getSnapshot().documents[0]! + const bytes = await exportWordDocx(document) + const imported = await importDocxToHtml(bytes) + expect(imported.document!.snapshot[part]).toEqual(document.snapshot[part]) + expect(imported.document!.snapshot.drawings).toEqual(document.snapshot.drawings) + expect(imported.document!.snapshot.lists).toEqual(document.snapshot.lists) + const archive = await JSZip.loadAsync(bytes) + const xml = await archive.file(`word/${part === 'headers' ? 'header' : 'footer'}.xml`)!.async('text') + expect(xml).toContain('Updated') + expect(xml).toContain('w:left="720" w:right="360"') + expect(xml).toContain('w:hanging="90"') + expect(xml).toContain('') + expect(xml).toContain('') + expect(xml).toContain('') + expect(xml).toContain('w:hyperlink') + store.dispose() + }) + + it('never aliases the canonical snapshot or baseline when the native draft changes', () => { + const snapshot = richSnapshot() + const expected = structuredClone(snapshot) + const draft = createWordHeaderFooterDraft(snapshot, 'headerHtml') + draft.snapshot.body!.paragraphs![0]!.paragraphStyle!.indentStart!.v = 999 + Object.values(draft.snapshot.drawings!)[0]!.docTransform.angle = 90 + expect(snapshot).toEqual(expected) + expect(draft.original).toEqual(expected) + }) + + it('does not replace canonical image coordinates with temporary body layout caches', () => { + const snapshot = richSnapshot() + const draft = createWordHeaderFooterDraft(snapshot, 'headerHtml') + const edited = structuredClone(draft.snapshot) + const drawing = Object.values(edited.drawings!)[0]! + drawing.transform = { ...drawing.transform, left: 300, top: 200 } + drawing.transforms = [{ ...drawing.transform }] + drawing.isMultiTransform = BooleanNumber.FALSE + const merged = mergeWordHeaderFooterDraft(snapshot, draft, edited) + expect(merged.drawings).toEqual(snapshot.drawings) + }) + + it('treats empty native array normalization and image layout caches as non-content changes', () => { + const draft = createWordHeaderFooterDraft(richSnapshot(), 'headerHtml') + const next = structuredClone(draft.snapshot) + next.body!.blockRanges = [] + next.body!.payloads = { clipboard: 'transient' } + next.body!.paragraphs![0]!.paragraphStyle = Object.fromEntries(Object.entries(next.body!.paragraphs![0]!.paragraphStyle!).reverse()) + const drawing = Object.values(next.drawings!)[0]! + drawing.transform = { ...drawing.transform, left: 100, top: 100 } + drawing.transforms = [{ ...drawing.transform }] + expect(wordHeaderFooterContentSignature(next)).toBe(wordHeaderFooterContentSignature(draft.snapshot)) + }) + + it('preserves drawing stacking order relative to images in other segments', () => { + const snapshot = richSnapshot() + const originalId = Object.keys(snapshot.drawings!)[0]! + snapshot.drawings!['footer-logo'] = { ...structuredClone(snapshot.drawings![originalId]!), drawingId: 'footer-logo' } + snapshot.drawingsOrder = [originalId, 'footer-logo'] + snapshot.headerFooterDrawingsOrder = [...snapshot.drawingsOrder] + snapshot.footers!['bridgic-word-footer']!.body = { dataStream: '\b\r\n', customBlocks: [{ startIndex: 0, blockId: 'footer-logo' }], paragraphs: [{ startIndex: 1 }], sectionBreaks: [{ startIndex: 2 }] } + const draft = createWordHeaderFooterDraft(snapshot, 'headerHtml') + const merged = mergeWordHeaderFooterDraft(snapshot, draft, draft.snapshot) + expect(merged.drawingsOrder).toEqual(snapshot.drawingsOrder) + expect(merged.headerFooterDrawingsOrder).toEqual(snapshot.headerFooterDrawingsOrder) + }) + + it('retains live body changes and unrelated plugin resources', () => { + const snapshot = richSnapshot() + const draft = createWordHeaderFooterDraft(snapshot, 'headerHtml') + const current = structuredClone(snapshot) + current.body!.dataStream = 'Latest body\r\n' + current.resources![0]!.data = 'latest plugin state' + const edited = structuredClone(draft.snapshot) + edited.body!.dataStream = edited.body!.dataStream.replace('Company', 'Updated') + const merged = mergeWordHeaderFooterDraft(current, draft, edited) + expect(merged.body).toEqual(current.body) + expect(merged.resources).toEqual(current.resources) + }) + + it('accepts a newly inserted native preset list with no persisted list map', () => { + const snapshot = richSnapshot() + const draft = createWordHeaderFooterDraft(snapshot, 'headerHtml') + const edited = htmlToUniverSnapshot('
  1. New ordered item
', draft.snapshot.id, '') + edited.lists = {} + const merged = mergeWordHeaderFooterDraft(snapshot, draft, edited) + expect(merged.headers![draft.segmentId]!.body.paragraphs![0]!.bullet!.listType).toBe(PresetListType.ORDER_LIST) + expect(merged.headers![draft.segmentId]!.body.dataStream).toContain('New ordered item') + }) + + it('isolates shared list definitions keyed by native listType, not just listId', () => { + const snapshot = richSnapshot() + snapshot.lists![PresetListType.ORDER_LIST] = structuredClone(PRESET_LIST_TYPE[PresetListType.ORDER_LIST]!) + snapshot.body!.paragraphs![0]!.bullet = { listId: 'body-list', listType: PresetListType.ORDER_LIST, nestingLevel: 0 } + const draft = createWordHeaderFooterDraft(snapshot, 'headerHtml') + const edited = structuredClone(draft.snapshot) + edited.lists![PresetListType.ORDER_LIST]!.nestingLevel[0]!.startNumber = 4 + const merged = mergeWordHeaderFooterDraft(snapshot, draft, edited) + expect(merged.body).toEqual(snapshot.body) + expect(merged.lists![PresetListType.ORDER_LIST]).toEqual(snapshot.lists![PresetListType.ORDER_LIST]) + const type = merged.headers![draft.segmentId]!.body.paragraphs!.find((p) => p.bullet)!.bullet!.listType + expect(type).not.toBe(PresetListType.ORDER_LIST) + expect(merged.lists![type]!.nestingLevel[0]!.startNumber).toBe(4) + }) + + it.each(['drawings', 'tableSource', 'lists'] as const)('isolates edited shared %s from other segments', (key) => { + const snapshot = richSnapshot() + snapshot.headers!['first']!.body = structuredClone(snapshot.headers!['bridgic-word-header']!.body) + const draft = createWordHeaderFooterDraft(snapshot, 'headerHtml') + const edited = structuredClone(draft.snapshot) + const id = Object.keys(edited[key]!)[0]! + if (key === 'drawings') edited.drawings![id]!.docTransform.angle = 45 + if (key === 'tableSource') edited.tableSource![id]!.tableColumns[0]!.size.width.v = 333 + if (key === 'lists') edited.lists![id]!.nestingLevel[0]!.startNumber = 5 + const merged = mergeWordHeaderFooterDraft(snapshot, draft, edited) + expect(merged[key]![id]).toEqual(snapshot[key]![id]) + expect(merged.headers!['first']).toEqual(snapshot.headers!['first']) + expect(Object.keys(merged[key]!)).toHaveLength(Object.keys(snapshot[key]!).length + 1) + const header = merged.headers![draft.segmentId]!.body + const changedIds = { drawings: header.customBlocks![0]!.blockId, tableSource: header.tables![0]!.tableId, lists: header.paragraphs!.find((p) => p.bullet)!.bullet!.listId } + const changedId = changedIds[key] + expect(changedId).not.toBe(id) + expect(merged[key]![changedId]).toBeDefined() + }) + + it('clears a segment without restoring stale import HTML or deleting shared assets', () => { + const snapshot = richSnapshot() + snapshot.headers!['first']!.body = structuredClone(snapshot.headers!['bridgic-word-header']!.body) + const draft = createWordHeaderFooterDraft(snapshot, 'headerHtml') + const edited = htmlToUniverSnapshot('


', draft.snapshot.id, '') + const merged = mergeWordHeaderFooterDraft(snapshot, draft, edited) + expect(merged.headers![draft.segmentId]!.body.dataStream.replace(/[\r\n]/g, '')).toBe('') + expect(merged.drawings).toEqual(snapshot.drawings) + expect(merged.tableSource).toEqual(snapshot.tableSource) + expect(merged.lists).toEqual(snapshot.lists) + expect(normalizeUniverDocumentSnapshot(merged, merged.id, 'Report', page, settings).headers).toEqual(merged.headers) + }) + + it('removes only deleted assets owned exclusively by the edited segment', () => { + const snapshot = richSnapshot() + const draft = createWordHeaderFooterDraft(snapshot, 'headerHtml') + const merged = mergeWordHeaderFooterDraft(snapshot, draft, htmlToUniverSnapshot('

Plain header

', draft.snapshot.id, '')) + expect(merged.drawings).toEqual({}) + expect(merged.drawingsOrder).toEqual([]) + expect(merged.headerFooterDrawingsOrder).toEqual([]) + expect(merged.tableSource).toEqual({}) + expect(merged.lists).toEqual({}) + expect(merged.headers!['first']).toEqual(snapshot.headers!['first']) + }) + + it.each(['headerHtml', 'footerHtml'] as const)('creates a new empty %s without removing first/even-page variants', (field) => { + const snapshot = richSnapshot() + const key = field === 'headerHtml' ? 'defaultHeaderId' : 'defaultFooterId' + const part = field === 'headerHtml' ? 'headers' : 'footers' + delete snapshot[part]![snapshot.documentStyle[key]!] + delete snapshot.documentStyle[key] + const draft = createWordHeaderFooterDraft(snapshot, field) + expect(draft.snapshot.body!.dataStream).toBe('\r\n') + const edited = htmlToUniverSnapshot('

New text

', draft.snapshot.id, '') + const merged = mergeWordHeaderFooterDraft(snapshot, draft, edited) + expect(merged[part]![draft.segmentId]!.body.dataStream).toBe('New text\r\n') + for (const [id, value] of Object.entries(snapshot[part]!)) expect(merged[part]![id]).toEqual(value) + }) + + it('rejects stale edits and missing resources instead of overwriting live data', () => { + const snapshot = richSnapshot() + const draft = createWordHeaderFooterDraft(snapshot, 'headerHtml') + const current = structuredClone(snapshot) + current.headers![draft.segmentId]!.body.dataStream = 'Concurrent header\r\n' + expect(() => mergeWordHeaderFooterDraft(current, draft, draft.snapshot)).toThrow('changed while') + const invalid = structuredClone(draft.snapshot) + invalid.drawings = {} + expect(() => mergeWordHeaderFooterDraft(snapshot, draft, invalid)).toThrow('missing drawings') + expect(snapshot).toEqual(draft.original) + }) + + it('normalizes only a missing side, not native text/formatting on the existing side', () => { + const snapshot = richSnapshot() + snapshot.footers = {} + delete snapshot.documentStyle.defaultFooterId + const normalized = normalizeUniverDocumentSnapshot(snapshot, snapshot.id, 'Report', page, settings) + expect(normalized.headers).toEqual(snapshot.headers) + expect(normalized.drawings).toEqual(snapshot.drawings) + expect(normalized.footers!['bridgic-word-footer']!.body.dataStream).toBe('Old footer\r\n') + delete snapshot.headers!['bridgic-word-header'] + delete snapshot.documentStyle.defaultHeaderId + expect(normalizeUniverDocumentSnapshot(snapshot, snapshot.id, 'Report', page, settings).headers).toEqual(snapshot.headers) + }) + + it('exports the referenced default, first and even-page parts, not the first map entry', async () => { + const snapshot = richSnapshot() + snapshot.headers = { first: snapshot.headers!['first']!, even: snapshot.headers!['even']!, 'bridgic-word-header': snapshot.headers!['bridgic-word-header']! } + snapshot.documentStyle.useFirstPageHeaderFooter = BooleanNumber.TRUE + snapshot.documentStyle.evenAndOddHeaders = BooleanNumber.TRUE + snapshot.documentStyle.marginHeader = 22 + snapshot.documentStyle.marginFooter = 44 + const document = { ...createWordWorkspace('variants-export', 'Report').documents[0]!, id: snapshot.id, snapshot, headerFooter: settings } + const zip = await JSZip.loadAsync(await exportWordDocx(document)) + const xml = await zip.file('word/document.xml')!.async('text') + expect(await zip.file('word/header.xml')!.async('text')).toContain('Company') + expect(await zip.file('word/header-first.xml')!.async('text')).toContain('First header') + expect(await zip.file('word/header-even.xml')!.async('text')).toContain('Even header') + expect(await zip.file('word/footer-first.xml')!.async('text')).toContain('First footer') + expect(xml).toContain('') + expect(xml).toContain('w:type="first"') + expect(xml).toContain('w:type="even"') + expect(xml).toContain('w:header="330" w:footer="660"') + expect(await zip.file('word/settings.xml')!.async('text')).toContain('') + expect(zip.file('word/_rels/header-first.xml.rels')).not.toBeNull() + const imported = await importDocxToHtml(await zip.generateAsync({ type: 'uint8array' })) + expect(imported.layout!.headerFooter.headerHtml).toContain('Company') + expect(imported.document!.snapshot.headers).toEqual(snapshot.headers) + }) + + it('exports native list glyphs and starting numbers instead of resetting them to plain decimals', async () => { + const snapshot = richSnapshot() + const bullet = snapshot.headers!['bridgic-word-header']!.body.paragraphs!.find((p) => p.bullet)!.bullet! + snapshot.lists![bullet.listType] = structuredClone(PRESET_LIST_TYPE[bullet.listType]!) + const level = snapshot.lists![bullet.listType]!.nestingLevel[0]! + level.glyphType = ListGlyphType.UPPER_ROMAN + level.startNumber = 3 + level.glyphFormat = '%1)' + const document = { ...createWordWorkspace('numbering-export', 'Report').documents[0]!, snapshot, headerFooter: settings } + const zip = await JSZip.loadAsync(await exportWordDocx(document)) + const xml = await zip.file('word/numbering.xml')!.async('text') + expect(xml).toContain('') + expect(xml).toContain('') + expect(xml).toContain('') + }) +}) diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/wordImport.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/wordImport.test.ts new file mode 100644 index 00000000..4710e760 --- /dev/null +++ b/desktop/apps/electron/src/renderer/lib/__tests__/wordImport.test.ts @@ -0,0 +1,415 @@ +import { afterAll, afterEach, beforeEach, describe, expect, it } from 'bun:test' +import { GlobalRegistrator } from '@happy-dom/global-registrator' +import { BooleanNumber, CustomRangeType, DocumentDataModel, LocaleService, PageOrientType, SectionType } from '@univerjs/core' +import { DocumentSkeleton, DocumentViewModel } from '@univerjs/engine-render' +import { resolve } from 'node:path' +import JSZip from 'jszip' + +GlobalRegistrator.register() +const { importDocxToHtml } = await import('../wordDocxImport') +const { importDocxInBackground } = await import('../wordImport') +const { createEmptyWordWorkspace, createWordDomainStore } = await import('../wordDomain') +const { exportWordDocx } = await import('../wordDocxExport') +const { createWordHeaderFooterDraft, mergeWordHeaderFooterDraft } = await import('../wordHeaderFooter') +const { htmlToUniverSnapshot } = await import('../wordUniverModel') + +const originalWorker = globalThis.Worker +class InlineWordImportWorker { + onmessage: ((event: MessageEvent) => void) | null = null + onerror: ((event: ErrorEvent) => void) | null = null + onmessageerror: (() => void) | null = null + postMessage(bytes: Uint8Array) { + // Exercise the real decoder and renderer initialization across the worker boundary. + void importDocxToHtml(bytes).then( + (value) => this.onmessage?.({ data: { ok: true, value } } as MessageEvent), + (error) => this.onmessage?.({ data: { ok: false, error: String(error) } } as MessageEvent), + ) + } + terminate() {} +} +beforeEach(() => { globalThis.Worker = InlineWordImportWorker as unknown as typeof Worker }) +afterEach(() => { globalThis.Worker = originalWorker }) +afterAll(async () => GlobalRegistrator.unregister()) + +async function externalDocument(options: { onlyFirst?: boolean; emptyFirst?: boolean } = {}) { + const base = resolve(import.meta.dir, '../../../../../../node_modules/mammoth/test/test-data/single-paragraph.docx') + const archive = await JSZip.loadAsync(await Bun.file(base).arrayBuffer()) + const parts = (['header', 'footer'] as const).flatMap((kind) => + (['default', 'first', 'even'] as const).filter((variant) => !options.onlyFirst || variant === 'first').map((variant) => ({ kind, variant, id: `${kind}-${variant}` }))) + archive.file('word/document.xml', `Report body${parts.map(({ kind, variant, id }) => ``).join('')}`) + archive.file('word/_rels/document.xml.rels', `${parts.map(({ kind, id }) => ``).join('')}`) + archive.file('word/settings.xml', '') + const image = '' + for (const { kind, variant, id } of parts) { + const tag = kind === 'header' ? 'hdr' : 'ftr' + const empty = options.emptyFirst && variant === 'first' + const rich = variant === 'first' && !empty + archive.file(`word/parts/${id}.xml`, `${empty ? '' : `${id}`}${rich ? `${image}${id} link${id} table` : ''}`) + if (rich) archive.file(`word/parts/_rels/${id}.xml.rels`, '') + } + archive.file('word/media/logo.png', 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl6T4cAAAAASUVORK5CYII=', { base64: true }) + return archive.generateAsync({ type: 'uint8array' }) +} + +async function sectionedDocument(changed: boolean) { + const archive = await JSZip.loadAsync(await externalDocument()) + const references = (['header', 'footer'] as const).flatMap((kind) => (['default', 'first', 'even'] as const).map((variant) => ``)).join('') + const section = (refs: string, first: boolean) => `${refs}${first ? '' : ''}` + const secondRefs = changed ? '' : '' + archive.file('word/document.xml', `${section(references, true)}Section oneBody table${section(secondRefs, true)}Section twoSection three${section('', false)}`) + if (changed) { + const rels = await archive.file('word/_rels/document.xml.rels')!.async('text') + archive.file('word/_rels/document.xml.rels', rels.replace('', '')) + archive.file('word/parts/alternate.xml', 'Second chapter header') + archive.file('word/parts/empty.xml', '') + } + return archive.generateAsync({ type: 'uint8array' }) +} + +describe('Word import native initialization', () => { + it.each(['Arabic', 'roman', 'ROMAN', 'alphabetic', 'ALPHABETIC'].flatMap((format) => [false, true].map((sectionFormat) => [format, sectionFormat] as const)))('keeps live PAGE/NUMPAGES fields through layout, native edits and external reopen (%s, section-format=%s)', async (format, sectionFormat) => { + const source = await JSZip.loadAsync(await externalDocument()) + const paragraphs = 'Report paragraph'.repeat(35) + source.file('word/settings.xml', '') + const nativeFormat = ({ Arabic: 'decimal', roman: 'lowerRoman', ROMAN: 'upperRoman', alphabetic: 'lowerLetter', ALPHABETIC: 'upperLetter' } as Record)[format]! + source.file('word/document.xml', `${paragraphs}`) + const instruction = sectionFormat ? 'PAGE' : `PAGE \\* ${format}` + source.file('word/parts/footer-default.xml', `Page PA${instruction.slice(2)}99 of 99`) + let bytes = await source.generateAsync({ type: 'uint8array' }) + for (let cycle = 0; cycle < 2; cycle++) { + const imported = await importDocxInBackground(bytes) + expect(imported.warnings).toEqual([]) + const store = createWordDomainStore(createEmptyWordWorkspace(`fields-${format}-${cycle}`), { defaultTitle: 'Report' }) + try { + expect((await store.dispatch({ type: 'document.open', ...imported, title: 'Report.docx', sourcePath: '/Report.docx', sourceMtimeMs: cycle + 1 })).ok).toBe(true) + const document = store.getSnapshot().documents[0]! + const draft = createWordHeaderFooterDraft(document.snapshot, 'footerHtml') + // Edit surrounding text with native field ranges, not a flattened HTML draft. + const edited = structuredClone(draft.snapshot) + edited.body!.dataStream = edited.body!.dataStream.replace('Page', 'PAGE') + expect(store.commitEditorSnapshot(document.id, mergeWordHeaderFooterDraft(document.snapshot, draft, edited))).toBe(true) + const current = store.getSnapshot().documents[0]! + const model = new DocumentDataModel(current.snapshot) + const locale = new LocaleService() + const skeleton = new DocumentSkeleton(new DocumentViewModel(model), locale) + try { + skeleton.calculate() + const pages = skeleton.getSkeletonData()!.pages + expect(pages.length).toBeGreaterThan(2) + const footerBody = current.snapshot.footers![pages[0]!.footerId]!.body + expect(footerBody.dataStream).toBe('PAGE \uFFFC of \uFFFC\r\n') + expect(footerBody.customRanges?.map((field) => field.properties?.field)).toEqual(['PAGE', 'NUMPAGES']) + const formatNumber = (number: number) => { + if (format === 'Arabic') return String(number) + if (format.toLowerCase() === 'alphabetic') return String.fromCharCode((format === 'alphabetic' ? 97 : 65) + number - 1) + const roman = ['IX', 'X', 'XI', 'XII', 'XIII', 'XIV', 'XV', 'XVI'][number - 9]! + return format === 'roman' ? roman.toLowerCase() : roman + } + for (const page of pages) { + const glyphs = page.footerSkeleton!.sections.flatMap((section) => section.columns.flatMap((column) => column.lines.flatMap((line) => line.divides.flatMap((divide) => divide.glyphGroup)))) + expect(glyphs.map((glyph) => glyph.content).join('').trim()).toBe(`PAGE ${formatNumber(page.pageNumber)} of ${pages.length}`) + const field = glyphs.find((glyph) => glyph.raw === '\uFFFC')! + expect(field.count).toBe(1) + expect(field.ts?.bl).toBe(BooleanNumber.TRUE) + expect(field.ts?.cl?.rgb).not.toBe('#274fee') + expect(page.footerId).toBe(pages[0]!.footerId) + } + skeleton.makeDirty(true) + skeleton.calculate() + expect(skeleton.getSkeletonData()!.pages).toHaveLength(pages.length) + expect(current.snapshot.footers![pages[0]!.footerId]!.body).toEqual(footerBody) + } finally { skeleton.dispose(); model.dispose(); locale.dispose() } + const archive = await JSZip.loadAsync(await exportWordDocx(current)) + const footer = await archive.file('word/footer.xml')!.async('text') + expect(footer).toContain(`w:instr="${instruction}"`) + expect(footer).toContain('w:instr="NUMPAGES"') + expect(footer.match(/w:dirty="true"/g)).toHaveLength(2) + if (sectionFormat) expect(await archive.file('word/document.xml')!.async('text')).toContain(`w:fmt="${nativeFormat}"`) + expect(footer).not.toContain('\uFFFC') + archive.remove('bridgic/editor-model.json') + bytes = await archive.generateAsync({ type: 'uint8array' }) + } finally { store.dispose() } + } + }) + + it.each(['vml', 'alternate', 'ignored-drawing'])('associates image dimensions by source instance, not conversion order (%s)', async (mode) => { + const source = await JSZip.loadAsync(await externalDocument()) + const image = (name: string, width: number, height: number) => `` + const vml = '' + let first = vml + if (mode === 'alternate') first = `${image('Ignored choice', 500, 400)}${vml}` + if (mode === 'ignored-drawing') first = '' + const namespaces = 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"' + source.file('word/document.xml', `${first}${image('Modern image', 240, 120)}${image('Repeated image', 120, 60)}`) + source.file('word/_rels/document.xml.rels', '') + source.file('word/parts/header-default.xml', `${first}${image('Header image', 150, 30)}`) + source.file('word/parts/_rels/header-default.xml.rels', '') + let bytes = await source.generateAsync({ type: 'uint8array' }) + for (let cycle = 0; cycle < 2; cycle++) { + const imported = await importDocxInBackground(bytes) + expect(imported.html).not.toContain('bridgic-word-import-') + const snapshot = imported.document!.snapshot + const drawings = Object.values(snapshot.drawings!) + for (const [name, width, height] of [['Modern image', 240, 120], ['Repeated image', 120, 60], ['Header image', 150, 30]] as const) { + expect(drawings.find((drawing) => drawing.description === name)?.docTransform.size).toEqual({ width, height }) + } + if (mode !== 'ignored-drawing') { + const legacy = drawings.filter((drawing) => drawing.description === 'Legacy logo') + expect(legacy).toHaveLength(2) + expect(legacy.every((drawing) => drawing.docTransform.size.width === 80 && drawing.docTransform.size.height === 20)).toBe(true) + } + expect(drawings.some((drawing) => drawing.description === 'Ignored choice')).toBe(false) + const store = createWordDomainStore(createEmptyWordWorkspace(`images-${mode}-${cycle}`), { defaultTitle: 'Report' }) + try { + expect((await store.dispatch({ type: 'document.open', ...imported, title: 'Images.docx', sourcePath: '/Images.docx', sourceMtimeMs: cycle + 1 })).ok).toBe(true) + const archive = await JSZip.loadAsync(await exportWordDocx(store.getSnapshot().documents[0]!)) + archive.remove('bridgic/editor-model.json') + bytes = await archive.generateAsync({ type: 'uint8array' }) + } finally { store.dispose() } + } + }) + + it.each([ + ['oddPage', SectionType.ODD_PAGE, 1, 3, 'header-default'], + ['evenPage', SectionType.EVEN_PAGE, 45, 4, 'header-even'], + ] as const)('keeps %s section pagination and headers through an external file cycle', async (type, sectionType, count, pageCount, header) => { + const source = await JSZip.loadAsync(await externalDocument()) + const first = '' + const paragraphs = Array.from({ length: count }, (_, index) => `${index === count - 1 ? `${first}` : ''}Chapter one paragraph ${index + 1}`).join('') + source.file('word/document.xml', `${paragraphs}Chapter two`) + let bytes = await source.generateAsync({ type: 'uint8array' }) + for (let cycle = 0; cycle < 2; cycle++) { + const imported = await importDocxInBackground(bytes) + const store = createWordDomainStore(createEmptyWordWorkspace(`parity-${type}-${cycle}`), { defaultTitle: 'Report' }) + try { + await store.dispatch({ type: 'document.open', ...imported, title: 'Chapters.docx', sourcePath: '/Chapters.docx', sourceMtimeMs: cycle + 1 }) + const document = store.getSnapshot().documents[0]! + const breaks = document.snapshot.body!.sectionBreaks! + expect(breaks[1]!.sectionType).toBe(sectionType) + const model = new DocumentDataModel(document.snapshot) + const locale = new LocaleService() + const skeleton = new DocumentSkeleton(new DocumentViewModel(model), locale) + try { + skeleton.calculate() + const pages = skeleton.getSkeletonData()!.pages + expect(pages).toHaveLength(pageCount) + expect(pages.at(-2)!.sections).toHaveLength(0) + expect(pages.at(-1)!.pageNumber).toBe(pageCount) + expect(pages.at(-1)!.st).toBe(breaks[0]!.startIndex + 1) + expect(document.snapshot.headers![pages.at(-1)!.headerId!]!.body.dataStream).toContain(header) + } finally { skeleton.dispose(); model.dispose(); locale.dispose() } + const archive = await JSZip.loadAsync(await exportWordDocx(document)) + expect(await archive.file('word/document.xml')!.async('text')).toContain(``) + archive.remove('bridgic/editor-model.json') + bytes = await archive.generateAsync({ type: 'uint8array' }) + } finally { store.dispose() } + } + }) + + it.each([false, true])('preserves mixed section geometry through edits, rendering and external save/reopen (landscape-first=%s)', async (landscapeFirst) => { + const source = await JSZip.loadAsync(await externalDocument()) + const geometry = [ + { width: 11906, height: 16838, orient: PageOrientType.PORTRAIT, top: 720, bottom: 840, left: 960, right: 1080 }, + { width: 15840, height: 12240, orient: PageOrientType.LANDSCAPE, top: 1440, bottom: 1560, left: 1680, right: 1800 }, + { width: 11906, height: 16838, orient: PageOrientType.PORTRAIT, top: 0, bottom: 1200, left: 1320, right: 1440 }, + ] + // Exercise both orientations as the document default. + if (landscapeFirst) [geometry[0], geometry[1]] = [geometry[1]!, geometry[0]!] + const sectionXml = geometry.map((size, index) => `${index === 0 ? '' : ''}`) + const body = geometry.map((_, index) => `${index < 2 ? `${sectionXml[index]}` : ''}Chapter ${index + 1}`).join('') + source.file('word/document.xml', `${body}${sectionXml[2]}`) + let bytes = await source.generateAsync({ type: 'uint8array' }) + for (let cycle = 0; cycle < 3; cycle++) { + const imported = await importDocxInBackground(bytes) + expect(imported.warnings).toEqual([]) + const store = createWordDomainStore(createEmptyWordWorkspace(`geometry-${landscapeFirst}-${cycle}`), { defaultTitle: 'Report' }) + try { + expect((await store.dispatch({ type: 'document.open', ...imported, title: 'Mixed.docx', sourcePath: '/Mixed.docx', sourceMtimeMs: cycle + 1 })).ok).toBe(true) + await store.dispatch({ type: 'document.append', text: 'Body correction' }) + const document = store.getSnapshot().documents[0]! + const sections = document.snapshot.body!.sectionBreaks! + expect(sections).toHaveLength(3) + const model = new DocumentDataModel(document.snapshot) + const locale = new LocaleService() + const skeleton = new DocumentSkeleton(new DocumentViewModel(model), locale) + try { + skeleton.calculate() + const pages = skeleton.getSkeletonData()!.pages + expect(pages).toHaveLength(3) + for (const [index, size] of geometry.entries()) { + expect(sections[index]).toMatchObject({ + pageSize: { width: size.width / 15, height: size.height / 15 }, pageOrient: size.orient, + marginTop: size.top / 15, marginBottom: size.bottom / 15, marginLeft: size.left / 15, marginRight: size.right / 15, + }) + expect(pages[index]).toMatchObject({ pageWidth: size.width / 15, pageHeight: size.height / 15, marginLeft: size.left / 15, marginRight: size.right / 15 }) + } + } finally { skeleton.dispose(); model.dispose(); locale.dispose() } + const archive = await JSZip.loadAsync(await exportWordDocx(document)) + const xml = await archive.file('word/document.xml')!.async('text') + expect([...(xml.match(/]*\/>/g) ?? [])]).toEqual(geometry.map((size) => ``)) + const exportedMargins = xml.match(/]*\/>/g)! + for (const [index, size] of geometry.entries()) for (const field of ['top', 'bottom', 'left', 'right'] as const) expect(exportedMargins[index]).toContain(`w:${field}="${size[field]}"`) + archive.remove('bridgic/editor-model.json') + bytes = await archive.generateAsync({ type: 'uint8array' }) + // Changing one Ribbon setting must leave unrelated section layout intact. + await store.dispatch({ type: 'document.page.update', page: { margins: 'wide' } }) + let updated = store.getSnapshot().documents[0]!.snapshot.body!.sectionBreaks! + expect(updated.map((item) => item.pageSize)).toEqual(sections.map((item) => item.pageSize)) + expect(updated.map((item) => item.pageOrient)).toEqual(geometry.map((size) => size.orient)) + expect(updated.every((item) => item.marginLeft === 96)).toBe(true) + await store.dispatch({ type: 'document.page.update', page: { orientation: 'landscape' } }) + updated = store.getSnapshot().documents[0]!.snapshot.body!.sectionBreaks! + expect(updated.every((item) => item.pageOrient === PageOrientType.LANDSCAPE && item.pageSize!.width! > item.pageSize!.height!)).toBe(true) + expect(updated.every((item) => item.marginLeft === 96)).toBe(true) + } finally { store.dispose() } + } + }) + + it('keeps a headerless cover section blank when later sections have headers through external reopen', async () => { + const source = await JSZip.loadAsync(await sectionedDocument(false)) + let xml = await source.file('word/document.xml')!.async('text') + const sections = xml.match(/[\s\S]*?<\/w:sectPr>/g)! + const size = '' + xml = xml.replace(sections[0]!, `${size}`).replace(sections[1]!, `${size}`) + source.file('word/document.xml', xml) + let bytes = await source.generateAsync({ type: 'uint8array' }) + for (let cycle = 0; cycle < 3; cycle++) { + const imported = await importDocxInBackground(bytes) + const { snapshot } = imported.document! + const breaks = snapshot.body!.sectionBreaks!.filter((item) => item.defaultHeaderId !== undefined) + expect(breaks).toHaveLength(3) + expect(breaks[0]).toMatchObject({ defaultHeaderId: '', defaultFooterId: '' }) + expect(snapshot.headers![breaks[1]!.defaultHeaderId!]!.body.dataStream).toContain('header-default') + expect(snapshot.footers![breaks[1]!.defaultFooterId!]!.body.dataStream).toContain('footer-default') + const store = createWordDomainStore(createEmptyWordWorkspace(`cover-${cycle}`), { defaultTitle: 'Report' }) + try { + await store.dispatch({ type: 'document.open', ...imported, title: 'Cover.docx', sourcePath: '/Cover.docx', sourceMtimeMs: cycle + 1 }) + const archive = await JSZip.loadAsync(await exportWordDocx(store.getSnapshot().documents[0]!)) + const exported = await archive.file('word/document.xml')!.async('text') + expect(exported.match(/[\s\S]*?<\/w:sectPr>/g)![0]).not.toContain('Reference') + archive.remove('bridgic/editor-model.json') + bytes = await archive.generateAsync({ type: 'uint8array' }) + } finally { store.dispose() } + } + }) + + it.each([false, true])('keeps per-section parts, inheritance and explicit blank overrides through native edits and external reopen (changed=%s)', async (changed) => { + let bytes = await sectionedDocument(changed) + for (let cycle = 0; cycle < 3; cycle++) { + const imported = await importDocxInBackground(bytes) + expect(imported.warnings).toEqual([]) + expect(imported.html).not.toContain('bridgic-word-section-') + const store = createWordDomainStore(createEmptyWordWorkspace(`sections-${changed}-${cycle}`), { defaultTitle: 'Report' }) + try { + expect((await store.dispatch({ type: 'document.open', ...imported, title: 'Sections.docx', sourcePath: '/Sections.docx', sourceMtimeMs: cycle + 1 })).ok).toBe(true) + const document = store.getSnapshot().documents[0]! + const { snapshot } = document + const sections = snapshot.body!.sectionBreaks!.filter((item) => item.defaultHeaderId !== undefined) + expect(sections).toHaveLength(3) + expect(sections.map((item) => item.useFirstPageHeaderFooter)).toEqual([1, 1, 0]) + for (const section of sections) { + expect(snapshot.body!.dataStream[section.startIndex]).toBe('\n') + expect(section.evenAndOddHeaders).toBe(1) + expect(snapshot.footers![section.defaultFooterId!]!.body.dataStream).toContain('footer-default') + expect(snapshot.headers![section.firstPageHeaderId!]!.body.dataStream).toContain('header-first') + expect(snapshot.headers![section.evenPageHeaderId!]!.body.dataStream).toContain('header-even') + } + expect(sections[2]!.defaultHeaderId).toBe(sections[1]!.defaultHeaderId) + expect(sections[2]!.firstPageFooterId).toBe(sections[1]!.firstPageFooterId) + expect(snapshot.headers![sections[0]!.defaultHeaderId!]!.body.dataStream).toContain('header-default') + if (changed) { + expect(sections[1]!.defaultHeaderId).not.toBe(sections[0]!.defaultHeaderId) + expect(snapshot.headers![sections[1]!.defaultHeaderId!]!.body.dataStream).toContain('Second chapter header') + expect(snapshot.footers![sections[1]!.firstPageFooterId!]!.body.dataStream).toBe('\r\n') + } else expect(sections.map((item) => item.defaultHeaderId)).toEqual(Array(3).fill(sections[0]!.defaultHeaderId)) + expect(Object.keys(snapshot.drawings!)).toHaveLength(2) + expect(snapshot.body!.tables).toHaveLength(1) + expect(Object.keys(snapshot.tableSource!)).toHaveLength(3) + const draft = createWordHeaderFooterDraft(snapshot, 'footerHtml') + const edited = htmlToUniverSnapshot('

footer-default edited

', draft.snapshot.id, '') + expect(store.commitEditorSnapshot(document.id, mergeWordHeaderFooterDraft(snapshot, draft, edited))).toBe(true) + await store.dispatch({ type: 'document.append', text: 'Body edit' }) + const archive = await JSZip.loadAsync(await exportWordDocx(store.getSnapshot().documents[0]!)) + const xml = await archive.file('word/document.xml')!.async('text') + expect(xml.match(//g)).toHaveLength(3) + expect(xml).toContain('Body table') + archive.remove('bridgic/editor-model.json') + bytes = await archive.generateAsync({ type: 'uint8array' }) + } finally { store.dispose() } + } + }) + + it('retains all six rich parts, flags and isolated assets through edits and two external save/reopen cycles', async () => { + let bytes = await externalDocument() + for (let cycle = 0; cycle < 3; cycle++) { + const imported = await importDocxInBackground(bytes) + expect(imported.sourceProtected).toBe(true) + expect(imported.warnings).toEqual([]) + const store = createWordDomainStore(createEmptyWordWorkspace(`variant-import-${cycle}`), { defaultTitle: 'Report' }) + try { + expect((await store.dispatch({ type: 'document.open', ...imported, title: 'Report.docx', sourcePath: '/Report.docx', sourceMtimeMs: cycle + 1 })).ok).toBe(true) + const document = store.getSnapshot().documents[0]! + const { snapshot } = document + expect(snapshot.documentStyle).toMatchObject({ useFirstPageHeaderFooter: BooleanNumber.TRUE, evenAndOddHeaders: BooleanNumber.TRUE, pageNumberStart: 3 }) + expect(document.headerFooter.differentFirstPage).toBe(true) + expect(Object.keys(snapshot.headers!)).toHaveLength(3) + expect(Object.keys(snapshot.footers!)).toHaveLength(3) + for (const kind of ['header', 'footer'] as const) { + const parts = kind === 'header' ? snapshot.headers! : snapshot.footers! + const ids = kind === 'header' + ? [snapshot.documentStyle.defaultHeaderId, snapshot.documentStyle.firstPageHeaderId, snapshot.documentStyle.evenPageHeaderId] + : [snapshot.documentStyle.defaultFooterId, snapshot.documentStyle.firstPageFooterId, snapshot.documentStyle.evenPageFooterId] + for (const [index, variant] of ['default', 'first', 'even'].entries()) { + const body = parts[ids[index]!]!.body + expect(body.dataStream).toContain(`${kind}-${variant}`) + expect(body.textRuns!.some((run) => run.ts?.bl === BooleanNumber.TRUE)).toBe(true) + if (variant !== 'first') continue + expect(body.tables).toHaveLength(1) + expect(body.customBlocks).toHaveLength(1) + const drawing = snapshot.drawings![body.customBlocks![0]!.blockId]! + expect(drawing.docTransform.size).toEqual({ width: 144, height: 36 }) + expect(drawing.unitId).toBe(document.id) + expect(body.customRanges!.find((range) => range.rangeType === CustomRangeType.HYPERLINK)?.properties?.url).toBe('https://example.com/') + } + } + expect(Object.keys(snapshot.drawings!)).toHaveLength(2) + expect(Object.keys(snapshot.tableSource!)).toHaveLength(2) + const links = [...Object.values(snapshot.headers!), ...Object.values(snapshot.footers!)].flatMap((part) => part.body.customRanges ?? []) + expect(new Set(links.map((range) => range.rangeId)).size).toBe(2) + await store.dispatch({ type: 'document.append', text: `Body correction ${cycle}` }) + expect(store.getSnapshot().documents[0]!.snapshot.headers).toEqual(snapshot.headers) + expect(store.getSnapshot().documents[0]!.snapshot.footers).toEqual(snapshot.footers) + const archive = await JSZip.loadAsync(await exportWordDocx(store.getSnapshot().documents[0]!)) + const xml = await archive.file('word/document.xml')!.async('text') + for (const kind of ['header', 'footer']) for (const type of ['default', 'first', 'even']) expect(xml).toContain(`') + expect(await archive.file('word/settings.xml')!.async('text')).toContain('') + archive.remove('bridgic/editor-model.json') + bytes = await archive.generateAsync({ type: 'uint8array' }) + } finally { store.dispose() } + } + }) + + it.each([false, true])('keeps explicit empty first-page parts without inventing a default (first-only=%s)', async (onlyFirst) => { + const imported = await importDocxInBackground(await externalDocument({ onlyFirst, emptyFirst: true })) + const { snapshot } = imported.document! + for (const kind of ['header', 'footer'] as const) { + const parts = kind === 'header' ? snapshot.headers! : snapshot.footers! + const id = kind === 'header' ? snapshot.documentStyle.firstPageHeaderId : snapshot.documentStyle.firstPageFooterId + expect(parts[id!]!.body.dataStream).toBe('\r\n') + if (onlyFirst) { + expect(Object.keys(parts)).toEqual([id!]) + expect(kind === 'header' ? snapshot.documentStyle.defaultHeaderId : snapshot.documentStyle.defaultFooterId).toBe('') + } + } + const store = createWordDomainStore(createEmptyWordWorkspace('empty-first-parts'), { defaultTitle: 'Report' }) + try { + await store.dispatch({ type: 'document.open', ...imported, title: 'Report.docx', sourcePath: '/Report.docx', sourceMtimeMs: 1 }) + const archive = await JSZip.loadAsync(await exportWordDocx(store.getSnapshot().documents[0]!)) + const xml = await archive.file('word/document.xml')!.async('text') + expect(xml.includes('Reference w:type="default"')).toBe(!onlyFirst) + expect(xml).toContain('headerReference w:type="first"') + expect(xml).toContain('footerReference w:type="first"') + } finally { store.dispose() } + }) +}) diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/wordLayout.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/wordLayout.test.ts index 2e1f7501..40321f1e 100644 --- a/desktop/apps/electron/src/renderer/lib/__tests__/wordLayout.test.ts +++ b/desktop/apps/electron/src/renderer/lib/__tests__/wordLayout.test.ts @@ -1,13 +1,166 @@ import { afterAll, describe, expect, it } from 'bun:test' import { GlobalRegistrator } from '@happy-dom/global-registrator' -import { BooleanNumber, DocumentDataModel, LocaleService } from '@univerjs/core' +import { BooleanNumber, DocumentDataModel, LocaleService, SectionType } from '@univerjs/core' import { DocumentSkeleton, DocumentViewModel, startWithEmoji } from '@univerjs/engine-render' -import { htmlToUniverSnapshot } from '../wordUniverModel' +import { appendTextBlockToSnapshot, createUniverSectionedDocumentSnapshot, htmlToUniverSnapshot } from '../wordUniverModel' GlobalRegistrator.register() afterAll(async () => { await GlobalRegistrator.unregister() }) describe('Word native layout memory sharing', () => { + it('renders a shared PAGE footer with distinct section formats and unchanged field indexes', () => { + const footer = { kind: 'footer' as const, variant: 'default' as const, id: 'shared-footer', html: '

Page 1

' } + const snapshot = createUniverSectionedDocumentSnapshot('shared-fields', 'Sections', { size: 'a4', orientation: 'portrait', margins: 'normal' }, { + headerHtml: '', footerHtml: '', showPageNumbers: false, differentFirstPage: false, pageNumberStart: 1, + }, ['lowerRoman', 'decimal'].map((pageNumberFormat) => ({ html: '

Chapter

', style: { + pageNumberFormat: pageNumberFormat as 'lowerRoman' | 'decimal', pageNumberStart: 1, defaultFooterId: footer.id, sectionType: SectionType.NEXT_PAGE, + }, parts: [footer] }))) + const model = new DocumentDataModel(snapshot) + const locale = new LocaleService() + const skeleton = new DocumentSkeleton(new DocumentViewModel(model), locale) + try { + skeleton.calculate() + const pages = skeleton.getSkeletonData()!.pages + expect(pages).toHaveLength(2) + const texts = pages.map((page) => page.footerSkeleton!.sections.flatMap((section) => section.columns.flatMap((column) => column.lines.flatMap((line) => line.divides.flatMap((divide) => divide.glyphGroup.map((glyph) => glyph.content))))).join('').trim()) + expect(texts).toEqual(['Page i', 'Page 1']) + expect(pages.map((page) => page.footerId)).toEqual([footer.id, footer.id]) + expect(pages[0]!.footerSkeleton).not.toBe(pages[1]!.footerSkeleton) + for (let page = 0; page < 2; page++) expect(skeleton.findNodePositionByCharIndex(5, true, footer.id, page)).toBeDefined() + expect(snapshot.footers![footer.id]!.body.dataStream).toBe('Page \uFFFC\r\n') + } finally { skeleton.dispose(); model.dispose(); locale.dispose() } + }) + + it('recomputes total-page fields after content grows without mutating canonical field ranges', () => { + let snapshot = createUniverSectionedDocumentSnapshot('total-fields', 'Totals', { size: 'a4', orientation: 'portrait', margins: 'normal' }, { + headerHtml: '', footerHtml: '', showPageNumbers: false, differentFirstPage: false, pageNumberStart: 1, + }, [{ html: '

Report paragraph

'.repeat(10), style: { defaultFooterId: 'total-footer' }, parts: [{ kind: 'footer', variant: 'default', id: 'total-footer', html: '

Total: 1

' }] }]) + snapshot.documentStyle.pageSize = { width: 400, height: 240 } + snapshot.documentStyle.marginTop = snapshot.documentStyle.marginBottom = 35 + let previousCount = 0 + for (let edit = 0; edit < 2; edit++) { + const canonical = structuredClone(snapshot) + const model = new DocumentDataModel(snapshot) + const locale = new LocaleService() + const skeleton = new DocumentSkeleton(new DocumentViewModel(model), locale) + try { + skeleton.calculate() + const pages = skeleton.getSkeletonData()!.pages + expect(pages.length).toBeGreaterThan(previousCount) + previousCount = pages.length + for (const page of pages) { + const glyphs = page.footerSkeleton!.sections.flatMap((section) => section.columns.flatMap((column) => column.lines.flatMap((line) => line.divides.flatMap((divide) => divide.glyphGroup)))) + expect(glyphs.find((glyph) => glyph.raw === '\uFFFC')?.content).toBe(String(pages.length)) + } + expect(snapshot).toEqual(canonical) + } finally { skeleton.dispose(); model.dispose(); locale.dispose() } + snapshot = appendTextBlockToSnapshot(snapshot, Array(30).fill('Added paragraph').join('\n'), 'paragraph') + } + }) + + it.each([ + [SectionType.ODD_PAGE, 1, true], [SectionType.ODD_PAGE, 6, false], + [SectionType.EVEN_PAGE, 1, false], [SectionType.EVEN_PAGE, 6, true], + ] as const)('respects section parity without adding body indexes (type=%s, paragraphs=%s)', (sectionType, count, needsBlank) => { + for (const restart of [false, true]) { + const snapshot = createUniverSectionedDocumentSnapshot('parity', 'Chapters', { size: 'a4', orientation: 'portrait', margins: 'normal' }, { + headerHtml: '', footerHtml: '', showPageNumbers: false, differentFirstPage: false, pageNumberStart: 1, + }, [ + { html: '

First chapter

'.repeat(count), style: { sectionType: SectionType.NEXT_PAGE }, parts: [] }, + { html: '

Second chapter

', style: { + sectionType, useFirstPageHeaderFooter: BooleanNumber.TRUE, firstPageHeaderId: 'chapter-first', + ...(restart ? { pageNumberStart: 10 } : {}), + }, parts: [{ kind: 'header', variant: 'first', id: 'chapter-first', html: '

Chapter opening

' }] }, + ]) + snapshot.documentStyle.pageSize = { width: 400, height: 240 } + snapshot.documentStyle.marginTop = snapshot.documentStyle.marginBottom = 35 + const model = new DocumentDataModel(snapshot) + const locale = new LocaleService() + const skeleton = new DocumentSkeleton(new DocumentViewModel(model), locale) + try { + skeleton.calculate() + const pages = skeleton.getSkeletonData()!.pages + const start = snapshot.body!.sectionBreaks![0]!.startIndex + 1 + const firstPageCount = count === 1 ? 1 : 2 + const secondPageIndex = firstPageCount + Number(needsBlank) + expect(pages).toHaveLength(secondPageIndex + 1) + expect((secondPageIndex + 1) % 2).toBe(sectionType === SectionType.ODD_PAGE ? 1 : 0) + expect(pages[secondPageIndex]!.st).toBe(start) + expect(pages[secondPageIndex]!.ed).toBe(snapshot.body!.dataStream.length - 1) + expect(pages[secondPageIndex]!.pageNumber).toBe(restart ? 10 : secondPageIndex + 1) + expect(pages[secondPageIndex]!.headerId).toBe('chapter-first') + if (needsBlank) { + const blank = pages[firstPageCount]! + expect(blank.sections).toHaveLength(0) + expect(blank.ed).toBeLessThan(blank.st) + expect(blank.headerId).toBe('') + expect(blank.footerId).toBe('') + } + // Recalculation must not duplicate the implicit page or move content indexes. + skeleton.makeDirty(true) + skeleton.calculate() + expect(skeleton.getSkeletonData()!.pages.map((page) => [page.st, page.ed, page.pageNumber])).toEqual(pages.map((page) => [page.st, page.ed, page.pageNumber])) + } finally { skeleton.dispose(); model.dispose(); locale.dispose() } + } + }) + + it.each([false, true])('numbers section pages correctly and renders each section first/even/default parts (restart=%s)', (restart) => { + const kinds = ['header', 'footer'] as const + const variants = ['default', 'first', 'even'] as const + const prefixes = { default: 'default', first: 'firstPage', even: 'evenPage' } + const sections = Array.from({ length: 3 }, (_, index) => ({ + html: Array.from({ length: 12 }, (_, paragraph) => `

Chapter ${index + 1} paragraph ${paragraph + 1}

`).join(''), + style: { + sectionType: SectionType.NEXT_PAGE, + useFirstPageHeaderFooter: BooleanNumber.TRUE, + evenAndOddHeaders: BooleanNumber.TRUE, + ...(index === 0 ? { pageNumberStart: 3 } : {}), + ...(restart && index === 1 ? { pageNumberStart: 10 } : {}), + ...Object.fromEntries(kinds.flatMap((kind) => variants.map((variant) => [ + `${prefixes[variant]}${kind === 'header' ? 'Header' : 'Footer'}Id`, `${kind}-${variant}-${index}`, + ]))), + }, + parts: kinds.flatMap((kind) => variants.map((variant) => ({ kind, variant, id: `${kind}-${variant}-${index}`, html: `

${kind} ${variant} ${index}

` }))), + })) + const snapshot = createUniverSectionedDocumentSnapshot('section-layout', 'Sections', { size: 'a4', orientation: 'portrait', margins: 'normal' }, { + headerHtml: '', footerHtml: '', showPageNumbers: false, differentFirstPage: true, pageNumberStart: 3, + }, sections) + snapshot.documentStyle.pageSize = { width: 400, height: 240 } + snapshot.documentStyle.marginTop = snapshot.documentStyle.marginBottom = 35 + const model = new DocumentDataModel(snapshot) + const locale = new LocaleService() + const skeleton = new DocumentSkeleton(new DocumentViewModel(model), locale) + try { + skeleton.calculate() + const pages = skeleton.getSkeletonData()!.pages + let previousNumber = 2 + for (const [index, section] of snapshot.body!.sectionBreaks!.entries()) { + const start = index === 0 ? 0 : snapshot.body!.sectionBreaks![index - 1]!.startIndex + 1 + const sectionPages = pages.filter((page) => page.st >= start && page.st <= section.startIndex) + expect(sectionPages.length).toBeGreaterThan(1) + for (const [pageIndex, page] of sectionPages.entries()) { + const expected = pageIndex === 0 && restart && index === 1 ? 10 : previousNumber + 1 + expect(page.pageNumber).toBe(expected) + let variant = expected % 2 === 0 ? 'even' : 'default' + if (pageIndex === 0) variant = 'first' + expect(page.headerId).toBe(`header-${variant}-${index}`) + expect(page.footerId).toBe(`footer-${variant}-${index}`) + previousNumber = page.pageNumber + } + } + } finally { skeleton.dispose(); model.dispose(); locale.dispose() } + }) + + it('opens a continuous first section without a preceding page', () => { + const snapshot = htmlToUniverSnapshot('

Continuous first section

', 'continuous', 'Continuous') + snapshot.body!.sectionBreaks![0]!.sectionType = SectionType.CONTINUOUS + const model = new DocumentDataModel(snapshot) + const locale = new LocaleService() + const skeleton = new DocumentSkeleton(new DocumentViewModel(model), locale) + try { skeleton.calculate(); expect(skeleton.getSkeletonData()!.pages).toHaveLength(1) } + finally { skeleton.dispose(); model.dispose(); locale.dispose() } + }) + it.each([ ['Ordinary text 😀', false], ['1234', false], ['# heading', false], ['* list', false], ['1\uFE0F\u20E3 keycap', true], ['#\u20E3 keycap', true], ['*\uFE0F\u20E3 keycap', true], diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/wordSaving.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/wordSaving.test.ts index e508386e..5bb69668 100644 --- a/desktop/apps/electron/src/renderer/lib/__tests__/wordSaving.test.ts +++ b/desktop/apps/electron/src/renderer/lib/__tests__/wordSaving.test.ts @@ -7,10 +7,72 @@ GlobalRegistrator.register() const { createWordWorkspace, createEmptyWordWorkspace, createWordDomainStore, isWordDocumentDirty } = await import('../wordDomain') const { exportWordDocx } = await import('../wordDocxExport') const { importDocxToHtml } = await import('../wordDocxImport') +const { createUniverDocumentSnapshot } = await import('../wordUniverModel') afterAll(() => GlobalRegistrator.unregister()) const saved: OfficeFileSaveResult = { ok: true, source: { path: '/report.docx', mtimeMs: 42 }, fileName: 'report.docx' } describe('Word explicit saving', () => { + it('preserves landscape Letter geometry through two external file cycles', async () => { + const store = createWordDomainStore(createWordWorkspace('landscape-letter', 'Report'), { defaultTitle: 'Report' }) + await store.dispatch({ type: 'document.update', html: '

Landscape report

' }) + await store.dispatch({ type: 'document.page.update', page: { size: 'letter', orientation: 'landscape' } }) + let current = store.getSnapshot().documents[0]! + for (let cycle = 0; cycle < 2; cycle++) { + const zip = await JSZip.loadAsync(await exportWordDocx(current)) + expect(await zip.file('word/document.xml')!.async('string')).toContain('w:w="15840" w:h="12240" w:orient="landscape"') + zip.remove('bridgic/editor-model.json') + const imported = await importDocxToHtml(await zip.generateAsync({ type: 'uint8array' })) + const { page, headerFooter } = imported.layout! + expect(page).toMatchObject({ size: 'letter', orientation: 'landscape' }) + current = { ...current, page, headerFooter, snapshot: createUniverDocumentSnapshot(current.id, current.title, page, headerFooter, imported.html) } + expect(current.snapshot.documentStyle.pageSize).toEqual({ width: 816, height: 1056 }) + } + store.dispose() + }) + + it('retains rich header/footer images and sizes through external import and repeated saving', async () => { + const logo = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl6T4cAAAAASUVORK5CYII=' + const store = createWordDomainStore(createWordWorkspace('rich-header', 'Report'), { defaultTitle: 'Report' }) + await store.dispatch({ type: 'document.update', html: '

Report body

' }) + await store.dispatch({ type: 'document.headerFooter.update', settings: { + headerHtml: `

Brand

`, + footerHtml: `

Confidential

`, + } }) + let bytes = await exportWordDocx(store.getSnapshot().documents[0]!) + for (let cycle = 0; cycle < 2; cycle++) { + const zip = await JSZip.loadAsync(bytes) + const headerXml = await zip.file('word/header.xml')!.async('string') + expect(headerXml).toContain('cx="762000" cy="190500"') + expect(headerXml).toContain('') + expect(await zip.file('word/_rels/header.xml.rels')!.async('string')).toContain('relationships/image') + // Exercise ordinary external DOCX import, not the embedded native snapshot. + zip.remove('bridgic/editor-model.json') + const imported = await importDocxToHtml(await zip.generateAsync({ type: 'uint8array' })) + expect(imported.document).toBeUndefined() + expect(imported.layout!.headerFooter.headerHtml).toContain('Brand') + expect(imported.layout!.headerFooter.headerHtml).toContain('width="80" height="20"') + const { page, headerFooter } = imported.layout! + const reopened = createWordDomainStore(createEmptyWordWorkspace(`rich-header-${cycle}`), { defaultTitle: 'Report' }) + try { + expect((await reopened.dispatch({ type: 'document.open', title: 'Report.docx', sourcePath: '/Report.docx', sourceMtimeMs: cycle + 1, ...imported, document: { + snapshot: createUniverDocumentSnapshot('imported', 'Report', page, headerFooter, imported.html), + page, headerFooter, footnotes: [], citations: [], + } })).ok).toBe(true) + const document = reopened.getSnapshot().documents[0]! + const header = document.snapshot.headers![document.snapshot.documentStyle.defaultHeaderId!]!.body + const footer = document.snapshot.footers![document.snapshot.documentStyle.defaultFooterId!]!.body + expect(header.customBlocks).toHaveLength(1) + expect(footer.customBlocks).toHaveLength(1) + expect(header.textRuns!.some((run) => run.ts?.bl === 1)).toBe(true) + expect(footer.textRuns!.some((run) => run.ts?.it === 1)).toBe(true) + expect(Object.values(document.snapshot.drawings!)).toHaveLength(2) + await reopened.dispatch({ type: 'document.append', text: `Correction ${cycle}` }) + bytes = await exportWordDocx(reopened.getSnapshot().documents[0]!) + } finally { reopened.dispose() } + } + store.dispose() + }) + it('opens Save as when closing an edited source that requires protection', async () => { const save = mock(async (): Promise => ({ ok: true, source: { path: '/Copy.docx', mtimeMs: 2 }, fileName: 'Copy.docx' })) const store = createWordDomainStore(createEmptyWordWorkspace('protected-close'), { defaultTitle: 'Report', confirmClose: async () => 'save', saveDocument: save }) diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/wordUniverModel.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/wordUniverModel.test.ts index fea4cf8a..a7c0da78 100644 --- a/desktop/apps/electron/src/renderer/lib/__tests__/wordUniverModel.test.ts +++ b/desktop/apps/electron/src/renderer/lib/__tests__/wordUniverModel.test.ts @@ -1,11 +1,12 @@ import { afterAll, describe, expect, it } from 'bun:test' import { GlobalRegistrator } from '@happy-dom/global-registrator' -import { BooleanNumber, DOC_RANGE_TYPE, NamedStyleType } from '@univerjs/core' +import { BooleanNumber, CustomRangeType, DOC_RANGE_TYPE, NamedStyleType } from '@univerjs/core' GlobalRegistrator.register() const { appendTextBlockToSnapshot, + applyHeaderFooterToSnapshot, createUniverDocumentSnapshot, extractWordReferences, getUniverDocumentText, @@ -13,6 +14,7 @@ const { getUniverPageCount, getUniverWordCount, htmlToUniverSnapshot, + normalizeUniverDocumentSnapshot, insertReferenceInSnapshot, removeReferenceFromSnapshot, updateReferenceInSnapshot, @@ -33,6 +35,68 @@ const headerFooter = { } describe('Univer Word model', () => { + it('parses safe hyperlinks with exact inclusive ranges and retains nested formatting', () => { + const snapshot = htmlToUniverSnapshot('

Visit our site or email us.Unsafe

', 'links', 'Links') + const body = snapshot.body! + expect(body.customRanges).toHaveLength(2) + expect(body.customRanges!.map((range) => ({ text: body.dataStream.slice(range.startIndex, range.endIndex + 1), type: range.rangeType, url: range.properties?.url }))).toEqual([ + { text: 'our site', type: CustomRangeType.HYPERLINK, url: 'https://example.com/?q=one&lang=en' }, + { text: 'email us', type: CustomRangeType.HYPERLINK, url: 'mailto:team@example.com' }, + ]) + expect(body.textRuns?.some((run) => run.st === 6 && run.ed === 14 && run.ts?.bl === BooleanNumber.TRUE)).toBe(true) + }) + + it('parses paragraph spacing in paragraphs, list items and table cells without inventing invalid values', () => { + const snapshot = htmlToUniverSnapshot('

Body

  • List

Cell

Defaults

', 'spacing', 'Spacing') + expect(snapshot.body!.paragraphs!.map((paragraph) => paragraph.paragraphStyle)).toEqual([ + { lineSpacing: 1.5, spaceAbove: { v: 12 }, spaceBelow: { v: 0 } }, + { lineSpacing: 2, spaceAbove: { v: 12 }, spaceBelow: { v: 18 } }, + { lineSpacing: 1.25, spaceAbove: { v: 0 }, spaceBelow: { v: 8 } }, + undefined, + ]) + }) + + it('keeps header/footer hyperlink identities stable and separate from the main body', () => { + const html = '

Website

' + const settings = { ...headerFooter, headerHtml: html, footerHtml: html } + const snapshot = createUniverDocumentSnapshot('stable-links', 'Report', page, settings, html) + expect(applyHeaderFooterToSnapshot(snapshot, settings)).toEqual(snapshot) + const ranges = [snapshot.body!, snapshot.headers!['bridgic-word-header']!.body, snapshot.footers!['bridgic-word-footer']!.body].flatMap((body) => body.customRanges ?? []) + expect(new Set(ranges.map((range) => range.rangeId)).size).toBe(3) + }) + + it('keeps rich header/footer images, tables and lists stable without changing body assets', () => { + const png = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Y9ZQmcAAAAASUVORK5CYII=' + const settings = { ...headerFooter, + headerHtml: `

Brand

Header table
  • Header list
`, + footerHtml: `

Footer

`, + } + const snapshot = createUniverDocumentSnapshot('rich-header', 'Report', page, settings, `

Body
  • Body list
`) + const header = snapshot.headers!['bridgic-word-header']!.body + const footer = snapshot.footers!['bridgic-word-footer']!.body + const headerDrawing = snapshot.drawings![header.customBlocks![0]!.blockId]! + expect(headerDrawing.docTransform.size).toEqual({ width: 80, height: 20 }) + expect(header.textRuns?.some((run) => run.ts?.bl === 1)).toBe(true) + expect(footer.textRuns?.some((run) => run.ts?.it === 1)).toBe(true) + expect(header.tables).toHaveLength(1) + expect(Object.keys(snapshot.drawings!)).toHaveLength(3) + expect(Object.keys(snapshot.tableSource!)).toHaveLength(2) + expect(Object.keys(snapshot.lists!)).toHaveLength(2) + expect(applyHeaderFooterToSnapshot(snapshot, settings)).toEqual(snapshot) + // Native header edits must survive the same normalization used for ordinary typing. + headerDrawing.docTransform.size.width = 90 + header.dataStream = header.dataStream.replace('Brand', 'Updated brand') + expect(normalizeUniverDocumentSnapshot(snapshot, snapshot.id, snapshot.title!, page, settings)).toEqual(snapshot) + const withoutHeader = applyHeaderFooterToSnapshot(snapshot, { ...settings, headerHtml: '' }) + expect(withoutHeader.headers).toEqual({}) + expect(Object.keys(withoutHeader.drawings!)).toHaveLength(2) + expect(Object.keys(withoutHeader.tableSource!)).toHaveLength(1) + expect(Object.keys(withoutHeader.lists!)).toHaveLength(1) + expect(withoutHeader.body).toEqual(snapshot.body) + const imageOnly = applyHeaderFooterToSnapshot(withoutHeader, { ...settings, headerHtml: `

` }) + expect(imageOnly.documentStyle.defaultHeaderId).toBe('bridgic-word-header') + expect(imageOnly.headers!['bridgic-word-header']!.body.customBlocks).toHaveLength(1) + }) it('converts legacy HTML into native paragraphs, text styles, lists, and headings', () => { const snapshot = htmlToUniverSnapshot( '

Overview

Hello world

  • First
  • Second
', diff --git a/desktop/apps/electron/src/renderer/lib/apiStub.ts b/desktop/apps/electron/src/renderer/lib/apiStub.ts index d62b136d..9a218362 100644 --- a/desktop/apps/electron/src/renderer/lib/apiStub.ts +++ b/desktop/apps/electron/src/renderer/lib/apiStub.ts @@ -122,6 +122,7 @@ export function installApiStub(): void { webContentsId: 0, loading: false, crashed: false, + documentCount: null, }), closeSession: async () => {}, activateSession: async () => {}, @@ -129,8 +130,16 @@ export function installApiStub(): void { setVisible: async () => {}, requestClose: async () => {}, setExpanded: async () => {}, + reportState: async () => {}, + openDocument: async () => { throw new Error('Opening PowerPoint files requires Electron') }, openFile: async () => { throw new Error('Opening PowerPoint files requires Electron') }, }, + mountReferences: { + usage: async () => ({ assetCount: 0, elementCount: 0, projectCount: 0 }), + remove: async () => ({ assetCount: 0, elementCount: 0, projectCount: 0 }), + rebind: async () => { throw new Error('Session files require Electron') }, + refresh: async () => {}, + }, word: { readDocument: async () => { throw new Error('Word document reads require Electron') @@ -155,6 +164,7 @@ export function installApiStub(): void { ready: false, crashed: false, dirty: false, + documentCount: null, }), openWorkbook: async () => {}, closeSession: async () => {}, diff --git a/desktop/apps/electron/src/renderer/lib/excelDrawingImport.ts b/desktop/apps/electron/src/renderer/lib/excelDrawingImport.ts new file mode 100644 index 00000000..02808f13 --- /dev/null +++ b/desktop/apps/electron/src/renderer/lib/excelDrawingImport.ts @@ -0,0 +1,177 @@ +import JSZip from 'jszip' +import { DOMParser, XMLSerializer } from '@xmldom/xmldom' + +interface DrawingAnchor { column: number; row: number; columnOffset: number; rowOffset: number } +export interface ImportedSheetTextBox { source: string; from: DrawingAnchor; to: DrawingAnchor } + +/** Preview ordinary native text boxes without pretending Univer supports editable Office shapes. */ +export async function importSheetTextBoxes(archive: JSZip, sheets: Map): Promise> { + const result = new Map() + const parser = new DOMParser() + const serializer = new XMLSerializer() + const children = (node: Element, name: string) => Array.from(node.childNodes).filter((child): child is Element => child.nodeType === 1 && (child as Element).localName === name) + const descendants = (node: Element, name: string) => Array.from(node.getElementsByTagName('*')).filter((child) => child.localName === name) + const context = typeof OffscreenCanvas === 'undefined' ? null : new OffscreenCanvas(1, 1).getContext('2d') + const graphemes = new Intl.Segmenter(undefined, { granularity: 'grapheme' }) + const wrapText = (text: string, width: number, size: number, font: string, wrap: boolean): string[] => { + if (context) context.font = font + const measure = (value: string) => { + if (context) return context.measureText(value).width + return Array.from(value).reduce((sum, character) => { + if (/\s/.test(character)) return sum + size * 0.33 + return sum + size * (character.codePointAt(0)! > 255 ? 1 : 0.55) + }, 0) + } + const lines: string[] = [] + for (const explicitLine of text.replace(/\r\n?/g, '\n').split('\n')) { + if (!wrap) { lines.push(explicitLine); continue } + let line = '' + for (const { segment } of graphemes.segment(explicitLine)) { + if (line && measure(line + segment) > width) { + const boundary = Math.max(line.lastIndexOf(' '), line.lastIndexOf('\t')) + if (boundary > 0) { + lines.push(line.slice(0, boundary).trimEnd()) + line = line.slice(boundary + 1) + segment + } else { + lines.push(line.trimEnd()) + line = segment.trimStart() + } + } else line += segment + } + lines.push(line) + } + return lines + } + const themeFile = archive.file('xl/theme/theme1.xml') + const theme = themeFile ? parser.parseFromString(await themeFile.async('text'), 'text/xml') : undefined + const scheme = theme && descendants(theme.documentElement, 'clrScheme')[0] + const fillColor = (fill: Element | undefined, fallback: string) => { + if (!fill) return fallback + const color = children(fill, 'srgbClr')[0] ?? children(fill, 'schemeClr')[0] ?? children(fill, 'sysClr')[0] + if (!color) return fallback + let hex = color.getAttribute('val') ?? '' + if (color.localName === 'schemeClr') { + const entry = scheme && children(scheme, hex)[0] + const rgb = entry && children(entry, 'srgbClr')[0] + const system = entry && children(entry, 'sysClr')[0] + hex = rgb?.getAttribute('val') ?? system?.getAttribute('lastClr') ?? '' + } else if (color.localName === 'sysClr') hex = color.getAttribute('lastClr') ?? '' + if (!/^[0-9a-f]{6}$/i.test(hex)) return fallback + const mod = Number(children(color, 'lumMod')[0]?.getAttribute('val') ?? 100000) / 100000 + const off = Number(children(color, 'lumOff')[0]?.getAttribute('val') ?? 0) / 100000 + return `#${[0, 2, 4].map((offset) => Math.round(Math.min(255, Math.max(0, parseInt(hex.slice(offset, offset + 2), 16) * mod + 255 * off))).toString(16).padStart(2, '0')).join('')}` + } + const pathFor = (part: string, target: string) => { + const parts: string[] = [] + for (const segment of (target.startsWith('/') ? target.slice(1) : `${part.slice(0, part.lastIndexOf('/') + 1)}${target}`).split('/')) { + if (segment === '..') parts.pop() + else if (segment && segment !== '.') parts.push(segment) + } + return parts.join('/') + } + for (const [sheetId, sheet] of sheets) { + const relsPath = sheet.path.replace(/\/([^/]+)$/, '/_rels/$1.rels') + const relsFile = archive.file(relsPath) + if (!relsFile) continue + const rels = parser.parseFromString(await relsFile.async('text'), 'text/xml') + const boxes: ImportedSheetTextBox[] = [] + for (const rel of Array.from(rels.getElementsByTagName('*'))) { + if (!rel.getAttribute('Type')?.endsWith('/drawing') || rel.getAttribute('TargetMode') === 'External') continue + const file = archive.file(pathFor(sheet.path, rel.getAttribute('Target') ?? '')) + if (!file) continue + const drawing = parser.parseFromString(await file.async('text'), 'text/xml') + for (const anchor of Array.from(drawing.documentElement.childNodes).filter((node): node is Element => node.nodeType === 1)) { + const shape = children(anchor, 'sp')[0] + const body = shape && children(shape, 'txBody')[0] + const from = children(anchor, 'from')[0] + const to = children(anchor, 'to')[0] + if (!shape || !body || !from) continue + const marker = (node: Element): DrawingAnchor => ({ + column: Number(children(node, 'col')[0]?.textContent ?? 0), row: Number(children(node, 'row')[0]?.textContent ?? 0), + columnOffset: Number(children(node, 'colOff')[0]?.textContent ?? 0) / 9525, rowOffset: Number(children(node, 'rowOff')[0]?.textContent ?? 0) / 9525, + }) + const extent = descendants(shape, 'ext')[0] + const width = Number(extent?.getAttribute('cx')) / 9525 + const height = Number(extent?.getAttribute('cy')) / 9525 + if (!(width > 0 && height > 0)) continue + const svg = parser.parseFromString('', 'text/xml') + svg.documentElement.setAttribute('width', String(width)) + svg.documentElement.setAttribute('height', String(height)) + svg.documentElement.setAttribute('viewBox', `0 0 ${width} ${height}`) + const properties = children(shape, 'spPr')[0] + const line = properties && children(properties, 'ln')[0] + const background = svg.createElementNS('http://www.w3.org/2000/svg', 'rect') + background.setAttribute('width', String(width)) + background.setAttribute('height', String(height)) + background.setAttribute('fill', fillColor(properties && children(properties, 'solidFill')[0], 'none')) + background.setAttribute('stroke', fillColor(line && children(line, 'solidFill')[0], 'none')) + background.setAttribute('stroke-width', String(Number(line?.getAttribute('w') || 9525) / 9525)) + svg.documentElement.appendChild(background) + const bodyProperties = children(body, 'bodyPr')[0] + const inset = (name: string, fallback: number) => Number(bodyProperties?.getAttribute(name) || fallback) / 9525 + const left = inset('lIns', 91440) + const right = inset('rIns', 91440) + const top = inset('tIns', 45720) + const bottom = inset('bIns', 45720) + const fontScale = Number(bodyProperties && children(bodyProperties, 'normAutofit')[0]?.getAttribute('fontScale') || 100000) / 100000 + const lines: Array<{ text: string; x: number; y: number; size: number; font: string; alignment?: string | null; properties?: Element }> = [] + let y = 0 + for (const paragraph of children(body, 'p')) { + const text = Array.from(paragraph.childNodes).filter((child): child is Element => child.nodeType === 1) + .map((child) => child.localName === 'br' ? '\n' : descendants(child, 't').map((run) => run.textContent ?? '').join('')).join('') + const properties = descendants(paragraph, 'rPr')[0] ?? descendants(paragraph, 'defRPr')[0] + const size = Number(properties?.getAttribute('sz') || 1100) / 75 * fontScale + const family = properties && (children(properties, 'latin')[0]?.getAttribute('typeface') || children(properties, 'ea')[0]?.getAttribute('typeface')) || 'Arial' + const font = `${properties?.getAttribute('b') === '1' ? 'bold ' : ''}${size}px "${family}", sans-serif` + const paragraphProperties = children(paragraph, 'pPr')[0] + const alignment = paragraphProperties?.getAttribute('algn') + const marginLeft = Number(paragraphProperties?.getAttribute('marL') || 0) / 9525 + const marginRight = Number(paragraphProperties?.getAttribute('marR') || 0) / 9525 + const available = Math.max(1, width - left - right - marginLeft - marginRight) + const spacing = paragraphProperties && children(paragraphProperties, 'lnSpc')[0] + const points = spacing && children(spacing, 'spcPts')[0] + const percent = spacing && children(spacing, 'spcPct')[0] + const lineHeight = points ? Number(points.getAttribute('val')) / 75 : size * Number(percent?.getAttribute('val') || 125000) / 100000 + const paragraphSpacing = (name: string) => { + const spacing = paragraphProperties && children(paragraphProperties, name)[0] + return spacing ? Number(children(spacing, 'spcPts')[0]?.getAttribute('val') || 0) / 75 : 0 + } + y += paragraphSpacing('spcBef') + let x = left + marginLeft + if (alignment === 'ctr') x += available / 2 + else if (alignment === 'r') x += available + for (const lineText of wrapText(text, available, size, font, bodyProperties?.getAttribute('wrap') !== 'none')) { + lines.push({ text: lineText, x, y: y + size, size, font: `"${family}", sans-serif`, alignment, properties }) + y += lineHeight + } + y += paragraphSpacing('spcAft') + } + let verticalOffset = top + if (bodyProperties?.getAttribute('anchor') === 'ctr') verticalOffset += Math.max(0, (height - top - bottom - y) / 2) + else if (bodyProperties?.getAttribute('anchor') === 'b') verticalOffset += Math.max(0, height - top - bottom - y) + for (const { text, x, y, size, font, alignment, properties } of lines) { + const node = svg.createElementNS('http://www.w3.org/2000/svg', 'text') + node.setAttribute('x', String(x)) + if (alignment === 'ctr') node.setAttribute('text-anchor', 'middle') + else if (alignment === 'r') node.setAttribute('text-anchor', 'end') + node.setAttribute('y', String(verticalOffset + y)) + node.setAttribute('font-family', font) + node.setAttribute('font-size', String(size)) + node.setAttribute('xml:space', 'preserve') + node.setAttribute('fill', fillColor(properties && children(properties, 'solidFill')[0], '#000000')) + if (properties?.getAttribute('b') === '1') node.setAttribute('font-weight', 'bold') + node.appendChild(svg.createTextNode(text)) + svg.documentElement.appendChild(node) + } + const bytes = new TextEncoder().encode(serializer.serializeToString(svg)) + let binary = '' + for (let offset = 0; offset < bytes.length; offset += 8192) binary += String.fromCharCode(...bytes.subarray(offset, offset + 8192)) + const start = marker(from) + const end = to ? marker(to) : { ...start, columnOffset: start.columnOffset + width, rowOffset: start.rowOffset + height } + boxes.push({ source: `data:image/svg+xml;base64,${btoa(binary)}`, from: start, to: end }) + } + } + if (boxes.length) result.set(sheetId, boxes) + } + return result +} diff --git a/desktop/apps/electron/src/renderer/lib/excelWorkbook.ts b/desktop/apps/electron/src/renderer/lib/excelWorkbook.ts index f334fbf8..fa62f101 100644 --- a/desktop/apps/electron/src/renderer/lib/excelWorkbook.ts +++ b/desktop/apps/electron/src/renderer/lib/excelWorkbook.ts @@ -9,6 +9,7 @@ import { type Worksheet, } from 'exceljs' import JSZip from 'jszip' +import { importSheetTextBoxes } from './excelDrawingImport' import { prepareOfficeImage } from './office/officeImage' import { SaxesParser, type SaxesTagNS } from 'saxes' import { @@ -17,6 +18,7 @@ import { CellValueType, CustomRangeType, DrawingTypeEnum, + ImageSourceType, HorizontalAlign, LocaleType, VerticalAlign, @@ -39,7 +41,7 @@ const FILTER_RESOURCE = 'SHEET_FILTER_PLUGIN' const DATA_VALIDATION_RESOURCE = 'SHEET_DATA_VALIDATION_PLUGIN' const CONDITIONAL_FORMATTING_RESOURCE = 'SHEET_CONDITIONAL_FORMATTING_PLUGIN' const DRAWING_RESOURCE = 'SHEET_DRAWING_PLUGIN' -const COMPATIBILITY_CUSTOM_KEY = 'bridgicXlsxUnsupportedFeatures' +export const COMPATIBILITY_CUSTOM_KEY = 'bridgicXlsxUnsupportedFeatures' export const EXCEL_SHOW_ZEROS_CUSTOM_KEY = 'bridgicExcelShowZeros' const BRIDGIC_METADATA_MARKER = 'Bridgic Excel internal metadata v1' const BRIDGIC_METADATA_SHEET = '__BRIDGIC_INTERNAL__' @@ -614,8 +616,20 @@ export async function importXlsx(bytes: Uint8Array, locale: LocaleType, onProgre onProgress?.({ phase: 'reading' }) const archive = await JSZip.loadAsync(bytes) const nativeViews = await readNativeSheetViews(archive) + const textBoxes = await importSheetTextBoxes(archive, nativeViews) const workbook = new Workbook() - const input = bytes.slice().buffer as ArrayBuffer + // ExcelJS rejects legal table filters it does not implement. Strip only those + // optional criteria from a decoder copy; keep the original for compatibility checks. + const decoderArchive = await JSZip.loadAsync(bytes) + let normalizedFilters = false + for (const entry of Object.values(decoderArchive.files)) { + if (!/^xl\/tables\/[^/]+\.xml$/.test(entry.name)) continue + const xml = await entry.async('text') + const normalized = xml.replace(/<((?:\w+:)?filterColumn)\b[^>]*>[\s\S]*?<\/\1\s*>/g, (column) => + column.replace(/<(?:\w+:)?(?:iconFilter|colorFilter|dynamicFilter|top10|extLst)\b[^>]*(?:\/\s*>|>[\s\S]*?<\/(?:\w+:)?(?:iconFilter|colorFilter|dynamicFilter|top10|extLst)\s*>)/g, '')) + if (normalized !== xml) { decoderArchive.file(entry.name, normalized); normalizedFilters = true } + } + const input = normalizedFilters ? await decoderArchive.generateAsync({ type: 'arraybuffer' }) : bytes.slice().buffer as ArrayBuffer await workbook.xlsx.load(input) const bridgicMetadata = readBridgicMetadata(workbook) const snapshot = workbookSnapshot(locale, workbook.title || 'Workbook') @@ -764,13 +778,14 @@ export async function importXlsx(bytes: Uint8Array, locale: LocaleType, onProgre let imageIndex = 0 for (const image of worksheet.getImages()) { const source = workbook.getImage(Number(image.imageId)) - const extension = source.extension === 'jpeg' || source.extension === 'gif' ? source.extension : 'png' + const extension = String(source.extension).toLowerCase().replace(/^jpg$/, 'jpeg') const base64 = source.base64 ?? (source.buffer ? bytesToBase64(new Uint8Array(source.buffer)) : null) if (!base64) continue const range = image.range as unknown as { tl: { col: number; row: number } - br: { col: number; row: number } + br?: { col: number; row: number } + ext?: { width: number; height: number } } const storedDrawings = bridgicMetadata?.drawingIds[sheetName] ?? [] const anchored = storedDrawings.find((candidate) => candidate @@ -786,12 +801,16 @@ export async function importXlsx(bytes: Uint8Array, locale: LocaleType, onProgre usedDrawingIds.add(drawingId) const sheetTransform = { from: anchorPosition(range.tl), - to: anchorPosition(range.br), + to: range.br ? anchorPosition(range.br) : { + ...anchorPosition(range.tl), + columnOffset: anchorPosition(range.tl).columnOffset + (range.ext?.width ?? 320), + rowOffset: anchorPosition(range.tl).rowOffset + (range.ext?.height ?? 200), + }, } sheetDrawings[drawingId] = { drawingId, drawingType: DrawingTypeEnum.DRAWING_IMAGE, - imageSourceType: 'BASE64', + imageSourceType: ImageSourceType.BASE64, source: base64.startsWith('data:') ? base64 : `data:image/${extension};base64,${base64}`, unitId: snapshot.id, subUnitId: sheetId, @@ -799,7 +818,12 @@ export async function importXlsx(bytes: Uint8Array, locale: LocaleType, onProgre axisAlignSheetTransform: sheetTransform, } } - if (Object.keys(sheetDrawings).length > 0) drawingResources[sheetId] = sheetDrawings + for (const box of textBoxes.get(worksheet.id) ?? []) { + const drawingId = crypto.randomUUID() + const sheetTransform = { from: box.from, to: box.to } + sheetDrawings[drawingId] = { drawingId, drawingType: DrawingTypeEnum.DRAWING_IMAGE, imageSourceType: ImageSourceType.BASE64, source: box.source, unitId: snapshot.id, subUnitId: sheetId, sheetTransform, axisAlignSheetTransform: sheetTransform } + } + if (Object.keys(sheetDrawings).length > 0) drawingResources[sheetId] = { data: sheetDrawings, order: Object.keys(sheetDrawings) } completed += 1 onProgress?.({ phase: 'converting', completed, total }) }) @@ -815,6 +839,7 @@ export async function importXlsx(bytes: Uint8Array, locale: LocaleType, onProgre } } const incompatible = await unsupportedFeatures(archive, workbook, nativeViews) + if (normalizedFilters && !incompatible.includes('active filter criteria')) incompatible.push('active filter criteria') if (incompatible.length > 0) { snapshot.custom = { ...snapshot.custom, [COMPATIBILITY_CUSTOM_KEY]: incompatible } } @@ -830,14 +855,14 @@ function bytesToBase64(bytes: Uint8Array): string { return btoa(binary) } -function anchorPosition(anchor: { col: number; row: number }) { - const column = Math.max(0, Math.floor(anchor.col)) - const row = Math.max(0, Math.floor(anchor.row)) +function anchorPosition(anchor: { col: number; row: number; nativeCol?: number; nativeRow?: number; nativeColOff?: number; nativeRowOff?: number }) { + const column = Math.max(0, anchor.nativeCol ?? Math.floor(anchor.col)) + const row = Math.max(0, anchor.nativeRow ?? Math.floor(anchor.row)) return { column, row, - columnOffset: Math.max(0, anchor.col - column) * 64, - rowOffset: Math.max(0, anchor.row - row) * 20, + columnOffset: anchor.nativeColOff !== undefined ? Math.max(0, anchor.nativeColOff / 9525) : Math.max(0, anchor.col - column) * 64, + rowOffset: anchor.nativeRowOff !== undefined ? Math.max(0, anchor.nativeRowOff / 9525) : Math.max(0, anchor.row - row) * 20, } } @@ -1041,10 +1066,12 @@ function hyperlinkFromCell(data: ICellData): { hyperlink: string; text: string } return { hyperlink, text } } -function fractionalAnchor(value: ResourceRule | undefined): { col: number; row: number } { +function nativeAnchor(value: ResourceRule | undefined) { return { - col: Math.max(0, Number(value?.column ?? 0) + Number(value?.columnOffset ?? 0) / 64), - row: Math.max(0, Number(value?.row ?? 0) + Number(value?.rowOffset ?? 0) / 20), + nativeCol: Math.max(0, Math.floor(Number(value?.column ?? 0))), + nativeRow: Math.max(0, Math.floor(Number(value?.row ?? 0))), + nativeColOff: Math.round(Math.max(0, Number(value?.columnOffset ?? 0)) * 9525), + nativeRowOff: Math.round(Math.max(0, Number(value?.rowOffset ?? 0)) * 9525), } } @@ -1170,7 +1197,14 @@ export async function exportXlsx( const sheetDrawings = drawings[sheetId] if (sheetDrawings && typeof sheetDrawings === 'object' && !Array.isArray(sheetDrawings)) { const drawingIds: Array<{ column: number; id: string; row: number }> = [] - for (const value of Object.values(sheetDrawings as ResourceMap)) { + const data = (sheetDrawings as ResourceMap).data ?? sheetDrawings + const order = (sheetDrawings as ResourceMap).order + const orderedIds = Array.isArray(order) ? order.filter((id): id is string => typeof id === 'string') : [] + // Native arrange commands update order, not the insertion order of the data map. + const ids = [...new Set([...orderedIds, ...Object.keys(data as ResourceMap)])] + for (const id of ids) { + const value = (data as ResourceMap)[id] + if (!value) continue const drawing = value as ResourceRule if (drawing.drawingType !== DrawingTypeEnum.DRAWING_IMAGE) { conversionFailures.add('non-image drawing') @@ -1190,8 +1224,8 @@ export async function exportXlsx( }) } worksheet.addImage(imageId, { - tl: fractionalAnchor(transform.from as ResourceRule), - br: fractionalAnchor(transform.to as ResourceRule), + tl: nativeAnchor(transform.from as ResourceRule), + br: nativeAnchor(transform.to as ResourceRule), editAs: 'oneCell', } as never) } diff --git a/desktop/apps/electron/src/renderer/lib/excelWorkbookImport.ts b/desktop/apps/electron/src/renderer/lib/excelWorkbookImport.ts index 6ba9b07d..b009e571 100644 --- a/desktop/apps/electron/src/renderer/lib/excelWorkbookImport.ts +++ b/desktop/apps/electron/src/renderer/lib/excelWorkbookImport.ts @@ -1,5 +1,30 @@ import type { IWorkbookData, LocaleType } from '@univerjs/core' -import type { ExcelImportProgress } from './excelWorkbook' +import { COMPATIBILITY_CUSTOM_KEY, unsupportedWorkbookFeatures, type ExcelImportProgress } from './excelWorkbook' +import { prepareOfficeImage } from './office/officeImage' + +async function prepareWorkbookImages(snapshot: IWorkbookData, signal?: AbortSignal): Promise { + const resource = snapshot.resources?.find((value) => value.name === 'SHEET_DRAWING_PLUGIN') + if (!resource) return snapshot + const drawings = JSON.parse(resource.data) as Record; order: string[] }> + for (const sheet of Object.values(drawings)) { + for (const [id, drawing] of Object.entries(sheet.data)) { + if (signal?.aborted) throw new DOMException('Workbook import canceled.', 'AbortError') + if (!drawing.source) continue + try { + drawing.source = (await prepareOfficeImage(drawing.source, 'excel')).dataUrl + } catch { + // One unsupported image must not hide an otherwise readable workbook. + // Compatibility metadata prevents an automatic lossy overwrite of the source. + delete sheet.data[id] + sheet.order = sheet.order.filter((drawingId) => drawingId !== id) + snapshot.custom = { ...snapshot.custom, [COMPATIBILITY_CUSTOM_KEY]: [...new Set([...unsupportedWorkbookFeatures(snapshot), 'unrenderable embedded images'])] } + } + } + } + if (signal?.aborted) throw new DOMException('Workbook import canceled.', 'AbortError') + resource.data = JSON.stringify(drawings) + return snapshot +} export type ExcelImportWorkerResponse = | { type: 'progress'; progress: ExcelImportProgress } @@ -36,7 +61,7 @@ export function importExcelWorkbook(bytes: Uint8Array, locale: LocaleType, optio if (response.type === 'progress') onProgress?.(response.progress) else if (response.type === 'complete') { cleanup() - resolve(response.snapshot) + void prepareWorkbookImages(response.snapshot, signal).then(resolve, reject) } else fail(new Error(response.message)) } worker.onerror = (event) => fail(new Error(event.message || 'Workbook import worker failed.')) diff --git a/desktop/apps/electron/src/renderer/lib/fileTypes.ts b/desktop/apps/electron/src/renderer/lib/fileTypes.ts index acec7e7c..bfa8ae4d 100644 --- a/desktop/apps/electron/src/renderer/lib/fileTypes.ts +++ b/desktop/apps/electron/src/renderer/lib/fileTypes.ts @@ -2,3 +2,8 @@ export function isDocxFileName(name: string): boolean { return name.trim().toLocaleLowerCase().endsWith('.docx') } + +/** Office formats owned by the in-app viewers open on a single click. */ +export function isOfficePreviewFileName(name: string): boolean { + return /\.(?:docx|xlsx|pptx)$/i.test(name.trim()) +} diff --git a/desktop/apps/electron/src/renderer/lib/office/__tests__/workspacePersistence.test.ts b/desktop/apps/electron/src/renderer/lib/office/__tests__/workspacePersistence.test.ts new file mode 100644 index 00000000..26f05917 --- /dev/null +++ b/desktop/apps/electron/src/renderer/lib/office/__tests__/workspacePersistence.test.ts @@ -0,0 +1,87 @@ +import { expect, it } from 'bun:test' +import { createIndexedDbWorkspacePersistence } from '../workspacePersistence' + +function fakeIndexedDb() { + const records = new Map() + let hasStore = false + let closed = false + const database = { + close: () => { closed = true }, + createObjectStore: () => { hasStore = true }, + objectStoreNames: { contains: () => hasStore }, + onversionchange: null, + transaction: (_storeName: string, mode: IDBTransactionMode) => { + const transaction = { + error: null, + onabort: null as (() => void) | null, + oncomplete: null as (() => void) | null, + onerror: null as (() => void) | null, + objectStore: () => ({ + get: (key: IDBValidKey) => { + const request = { error: null, onsuccess: null as (() => void) | null, onerror: null as (() => void) | null, result: undefined as unknown } + queueMicrotask(() => { + request.result = records.has(key) ? structuredClone(records.get(key)) : undefined + request.onsuccess?.() + }) + return request + }, + put: (value: unknown, key: IDBValidKey) => { + records.set(key, structuredClone(value)) + queueMicrotask(() => transaction.oncomplete?.()) + }, + }), + } + if (mode !== 'readonly' && mode !== 'readwrite') throw new Error('Unexpected transaction mode') + return transaction + }, + } + const factory = { + open: (_name: string, _version: number) => { + const request = { + error: null, + onerror: null as (() => void) | null, + onsuccess: null as (() => void) | null, + onupgradeneeded: null as (() => void) | null, + result: database, + } + queueMicrotask(() => { + if (!hasStore) request.onupgradeneeded?.() + request.onsuccess?.() + }) + return request + }, + } + return { + closed: () => closed, + factory: factory as unknown as IDBFactory, + records, + } +} + +it('stores a structured Session workspace in IndexedDB and restores it', async () => { + const indexed = fakeIndexedDb() + const persistence = createIndexedDbWorkspacePersistence<{ title: string }>({ + appKind: 'presentation', + databaseName: 'presentation-test', + indexedDB: indexed.factory, + sessionId: 'session-a', + storeName: 'projects', + }) + try { + expect(await persistence.load()).toBeNull() + persistence.schedule({ title: 'First' }) + persistence.schedule({ title: 'Latest' }) + await persistence.flush() + + expect(indexed.records.get('session-a')).toEqual({ title: 'Latest' }) + expect(await persistence.load()).toEqual({ title: 'Latest' }) + expect(persistence.getSnapshot()).toMatchObject({ + policy: { appKind: 'presentation', sessionId: 'session-a', storage: 'browser-storage' }, + status: 'saved', + }) + } finally { + persistence.dispose() + await new Promise((resolve) => setTimeout(resolve, 0)) + expect(indexed.closed()).toBe(true) + } +}) diff --git a/desktop/apps/electron/src/renderer/lib/office/officeImage.ts b/desktop/apps/electron/src/renderer/lib/office/officeImage.ts index 8327958f..76a6f691 100644 --- a/desktop/apps/electron/src/renderer/lib/office/officeImage.ts +++ b/desktop/apps/electron/src/renderer/lib/office/officeImage.ts @@ -7,7 +7,7 @@ export interface OfficeImage { extension: 'png' | 'jpeg' | 'gif' } -/** Embed remote images and convert browser-supported rasters to portable Office media. */ +/** Embed remote images and convert supported raster/vector formats to portable Office media. */ export async function prepareOfficeImage(source: string, kind: OfficeFileKind): Promise { let embedded = source.trim() if (/^https:\/\//i.test(embedded)) { @@ -15,8 +15,8 @@ export async function prepareOfficeImage(source: string, kind: OfficeFileKind): ? await window.officeFiles.readImage(kind, embedded) : await downloadOfficeImage(embedded) } - const match = /^data:image\/(png|jpe?g|gif|bmp|x-ms-bmp|webp);base64,([a-z0-9+/=\s]+)$/i.exec(embedded) - if (!match) throw new Error('Use an embedded PNG, JPEG, GIF, BMP or WebP image') + const match = /^data:image\/(png|jpe?g|gif|bmp|x-ms-bmp|webp|svg\+xml|(?:x-)?wmf|(?:x-)?emf);base64,([a-z0-9+/=\s]+)$/i.exec(embedded) + if (!match) throw new Error('Use an embedded PNG, JPEG, GIF, BMP, WebP, SVG, WMF or EMF image') const mime = match[1]!.toLowerCase() const base64 = match[2]!.replace(/\s/g, '') if (base64.length > Math.ceil(MAX_OFFICE_IMAGE_BYTES / 3) * 4) throw new Error('The image is too large to embed') @@ -25,6 +25,35 @@ export async function prepareOfficeImage(source: string, kind: OfficeFileKind): return { extension, base64, dataUrl: `data:image/${extension};base64,${base64}` } } const bytes = Uint8Array.from(atob(base64), (character) => character.charCodeAt(0)) + if (mime === 'svg+xml') return rasterizeOfficeSvg(new TextDecoder().decode(bytes), kind) + if (/(?:wmf|emf)$/.test(mime)) { + const { EMFJS, WMFJS } = await import('rtf.js') + EMFJS.loggingEnabled(false) + WMFJS.loggingEnabled(false) + const view = new DataView(bytes.buffer) + const emf = mime.endsWith('emf') + let width = 1024 + let height = 768 + if (emf && bytes.length >= 24) { + width = Math.max(1, view.getInt32(16, true) - view.getInt32(8, true)) + height = Math.max(1, view.getInt32(20, true) - view.getInt32(12, true)) + } else if (!emf && bytes.length >= 22 && view.getUint32(0, true) === 0x9ac6cdd7) { + width = Math.max(1, view.getInt16(10, true) - view.getInt16(6, true)) + height = Math.max(1, view.getInt16(12, true) - view.getInt16(8, true)) + } + const scale = Math.min(2, 2048 / Math.max(width, height)) + const pixelWidth = Math.max(1, Math.round(width * scale)) + const pixelHeight = Math.max(1, Math.round(height * scale)) + const settings = { width: `${pixelWidth}px`, height: `${pixelHeight}px`, xExt: pixelWidth, yExt: pixelHeight, wExt: width, hExt: height, mapMode: 8 } + const svg = emf ? new EMFJS.Renderer(normalizeLegacyEmfHeader(bytes).buffer).render(settings) : new WMFJS.Renderer(bytes.buffer).render(settings) + if (emf && bytes.length >= 24) { + // EMF coordinates may be negative. Crop the device frame, not an invented + // origin-zero viewport that clips valid drawings outside the first quadrant. + svg.setAttribute('viewBox', `${view.getInt32(8, true)} ${view.getInt32(12, true)} ${width} ${height}`) + for (const viewport of svg.querySelectorAll('svg')) viewport.setAttribute('overflow', 'visible') + } + return rasterizeOfficeSvg(new XMLSerializer().serializeToString(svg), kind) + } const bitmap = await createImageBitmap(new Blob([bytes], { type: `image/${mime}` })) try { const canvas = new OffscreenCanvas(bitmap.width, bitmap.height) @@ -35,3 +64,51 @@ export async function prepareOfficeImage(source: string, kind: OfficeFileKind): return prepareOfficeImage(officeImageDataUrl(new Uint8Array(await png.arrayBuffer()), 'image/png'), kind) } finally { bitmap.close() } } + +async function rasterizeOfficeSvg(svg: string, kind: OfficeFileKind): Promise { + const url = URL.createObjectURL(new Blob([svg], { type: 'image/svg+xml' })) + try { + const image = new Image() + await new Promise((resolve, reject) => { + const finish = (error?: Error) => { + clearTimeout(timeout) + image.onload = null + image.onerror = null + if (error) reject(error) + else resolve() + } + const timeout = setTimeout(() => finish(new Error('The Office vector image preview timed out')), 10000) + image.onload = () => finish() + image.onerror = () => finish(new Error('The Office vector image could not be rendered')) + image.src = url + }) + if (!image.naturalWidth || !image.naturalHeight) throw new Error('The Office image has no dimensions') + const scale = Math.min(1, 2048 / Math.max(image.naturalWidth, image.naturalHeight)) + const canvas = new OffscreenCanvas(Math.max(1, Math.round(image.naturalWidth * scale)), Math.max(1, Math.round(image.naturalHeight * scale))) + const context = canvas.getContext('2d') + if (!context) throw new Error('Image conversion is unavailable') + context.drawImage(image, 0, 0, canvas.width, canvas.height) + const png = await canvas.convertToBlob({ type: 'image/png' }) + return prepareOfficeImage(officeImageDataUrl(new Uint8Array(await png.arrayBuffer()), 'image/png'), kind) + } finally { URL.revokeObjectURL(url) } +} + +/** Legacy EMF descriptions start at byte 88, not in an extension/OpenGL header. */ +export function normalizeLegacyEmfHeader(bytes: Uint8Array): Uint8Array { + const owned = new Uint8Array(bytes) + if (owned.length < 88) return owned + const view = new DataView(owned.buffer) + const size = view.getUint32(4, true) + const count = view.getUint32(60, true) + const offset = view.getUint32(64, true) + if (!count || offset !== 88 || size < offset + count * 2 || size > owned.length) return owned + const normalized = new Uint8Array(owned.length - (size - 88)) + normalized.set(owned.subarray(0, 88)) + normalized.set(owned.subarray(size), 88) + const header = new DataView(normalized.buffer) + header.setUint32(4, 88, true) + header.setUint32(48, normalized.length, true) + header.setUint32(60, 0, true) + header.setUint32(64, 0, true) + return normalized +} diff --git a/desktop/apps/electron/src/renderer/lib/office/officePersistence.ts b/desktop/apps/electron/src/renderer/lib/office/officePersistence.ts index d512824a..54a5ea1f 100644 --- a/desktop/apps/electron/src/renderer/lib/office/officePersistence.ts +++ b/desktop/apps/electron/src/renderer/lib/office/officePersistence.ts @@ -4,7 +4,7 @@ import type { OfficeAppKind } from './officeSurfaceStatus' export interface OfficePersistencePolicy { readonly appKind: OfficeAppKind readonly sessionId: string - readonly kind: 'recovery' | 'source' | 'export' + readonly kind: 'recovery' | 'workspace' | 'source' | 'export' readonly storage: 'browser-storage' | 'session-memory' | 'source-file' | 'download' | 'recovery-file' readonly automatic: boolean } diff --git a/desktop/apps/electron/src/renderer/lib/office/officeSurfaceStatus.ts b/desktop/apps/electron/src/renderer/lib/office/officeSurfaceStatus.ts index 45aa7516..af1ffb77 100644 --- a/desktop/apps/electron/src/renderer/lib/office/officeSurfaceStatus.ts +++ b/desktop/apps/electron/src/renderer/lib/office/officeSurfaceStatus.ts @@ -22,7 +22,7 @@ export interface OfficeSurfaceStatus { export type OfficeSurfaceStatuses = Readonly> -/** Adapt existing producers without changing their protocols or inventing document counts. */ +/** Adapt existing producers without inventing document counts. */ export function projectOfficeSurfaceStatuses({ sessionId, powerPointSession, @@ -47,8 +47,8 @@ export function projectOfficeSurfaceStatuses({ sessionId, hasNativeTarget: ppt !== null, runtimeState: nativeRuntimeState(ppt, ppt?.loading ?? false), - documentCount: null, - documentInventory: 'unsupported', + documentCount: ppt?.documentCount ?? null, + documentInventory: ppt?.documentCount != null ? 'ready' : 'pending', agentActivity: sessionId && powerPointAgentActive ? 'active' : 'idle', needsAttention: sessionId !== null && powerPointNeedsAttention, dirty: null, @@ -69,8 +69,8 @@ export function projectOfficeSurfaceStatuses({ sessionId, hasNativeTarget: excel !== null, runtimeState: nativeRuntimeState(excel, excel?.ready === false), - documentCount: null, - documentInventory: 'unsupported', + documentCount: excel?.documentCount ?? null, + documentInventory: excel?.documentCount != null ? 'ready' : 'pending', agentActivity: 'unavailable', needsAttention: null, dirty: excel?.dirty ?? null, @@ -84,7 +84,7 @@ function nativeRuntimeState(target: { crashed: boolean } | null, loading: boolea return loading ? 'loading' : 'ready' } -/** Preserve native-target markers until those runtimes publish authoritative document counts. */ +/** Only runtimes without document inventory fall back to their native-target marker. */ export function hasOfficeBackgroundContent(status: OfficeSurfaceStatus): boolean { if (status.sessionId === null) return false if (status.documentCount !== null) return status.documentCount > 0 diff --git a/desktop/apps/electron/src/renderer/lib/office/workspacePersistence.ts b/desktop/apps/electron/src/renderer/lib/office/workspacePersistence.ts new file mode 100644 index 00000000..055a6d5c --- /dev/null +++ b/desktop/apps/electron/src/renderer/lib/office/workspacePersistence.ts @@ -0,0 +1,101 @@ +import type { OfficeAppKind } from './officeSurfaceStatus' +import { + createOfficePersistenceScheduler, + type OfficePersistenceScheduler, +} from './officePersistence' + +export interface WorkspacePersistence extends OfficePersistenceScheduler { + load(): Promise +} + +/** Persist one Session-owned structured workspace directly in the renderer. */ +export function createIndexedDbWorkspacePersistence(options: { + appKind: OfficeAppKind + databaseName: string + sessionId: string + storeName: string + version?: number + delayMs?: number + indexedDB?: IDBFactory +}): WorkspacePersistence { + let databasePromise: Promise | null = null + let disposed = false + + const openDatabase = (): Promise => { + if (databasePromise) return databasePromise + const opening = new Promise((resolve, reject) => { + const indexedDB = options.indexedDB ?? window.indexedDB + if (!indexedDB) { + reject(new Error('IndexedDB is unavailable.')) + return + } + const request = indexedDB.open(options.databaseName, options.version ?? 1) + request.onerror = () => reject(request.error ?? new Error(`Unable to open ${options.appKind} project storage.`)) + request.onupgradeneeded = () => { + if (!request.result.objectStoreNames.contains(options.storeName)) { + request.result.createObjectStore(options.storeName) + } + } + request.onsuccess = () => { + const database = request.result + database.onversionchange = () => { + database.close() + databasePromise = null + } + resolve(database) + } + }) + databasePromise = opening.catch((error) => { + databasePromise = null + throw error + }) + return databasePromise + } + + const load = async (): Promise => { + if (disposed) throw new Error('This workspace store is closed.') + const database = await openDatabase() + return new Promise((resolve, reject) => { + const transaction = database.transaction(options.storeName, 'readonly') + const request = transaction.objectStore(options.storeName).get(options.sessionId) + request.onerror = () => reject(request.error ?? new Error(`Unable to read the ${options.appKind} workspace.`)) + request.onsuccess = () => resolve(request.result ?? null) + }) + } + + const scheduler = createOfficePersistenceScheduler({ + policy: { + appKind: options.appKind, + sessionId: options.sessionId, + kind: 'workspace', + storage: 'browser-storage', + automatic: true, + }, + delayMs: options.delayMs ?? 150, + write: async (workspace) => { + const database = await openDatabase() + await new Promise((resolve, reject) => { + const transaction = database.transaction(options.storeName, 'readwrite') + transaction.onabort = () => reject(transaction.error ?? new Error(`Unable to save the ${options.appKind} workspace.`)) + transaction.onerror = () => reject(transaction.error ?? new Error(`Unable to save the ${options.appKind} workspace.`)) + transaction.oncomplete = () => resolve() + transaction.objectStore(options.storeName).put(workspace, options.sessionId) + }) + }, + }) + + return { + ...scheduler, + load, + dispose() { + if (disposed) return + disposed = true + scheduler.dispose() + void scheduler.flush().catch(() => undefined).finally(() => { + const pendingDatabase = databasePromise + databasePromise = null + if (pendingDatabase) void pendingDatabase.then((database) => database.close(), () => undefined) + }) + }, + } +} diff --git a/desktop/apps/electron/src/renderer/lib/powerPointProtocol.ts b/desktop/apps/electron/src/renderer/lib/powerPointProtocol.ts index 0ff30109..9bd00927 100644 --- a/desktop/apps/electron/src/renderer/lib/powerPointProtocol.ts +++ b/desktop/apps/electron/src/renderer/lib/powerPointProtocol.ts @@ -1,54 +1,27 @@ import { - PRESENTATION_TRANSITION_DIRECTIONS, - PRESENTATION_TRANSITION_EFFECTS, - createBlankPresentationDocument, - replacePresentationPages, + createBlankPresentationProject, selectPresentationPage, type PresentationAgentChange, - type PresentationAsset, - type PresentationDocument, type PresentationFileSource, + type PresentationProject, type PresentationSlide, - type PresentationWorkspace, } from '@/atoms/presentation' -import { - applyPresentationDesign, - normalizePresentationDesignColor, - type PresentationDesignPatch, - type PresentationThemePresetId, -} from '@/lib/presentationDesign' -import { - compilePresentationElementMarkdown, - compilePresentationSlideMarkdown, - decompilePresentationSlideMarkdown, - inspectPresentationMarkdownAssets, - type PresentationMarkdownAssets, -} from '@/lib/presentationMarkdown' +import { decompilePresentationSlideMarkdown } from '@/lib/presentationMarkdown' import { importPresentationPptx } from '@/lib/presentationPptxImport' -import { validatePresentationDocument } from '@/presentation/model/reducer' -import { - clearPresentationHyperlinksToPages, - detachPresentationCommentsFromElements, - mergePresentationAssets, - presentationAsset, - presentationElementSource, -} from '@/presentation/project' +import { editPresentationPage, managePresentationDeck } from '@/presentation/agentCommands' +import { editPresentationProject } from '@/presentation/model/reducer' +import { isPresentationAssetElement, presentationAsset, presentationElementSource } from '@/presentation/project' -export const POWERPOINT_PROTOCOL_VERSION = 5 as const +export const POWERPOINT_PROTOCOL_VERSION = 7 as const export type PowerPointMethod = - | 'save_ppt' - | 'view_ppt' - | 'inspect_ppt_assets' - | 'get_ppt_page' - | 'update_ppt_design' - | 'edit_ppt_page' - | 'insert_ppt_element' - | 'remove_ppt_element' - | 'insert_ppt_page' - | 'remove_ppt_page' - | 'move_ppt_page' - | 'goto_ppt_page' + | 'open' + | 'read_deck' + | 'read_page' + | 'inspect' + | 'edit_page' + | 'manage_deck' + | 'save' export interface PowerPointRequest { method: PowerPointMethod @@ -57,334 +30,224 @@ export interface PowerPointRequest { export interface PowerPointRuntimeContext { currentTarget: string | null - fileName: string - importPptx?: (encoded: string, fileName: string) => Promise + fileNameOf?: (projectId: string) => string | undefined + importPptx?: (encoded: string, fileName: string) => Promise + materializeProject?: (project: PresentationProject) => Promise + revisionOf?: (projectId: string) => number +} + +export interface PowerPointProjectCollection { + activeProjectId: string + projects: PresentationProject[] } export interface PowerPointDispatchResult { agentChange?: Omit + contentChanged?: boolean + changedProjectId?: string + projects?: PowerPointProjectCollection result: unknown - workspace?: PresentationWorkspace target?: string - persist?: boolean } +export type PowerPointProtocolErrorCode = 'document_changed' | 'document_not_found' | 'page_changed' + export class PowerPointProtocolError extends Error { - constructor(message: string, readonly code: 'deck_changed' | 'document_changed' | 'page_changed') { + constructor(message: string, readonly code: PowerPointProtocolErrorCode) { super(message) this.name = 'PowerPointProtocolError' } } -/** Execute one page-level PPT request against the same native model used by the editor. */ +/** Execute one structured PPT request against the editor's authoritative model. */ export async function executePowerPointRequest( - current: PresentationWorkspace, + current: PowerPointProjectCollection, request: PowerPointRequest, - context: PowerPointRuntimeContext = { currentTarget: null, fileName: 'Untitled.pptx' }, + context: PowerPointRuntimeContext = { currentTarget: null }, ): Promise { if (!request || typeof request !== 'object') throw new TypeError('PowerPoint request is required') const params = request.params ?? {} - if (request.method === 'view_ppt') { + if (request.method === 'open') { const target = requiredString(params.target, 'target') const fileName = requiredString(params.file_name, 'file_name') if (context.currentTarget === target) { - return { result: { ...deckOverview(requireActiveDocument(current), fileName), reused: true }, target } + const project = requireActiveProject(current) + return { result: { ...deckRead(project, fileName, revisionOf(context, project.id)), reused: true }, target } } const encoded = optionalString(params.content_base64, 'content_base64') - const document = encoded + const project = encoded ? await (context.importPptx ? context.importPptx(encoded, fileName) : importPresentationPptx(decodeBase64(encoded), fileName, { restoreEditorModel: true })) - : createBlankPresentationDocument(fileName.replace(/\.pptx$/i, '')) - const workspace = { activeDocumentId: document.id, documents: [document] } - return { result: { ...deckOverview(document, fileName), reused: false }, workspace, target, persist: !encoded } - } - - if (request.method === 'inspect_ppt_assets') { - return { result: inspectPresentationMarkdownAssets(requiredString(params.markdown, 'markdown')) } + : createBlankPresentationProject(fileName.replace(/\.pptx$/i, '')) + const projects = { activeProjectId: project.id, projects: [project] } + return { result: { ...deckRead(project, fileName, 1), reused: false }, projects, target } } - const document = requireActiveDocument(current) - if (request.method === 'get_ppt_page') { - return { result: pageView(document, requireSlide(document, requiredString(params.page_id, 'page_id'))) } - } - - if (request.method === 'goto_ppt_page') { - const slide = requireSlide(document, requiredString(params.page_id, 'page_id')) - const nextDocument = { ...document, slides: selectPresentationPage(document.slides, slide.id) } + const documentId = requiredString(params.document_id, 'document_id') + const project = requireProject(current, documentId) + const activeProjects = current.activeProjectId === project.id + ? current + : { ...current, activeProjectId: project.id } + const projectRevision = revisionOf(context, project.id) + + if (request.method === 'read_deck') { + assertKeys(params, ['document_id', 'include_theme'], 'read_deck') + const includeTheme = optionalBoolean(params.include_theme, 'include_theme') ?? false + const fileName = context.fileNameOf?.(project.id) || `${project.title.replace(/\.pptx$/i, '') || 'Untitled'}.pptx` return { - result: { page_id: slide.id, index: document.slides.pages.indexOf(slide), visible: true }, - workspace: replaceDocument(current, nextDocument), - } - } - - if (request.method === 'update_ppt_design') { - assertDocumentRevision(document, requiredString(params.expected_document_revision, 'expected_document_revision')) - const designed = applyPresentationDesign(document, designPatch(params.design, document)) - const nextDocument = { ...designed, revision: document.revision + 1 } - const selectedSlide = requireSlide(nextDocument, nextDocument.slides.selectedPageId) - return { - agentChange: { - elementIds: selectedSlide.elements.map((element) => element.id), - kind: 'design', - slideId: selectedSlide.id, - }, - result: deckOverview(nextDocument, context.fileName), - workspace: replaceDocument(current, nextDocument), - persist: true, + result: deckRead(project, fileName, projectRevision, includeTheme), + ...(activeProjects === current ? {} : { projects: activeProjects }), } } - if (request.method === 'edit_ppt_page') { - const slide = requireSlide(document, requiredString(params.page_id, 'page_id')) - assertPageRevision(document, slide, requiredString(params.expected_revision, 'expected_revision')) - const ref = requiredString(params.ref, 'ref') - const elementIndex = slide.elements.findIndex((element) => element.id === ref) - if (elementIndex < 0) throw new Error(`Unknown PowerPoint element ref: ${ref}`) - const compiled = compileElement( - requiredString(params.replacement, 'replacement'), document, slide, assetsValue(params.assets), ref, - ) - if ('invalid' in compiled) return { result: compiled.invalid } - const elements = [...slide.elements] - elements[elementIndex] = compiled.element - const replacement = { ...slide, elements } - const nextDocument = replaceSlide(document, replacement, compiled.assets) + if (request.method === 'read_page') { + assertKeys(params, ['document_id', 'page_id', 'format', 'element_ids'], 'read_page') + const slide = requireSlide(project, requiredString(params.page_id, 'page_id')) + const format = enumValue(params.format ?? 'compact', new Set(['compact', 'model', 'both'] as const), 'format') + const elementIds = stringArray(params.element_ids, 'element_ids') + const assetProject = context.materializeProject ? await context.materializeProject(project) : project return { - agentChange: { - elementIds: [ref], - kind: 'content', - slideId: replacement.id, - }, - result: { - status: 'ready', - diagnostics: diagnostics(compiled.diagnostics), - document_revision: documentRevision(nextDocument), - element_ref: ref, - ...pageView(nextDocument, replacement), - }, - workspace: replaceDocument(current, nextDocument), - persist: true, + result: pageRead(project, slide, format, elementIds, assetProject), + ...(activeProjects === current ? {} : { projects: activeProjects }), } } - if (request.method === 'insert_ppt_element') { - const slide = requireSlide(document, requiredString(params.page_id, 'page_id')) - assertPageRevision(document, slide, requiredString(params.expected_revision, 'expected_revision')) - const compiled = compileElement( - requiredString(params.element, 'element'), document, slide, assetsValue(params.assets), - ) - if ('invalid' in compiled) return { result: compiled.invalid } - const replacement = { ...slide, elements: [...slide.elements, compiled.element] } - const nextDocument = replaceSlide(document, replacement, compiled.assets) + if (request.method === 'inspect') { + assertKeys(params, ['document_id', 'kind', 'page_id'], 'inspect') + if (params.kind !== 'render') throw new Error(`Unsupported PowerPoint inspection: ${String(params.kind)}`) + const slide = requireSlide(project, optionalString(params.page_id, 'page_id') ?? project.slides.selectedPageId) + const nextProject = { ...project, slides: selectPresentationPage(project.slides, slide.id) } return { - agentChange: { - elementIds: [compiled.element.id], - kind: 'content', - slideId: replacement.id, - }, result: { - status: 'ready', - diagnostics: diagnostics(compiled.diagnostics), - document_revision: documentRevision(nextDocument), - element_ref: compiled.element.id, - ...pageView(nextDocument, replacement), + kind: 'render', + document_id: project.id, + document_revision: projectRevision, + page_id: slide.id, + index: project.slides.pages.indexOf(slide), + revision: pageRevision(project, slide), }, - workspace: replaceDocument(current, nextDocument), - persist: true, + projects: replaceProject(activeProjects, nextProject), + changedProjectId: project.id, + contentChanged: false, } } - if (request.method === 'remove_ppt_element') { - const slide = requireSlide(document, requiredString(params.page_id, 'page_id')) - assertPageRevision(document, slide, requiredString(params.expected_revision, 'expected_revision')) - const ref = requiredString(params.ref, 'ref') - if (!slide.elements.some((element) => element.id === ref)) { - throw new Error(`Unknown PowerPoint element ref: ${ref}`) + if (request.method === 'edit_page') { + assertKeys(params, ['document_id', 'page_id', 'expected_revision', 'operations', 'assets', 'validate_only'], 'edit_page') + const pageId = requiredString(params.page_id, 'page_id') + const slide = requireSlide(project, pageId) + assertPageRevision(project, slide, requiredString(params.expected_revision, 'expected_revision')) + const edited = editPresentationPage(project, pageId, params.operations, assetsValue(params.assets)) + const validateOnly = optionalBoolean(params.validate_only, 'validate_only') ?? false + if (validateOnly) { + return { result: { status: 'validated', document_id: project.id, page_id: pageId, changed_page_ids: edited.changedPageIds, changed_element_ids: edited.changedElementIds } } } - const replacement = { - ...detachPresentationCommentsFromElements(slide, new Set([ref])), - elements: slide.elements.filter((element) => element.id !== ref), - } - const nextDocument = replaceSlide(document, replacement) + const nextProject = editPresentationProject(project, edited.project) + const nextSlide = requireSlide(nextProject, pageId) + const nextRevision = projectRevision + 1 return { - agentChange: { elementIds: [], kind: 'content', slideId: replacement.id }, + agentChange: { elementIds: edited.changedElementIds, kind: 'content', slideId: pageId }, result: { status: 'ready', - diagnostics: [], - document_revision: documentRevision(nextDocument), - element_ref: ref, - ...pageView(nextDocument, replacement), + document_id: project.id, + page_id: pageId, + changed_page_ids: edited.changedPageIds, + changed_element_ids: edited.changedElementIds, + revision: pageRevision(nextProject, nextSlide), + deck_revision: documentRevision(nextProject, nextRevision), }, - workspace: replaceDocument(current, nextDocument), - persist: true, + projects: replaceProject(activeProjects, nextProject), + changedProjectId: project.id, + contentChanged: true, } } - if (request.method === 'insert_ppt_page') { - const compiled = compilePage(requiredString(params.markdown, 'markdown'), document, assetsValue(params.assets)) - if ('invalid' in compiled) return { result: compiled.invalid } - const afterPageId = optionalString(params.after_page_id, 'after_page_id') - const insertionIndex = afterPageId - ? document.slides.pages.findIndex((slide) => slide.id === afterPageId) + 1 - : document.slides.pages.length - if (afterPageId && insertionIndex === 0) throw new Error(`Unknown PowerPoint page: ${afterPageId}`) - const slides = [...document.slides.pages] - slides.splice(insertionIndex, 0, compiled.slide) - const nextDocument = { - ...document, - assets: mergePresentationAssets(document.assets, compiled.assets), - slides: replacePresentationPages(document.slides, slides, compiled.slide.id), - revision: document.revision + 1, + if (request.method === 'manage_deck') { + assertKeys(params, ['document_id', 'expected_revision', 'operations', 'validate_only'], 'manage_deck') + assertDocumentRevision(project, projectRevision, requiredString(params.expected_revision, 'expected_revision')) + const edited = managePresentationDeck(project, params.operations) + const validateOnly = optionalBoolean(params.validate_only, 'validate_only') ?? false + if (validateOnly) { + return { result: { status: 'validated', document_id: project.id, changed_page_ids: edited.changedPageIds } } } + const nextProject = editPresentationProject(project, edited.project) + const selected = requireSlide(nextProject, nextProject.slides.selectedPageId) return { - agentChange: { - elementIds: compiled.slide.elements.map((element) => element.id), - kind: 'content', - slideId: compiled.slide.id, - }, - result: { - status: 'ready', - diagnostics: diagnostics(compiled.diagnostics), - ...deckOverview(nextDocument, context.fileName), - ...pageView(nextDocument, compiled.slide), - }, - workspace: replaceDocument(current, nextDocument), - persist: true, - } - } - - if (request.method === 'remove_ppt_page') { - const slide = requireSlide(document, requiredString(params.page_id, 'page_id')) - assertPageRevision(document, slide, requiredString(params.expected_revision, 'expected_revision')) - assertDeckRevision(document, requiredString(params.expected_deck_revision, 'expected_deck_revision')) - if (document.slides.pages.length === 1) throw new Error('A PowerPoint must keep at least one page') - const oldIndex = document.slides.pages.indexOf(slide) - const slides = clearPresentationHyperlinksToPages( - document.slides.pages.filter((item) => item.id !== slide.id), - new Set([slide.id]), - ) - const selectedPageId = document.slides.selectedPageId === slide.id - ? slides[Math.min(oldIndex, slides.length - 1)]!.id - : document.slides.selectedPageId - const nextDocument = { - ...document, - slides: replacePresentationPages(document.slides, slides, selectedPageId), - revision: document.revision + 1, - } - return { - result: deckOverview(nextDocument, context.fileName), - workspace: replaceDocument(current, nextDocument), - persist: true, - } - } - - if (request.method === 'move_ppt_page') { - assertDeckRevision(document, requiredString(params.expected_deck_revision, 'expected_deck_revision')) - const slide = requireSlide(document, requiredString(params.page_id, 'page_id')) - const target = requireSlide(document, requiredString(params.target_page_id, 'target_page_id')) - const position = requiredString(params.position, 'position') - if (slide.id === target.id) throw new Error('A PowerPoint page cannot be moved relative to itself') - if (position !== 'before' && position !== 'after') throw new Error("position must be 'before' or 'after'") - const slides = document.slides.pages.filter((item) => item.id !== slide.id) - const targetIndex = slides.findIndex((item) => item.id === target.id) - slides.splice(targetIndex + (position === 'after' ? 1 : 0), 0, slide) - const nextDocument = { - ...document, - slides: replacePresentationPages(document.slides, slides), - revision: document.revision + 1, - } - return { - result: deckOverview(nextDocument, context.fileName), - workspace: replaceDocument(current, nextDocument), - persist: true, + agentChange: { elementIds: selected.elements.map((element) => element.id), kind: edited.designChanged ? 'design' : 'content', slideId: selected.id }, + result: { status: 'ready', document_id: project.id, changed_page_ids: edited.changedPageIds, revision: documentRevision(nextProject, projectRevision + 1) }, + projects: replaceProject(activeProjects, nextProject), + changedProjectId: project.id, + contentChanged: true, } } throw new Error(`Unsupported PowerPoint method: ${String(request.method)}`) } -function compilePage(markdown: string, document: PresentationDocument, assets: PresentationMarkdownAssets): - | { assets: PresentationAsset[]; slide: PresentationSlide; diagnostics: string[] } - | { invalid: { status: 'invalid'; diagnostics: Array> } } { - try { - return compilePresentationSlideMarkdown(markdown, { assets, document, existingDocument: document }) - } catch (error) { - return { - invalid: { - status: 'invalid', - diagnostics: [{ - code: 'markdown_compile_error', - message: error instanceof Error ? error.message : String(error), - severity: 'error', - }], - }, - } - } -} - -function compileElement( - markdown: string, - document: PresentationDocument, - slide: PresentationSlide, - assets: PresentationMarkdownAssets, - elementId?: string, -): - | { assets: PresentationAsset[]; element: PresentationSlide['elements'][number]; diagnostics: string[] } - | { invalid: { status: 'invalid'; diagnostics: Array> } } { - try { - return compilePresentationElementMarkdown(markdown, { - assets, - document, - elementId, - existingDocument: document, - slide, - }) - } catch (error) { - return { - invalid: { - status: 'invalid', - diagnostics: [{ - code: 'element_compile_error', - message: error instanceof Error ? error.message : String(error), - severity: 'error', - }], - }, - } - } -} - -function deckOverview(document: PresentationDocument, fileName: string): Record { +function deckRead(document: PresentationProject, fileName: string, revision: number, includeTheme = true): Record { const selectedIndex = Math.max(0, document.slides.pages.findIndex((slide) => slide.id === document.slides.selectedPageId)) return { - identity: { - document_id: document.id, - name: document.title || fileName.replace(/\.pptx$/i, ''), - file_name: fileName, - }, - meta: { + document_id: document.id, + revision: documentRevision(document, revision), + deck: { + id: document.id, title: document.title, - theme: structuredClone(document.theme), + file_name: fileName, page_size: structuredClone(document.pageSize), total_pages: document.slides.pages.length, - current_page_id: document.slides.selectedPageId, - current_page_index: selectedIndex, - current_position: selectedIndex + 1, + active_page_id: document.slides.selectedPageId, + active_page_index: selectedIndex, + ...(includeTheme ? { theme: structuredClone(document.theme) } : {}), + pages: document.slides.pages.map((slide, index) => pageSummary(document, slide, index)), + }, + } +} + +function pageRead(document: PresentationProject, slide: PresentationSlide, format: 'both' | 'compact' | 'model', elementIds?: string[], assetProject = document): Record { + const index = document.slides.pages.findIndex((item) => item.id === slide.id) + const selectedElements = elementIds?.length + ? slide.elements.filter((element) => elementIds.includes(element.id)) + : slide.elements + if (elementIds?.some((id) => !slide.elements.some((element) => element.id === id))) { + throw new Error('element_ids contains an unknown PowerPoint element') + } + const assets = pageAssets(assetProject, { ...slide, elements: selectedElements }) + return { + document_id: document.id, + page_id: slide.id, + revision: pageRevision(document, slide), + page: { + ...pageSummary(document, slide, index), + refs: selectedElements.map((element) => element.id), + ...(format === 'compact' || format === 'both' ? { markdown: decompilePresentationSlideMarkdown({ ...slide, elements: selectedElements }, assetProject) } : {}), + ...(format === 'model' || format === 'both' ? { + model: { + id: slide.id, + name: slide.name, + layout: slide.layout, + background: slide.background, + notes: slide.notes, + footer: slide.footer, + transition: structuredClone(slide.transition), + comments: structuredClone(slide.comments ?? []), + elements: selectedElements.map((element) => pageModelElement(assetProject, element)), + }, + } : {}), }, - deck_revision: deckRevision(document), - document_revision: documentRevision(document), - pages: document.slides.pages.map((slide, index) => pageSummary(document, slide, index)), + assets, } } -function pageSummary(document: PresentationDocument, slide: PresentationSlide, index: number): Record { +function pageSummary(document: PresentationProject, slide: PresentationSlide, index: number): Record { const text = slide.elements.flatMap((element) => ( 'text' in element && typeof element.text === 'string' ? [element.text.trim()] : [] )).filter(Boolean).join(' ') return { - page_id: slide.id, + id: slide.id, index, - title: slide.name, + name: slide.name, layout: slide.layout ?? 'blank', summary: text.slice(0, 240) || undefined, has_content: slide.elements.length > 0 || Boolean(slide.notes?.trim()), @@ -392,38 +255,13 @@ function pageSummary(document: PresentationDocument, slide: PresentationSlide, i } } -function pageView(document: PresentationDocument, slide: PresentationSlide): Record { - const index = document.slides.pages.findIndex((item) => item.id === slide.id) - const assets = pageAssets(document, slide) - return { - page: { - ...pageSummary(document, slide, index), - markdown: decompilePresentationSlideMarkdown(slide, document), - asset_paths: assets.map((asset) => asset.path), - refs: slide.elements.map((element) => element.id), - }, - assets, - } -} - -function pageAssets(document: PresentationDocument, slide: PresentationSlide): Array<{ - path: string - file_name: string - mime_type: string - data_url?: string -}> { - const found = new Map() +function pageAssets(document: PresentationProject, slide: PresentationSlide): Array<{ path: string; file_name: string; mime_type: string; data_url?: string }> { + const found = new Map() for (const element of slide.elements) { - if (element.type !== 'image' && element.type !== 'audio' && element.type !== 'video') continue + if (!isPresentationAssetElement(element)) continue const source = presentationElementSource(document, element) if (!source) continue - const safeName = source.fileName.replace(/[^A-Za-z0-9._-]+/g, '-') || `${element.id}.bin` - const path = source.path ?? `.ppt-assets/${encodeURIComponent(source.assetId ?? element.id)}-${safeName}` + const path = pageAssetPath(source, element.id) if (found.has(path)) continue found.set(path, { path, @@ -435,34 +273,32 @@ function pageAssets(document: PresentationDocument, slide: PresentationSlide): A return [...found.values()] } -const mediaRevisions = new WeakMap() +function pageModelElement(document: PresentationProject, element: PresentationSlide['elements'][number]): Record { + if (!isPresentationAssetElement(element)) { + return structuredClone(element) as unknown as Record + } + const source = presentationElementSource(document, element) + if (!source) throw new Error(`PowerPoint element refers to a missing asset: ${element.id}`) + const { sourceAssetId: _sourceAssetId, ...projected } = structuredClone(element) + return { ...projected, src: pageAssetPath(source, element.id) } +} + +function pageAssetPath(source: PresentationFileSource, elementId: string): string { + const safeName = source.fileName.replace(/[^A-Za-z0-9._-]+/g, '-') || `${elementId}.bin` + return source.path ?? `.ppt-assets/${encodeURIComponent(source.assetId ?? elementId)}-${safeName}` +} -function pageRevision(document: PresentationDocument, slide: PresentationSlide): string { +function pageRevision(document: PresentationProject, slide: PresentationSlide): string { const referencedAssets = slide.elements.flatMap((element) => { - if (element.type !== 'image' && element.type !== 'audio' && element.type !== 'video') return [] + if (!isPresentationAssetElement(element)) return [] const asset = presentationAsset(document, element.sourceAssetId) return asset ? [asset] : [] }) - // Large media payloads can be shared across pages. Hash each source object once, - // but include every referenced asset in the optimistic page revision. - return fingerprint(JSON.stringify({ slide, assets: referencedAssets }, function (key, value: unknown) { - if (key !== 'dataUrl' || typeof value !== 'string') return value - const source = this as object - let cached = mediaRevisions.get(source) - if (!cached || cached.dataUrl !== value) { - cached = { dataUrl: value, revision: `${value.length}:${fingerprint(value)}` } - mediaRevisions.set(source, cached) - } - return cached.revision - })) -} - -function deckRevision(document: PresentationDocument): string { - return fingerprint(JSON.stringify(document.slides.pages.map((slide) => slide.id))) + return fingerprint(JSON.stringify({ slide, assets: referencedAssets, pageSize: document.pageSize, theme: document.theme })) } -function documentRevision(document: PresentationDocument): string { - return fingerprint(`${document.id}:${document.revision}`) +function documentRevision(document: PresentationProject, revision: number): string { + return fingerprint(`${document.id}:${revision}`) } function fingerprint(value: string): string { @@ -474,176 +310,90 @@ function fingerprint(value: string): string { return (hash >>> 0).toString(16).padStart(8, '0') } -function assertPageRevision(document: PresentationDocument, slide: PresentationSlide, expected: string): void { - if (pageRevision(document, slide) === expected) return - throw new PowerPointProtocolError( - `PowerPoint page ${slide.id} changed after it was read. Call get_ppt_page again before writing.`, - 'page_changed', - ) +function assertDocumentRevision(document: PresentationProject, revision: number, expected: string): void { + if (documentRevision(document, revision) === expected) return + throw new PowerPointProtocolError('The PowerPoint changed after it was read. Read the deck again before retrying.', 'document_changed') } -function assertDeckRevision(document: PresentationDocument, expected: string): void { - if (deckRevision(document) === expected) return - throw new PowerPointProtocolError( - 'The PowerPoint page order changed. Call view_ppt again before changing the structure.', - 'deck_changed', - ) +function assertPageRevision(document: PresentationProject, slide: PresentationSlide, expected: string): void { + if (pageRevision(document, slide) === expected) return + throw new PowerPointProtocolError(`PowerPoint page ${slide.id} changed after it was read. Read it again before retrying.`, 'page_changed') } -function assertDocumentRevision(document: PresentationDocument, expected: string): void { - if (documentRevision(document) === expected) return - throw new PowerPointProtocolError( - 'The PowerPoint changed after its design was read. Call view_ppt again before changing global design.', - 'document_changed', - ) +function assetsValue(value: unknown): Record { + if (value === undefined) return {} + if (!isRecord(value)) throw new TypeError('assets must be an object') + return value as Record } -function designPatch(value: unknown, document: PresentationDocument): PresentationDesignPatch { - if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TypeError('design must be a mapping') - const raw = value as Record - const patch: PresentationDesignPatch = {} - const themeIds = new Set(['lavender', 'light', 'midnight', 'paper']) - const pageSizes = new Set(['standard', 'wide'] as const) - const transitionEffects = new Set(PRESENTATION_TRANSITION_EFFECTS) - const transitionDirections = new Set(PRESENTATION_TRANSITION_DIRECTIONS) - - if (raw.theme !== undefined) patch.theme = enumValue(raw.theme, themeIds, 'design.theme') - if (raw.background !== undefined) patch.background = normalizePresentationDesignColor(requiredString(raw.background, 'design.background')) - if (raw.accent_colors !== undefined) { - if (!Array.isArray(raw.accent_colors) || raw.accent_colors.length === 0) { - throw new TypeError('design.accent_colors must be a non-empty string array') - } - patch.accentColors = raw.accent_colors.map((color) => ( - normalizePresentationDesignColor(requiredString(color, 'design.accent_colors[]')) - )) - } - if (raw.title_font_family !== undefined) patch.titleFontFamily = requiredString(raw.title_font_family, 'design.title_font_family') - if (raw.body_font_family !== undefined) patch.bodyFontFamily = requiredString(raw.body_font_family, 'design.body_font_family') - if (raw.page_size !== undefined) patch.pageSize = enumValue(raw.page_size, pageSizes, 'design.page_size') - if (raw.title !== undefined) { - if (typeof raw.title !== 'string') throw new TypeError('design.title must be a string') - patch.title = raw.title.trim() - } - if (raw.footer !== undefined) { - if (!raw.footer || typeof raw.footer !== 'object' || Array.isArray(raw.footer)) { - throw new TypeError('design.footer must be a mapping') - } - const footerRaw = raw.footer as Record - patch.footer = { - ...(footerRaw.text === undefined ? {} : { text: stringValue(footerRaw.text, 'design.footer.text') }), - ...(footerRaw.show_date === undefined ? {} : { showDate: booleanValue(footerRaw.show_date, 'design.footer.show_date') }), - ...(footerRaw.show_slide_number === undefined - ? {} - : { showSlideNumber: booleanValue(footerRaw.show_slide_number, 'design.footer.show_slide_number') }), - } - } - if (raw.transition !== undefined) { - if (!raw.transition || typeof raw.transition !== 'object' || Array.isArray(raw.transition)) { - throw new TypeError('design.transition must be a mapping') - } - const transitionRaw = raw.transition as Record - const fallback = document.slides.pages.find((slide) => slide.id === document.slides.selectedPageId)?.transition - ?? { effect: 'none' as const, durationMs: 500 } - patch.transition = { - effect: transitionRaw.effect === undefined - ? fallback.effect - : enumValue(transitionRaw.effect, transitionEffects, 'design.transition.effect'), - durationMs: transitionRaw.duration_ms === undefined - ? fallback.durationMs - : nonNegativeNumber(transitionRaw.duration_ms, 'design.transition.duration_ms'), - } - const direction = transitionRaw.direction === undefined - ? fallback.direction - : enumValue(transitionRaw.direction, transitionDirections, 'design.transition.direction') - if (direction) patch.transition.direction = direction - const throughBlack = transitionRaw.through_black === undefined - ? fallback.throughBlack - : booleanValue(transitionRaw.through_black, 'design.transition.through_black') - if (throughBlack !== undefined) patch.transition.throughBlack = throughBlack +function replaceProject(collection: PowerPointProjectCollection, project: PresentationProject): PowerPointProjectCollection { + return { + activeProjectId: project.id, + projects: collection.projects.map((candidate) => candidate.id === project.id ? project : candidate), } - if (Object.keys(patch).length === 0) throw new Error('update_ppt_design requires at least one design change') - return patch } -function diagnostics(items: string[]): Array> { - return items.map((message) => ({ code: 'markdown_notice', message, severity: 'warning' })) +function requireActiveProject(collection: PowerPointProjectCollection): PresentationProject { + return requireProject(collection, collection.activeProjectId) } -function assetsValue(value: unknown): PresentationMarkdownAssets { - if (value === undefined) return {} - if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TypeError('assets must be a mapping') - return value as Record +function requireProject(collection: PowerPointProjectCollection, projectId: string): PresentationProject { + const project = collection.projects.find((candidate) => candidate.id === projectId) + if (!project) throw new PowerPointProtocolError(`PowerPoint project not found: ${projectId}`, 'document_not_found') + return project } -function decodeBase64(value: string): Uint8Array { - const decoded = atob(value) - return Uint8Array.from(decoded, (character) => character.charCodeAt(0)) +function revisionOf(context: PowerPointRuntimeContext, projectId: string): number { + return context.revisionOf?.(projectId) ?? 1 } -function replaceDocument(workspace: PresentationWorkspace, document: PresentationDocument): PresentationWorkspace { - const validated = validatePresentationDocument(document) - return { - activeDocumentId: validated.id, - documents: workspace.documents.map((item) => item.id === validated.id ? validated : item), - } -} - -function replaceSlide(document: PresentationDocument, slide: PresentationSlide, assets: readonly PresentationAsset[] = []): PresentationDocument { - return { - ...document, - assets: mergePresentationAssets(document.assets, assets), - slides: replacePresentationPages( - document.slides, - document.slides.pages.map((item) => item.id === slide.id ? slide : item), - slide.id, - ), - revision: document.revision + 1, - } +function requireSlide(document: PresentationProject, pageId: string): PresentationSlide { + const slide = document.slides.pages.find((candidate) => candidate.id === pageId) + if (!slide) throw new Error(`PowerPoint page not found: ${pageId}`) + return slide } -function requireActiveDocument(workspace: PresentationWorkspace): PresentationDocument { - const document = workspace.documents.find((item) => item.id === workspace.activeDocumentId) - if (!document) throw new Error('The Session has no active PowerPoint') - return document +function decodeBase64(value: string): Uint8Array { + const decoded = atob(value) + return Uint8Array.from(decoded, (character) => character.charCodeAt(0)) } -function requireSlide(document: PresentationDocument, pageId: string): PresentationSlide { - const slide = document.slides.pages.find((item) => item.id === pageId) - if (!slide) throw new Error(`Unknown PowerPoint page: ${pageId}`) - return slide +function isRecord(value: unknown): value is Record { + return Boolean(value) && typeof value === 'object' && !Array.isArray(value) } function requiredString(value: unknown, name: string): string { - if (typeof value !== 'string' || !value.trim()) throw new TypeError(`${name} is required`) + if (typeof value !== 'string' || !value.trim()) throw new TypeError(`${name} must be a non-empty string`) return value.trim() } function optionalString(value: unknown, name: string): string | undefined { - if (value === undefined || value === null || value === '') return undefined + if (value === undefined || value === null) return undefined if (typeof value !== 'string') throw new TypeError(`${name} must be a string`) return value.trim() || undefined } -function stringValue(value: unknown, name: string): string { - if (typeof value !== 'string') throw new TypeError(`${name} must be a string`) - return value.trim() -} - -function booleanValue(value: unknown, name: string): boolean { +function optionalBoolean(value: unknown, name: string): boolean | undefined { + if (value === undefined) return undefined if (typeof value !== 'boolean') throw new TypeError(`${name} must be a boolean`) return value } -function nonNegativeNumber(value: unknown, name: string): number { - if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) { - throw new TypeError(`${name} must be a non-negative number`) +function stringArray(value: unknown, name: string): string[] | undefined { + if (value === undefined) return undefined + if (!Array.isArray(value) || value.some((item) => typeof item !== 'string' || !item.trim())) { + throw new TypeError(`${name} must be an array of non-empty strings`) } - return value + return [...new Set(value.map((item) => item.trim()))] } function enumValue(value: unknown, allowed: ReadonlySet, name: string): T { - if (typeof value !== 'string' || !allowed.has(value as T)) { - throw new Error(`${name} must be one of: ${[...allowed].join(', ')}`) - } - return value as T + const normalized = requiredString(value, name) + if (!allowed.has(normalized as T)) throw new Error(`Unsupported ${name}: ${normalized}`) + return normalized as T +} + +function assertKeys(value: Record, allowed: readonly string[], name: string): void { + const unexpected = Object.keys(value).find((key) => !allowed.includes(key)) + if (unexpected) throw new Error(`Unsupported ${name} parameter: ${unexpected}`) } diff --git a/desktop/apps/electron/src/renderer/lib/presentationAnimationPreview.ts b/desktop/apps/electron/src/renderer/lib/presentationAnimationPreview.ts index b25e28e5..4e698b96 100644 --- a/desktop/apps/electron/src/renderer/lib/presentationAnimationPreview.ts +++ b/desktop/apps/electron/src/renderer/lib/presentationAnimationPreview.ts @@ -316,7 +316,7 @@ function dissolveOrder(elementId: string): number[] { function animationColorElement(animation: NormalizedPresentationAnimation, element: PresentationElement): PresentationElement { if (animation.effect === 'fillColor' && isPresentationShapeElement(element)) { - return { ...element, fill: animation.color } + return { ...element, fill: animation.color, fillOpacity: undefined, gradientFill: undefined, patternFill: undefined } } if (animation.effect === 'textColor' && isPresentationTextElement(element)) { return patchPresentationText(element, { color: animation.color }) diff --git a/desktop/apps/electron/src/renderer/lib/presentationDesign.ts b/desktop/apps/electron/src/renderer/lib/presentationDesign.ts index 9229fc39..c8b55ebd 100644 --- a/desktop/apps/electron/src/renderer/lib/presentationDesign.ts +++ b/desktop/apps/electron/src/renderer/lib/presentationDesign.ts @@ -4,7 +4,7 @@ import { presentationSlideBackground, replacePresentationPages, type PresentationChartElement, - type PresentationDocument, + type PresentationProject, type PresentationElement, type PresentationFooter, type PresentationPageSizePreset, @@ -99,7 +99,7 @@ export function presentationThemePreset(id: PresentationThemePresetId): Presenta return preset } -export function matchingPresentationTheme(document: PresentationDocument): PresentationThemePresetId | 'custom' { +export function matchingPresentationTheme(document: PresentationProject): PresentationThemePresetId | 'custom' { const master = document.theme return PRESENTATION_THEME_PRESETS.find((preset) => ( preset.background === master.background @@ -110,7 +110,7 @@ export function matchingPresentationTheme(document: PresentationDocument): Prese ))?.id ?? 'custom' } -export function applyPresentationDesign(document: PresentationDocument, patch: PresentationDesignPatch): PresentationDocument { +export function applyPresentationDesign(document: PresentationProject, patch: PresentationDesignPatch): PresentationProject { const preset = patch.theme ? presentationThemePreset(patch.theme) : null const background = normalizePresentationDesignColor(patch.background ?? preset?.background ?? document.theme.background) const accentColors = (patch.accentColors ?? preset?.accentColors ?? document.theme.accentColors) @@ -166,13 +166,13 @@ export function applyPresentationDesign(document: PresentationDocument, patch: P if ('fill' in element && 'borderColor' in element) { const shape = element as PresentationShapeElement return colorsChanged && shape.fill !== 'transparent' - ? { ...shape, borderColor: accent, fill: accent } + ? { ...shape, borderColor: accent, borderOpacity: undefined, fill: accent, fillOpacity: undefined, gradientFill: undefined, patternFill: undefined } : shape } return element } - let next: PresentationDocument = { + let next: PresentationProject = { ...document, ...(patch.title === undefined ? {} : { title: patch.title }), theme: { accentColors, background, bodyFontFamily, footer, titleFontFamily }, @@ -185,11 +185,11 @@ export function applyPresentationDesign(document: PresentationDocument, patch: P } })), } - if (patch.pageSize) next = resizePresentationDocument(next, patch.pageSize) + if (patch.pageSize) next = resizePresentationProject(next, patch.pageSize) return next } -export function resizePresentationDocument(document: PresentationDocument, preset: PresentationPageSizePreset): PresentationDocument { +export function resizePresentationProject(document: PresentationProject, preset: PresentationPageSizePreset): PresentationProject { const previousSize = getPresentationPageSize(document) const nextSize = PRESENTATION_PAGE_SIZES[preset] if (previousSize.preset === preset && previousSize.width === nextSize.width && previousSize.height === nextSize.height) { @@ -219,7 +219,28 @@ export function resizePresentationDocument(document: PresentationDocument, prese }) } if (scaled.type === 'table') { - return { ...scaled, fontSize: Math.max(8, Number((scaled.fontSize * scale).toFixed(1))) } + return { + ...scaled, + fontSize: Math.max(8, Number((scaled.fontSize * scale).toFixed(1))), + cellStyles: scaled.cellStyles?.map(row => row.map(style => ({ + ...style, + ...(style.fontSize ? { fontSize: Math.max(8, Number((style.fontSize * scale).toFixed(1))) } : {}), + ...(style.textRuns ? { textRuns: style.textRuns.map(run => ({ + ...run, + style: { + ...run.style, + ...(run.style.fontSize ? { fontSize: Math.max(8, Number((run.style.fontSize * scale).toFixed(1))) } : {}), + }, + })) } : {}), + ...(style.padding ? { padding: { + left: style.padding.left * scale, right: style.padding.right * scale, + top: style.padding.top * scale, bottom: style.padding.bottom * scale, + } } : {}), + ...(style.borders ? { borders: Object.fromEntries(Object.entries(style.borders).filter(([, border]) => border).map(([edge, border]) => ( + [edge, { ...border, width: border.width * scale }] + ))) as typeof style.borders } : {}), + }))), + } } if ('borderWidth' in scaled && 'fill' in scaled) { return { diff --git a/desktop/apps/electron/src/renderer/lib/presentationEditorDriver.ts b/desktop/apps/electron/src/renderer/lib/presentationEditorDriver.ts index a6859941..28377b51 100644 --- a/desktop/apps/electron/src/renderer/lib/presentationEditorDriver.ts +++ b/desktop/apps/electron/src/renderer/lib/presentationEditorDriver.ts @@ -1,4 +1,4 @@ -import type { PresentationDocument } from '@/atoms/presentation' +import type { PresentationProject } from '@/atoms/presentation' import type { OfficeEditorDriver, OfficeEditorLease } from './office/officeEditorBinding' export interface PresentationEditingObject { @@ -8,7 +8,7 @@ export interface PresentationEditingObject { } /** Canvas callbacks also belong to a slide, while the common lease identifies its document. */ -export function bindPresentationNativeEdit(lease: OfficeEditorLease, slideId: string, readDocument: () => PresentationDocument, apply: (...args: TArgs) => void): (...args: TArgs) => void { +export function bindPresentationNativeEdit(lease: OfficeEditorLease, slideId: string, readDocument: () => PresentationProject, apply: (...args: TArgs) => void): (...args: TArgs) => void { return (...args) => { if (!lease.isCurrent()) return const document = readDocument() @@ -17,9 +17,9 @@ export function bindPresentationNativeEdit(lease: Offic } } -/** Fabric is a projection of the Jotai document, not another document snapshot store. */ +/** Fabric is a projection of the PresentationStore project, not another project store. */ export function createPresentationEditorDriver(options: { - readSnapshot: () => PresentationDocument | null + readSnapshot: () => PresentationProject | null readEditingObject: () => PresentationEditingObject | null flushPendingEdit: () => void dispose: () => void @@ -40,5 +40,5 @@ export function createPresentationEditorDriver(options: { lease.assertCurrent() }, dispose: options.dispose, - } satisfies OfficeEditorDriver + } satisfies OfficeEditorDriver } diff --git a/desktop/apps/electron/src/renderer/lib/presentationFileController.ts b/desktop/apps/electron/src/renderer/lib/presentationFileController.ts index 7cfb2cd5..b0dd2d9a 100644 --- a/desktop/apps/electron/src/renderer/lib/presentationFileController.ts +++ b/desktop/apps/electron/src/renderer/lib/presentationFileController.ts @@ -1,111 +1,71 @@ -import type { PresentationDocument, PresentationWorkspace } from '@/atoms/presentation' -import type { OfficeFilesAPI } from '../../shared/office-files' -import { createOfficePersistenceScheduler } from './office/officePersistence' -import { isPresentationDirty } from './presentationWorkspaceRuntime' +import type { PresentationProject } from '@/atoms/presentation' +import type { OfficeFileSource, OfficeFilesAPI } from '../../shared/office-files' +import { + type PresentationWorkspace, + type PresentationProjectMetadata, +} from '@/presentation/workspace' import { i18n } from './i18n' -import { createOfficeAutoSave } from './office/officeAutoSave' -import { migratePresentationDocument } from '@/presentation/project' -/** Source files and recovery checkpoints have deliberately separate writers. */ +/** PPTX is an explicit import/export boundary; workspace persistence belongs to PresentationStore. */ export function createPresentationFileController(options: { - sessionId: string files: OfficeFilesAPI read: () => PresentationWorkspace - write: (workspace: PresentationWorkspace) => void - encode: (document: PresentationDocument) => Promise + commitExport: (projectId: string, fileName: string, source: OfficeFileSource, exportedRevision: number) => void | Promise + encode: (project: PresentationProject) => Promise flushEditor: () => Promise - locale: () => string - automatic?: boolean - runAutoSave?: (save: () => Promise) => Promise - onSaveStatus?: (status: 'saving' | 'saved' | 'error', error?: string) => void + /** Whether the destination is a Session-managed file rather than a user-owned import. */ + managed: boolean + onExportStatus?: (status: 'saving' | 'saved' | 'error', error?: string) => void }) { - const { files, read, write } = options - let ready = false - const recovery = createOfficePersistenceScheduler({ - policy: { appKind: 'presentation', sessionId: options.sessionId, kind: 'recovery', storage: 'recovery-file', automatic: true }, - delayMs: 150, - write: (workspace) => files.setRecovery('presentation', options.sessionId, JSON.stringify(workspace)), - }) - const save = async (documentId: string, saveAs = false, destination?: string, background = false): Promise => { - if (!background) await options.flushEditor() - const document = read().documents.find((item) => item.id === documentId) - if (!document) throw new Error('The presentation is no longer open') - if (!saveAs && !isPresentationDirty(document)) { - // A successful source write can still leave a failed recovery checkpoint. - await recovery.persist(read()) - return !isPresentationDirty(read().documents.find((item) => item.id === documentId)!) + const save = async (projectId: string, saveAs = false, destination?: string): Promise => { + await options.flushEditor() + const workspace = options.read() + const project = workspace.projects.find((item) => item.id === projectId) + const metadata = workspace.projectMetadata[projectId] + if (!project || !metadata) throw new Error('The presentation project is no longer open') + if (!saveAs && !isPresentationProjectDirty(metadata)) { + const current = options.read().projectMetadata[projectId] + return Boolean(current && !isPresentationProjectDirty(current)) } - if (document.sourceProtected && !saveAs && !options.automatic) throw new Error(i18n.t('office.protectedSave')) - const result = await files.save({ kind: 'presentation', managed: options.automatic, documentId, source: document.source, preserveSource: document.sourceProtected, saveAs, destination, suggestedName: `${document.title.replace(/\.pptx$/i, '') || 'Untitled'}.pptx`, bytes: await options.encode(document) }) + if (metadata.sourceProtected && !saveAs && !options.managed) throw new Error(i18n.t('office.protectedSave')) + const exportedRevision = metadata.revision + const result = await options.files.save({ + kind: 'presentation', + managed: options.managed, + documentId: projectId, + source: metadata.source, + preserveSource: metadata.sourceProtected, + saveAs, + destination, + suggestedName: `${project.title.replace(/\.pptx$/i, '') || 'Untitled'}.pptx`, + bytes: await options.encode(project), + }) if (!result.ok) { if (result.reason === 'conflict') throw new Error('The file changed outside the editor. Your edits have been retained; retry after resolving the file change.') if (result.reason === 'source-protected') throw new Error(i18n.t('office.protectedSave')) return false } - if (!background) await options.flushEditor() - const current = read() - write({ ...current, documents: current.documents.map((item) => { - if (item.id === documentId) return { ...item, title: result.fileName.replace(/\.pptx$/i, ''), source: result.source, sourceProtected: false, savedRevision: document.revision } - return item.source?.path === result.source.path ? { ...item, source: undefined, savedRevision: undefined } : item - }) }) - await recovery.persist(read()) - return !isPresentationDirty(read().documents.find((item) => item.id === documentId)!) + await options.flushEditor() + await options.commitExport(projectId, result.fileName, result.source, exportedRevision) + const current = options.read().projectMetadata[projectId] + return Boolean(current && !isPresentationProjectDirty(current)) } - const saveDirty = async (requireComplete = false, background = false) => { - if (!background) await options.flushEditor() - for (const document of read().documents.filter(isPresentationDirty)) { - if (!await save(document.id, false, undefined, background) && requireComplete) throw new Error(i18n.t('office.changedDuringClose')) - } - } - const autoSave = createOfficeAutoSave(() => options.runAutoSave ? options.runAutoSave(() => saveDirty(false, true)) : saveDirty(false, true), options.onSaveStatus) + return { - recovery, - autoSave, - saveDirty, - async restore() { - const serialized = await files.getRecovery('presentation', options.sessionId) - if (serialized !== null) { - const workspace = JSON.parse(serialized) as { activeDocumentId?: unknown; documents?: unknown } - if (!Array.isArray(workspace.documents) || typeof workspace.activeDocumentId !== 'string') throw new Error('The PowerPoint recovery checkpoint is invalid') - const documents = workspace.documents.map((document) => migratePresentationDocument(document)) - if (documents.length) write({ activeDocumentId: workspace.activeDocumentId, documents: documents.map((document) => ({ - ...document, sourceProtected: document.sourceProtected ?? Boolean(document.source && document.source.mtimeMs !== null), - })) }) - } - ready = true - if (options.automatic) autoSave.schedule(read().documents.filter(isPresentationDirty).map((document) => `${document.id}:${document.revision}`).join('|')) - }, - schedule() { - if (!ready) return - recovery.schedule(read()) - if (options.automatic) autoSave.schedule(read().documents.filter(isPresentationDirty).map((document) => `${document.id}:${document.revision}`).join('|')) - }, - async flush() { - if (!ready) throw new Error('PowerPoint recovery is not ready') - await options.flushEditor() - await recovery.persist(read()) - }, - async save(documentId: string, saveAs = false, destination?: string) { - options.onSaveStatus?.('saving') + async save(projectId: string, saveAs = false, destination?: string) { + options.onExportStatus?.('saving') try { - const saved = await save(documentId, saveAs, destination) - options.onSaveStatus?.(saved ? 'saved' : 'saving') + const saved = await save(projectId, saveAs, destination) + options.onExportStatus?.(saved ? 'saved' : 'saving') return saved } catch (error) { - options.onSaveStatus?.('error', error instanceof Error ? error.message : String(error)) + options.onExportStatus?.('error', error instanceof Error ? error.message : String(error)) throw error } }, - async beforeClose(documentId: string): Promise { - await options.flushEditor() - const document = read().documents.find((item) => item.id === documentId) - if (!document || !isPresentationDirty(document)) return true - if (options.automatic) return save(documentId) - const decision = await files.confirmClose(`${document.title.replace(/\.pptx$/i, '')}.pptx`, options.locale()) - if (decision === 'cancel') return false - if (decision === 'save') return save(documentId, Boolean(document.sourceProtected)) - await options.flushEditor() - return read().documents.find((item) => item.id === documentId)?.revision === document.revision - }, } } + +export function isPresentationProjectDirty(metadata: PresentationProjectMetadata): boolean { + return !metadata.source || metadata.source.mtimeMs === null || metadata.savedRevision !== metadata.revision +} diff --git a/desktop/apps/electron/src/renderer/lib/presentationImport.ts b/desktop/apps/electron/src/renderer/lib/presentationImport.ts index c4d168df..9c7c7e0e 100644 --- a/desktop/apps/electron/src/renderer/lib/presentationImport.ts +++ b/desktop/apps/electron/src/renderer/lib/presentationImport.ts @@ -1,4 +1,4 @@ -import type { PresentationDocument } from '@/atoms/presentation' +import type { PresentationProject } from '@/atoms/presentation' import type { PresentationPptxImportOptions } from './presentationPptxImport' import { runOfficeImportWorker } from './office/officeImportWorker' @@ -8,12 +8,12 @@ export interface PresentationImportRequest { options: PresentationPptxImportOptions } -export function importPresentationInBackground(input: Uint8Array | ArrayBuffer | string, fileName: string, options: PresentationPptxImportOptions = {}): Promise { +export function importPresentationInBackground(input: Uint8Array | ArrayBuffer | string, fileName: string, options: PresentationPptxImportOptions = {}): Promise { let owned: Uint8Array | string if (typeof input === 'string') owned = input else if (input instanceof Uint8Array) owned = input.slice() else owned = new Uint8Array(input.slice(0)) - return runOfficeImportWorker( + return runOfficeImportWorker( () => new Worker(new URL('./presentationImport.worker.ts', import.meta.url), { type: 'module' }), { input: owned, fileName, options: { restoreEditorModel: true, ...options } } satisfies PresentationImportRequest, typeof owned === 'string' ? [] : [owned.buffer], diff --git a/desktop/apps/electron/src/renderer/lib/presentationImport.worker.ts b/desktop/apps/electron/src/renderer/lib/presentationImport.worker.ts index 823b6a1c..452aa392 100644 --- a/desktop/apps/electron/src/renderer/lib/presentationImport.worker.ts +++ b/desktop/apps/electron/src/renderer/lib/presentationImport.worker.ts @@ -1,10 +1,10 @@ import { importPresentationPptx } from './presentationPptxImport' import type { PresentationImportRequest } from './presentationImport' -import type { PresentationDocument } from '@/atoms/presentation' +import type { PresentationProject } from '@/atoms/presentation' import type { OfficeImportWorkerReply } from './office/officeImportWorker' self.onmessage = async ({ data }: MessageEvent) => { - let response: OfficeImportWorkerReply + let response: OfficeImportWorkerReply try { const bytes = typeof data.input === 'string' ? Uint8Array.from(atob(data.input), (character) => character.charCodeAt(0)) diff --git a/desktop/apps/electron/src/renderer/lib/presentationMarkdown.ts b/desktop/apps/electron/src/renderer/lib/presentationMarkdown.ts index f7e77ccf..4e89392e 100644 --- a/desktop/apps/electron/src/renderer/lib/presentationMarkdown.ts +++ b/desktop/apps/electron/src/renderer/lib/presentationMarkdown.ts @@ -1,1158 +1,18 @@ -import { dump, load } from 'js-yaml' -import { marked, type Token, type Tokens } from 'marked' -import { - PRESENTATION_ANIMATION_EFFECTS, - PRESENTATION_ANIMATION_STARTS, - PRESENTATION_ANIMATION_TRIGGERS, - PRESENTATION_CHART_TYPES, - PRESENTATION_PAGE_SIZES, - PRESENTATION_SHAPE_TYPES, - PRESENTATION_SLIDE_LAYOUTS, - PRESENTATION_TRANSITION_DIRECTIONS, - PRESENTATION_TRANSITION_EFFECTS, - createBlankPresentationDocument, - createBlankPresentationSlide, - presentationSlideBackground, - replacePresentationPages, - type PresentationAsset, - type PresentationChartElement, - type PresentationDocument, - type PresentationElement, - type PresentationFileSource, - type PresentationFooter, - type PresentationPageSize, - type PresentationShapeType, - type PresentationSlide, - type PresentationSlideLayout, - type PresentationTheme, - type PresentationTextElement, - type PresentationTextRun, - type PresentationTextParagraph, - type PresentationParagraphStyle, - type PresentationTextStyle, - type PresentationTransition, -} from '@/atoms/presentation' -import { normalizePresentationDesignColor, presentationThemeTextColors } from '@/lib/presentationDesign' -import { patchPresentationText, PRESENTATION_TEXT_STYLE_KEYS, PRESENTATION_TEXT_RUN_STYLE_KEYS, PRESENTATION_PARAGRAPH_STYLE_KEYS, PRESENTATION_NUMBER_FORMATS } from '@/lib/presentationText' -import { createPresentationAsset, mergePresentationAssets, normalizePresentationProject, presentationAsset, presentationElementSource } from '@/presentation/project' +import { dump } from 'js-yaml' +import type { PresentationProject, PresentationElement, PresentationSlide } from '@/atoms/presentation' +import { presentationElementSource } from '@/presentation/project' -export type PresentationMarkdownAssets = Record - -interface CompilePresentationMarkdownOptions { - assets?: PresentationMarkdownAssets - existingDocument?: PresentationDocument -} - -interface CompilePresentationMarkdownResult { - diagnostics: string[] - document: PresentationDocument -} - -interface CompilePresentationSlideMarkdownOptions extends CompilePresentationMarkdownOptions { - document: PresentationDocument -} - -interface CompilePresentationSlideMarkdownResult { - assets: PresentationAsset[] - diagnostics: string[] - slide: PresentationSlide -} - -interface CompilePresentationElementMarkdownOptions extends CompilePresentationMarkdownOptions { - document: PresentationDocument - elementId?: string - slide: PresentationSlide -} - -interface CompilePresentationElementMarkdownResult { - assets: PresentationAsset[] - diagnostics: string[] - element: PresentationElement -} - -interface ParsedSlideSource { - body: string - frontmatter: Record - index: number -} - -interface ParsedBody { - body: string - notes: string -} - -interface LayoutCursor { - full: number - left: number - right: number - slot: 'full' | 'left' | 'right' -} - -interface ElementCompilerContext { - assets: PresentationMarkdownAssets - background: string - cursor: LayoutCursor - diagnostics: string[] - elementOrdinal: number - existingDocument?: PresentationDocument - pageSize: PresentationPageSize - projectAssets: PresentationAsset[] - slideId: string - theme: PresentationTheme - usedElementIds: Set -} - -interface NativeComponent { - attrs: Record - body: string - name: 'PptAudio' | 'PptChart' | 'PptImage' | 'PptShape' | 'PptTable' | 'PptText' | 'PptVideo' -} - -const MAX_SLIDES = 200 -const MAX_ELEMENTS_PER_SLIDE = 1_000 -const ID_PATTERN = /^[A-Za-z0-9_.:-]+$/ -const NATIVE_COMPONENT_PATTERN = /^]*?)(?:\/\s*>|>([\s\S]*?)<\/Ppt\1\s*>)/ -const SHAPE_TYPES = new Set(PRESENTATION_SHAPE_TYPES) -const LAYOUTS = new Set(PRESENTATION_SLIDE_LAYOUTS) -const TRANSITION_EFFECTS = new Set(PRESENTATION_TRANSITION_EFFECTS) -const TRANSITION_DIRECTIONS = new Set>(PRESENTATION_TRANSITION_DIRECTIONS) -const ANIMATION_EFFECTS = new Set(PRESENTATION_ANIMATION_EFFECTS) -const ANIMATION_STARTS = new Set(PRESENTATION_ANIMATION_STARTS) -const ANIMATION_TRIGGERS = new Set(PRESENTATION_ANIMATION_TRIGGERS) -const CHART_TYPES = new Set(PRESENTATION_CHART_TYPES) -const MEDIA_COMPONENT_NAMES = new Set(['PptImage', 'PptAudio', 'PptVideo']) -const COMMON_COMPONENT_ATTRS = new Set([ - 'id', 'ref', 'x', 'y', 'width', 'height', 'rotation', 'opacity', 'groupId', 'shadow', - 'flipHorizontal', 'flipVertical', - 'animation', 'animationDuration', 'animationDelay', 'animationStart', 'animationTrigger', - 'animationColor', 'href', 'slideHref', 'tooltip', -]) -const COMPONENT_ATTRS: Record> = { - PptText: new Set([ - ...COMMON_COMPONENT_ATTRS, - 'fontSize', 'fontFamily', 'fontWeight', 'italic', 'underline', 'strikethrough', 'baseline', - 'highlightColor', 'characterSpacing', 'lineHeight', 'indentLevel', 'listStyle', 'color', 'align', - 'verticalAlign', 'textDirection', 'wordWrap', 'insetLeft', 'insetTop', 'insetRight', 'insetBottom', 'textRuns', 'paragraphs', 'lineSpacing', - ]), - PptShape: new Set([...COMMON_COMPONENT_ATTRS, 'kind', 'type', 'fill', 'borderColor', 'borderWidth', 'radius', 'connectorPath']), - PptImage: new Set([ - ...COMMON_COMPONENT_ATTRS, - 'src', 'alt', 'altText', 'fit', 'clipShape', 'cropLeft', 'cropTop', 'cropRight', 'cropBottom', - ]), - PptAudio: new Set([...COMMON_COMPONENT_ATTRS, 'src', 'autoplay', 'loop', 'muted']), - PptVideo: new Set([...COMMON_COMPONENT_ATTRS, 'src', 'autoplay', 'loop', 'muted']), - PptTable: new Set([ - ...COMMON_COMPONENT_ATTRS, - 'headerRow', 'headerFill', 'headerTextColor', 'bodyFill', 'textColor', 'borderColor', 'fontSize', - ]), - PptChart: new Set([ - ...COMMON_COMPONENT_ATTRS, - 'type', 'chartType', 'showLegend', 'showValue', 'displayBlanksAs', 'holeSize', 'title', 'colors', 'chartAreaFill', - 'plotAreaFill', 'categoryAxisLabelColor', 'valueAxisLabelColor', 'gridLineColor', 'dataLabelColor', - ]), -} - -/** Compile a complete Slidev-style Markdown deck into the native editable PPT IR. */ -export function compilePresentationMarkdown( - markdown: string, - options: CompilePresentationMarkdownOptions = {}, -): CompilePresentationMarkdownResult { - const sources = parsePresentationMarkdown(markdown) - if (sources.length > MAX_SLIDES) throw new Error(`A presentation may contain at most ${MAX_SLIDES} slides`) - const blank = createBlankPresentationDocument(optionalString(sources[0]!.frontmatter.title) ?? '') - const pageSize = parsePageSize(sources[0]!.frontmatter.pageSize) - const theme = parseTheme(sources[0]!.frontmatter.theme, blank.theme) - const usedSlideIds = new Set() - const usedElementIds = new Set() - const diagnostics: string[] = [] - const projectAssets: PresentationAsset[] = [] - const slides = sources.map((source) => compileSlideSource(source, { - assets: options.assets ?? {}, - diagnostics, - existingDocument: options.existingDocument, - pageSize, - projectAssets, - theme, - usedElementIds, - usedSlideIds, - })) - const existingSelection = options.existingDocument?.slides.selectedPageId - const selectedPageId = existingSelection && slides.some((slide) => slide.id === existingSelection) - ? existingSelection - : slides[0]!.id - return { - diagnostics, - document: normalizePresentationProject({ - ...blank, - id: options.existingDocument?.id ?? blank.id, - theme, - pageSize, - assets: projectAssets, - slides: replacePresentationPages(blank.slides, slides, selectedPageId), - title: optionalString(sources[0]!.frontmatter.title) ?? options.existingDocument?.title ?? '', - revision: options.existingDocument?.revision ?? 1, - }), - } -} - -/** Compile exactly one slide Markdown fragment against an existing document. */ -export function compilePresentationSlideMarkdown( - markdown: string, - options: CompilePresentationSlideMarkdownOptions, -): CompilePresentationSlideMarkdownResult { - const sources = parsePresentationMarkdown(markdown) - if (sources.length !== 1) throw new Error('A slide update must contain exactly one Markdown slide') - const usedSlideIds = new Set(options.document.slides.pages.map((slide) => slide.id)) - const requestedId = optionalString(sources[0]!.frontmatter.id) - if (requestedId) usedSlideIds.delete(requestedId) - const usedElementIds = new Set(options.document.slides.pages.flatMap((slide) => ( - slide.id === requestedId ? [] : slide.elements.map((element) => element.id) - ))) - const diagnostics: string[] = [] - const projectAssets: PresentationAsset[] = [] - const slide = compileSlideSource(sources[0]!, { - assets: options.assets ?? {}, - diagnostics, - existingDocument: options.existingDocument ?? options.document, - pageSize: options.document.pageSize, - projectAssets, - theme: options.document.theme, - usedElementIds, - usedSlideIds, - }) - return { assets: projectAssets, diagnostics, slide } -} - -/** Compile exactly one canonical Ppt* element fragment against a live slide. */ -export function compilePresentationElementMarkdown( - markdown: string, - options: CompilePresentationElementMarkdownOptions, -): CompilePresentationElementMarkdownResult { - if (typeof markdown !== 'string' || !markdown.trim()) throw new TypeError('PowerPoint element Markdown is required') - const components = parseNativeComponents(markdown) - if (!components || components.length !== 1) { - throw new Error('PowerPoint element Markdown must contain exactly one Ppt* element') - } - const component = components[0]! - const requested = componentRef(component.attrs) - if (options.elementId) { - if (requested && requested !== options.elementId) { - throw new Error(`PowerPoint element ref must remain ${options.elementId}`) - } - component.attrs.ref = options.elementId - delete component.attrs.id - } else if (requested) { - throw new Error('A new PowerPoint element must not provide id or ref; the editor assigns its ref') - } - const usedElementIds = new Set(options.document.slides.pages.flatMap((slide) => ( - slide.elements.flatMap((element) => element.id === options.elementId ? [] : [element.id]) - ))) - const diagnostics: string[] = [] - const projectAssets: PresentationAsset[] = [] - const context: ElementCompilerContext = { - assets: options.assets ?? {}, - background: presentationSlideBackground(options.document.theme, options.slide), - cursor: { full: 56, left: 76, right: 76, slot: 'full' }, - diagnostics, - elementOrdinal: options.slide.elements.length, - existingDocument: options.existingDocument ?? options.document, - pageSize: options.document.pageSize, - projectAssets, - slideId: options.slide.id, - theme: options.document.theme, - usedElementIds, - } - return { assets: projectAssets, diagnostics, element: compileNativeComponent(component, context) } -} - -/** Return the local paths referenced by parsed Markdown without mutating any presentation state. */ -export function inspectPresentationMarkdownAssets(markdown: string): string[] { - const paths = new Set() - if (markdown.trimStart().startsWith(' { - if (nestedToken.type === 'image') collectAssetPath((nestedToken as Tokens.Image).href, paths) - }) - } - } - return [...paths] -} - -/** Produce one canonical, self-contained slide Markdown fragment. */ +/** Produce a compact, read-only Agent projection of one native slide. */ export function decompilePresentationSlideMarkdown( slide: PresentationSlide, - project?: Pick, + project?: Pick, ): string { - return decompileSlide(slide, project) -} - -/** Produce one canonical Agent-editable element fragment with a stable ref. */ -export function decompilePresentationElementMarkdown(element: PresentationElement, project?: Pick): string { - return decompileElement(element, project) -} - -function parsePresentationMarkdown(markdown: string): ParsedSlideSource[] { - if (typeof markdown !== 'string' || !markdown.trim()) throw new TypeError('PowerPoint Markdown is required') - const lines = markdown.replace(/\r\n?/g, '\n').split('\n') - const delimiters = findTopLevelDelimiters(lines) - const firstContentLine = lines.findIndex((line) => line.trim()) - if (firstContentLine < 0 || delimiters[0] !== firstContentLine) { - throw new Error('PowerPoint Markdown must begin with a --- frontmatter block') - } - if (delimiters.length < 2 || delimiters.length % 2 !== 0) { - throw new Error('Every PowerPoint slide must have a closed --- frontmatter block') - } - const slides: ParsedSlideSource[] = [] - for (let pair = 0; pair < delimiters.length; pair += 2) { - const open = delimiters[pair]! - const close = delimiters[pair + 1]! - const next = delimiters[pair + 2] ?? lines.length - if (close <= open + 0) throw new Error(`Slide ${pair / 2 + 1} has invalid frontmatter`) - const yamlSource = lines.slice(open + 1, close).join('\n') - let value: unknown - try { - value = load(yamlSource) ?? {} - } catch (error) { - throw new Error(`Invalid YAML in slide ${pair / 2 + 1}: ${error instanceof Error ? error.message : String(error)}`) - } - if (!isRecord(value)) throw new TypeError(`Slide ${pair / 2 + 1} frontmatter must be a YAML mapping`) - slides.push({ body: lines.slice(close + 1, next).join('\n').trim(), frontmatter: value, index: pair / 2 }) - } - if (slides.length === 0) throw new Error('A presentation must contain at least one slide') - return slides -} - -function findTopLevelDelimiters(lines: string[]): number[] { - const delimiters: number[] = [] - let fence: { character: '`' | '~'; length: number } | null = null - let inComment = false - let opaqueTag: 'script' | 'style' | 'template' | null = null - let nativeComponent: { name: string; openingTag: boolean } | null = null - lines.forEach((line, index) => { - if (fence) { - if (new RegExp(`^ {0,3}${fence.character}{${fence.length},}\\s*$`).test(line)) fence = null - return - } - if (inComment) { - if (line.includes('-->')) inComment = false - return - } - if (opaqueTag) { - if (new RegExp(``, 'i').test(line)) opaqueTag = null - return - } - if (nativeComponent) { - if (nativeComponent.openingTag) { - if (/\/\s*>/.test(line)) nativeComponent = null - else if (/>/.test(line)) { - nativeComponent = new RegExp(``).test(line) - ? null - : { ...nativeComponent, openingTag: false } - } - } else if (new RegExp(``).test(line)) { - nativeComponent = null - } - return - } - const fenceMatch = line.match(/^ {0,3}(`{3,}|~{3,})/) - if (fenceMatch) { - fence = { - character: fenceMatch[1]![0] as '`' | '~', - length: fenceMatch[1]!.length, - } - return - } - const commentStart = line.indexOf('', commentStart + 4) < 0) { - inComment = true - return - } - const opaqueMatch = line.match(/<(script|style|template)\b/i) - if (opaqueMatch && !new RegExp(``, 'i').test(line)) { - opaqueTag = opaqueMatch[1]!.toLowerCase() as 'script' | 'style' | 'template' - return - } - const nativeMatch = line.match(/<(Ppt(?:Text|Shape|Image|Audio|Video|Table|Chart))\b/) - if (nativeMatch && !/\/\s*>/.test(line) && !new RegExp(``).test(line)) { - nativeComponent = { name: nativeMatch[1]!, openingTag: !/>/.test(line) } - return - } - if (/^---\s*$/.test(line)) delimiters.push(index) - }) - return delimiters -} - -function compileSlideSource( - source: ParsedSlideSource, - context: Omit & { usedSlideIds: Set }, -): PresentationSlide { - const frontmatter = source.frontmatter - const id = optionalString(frontmatter.id) ?? `slide-${source.index + 1}` - validateId(id, 'slide id') - if (context.usedSlideIds.has(id)) throw new Error(`Duplicate slide id: ${id}`) - context.usedSlideIds.add(id) - const template = createBlankPresentationSlide(optionalString(frontmatter.name) ?? `Slide ${source.index + 1}`) - const background = frontmatter.background === undefined - ? undefined - : requiredString(frontmatter.background, 'background') - const parsedBody = extractNotes(source.body) - const cursor: LayoutCursor = { full: 56, left: 76, right: 76, slot: 'full' } - const elementContext: ElementCompilerContext = { - ...context, - background: background ?? context.theme.background, - cursor, - elementOrdinal: 0, - slideId: id, - } - const elements = compileMarkdownBlocks(parsedBody.body, elementContext) - if (elements.length > MAX_ELEMENTS_PER_SLIDE) { - throw new Error(`Slide ${id} may contain at most ${MAX_ELEMENTS_PER_SLIDE} elements`) - } - return { - ...template, - ...(background === undefined ? {} : { background }), - ...(frontmatter.comments === undefined ? {} : { comments: parseComments(frontmatter.comments, id) }), - elements, - ...(frontmatter.footer === undefined ? {} : { footer: parseFooter(frontmatter.footer, 'footer') }), - id, - layout: parseLayout(frontmatter.layout), - name: optionalString(frontmatter.name) ?? `Slide ${source.index + 1}`, - notes: parsedBody.notes, - transition: parseTransition(frontmatter.transition, template.transition), - } -} - -function extractNotes(body: string): ParsedBody { - const match = body.match(/(?:^|\n)\s*\s*$/i) - if (!match || match.index === undefined) return { body, notes: '' } - return { body: body.slice(0, match.index).trimEnd(), notes: match[1]!.trim() } -} - -function parseNativeComponents(source: string): NativeComponent[] | null { - let remaining = source.trim() - const components: NativeComponent[] = [] - while (remaining) { - const match = remaining.match(NATIVE_COMPONENT_PATTERN) - if (!match) return null - components.push({ - attrs: parseComponentAttrs(match[2] ?? ''), - body: (match[3] ?? '').replace(/^\n/, '').replace(/\n$/, ''), - name: `Ppt${match[1]}` as NativeComponent['name'], - }) - remaining = remaining.slice(match[0].length).trimStart() - } - return components.length > 0 ? components : null -} - -function parseComponentAttrs(source: string): Record { - const attrs: Record = {} - const consumed = source.replace(/([A-Za-z_][\w:.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g, (_, key: string, double: string, single: string) => { - attrs[key] = decodeEntities(double ?? single ?? '') - return ' ' - }) - for (const token of consumed.trim().split(/\s+/).filter(Boolean)) { - if (!/^[A-Za-z_][\w:.-]*$/.test(token)) throw new Error(`Invalid native component attributes: ${source.trim()}`) - attrs[token] = 'true' - } - return attrs -} - -function compileMarkdownBlocks(source: string, context: ElementCompilerContext): PresentationElement[] { - if (!source.trim()) return [] - const elements: PresentationElement[] = [] - for (const token of marked.lexer(source, { gfm: true })) { - if (token.type === 'space') continue - if (token.type !== 'code') { - const components = parseNativeComponents(token.raw) - if (components) { - for (const component of components) { - const element = compileNativeComponent(component, context) - elements.push(element) - const slot = context.cursor.slot - context.cursor[slot] = Math.max(context.cursor[slot], element.y + element.height + 18) - } - continue - } - } - if (token.type === 'html') { - const raw = token.raw.trim() - if (/^$/.test(raw)) continue - if (/^$/i.test(raw)) { - context.diagnostics.push(`[slide_ref=${context.slideId}]