From 5073e4d36b31100d549163f66c5939ceb00b3638 Mon Sep 17 00:00:00 2001 From: merrick-2002 Date: Mon, 24 Aug 2026 23:20:31 +0800 Subject: [PATCH] Sync snapshot (2026-08-24) (#143) - Add Word-parity Docs shortcuts, shape-text formatting, and safer AI-created documents - Add selection-scoped Ask AI, right-to-left grids, active row and column highlighting, and full-workbook Find improvements in Sheets - Add local OCR text layers and persistent AI chat history in PDF - Add selection Ask AI, effects editing, true vertical text, and rendering fidelity improvements in Slides - Improve Korean font metrics and Office document layout fidelity across the suite - Report an OS-locale country dimension in opt-out usage analytics with an updated privacy disclosure Co-authored-by: GenOffice --- PRIVACY.md | 10 +- apps/docs/src/main/docs-main.ts | 133 +- apps/docs/src/preload/index.ts | 2 + apps/docs/src/renderer/App.tsx | 335 +++-- apps/docs/src/renderer/ai/protocol.ts | 1 + apps/docs/src/renderer/ai/tools.ts | 59 +- .../src/renderer/components/AiAskPopover.tsx | 22 +- .../renderer/components/HeaderFooterArea.tsx | 4 + apps/docs/src/renderer/components/Ribbon.tsx | 254 +++- .../renderer/components/ShortcutsDialog.tsx | 71 ++ .../renderer/components/WordCountDialog.tsx | 62 + .../components/ribbon-format-state.ts | 70 +- .../src/renderer/components/ribbon-tabs.tsx | 34 +- apps/docs/src/renderer/editor/caret-marks.ts | 2 +- .../src/renderer/editor/case-transform.ts | 71 ++ apps/docs/src/renderer/editor/extensions.ts | 45 +- apps/docs/src/renderer/editor/hf-dom.ts | 61 +- apps/docs/src/renderer/editor/indent.ts | 38 + apps/docs/src/renderer/editor/move-block.ts | 41 + .../src/renderer/editor/protected-render.ts | 2 + apps/docs/src/renderer/file-actions.ts | 82 +- .../renderer/fonts/GenOfficeCheLatinKR.woff2 | Bin 0 -> 8296 bytes .../GenOfficeSansKR-Regular-subset.woff2 | Bin 262080 -> 266128 bytes .../GenOfficeSerifKR-Regular-subset.woff2 | Bin 511576 -> 512436 bytes apps/docs/src/renderer/fonts/README.md | 26 +- apps/docs/src/renderer/fonts/fonts.css | 13 + apps/docs/src/renderer/i18n/strings-ai.ts | 38 + apps/docs/src/renderer/i18n/strings-app.ts | 570 +++++++++ apps/docs/src/renderer/line-metrics.ts | 64 +- apps/docs/src/renderer/pagination.ts | 114 +- apps/docs/src/renderer/shortcuts.ts | 182 +++ apps/docs/src/renderer/styles.css | 100 +- apps/docs/src/shared/ipc.ts | 29 + apps/docs/tests/ai-create-document.test.ts | 144 +++ apps/docs/tests/all-selection-enter.test.ts | 39 + apps/docs/tests/helpers/ribbon-props.ts | 93 ++ apps/docs/tests/kr-font-metrics.test.ts | 17 + apps/docs/tests/line-metrics.test.ts | 17 +- apps/docs/tests/pagination.test.ts | 146 ++- apps/docs/tests/render-isolation.test.ts | 89 +- apps/docs/tests/shape-format-text.test.ts | 230 ++++ apps/docs/tests/shape-insert.test.ts | 24 + apps/docs/tests/shortcut-registry.test.ts | 86 ++ apps/docs/tests/shortcuts-dialog.test.ts | 74 ++ apps/docs/tests/word-shortcut-actions.test.ts | 209 +++ .../src/renderer/components/AiAskPopover.tsx | 22 +- apps/markdown/src/renderer/styles.css | 16 +- apps/pdf/src/main/ocr.ts | 66 + apps/pdf/src/main/pdf-main.ts | 106 +- apps/pdf/src/preload/index.ts | 15 + apps/pdf/src/renderer/App.tsx | 78 +- apps/pdf/src/renderer/ai/AiPanel.tsx | 155 +++ apps/pdf/src/renderer/ai/pdf-skill.ts | 1 + apps/pdf/src/renderer/ai/tools.ts | 71 ++ apps/pdf/src/renderer/i18n/strings.ts | 38 + apps/pdf/src/renderer/icons.tsx | 7 +- apps/pdf/src/renderer/ocr-layer.tsx | 223 ++++ apps/pdf/src/renderer/styles.css | 29 +- apps/pdf/src/shared/ipc.ts | 34 + apps/pdf/tests/ai-context.test.ts | 1 + apps/pdf/tests/ai-tools.test.ts | 69 + apps/pdf/tests/ocr-layer.test.ts | 153 +++ apps/pdf/tests/open-path.test.ts | 68 +- apps/pdf/tsconfig.json | 7 +- apps/sheets/native/xlsx-engine/src/lib.rs | 93 +- apps/sheets/native/xlsx-engine/src/visuals.rs | 46 +- apps/sheets/src/gateway/xlsx-drawing-edit.ts | 46 +- apps/sheets/src/preload/index.ts | 12 +- apps/sheets/src/renderer/App.tsx | 280 ++++- apps/sheets/src/renderer/ExcelShell.tsx | 39 + apps/sheets/src/renderer/WorkbookVisuals.tsx | 27 +- apps/sheets/src/renderer/ai/AiChatPanel.tsx | 188 ++- .../sheets/src/renderer/ai/AiSelectionAsk.tsx | 167 +++ apps/sheets/src/renderer/ai/prompts/base.md | 4 +- apps/sheets/src/renderer/ai/selection-ask.ts | 65 + .../sheets/src/renderer/ai/selection-scope.ts | 117 ++ apps/sheets/src/renderer/ai/sheet-nav.ts | 40 + apps/sheets/src/renderer/ai/tools.ts | 41 +- .../src/renderer/ai/workbook-readers.ts | 30 +- apps/sheets/src/renderer/autofit-multi-row.ts | 2 +- .../sheets/src/renderer/cell-font-fallback.ts | 253 +++- apps/sheets/src/renderer/cross-highlight.tsx | 426 ++++--- apps/sheets/src/renderer/i18n/strings-ai.ts | 131 ++ apps/sheets/src/renderer/lazy-find.ts | 205 ++- apps/sheets/src/renderer/numfmt-fix.ts | 39 +- apps/sheets/src/renderer/ribbon-actions.ts | 24 +- .../sheets/src/renderer/rich-text-bidi-fix.ts | 290 +++++ apps/sheets/src/renderer/rtl-grid-mirror.ts | 661 ++++++++++ apps/sheets/src/renderer/rtl-text-fix.ts | 105 +- apps/sheets/src/renderer/save-actions.ts | 19 +- apps/sheets/src/renderer/shape-draw.ts | 74 +- apps/sheets/src/renderer/styles.css | 270 ++-- apps/sheets/src/renderer/univer-sync.ts | 173 ++- apps/sheets/src/renderer/view-transform.ts | 158 ++- apps/sheets/src/shared/desktop-api.ts | 15 +- apps/sheets/tests/array-formulas.test.ts | 31 + apps/sheets/tests/autofit-multi-row.test.ts | 13 +- apps/sheets/tests/cell-font-fallback.test.ts | 94 +- apps/sheets/tests/column-width-mdw.test.ts | 110 +- apps/sheets/tests/cross-highlight.test.ts | 200 ++- .../formula-closure-structural-race.test.ts | 137 ++ apps/sheets/tests/lazy-find.test.ts | 320 ++++- apps/sheets/tests/numfmt-overflow.test.ts | 11 +- apps/sheets/tests/rtl-grid-mirror.test.ts | 97 ++ apps/sheets/tests/rtl-rich-text.test.ts | 228 ++++ apps/sheets/tests/rtl-text-direction.test.ts | 83 +- apps/sheets/tests/selection-ask.test.ts | 31 + apps/sheets/tests/selection-scope.test.ts | 161 +++ apps/sheets/tests/shape-draw-anchor.test.ts | 83 ++ apps/sheets/tests/sheet-nav.test.ts | 80 ++ apps/sheets/tests/view-transform.test.ts | 108 ++ .../sheets/tests/workbook-skill-tools.test.ts | 94 ++ apps/sheets/tests/xlsx-drawing-edit.test.ts | 146 +++ apps/shell/src/main/analytics.ts | 24 +- apps/shell/src/main/index.ts | 7 + apps/shell/src/main/tab-manager.ts | 8 +- apps/shell/tests/analytics.test.ts | 27 + apps/slides/src/main/fonts.ts | 55 +- apps/slides/src/main/ops/element-ops.ts | 28 + apps/slides/src/main/session-state.ts | 74 +- apps/slides/src/main/slides-main.ts | 30 + apps/slides/src/preload/index.ts | 3 + apps/slides/src/renderer/App.tsx | 186 ++- apps/slides/src/renderer/NodeBody.tsx | 198 ++- apps/slides/src/renderer/TextEditOverlay.tsx | 74 +- apps/slides/src/renderer/ai/AiPanel.tsx | 46 +- apps/slides/src/renderer/ai/slide-qc.ts | 92 +- .../src/renderer/components/AiAskPopover.tsx | 143 ++- .../src/renderer/components/FormatPane.tsx | 1115 ++++++++++++++++- apps/slides/src/renderer/i18n/strings-ai.ts | 114 +- .../slides/src/renderer/i18n/strings-panes.ts | 532 ++++++++ apps/slides/src/renderer/konva-adapter.ts | 141 ++- apps/slides/src/renderer/styles.css | 202 ++- apps/slides/src/shared/ipc.ts | 29 + apps/slides/src/shared/op-docs.ts | 4 + apps/slides/tests/edit-fidelity.test.ts | 48 +- apps/slides/tests/effects-op-probe.test.ts | 26 + apps/slides/tests/slide-qc.test.ts | 96 ++ apps/slides/tests/svg-theme-retint.test.ts | 73 ++ package-lock.json | 5 +- packages/docx-engine/src/parse.ts | 136 +- packages/docx-engine/src/types.ts | 7 + .../src/vendor/emf-converter/index.mjs | 75 ++ .../tests/balance-dbcs-spacing.test.ts | 71 ++ packages/docx-engine/tests/hf-images.test.ts | 9 + .../tests/inline-image-mixed.test.ts | 20 + packages/electron-utils/package.json | 3 + packages/electron-utils/src/index.ts | 7 + packages/electron-utils/src/print-html-pdf.ts | 197 +++ .../tests/print-html-pdf.test.ts | 107 ++ packages/pptx-engine/src/index.ts | 200 ++- packages/pptx-engine/src/parse.ts | 100 +- packages/pptx-engine/src/placeholder.ts | 49 +- packages/pptx-engine/src/table-style.ts | 24 +- packages/pptx-engine/src/types.ts | 34 +- packages/pptx-engine/tests/effects.test.ts | 140 +++ .../pptx-engine/tests/table-style.test.ts | 18 +- packages/pptx-render/src/build-chart.ts | 11 +- packages/pptx-render/src/build-slide.ts | 13 +- packages/pptx-render/src/fill.ts | 21 + packages/pptx-render/src/metrics.ts | 10 + packages/pptx-render/src/render-tree.ts | 34 +- packages/pptx-render/src/text-layout.ts | 299 ++++- .../pptx-render/tests/text-layout.test.ts | 202 ++- packages/ui/src/Markdown.tsx | 10 +- packages/ui/src/dropdown.css | 8 +- packages/ui/src/tokens.css | 9 + tools/build-kr-che-latin-font.py | 97 ++ tools/gen-third-party-notices.mjs | 7 +- tools/normalize-kr-latin-metrics.py | 139 ++ tools/scale-kr-sans-latin-ink.py | 95 ++ tools/sheets-fidelity-compare.mjs | 42 +- 172 files changed, 15164 insertions(+), 1339 deletions(-) create mode 100644 apps/docs/src/renderer/components/ShortcutsDialog.tsx create mode 100644 apps/docs/src/renderer/components/WordCountDialog.tsx create mode 100644 apps/docs/src/renderer/editor/case-transform.ts create mode 100644 apps/docs/src/renderer/editor/move-block.ts create mode 100644 apps/docs/src/renderer/fonts/GenOfficeCheLatinKR.woff2 create mode 100644 apps/docs/src/renderer/shortcuts.ts create mode 100644 apps/docs/tests/ai-create-document.test.ts create mode 100644 apps/docs/tests/helpers/ribbon-props.ts create mode 100644 apps/docs/tests/shape-format-text.test.ts create mode 100644 apps/docs/tests/shortcut-registry.test.ts create mode 100644 apps/docs/tests/shortcuts-dialog.test.ts create mode 100644 apps/docs/tests/word-shortcut-actions.test.ts create mode 100644 apps/pdf/src/main/ocr.ts create mode 100644 apps/pdf/src/renderer/ocr-layer.tsx create mode 100644 apps/pdf/tests/ocr-layer.test.ts create mode 100644 apps/sheets/src/renderer/ai/AiSelectionAsk.tsx create mode 100644 apps/sheets/src/renderer/ai/selection-ask.ts create mode 100644 apps/sheets/src/renderer/ai/selection-scope.ts create mode 100644 apps/sheets/src/renderer/ai/sheet-nav.ts create mode 100644 apps/sheets/src/renderer/rich-text-bidi-fix.ts create mode 100644 apps/sheets/src/renderer/rtl-grid-mirror.ts create mode 100644 apps/sheets/tests/formula-closure-structural-race.test.ts create mode 100644 apps/sheets/tests/rtl-grid-mirror.test.ts create mode 100644 apps/sheets/tests/rtl-rich-text.test.ts create mode 100644 apps/sheets/tests/selection-ask.test.ts create mode 100644 apps/sheets/tests/selection-scope.test.ts create mode 100644 apps/sheets/tests/shape-draw-anchor.test.ts create mode 100644 apps/sheets/tests/sheet-nav.test.ts create mode 100644 apps/slides/tests/effects-op-probe.test.ts create mode 100644 apps/slides/tests/svg-theme-retint.test.ts create mode 100644 packages/docx-engine/tests/balance-dbcs-spacing.test.ts create mode 100644 packages/electron-utils/src/print-html-pdf.ts create mode 100644 packages/electron-utils/tests/print-html-pdf.test.ts create mode 100644 packages/pptx-engine/tests/effects.test.ts create mode 100644 tools/build-kr-che-latin-font.py create mode 100644 tools/normalize-kr-latin-metrics.py create mode 100644 tools/scale-kr-sans-latin-ink.py diff --git a/PRIVACY.md b/PRIVACY.md index d6c2772..e2042c8 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -1,6 +1,6 @@ # GenOffice Privacy -Last updated: August 19, 2026 +Last updated: August 24, 2026 GenOffice opens, edits, and saves documents locally. Document editing does not upload files to GenOffice. AI features require a network connection and send @@ -35,8 +35,14 @@ Every event includes: - a per-process `session_id` derived from the process start time - `engagement_time_msec` with the fixed value `100` +When available, the payload also includes `country_id`, the two-letter country +code from the operating system's regional locale. This can differ from the +user's physical location. + The Google Analytics 4 payload also uses a random install UUID as `client_id`. -Neither identifier is a Genspark account or email address. +The country code is sent through GA4's country-only `user_location` field; the +app does not send a city or region. Neither identifier is a Genspark account or +email address. ## Network information diff --git a/apps/docs/src/main/docs-main.ts b/apps/docs/src/main/docs-main.ts index 240d500..46d3e07 100644 --- a/apps/docs/src/main/docs-main.ts +++ b/apps/docs/src/main/docs-main.ts @@ -8,7 +8,7 @@ import { unlinkSync, writeFileSync, } from 'node:fs' -import { copyFile, mkdir, readFile, readdir, stat, unlink } from 'node:fs/promises' +import { copyFile, mkdir, readFile, readdir, stat, unlink, writeFile } from 'node:fs/promises' import { basename, join } from 'node:path' import { BrowserWindow, @@ -24,11 +24,13 @@ import { } from 'electron' import { appMenuLabels, + buildPrintableHtml, configuredDefaultSaveDir, contextMenuLabels, fetchRemoteImage, installContextMenu, installNavigationGuard, + printHtmlToPdf, safeExternalUrl, showOpenDialogWithMemory, showSaveDialogWithMemory, @@ -74,10 +76,13 @@ import { imageSearch, } from '@genoffice/ai-search' import type { + AiDocContent, AttachmentAddResult, AttachmentImageResult, AttachmentMeta, AttachmentReadResult, + CreateDocumentRequest, + CreateDocumentResult, DecryptOpenResult, DocsTabInfo, MenuCommand, @@ -206,6 +211,7 @@ const tMain = createI18n({ menuAiProofread: 'AI 校对', menuWindow: '窗口', menuHelp: '帮助', + menuShortcuts: '键盘快捷键', menuDocsHelp: 'GenOffice Docs 帮助', }, en: { @@ -299,6 +305,7 @@ const tMain = createI18n({ menuAiProofread: 'AI Proofread', menuWindow: 'Window', menuHelp: 'Help', + menuShortcuts: 'Keyboard Shortcuts', menuDocsHelp: 'GenOffice Docs Help', }, ja: { @@ -392,6 +399,7 @@ const tMain = createI18n({ menuAiProofread: 'AI 校正', menuWindow: 'ウィンドウ', menuHelp: 'ヘルプ', + menuShortcuts: 'キーボードショートカット', menuDocsHelp: 'GenOffice Docs ヘルプ', }, ko: { @@ -486,6 +494,7 @@ const tMain = createI18n({ menuAiProofread: 'AI 교정', menuWindow: '창', menuHelp: '도움말', + menuShortcuts: '키보드 바로 가기', menuDocsHelp: 'GenOffice Docs 도움말', }, fr: { @@ -581,6 +590,7 @@ const tMain = createI18n({ menuAiProofread: 'Relecture IA', menuWindow: 'Fenêtre', menuHelp: 'Aide', + menuShortcuts: 'Raccourcis clavier', menuDocsHelp: 'Aide GenOffice Docs', }, de: { @@ -676,6 +686,7 @@ const tMain = createI18n({ menuAiProofread: 'KI-Korrektur', menuWindow: 'Fenster', menuHelp: 'Hilfe', + menuShortcuts: 'Tastenkombinationen', menuDocsHelp: 'GenOffice Docs-Hilfe', }, es: { @@ -770,6 +781,7 @@ const tMain = createI18n({ menuAiProofread: 'Corrección con IA', menuWindow: 'Ventana', menuHelp: 'Ayuda', + menuShortcuts: 'Atajos de teclado', menuDocsHelp: 'Ayuda de GenOffice Docs', }, th: { @@ -863,6 +875,7 @@ const tMain = createI18n({ menuAiProofread: 'พิสูจน์อักษรด้วย AI', menuWindow: 'หน้าต่าง', menuHelp: 'วิธีใช้', + menuShortcuts: 'แป้นพิมพ์ลัด', menuDocsHelp: 'วิธีใช้ GenOffice Docs', }, id: { @@ -956,6 +969,7 @@ const tMain = createI18n({ menuAiProofread: 'Koreksi AI', menuWindow: 'Jendela', menuHelp: 'Bantuan', + menuShortcuts: 'Pintasan Papan Ketik', menuDocsHelp: 'Bantuan GenOffice Docs', }, ru: { @@ -1050,6 +1064,7 @@ const tMain = createI18n({ menuAiProofread: 'ИИ-корректура', menuWindow: 'Окно', menuHelp: 'Справка', + menuShortcuts: 'Сочетания клавиш', menuDocsHelp: 'Справка GenOffice Docs', }, ar: { @@ -1144,6 +1159,7 @@ const tMain = createI18n({ menuAiProofread: 'تدقيق بالذكاء الاصطناعي', menuWindow: 'نافذة', menuHelp: 'تعليمات', + menuShortcuts: 'اختصارات لوحة المفاتيح', menuDocsHelp: 'تعليمات GenOffice Docs', }, pt: { @@ -1238,6 +1254,7 @@ const tMain = createI18n({ menuAiProofread: 'Revisão com IA', menuWindow: 'Janela', menuHelp: 'Ajuda', + menuShortcuts: 'Atalhos de Teclado', menuDocsHelp: 'Ajuda do GenOffice Docs', }, it: { @@ -1332,6 +1349,7 @@ const tMain = createI18n({ menuAiProofread: 'Correzione IA', menuWindow: 'Finestra', menuHelp: 'Aiuto', + menuShortcuts: 'Scelte rapide da tastiera', menuDocsHelp: 'Guida di GenOffice Docs', }, pl: { @@ -1426,6 +1444,7 @@ const tMain = createI18n({ menuAiProofread: 'Korekta AI', menuWindow: 'Okno', menuHelp: 'Pomoc', + menuShortcuts: 'Skróty klawiaturowe', menuDocsHelp: 'Pomoc GenOffice Docs', }, nl: { @@ -1520,6 +1539,7 @@ const tMain = createI18n({ menuAiProofread: 'AI-proeflezen', menuWindow: 'Venster', menuHelp: 'Help', + menuShortcuts: 'Sneltoetsen', menuDocsHelp: 'GenOffice Docs Help', }, ms: { @@ -1614,6 +1634,7 @@ const tMain = createI18n({ menuAiProofread: 'Pembacaan Pruf AI', menuWindow: 'Tetingkap', menuHelp: 'Bantuan', + menuShortcuts: 'Pintasan Papan Kekunci', menuDocsHelp: 'Bantuan GenOffice Docs', }, he: { @@ -1706,6 +1727,7 @@ const tMain = createI18n({ menuAiProofread: 'הגהת AI', menuWindow: 'חלון', menuHelp: 'עזרה', + menuShortcuts: 'קיצורי מקלדת', menuDocsHelp: 'עזרה של GenOffice Docs', }, hi: { @@ -1800,6 +1822,7 @@ const tMain = createI18n({ menuAiProofread: 'AI प्रूफ़रीडिंग', menuWindow: 'विंडो', menuHelp: 'सहायता', + menuShortcuts: 'कीबोर्ड शॉर्टकट', menuDocsHelp: 'GenOffice Docs सहायता', }, 'zh-TW': { @@ -1891,6 +1914,7 @@ const tMain = createI18n({ menuAiProofread: 'AI 校對', menuWindow: '視窗', menuHelp: '說明', + menuShortcuts: '鍵盤快速鍵', menuDocsHelp: 'GenOffice Docs 說明', }, }) @@ -1935,6 +1959,14 @@ export function markDocsNewBlank(wcId: number): void { pendingNewBlankIds.add(wcId) } +/** AI-authored content waiting for its create_document tab, keyed by webContents id */ +const pendingAiDocContents = new Map() + +/** queue AI content for a fresh blank docs tab (called by the shell right after creating the view) */ +export function queueDocsAiContent(wcId: number, content: AiDocContent): void { + pendingAiDocContents.set(wcId, content) +} + /** the single real BrowserWindow hosting the tab strip, used as dialog parent in tab mode */ let docsShellWindow: BrowserWindow | null = null export function setDocsShellWindow(win: BrowserWindow | null): void { @@ -3073,6 +3105,13 @@ export function registerDocsIpc(): void { return false }) + /** one-shot AI content queued by create_document for this tab; null when none */ + ipcMain.handle('docs:consume-ai-doc-content', (event): AiDocContent | null => { + const content = pendingAiDocContents.get(event.sender.id) ?? null + pendingAiDocContents.delete(event.sender.id) + return content + }) + ipcMain.handle( 'docs:save', async (event, filePath: string, data: ArrayBuffer, auto?: boolean) => { @@ -3246,6 +3285,12 @@ export function registerDocsIpc(): void { } }) + ipcMain.handle( + 'docs:create-document', + (_event, request: CreateDocumentRequest): Promise => + createAiDocument(request), + ) + ipcMain.handle('docs:recent', () => readJson(RECENT_PATH(), []).filter((p) => existsSync(p)), ) @@ -3429,7 +3474,7 @@ export function registerDocsIpc(): void { margins: { top: 0, bottom: 0, left: 0, right: 0 }, }) writeFileSync(filePath, data) - openExportedPdf(filePath) + openGeneratedFile(filePath) return { ok: true, path: filePath } } catch (err) { return { ok: false, error: String(err) } @@ -3484,7 +3529,7 @@ export function registerDocsIpc(): void { for (const page of pages) merged.addPage(page) } writeFileSync(filePath, Buffer.from(await merged.save())) - openExportedPdf(filePath) + openGeneratedFile(filePath) return { ok: true, path: filePath } } catch (err) { return { ok: false, error: String(err) } @@ -3528,6 +3573,8 @@ export function registerDocsIpc(): void { * and falls back to real multi-BrowserWindow behavior. */ interface DocsShellHooks { openTab(openPath?: string, options?: { newBlank?: boolean }): void + /** open a blank docs tab that consumes the queued AI content on boot (create_document) */ + openAiDocTab?(content: AiDocContent): void listTabs(): DocsTabInfo[] focusTab(id: string): void /** closes the calling tab instead of the whole shell window (Cmd+W / role:'close') */ @@ -3540,18 +3587,78 @@ export function setDocsShellHooks(hooks: DocsShellHooks | null): void { shellHooks = hooks } -/** After a successful Docs → PDF export: open the file in a PDF tab (shell) - * or reveal it in the folder (standalone). Tab-opening failure must not - * report the export itself as failed — the file is already persisted. */ -function openExportedPdf(path: string): void { +/** After writing an exported/AI-generated file: open it in the right tab + * (shell) or reveal it in the folder (standalone). Tab-opening failure must + * not report the write itself as failed — the file is already persisted. */ +function openGeneratedFile(path: string): void { try { if (shellHooks?.openGeneratedPath?.(path)) return } catch (err) { - console.warn('[docs] Failed to open exported PDF:', err) + console.warn('[docs] Failed to open generated file:', err) } shell.showItemInFolder(path) } +/** Pick a safe file-name stem for an AI-created document. */ +export function sanitizeAiDocFileBase(title: string): string { + // Control characters are intentionally rejected from generated file names. + const cleaned = String(title ?? '') + // eslint-disable-next-line no-control-regex + .replace(/[/\\:*?"<>|\u0000-\u001f]/g, '_') + .trim() + .slice(0, 80) + .trim() + return cleaned && cleaned !== '.' && cleaned !== '..' ? cleaned : 'Untitled' +} + +/** + * AI create_document: build a new standalone file in the default folder and + * open it in a new tab. docx routes through a fresh blank docs tab that + * inserts the queued content on boot and saves itself (the full-fidelity + * HTML → docx conversion lives in the docs renderer); pdf and md are written + * directly here. Also called by other apps' mains via shell-wired hooks. + */ +export async function createAiDocument( + request: CreateDocumentRequest, +): Promise { + const type = request?.type + const title = sanitizeAiDocFileBase(request?.title) + const content = String(request?.content ?? '') + if (!content.trim()) return { ok: false, error: 'content must not be empty' } + try { + if (type === 'docx') { + const payload: AiDocContent = { title, html: content } + if (shellHooks?.openAiDocTab) shellHooks.openAiDocTab(payload) + else { + const win = createDocsWindow(undefined) + markDocsNewBlank(win.webContents.id) + queueDocsAiContent(win.webContents.id, payload) + } + return { ok: true } + } + if (type === 'pdf') { + const bytes = await printHtmlToPdf( + buildPrintableHtml(title, content), + () => + new BrowserWindow({ show: false, webPreferences: { sandbox: true, javascript: false } }), + ) + const filePath = uniquePathIn(defaultSaveDir(), `${title}.pdf`) + await writeFile(filePath, bytes) + openGeneratedFile(filePath) + return { ok: true, path: filePath } + } + if (type === 'md') { + const filePath = uniquePathIn(defaultSaveDir(), `${title}.md`) + await writeFile(filePath, content, 'utf8') + openGeneratedFile(filePath) + return { ok: true, path: filePath } + } + return { ok: false, error: `unsupported document type: ${String(type)}` } + } catch (err) { + return { ok: false, error: err instanceof Error ? err.message : String(err) } + } +} + // ---- application menu ---- function sendCommand(command: MenuCommand, payload?: string): void { @@ -3805,7 +3912,15 @@ export function buildDocsMenu(): void { { label: tm('menuHelp'), role: 'help', - submenu: [{ label: tm('menuDocsHelp'), enabled: false }], + submenu: [ + { + label: tm('menuShortcuts'), + accelerator: 'CmdOrCtrl+/', + click: () => sendCommand('shortcuts'), + }, + { type: 'separator' }, + { label: tm('menuDocsHelp'), enabled: false }, + ], }, ] diff --git a/apps/docs/src/preload/index.ts b/apps/docs/src/preload/index.ts index c0b0d33..dc4fbda 100644 --- a/apps/docs/src/preload/index.ts +++ b/apps/docs/src/preload/index.ts @@ -48,6 +48,8 @@ const api: DesktopApi = { ipcRenderer.invoke('docs:discard-password-intents', throughRevision), consumePendingOpenDocx: () => ipcRenderer.invoke('docs:consume-pending-open'), consumeNewBlankDoc: () => ipcRenderer.invoke('docs:consume-new-blank'), + consumeAiDocContent: () => ipcRenderer.invoke('docs:consume-ai-doc-content'), + createDocument: (request) => ipcRenderer.invoke('docs:create-document', request), onOpenDocx: (handler) => { const listener = (_event: IpcRendererEvent, result: Parameters[0]) => handler(result) diff --git a/apps/docs/src/renderer/App.tsx b/apps/docs/src/renderer/App.tsx index c5dc698..c50456e 100644 --- a/apps/docs/src/renderer/App.tsx +++ b/apps/docs/src/renderer/App.tsx @@ -35,7 +35,7 @@ import { type ThemeColors, type ThemeFonts, } from '@genoffice/docx-engine' -import type { AiSettings, OpenDocxResult } from '../shared/ipc' +import type { AiDocContent, AiSettings, OpenDocxResult } from '../shared/ipc' import { AI_PROVIDERS } from '../shared/ipc' import { AiPanel, AI_REVISION_AUTHOR } from './ai/AiPanel' import type { AiCommentsAccess, AiHeaderFooterAccess } from './ai/tools' @@ -137,6 +137,7 @@ import { LinkInsertModal, TableInsertModal, applyParagraphStyle, + clearParagraphFormatting, insertImageFromDataUrl, insertImageViaDialog, insertPageBreakAt, @@ -153,6 +154,10 @@ import { type ContextMenuState, } from './components/ContextMenu' import { PromptModal } from './components/PromptModal' +import { ShortcutsDialog } from './components/ShortcutsDialog' +import { WordCountDialog, type DocStats } from './components/WordCountDialog' +import { applyCase, nextCaseMode, selectionText } from './editor/case-transform' +import { stepHangingIndent, stepParagraphIndent } from './editor/indent' import { PasswordDialog } from './components/PasswordDialog' import { ProtectDialog, type ProtectDialogResult } from './components/ProtectDialog' import { t, useI18n } from './i18n/locale' @@ -190,6 +195,7 @@ import { type PendingNumbering, } from './doc-state' import { + applyAiDocContent as applyAiDocContentImpl, exportPdf as exportPdfImpl, loadFile as loadFileImpl, newFile as newFileImpl, @@ -223,7 +229,7 @@ import { type ReviewContext, } from './review-actions' -const _IS_MAC = navigator.platform.toLowerCase().includes('mac') +const IS_MAC = navigator.platform.toLowerCase().includes('mac') const twipsToPx = (twips: number) => (twips / 1440) * 96 @@ -346,18 +352,6 @@ function makeGapNotesEl( return wrap } -/** fields of Word's Word Count dialog */ -interface DocStats { - pages: number - words: number - asianChars: number - nonAsianWords: number - charsNoSpace: number - charsWithSpace: number - paragraphs: number - lines: number -} - const DEFAULT_SETTINGS: AiSettings = { provider: 'anthropic', providers: Object.fromEntries( @@ -373,7 +367,9 @@ export function App() { const { lang } = useI18n() const [doc, setDoc] = useState(null) /** true until the pending-open / new-blank boot checks settle; the start screen stays hidden meanwhile */ - const bootPendingRef = useRef | null>(null) + const bootPendingRef = useRef | null>( + null, + ) const bootHandledRef = useRef(false) /** password prompt for an ECMA-376 encrypted docx; submit retries via openDocxDecrypt */ const [docPwdPrompt, setDocPwdPrompt] = useState<{ @@ -583,7 +579,11 @@ export function App() { const [splitHtml, setSplitHtml] = useState('') const [showFind, setShowFind] = useState(false) const [findFocusReplace, setFindFocusReplace] = useState(0) - const ribbonActionsRef = useRef<{ stepFontSize?: (dir: 1 | -1) => void }>({}) + const [showShortcuts, setShowShortcuts] = useState(false) + const ribbonActionsRef = useRef<{ + stepFontSize?: (dir: 1 | -1) => void + nudgeFontSize?: (dir: 1 | -1) => void + }>({}) const [showComments, setShowComments] = useState(false) /** Style definitions pending write-back (key = styleId), saved via SaveOptions.styleUpserts */ const [styleUpserts, setStyleUpserts] = useState>({}) @@ -714,10 +714,36 @@ export function App() { const data = event.clipboardData if (!data) return false const html = data.getData('text/html') + // web-copied images (r139): "Copy image" in a browser puts a bitmap + + // an HTML fragment + often the URL as text/plain + // on the clipboard. Detect image-only HTML so the bitmap wins over + // text parsing, and so a bitmap-less copy can fetch the referenced + // image instead of pasting nothing (our parse rules are data:-only). + let htmlImgSrcs: string[] = [] + let htmlHasText = false + if (html) { + try { + const imgDom = new window.DOMParser().parseFromString(html, 'text/html') + htmlImgSrcs = [...imgDom.querySelectorAll('img')] + .map((img) => img.getAttribute('src') ?? '') + .filter(Boolean) + htmlHasText = (imgDom.body.textContent ?? '').trim().length > 0 + } catch { + /* unparseable html: treat as not-an-image copy */ + } + } + // remote-only: in-app data: copies carry data-image-meta and must keep + // going through the DocProtected parse rules (size/align/wrap round-trip + // — bugbot); only web copies divert to bitmap/fetch handling + const imageOnlyHtml = + htmlImgSrcs.length > 0 && + !htmlHasText && + htmlImgSrcs.every((src) => /^https?:\/\//i.test(src)) // pasting block HTML onto an empty paragraph: replace wholesale (ProseMirror's default // first-block merge would demote headings to body text; Word keeps the source block format on empty paragraphs) const { $from, empty: selEmpty } = view.state.selection if ( + !imageOnlyHtml && html && selEmpty && $from.parent.isTextblock && @@ -741,7 +767,9 @@ export function App() { .find((item) => item.type.startsWith('image/')) ?.getAsFile() const text = data.getData('text/plain') - if (imageFile && !text.trim()) { + // image-only copies keep the bitmap even when text/plain carries the + // source URL (browser "Copy image" does that) — Word pastes the picture + if (imageFile && (!text.trim() || imageOnlyHtml)) { const reader = new FileReader() reader.onload = () => { const ed = editorRef.current @@ -752,6 +780,25 @@ export function App() { reader.readAsDataURL(imageFile) return true } + // bitmap-less web image copy: fetch the referenced image(s) through the + // hardened main-process fetcher (SSRF-guarded, CDN headers) and insert + if (!imageFile && imageOnlyHtml) { + void (async () => { + for (const src of htmlImgSrcs.slice(0, 10)) { + const ed = editorRef.current + if (!ed) return + const fetched = await window.desktop.fetchImage(src) + if (fetched) { + await insertImageFromDataUrl( + ed, + `data:${fetched.mime};base64,${fetched.base64}`, + 'Image (pasted)', + ) + } + } + })() + return true + } // text/plain-only Markdown (code blocks, terminals, .md files, LLM // output): convert and insert as formatted content instead of literal // "## Heading" / "**bold**" characters @@ -1113,9 +1160,10 @@ export function App() { window.desktop.consumePendingOpenDocx(), // Still consume the one-shot new-blank flag so it doesn't leak into the next open window.desktop.consumeNewBlankDoc(), + window.desktop.consumeAiDocContent(), ]) void bootPendingRef.current - .then(async ([pending]) => { + .then(async ([pending, , aiContent]) => { if (bootHandledRef.current) return bootHandledRef.current = true // A failed open (corrupt file etc.) falls back to a blank document — @@ -1124,6 +1172,13 @@ export function App() { // 'password': the prompt is up; its cancel path lands on blank instead. const outcome = pending ? await loadFile(pending) : 'canceled' if (outcome === 'failed' || outcome === 'canceled') await newFile() + if (aiContent && !pending) { + // fileCtxRef refreshes per render: wait until newFile's setDoc landed + for (let i = 0; i < 100 && !fileCtxRef.current.doc; i++) { + await new Promise((resolve) => setTimeout(resolve, 20)) + } + await applyAiDocContentImpl(fileCtxRef.current, aiContent) + } }) // Open failures also land on a blank document, or the tab stays at "Opening…" forever .catch(() => { @@ -1771,7 +1826,8 @@ export function App() { const b = doc?.parsed.blocks.find((bl) => bl.docxIndex === docxIndex) if (!b) return undefined if (b.type === 'table') { - if (!b.originalXml || !/tblHeader|cantSplit/.test(b.originalXml)) return undefined + if (!b.originalXml || !/tblHeader|cantSplit|= 15 ? { modernTableHeaders: true } : {}), @@ -2911,6 +2967,19 @@ export function App() { }) }, [editor, zoom, pageInfo.total]) + // Review > Editor, the Tools menu and Word's F7 all run the same AI proofread + // behind the one-time whole-document-rewrite acknowledgement + const runAiProofread = useCallback(() => { + if ( + localStorage.getItem(AI_REWRITE_ACK_KEY) !== '1' && + !window.confirm(t('ribbonAiRewriteConfirm')) + ) + return + localStorage.setItem(AI_REWRITE_ACK_KEY, '1') + setShowAi(true) + setAiPreset({ text: t('ribbonEditorPrompt'), nonce: Date.now(), autoRun: true }) + }, []) + // "has unsaved changes" check shared by the close guard and autosave; refreshed on every // render (all edit paths forceRender), so the guard's query reads the latest value const anyDirtyRef = useRef(false) @@ -3098,10 +3167,128 @@ export function App() { e.preventDefault() ribbonActionsRef.current.stepFontSize?.(e.code === 'Period' ? 1 : -1) } + // Word's one-point nudge ⌘] / ⌘[ + if ( + (e.metaKey || e.ctrlKey) && + !e.shiftKey && + !e.altKey && + (e.code === 'BracketRight' || e.code === 'BracketLeft') && + editor && + canEdit + ) { + e.preventDefault() + ribbonActionsRef.current.nudgeFontSize?.(e.code === 'BracketRight' ? 1 : -1) + } + // Superscript / subscript. Word's own ⌘= / ⇧⌘= collide with the zoom + // accelerators for the "=" half only, so the unshifted pair is on ⌘. / ⌘, + // (the same keys the shifted grow/shrink pair uses). + const vertAlign = e.shiftKey + ? e.code === 'Equal' + ? 'superscript' + : null + : e.code === 'Period' + ? 'superscript' + : e.code === 'Comma' + ? 'subscript' + : null + if ((e.metaKey || e.ctrlKey) && !e.altKey && vertAlign && editor && canEdit) { + e.preventDefault() + const target = getActiveSubEditor() ?? editor + const current = target.getAttributes('docTextStyle').vertAlign + target + .chain() + .focus() + .setMark('docTextStyle', { vertAlign: current === vertAlign ? null : vertAlign }) + .run() + } + // Word's Shift+F3 case ring + if (e.shiftKey && e.key === 'F3' && editor && canEdit) { + e.preventDefault() + const target = getActiveSubEditor() ?? editor + applyCase(target, nextCaseMode(selectionText(target))) + } + // Clear character formatting ⌃␣ (Word uses Ctrl+Space on both platforms) + if (e.ctrlKey && !e.metaKey && !e.shiftKey && !e.altKey && e.code === 'Space' && canEdit) { + e.preventDefault() + ;(getActiveSubEditor() ?? editor)?.chain().focus().unsetAllMarks().run() + } + // Indent ⌃M / outdent ⌃⇧M and hanging indent ⌘T / ⇧⌘T. Ctrl-only on both + // platforms: ⌘M minimizes the window, and indenting a paragraph on the way + // out would be a silent edit. + if (e.ctrlKey && !e.metaKey && !e.altKey && e.code === 'KeyM' && editor && canEdit) { + e.preventDefault() + if (!getActiveSubEditor()) stepParagraphIndent(editor, e.shiftKey ? -1 : 1) + } + if ((e.metaKey || e.ctrlKey) && !e.altKey && e.code === 'KeyT' && editor && canEdit) { + e.preventDefault() + if (!getActiveSubEditor()) stepHangingIndent(editor, e.shiftKey ? -1 : 1) + } + // Clear paragraph formatting — Word's Ctrl+Q (⌘Q quits on macOS) + if (e.ctrlKey && !e.metaKey && !e.shiftKey && !e.altKey && e.code === 'KeyQ' && canEdit) { + e.preventDefault() + if (editor && !getActiveSubEditor()) clearParagraphFormatting(editor) + } + // Formatting marks: ⌘8 in Word for Mac, Ctrl+Shift+8 on Windows + if ((e.metaKey || e.ctrlKey) && !e.altKey && e.code === 'Digit8' && doc) { + e.preventDefault() + setShowMarks((v) => !v) + } + // Track changes ⇧⌘E; forced by an editing restriction it cannot be turned off + if ((e.metaKey || e.ctrlKey) && e.shiftKey && !e.altKey && e.code === 'KeyE' && doc) { + e.preventDefault() + if (!trackChangesForced) setTrackChanges((v) => !v) + } + // Word count ⇧⌘G + if ((e.metaKey || e.ctrlKey) && e.shiftKey && !e.altKey && e.code === 'KeyG' && doc) { + e.preventDefault() + openStats() + } + // New comment ⌥⌘A (Word for Mac; Windows Word's Ctrl+Alt+M stays on the + // Paragraph dialog here) + if ((e.metaKey || e.ctrlKey) && e.altKey && e.code === 'KeyA' && doc && canEdit) { + e.preventDefault() + setShowComments(true) + startNewComment() + } + // Footnote ⌥⌘F, endnote ⌥⌘E on the Mac / Ctrl+Alt+D on Windows. The + // endnote key is platform-exclusive: ⌥⌘D belongs to the macOS Dock. + if ((e.metaKey || e.ctrlKey) && e.altKey && doc && canEdit) { + const endnoteCode = IS_MAC ? 'KeyE' : 'KeyD' + const note = e.code === 'KeyF' ? 'footnote' : e.code === endnoteCode ? 'endnote' : null + if (note) { + e.preventDefault() + insertNote(note) + } + } + // Date / time fields ⌥⇧D / ⌥⇧T + if (e.altKey && e.shiftKey && !e.metaKey && !e.ctrlKey && doc && canEdit) { + const instr = e.code === 'KeyD' ? 'DATE' : e.code === 'KeyT' ? 'TIME' : null + if (instr) { + e.preventDefault() + insertField(instr) + } + } + // Proofread F7 (Word's spelling & grammar check) + if (e.key === 'F7' && !e.shiftKey && doc) { + e.preventDefault() + runAiProofread() + } } window.addEventListener('keydown', handler) return () => window.removeEventListener('keydown', handler) - }, [save, openFile, editor, doc, updateFields]) + }, [ + save, + openFile, + editor, + doc, + updateFields, + openStats, + startNewComment, + insertNote, + insertField, + runAiProofread, + trackChangesForced, + ]) // double-click an inline equation / click an equation block's edit button (ones with LaTeX source) → reopen the equation dialog for editing useEffect(() => { @@ -3195,18 +3382,10 @@ export function App() { if (doc) openStats() break case 'ai-proofread': - // Same flow as Review > Editor: one-time whole-document-rewrite ack, - // then auto-run the AI proofread preset - if (doc) { - if ( - localStorage.getItem(AI_REWRITE_ACK_KEY) === '1' || - window.confirm(t('ribbonAiRewriteConfirm')) - ) { - localStorage.setItem(AI_REWRITE_ACK_KEY, '1') - setShowAi(true) - setAiPreset({ text: t('ribbonEditorPrompt'), nonce: Date.now(), autoRun: true }) - } - } + if (doc) runAiProofread() + break + case 'shortcuts': + setShowShortcuts(true) break case 'bold': editor?.chain().focus().toggleMark('bold').run() @@ -3255,6 +3434,7 @@ export function App() { zoomFit, openStats, startNewComment, + runAiProofread, ]) // Word: TOC entries jump on ⌘/Ctrl+click only; a plain click just places the @@ -3672,9 +3852,43 @@ export function App() { const canvasBox = canvasSection ? sectionPageBox(canvasSection) : null const canvasTop = canvasSection ? effectiveTopPx(canvasSection, singleHfPx.headerPx) : 0 const canvasBottom = canvasSection ? effectiveBottomPx(canvasSection, singleHfPx.footerPx) : 0 + // the shared paper must cover the widest section or its content lays out past + // the paper edge onto the editor background (a white band down the right side) + const paperW = canvasBox + ? Math.max(canvasBox.width, ...sections.map((s) => twipsToPx(s.settings.pageWidth))) + : 0 + // the trailing footer strip belongs to the LAST page, which is always in the + // last section; on differing-width docs the stylesheet centering (50% of the + // first-section paper) puts it at the wrong x, so pin it to its own section + const lastSection = sections[sections.length - 1]?.settings ?? section + const lastBox = lastSection ? sectionPageBox(lastSection) : null + // pin whenever the shared paper is wider than the footer's own section (a wider + // middle section widens the paper too) or the strip width differs from the + // first-section default + const edgeFooterStyle = + lastBox && + canvasBox && + (paperW - lastBox.width > 0.5 || Math.abs(lastBox.contentWidth - canvasBox.contentWidth) > 0.5) + ? { + width: `${lastBox.contentWidth}px`, + left: `${twipsToPx(lastSection!.marginLeft)}px`, + transform: 'none', + bottom: `${lastBox.footerDist}px`, + } + : undefined + // symmetric pin for the leading header (it belongs to the first section): the + // widened shared paper would otherwise re-center it at the wrong x + const edgeHeaderStyle = + canvasBox && canvasSection && paperW - canvasBox.width > 0.5 + ? { + width: `${canvasBox.contentWidth}px`, + left: `${twipsToPx(canvasSection.marginLeft)}px`, + transform: 'none', + } + : undefined const docZoomStyle = { zoom: zoom / 100, - '--page-w': canvasBox ? `${canvasBox.width}px` : undefined, + '--page-w': canvasBox ? `${paperW}px` : undefined, '--page-h': canvasBox ? `${canvasBox.height}px` : undefined, '--section-content-w': canvasBox ? `${canvasBox.contentWidth}px` : undefined, '--page-pad': canvasSection @@ -3920,6 +4134,7 @@ export function App() { readOnly={isProtected || readMode} onCommit={(next) => commitHf('header', next)} pageTotal={pageInfo.total} + style={edgeHeaderStyle} /> )} @@ -3952,6 +4167,7 @@ export function App() { onCommit={(next) => commitHf('footer', next)} pageNo={lastPageNo?.text ?? pageInfo.total} pageTotal={pageInfo.total} + style={edgeFooterStyle} /> )} {(inkAnnotations.length > 0 || inkTool !== 'select') && !readMode && ( @@ -4071,6 +4287,7 @@ export function App() { + {showShortcuts && setShowShortcuts(false)} />} {showLinkModal && setShowLinkModal(false)} />} {showTableModal && ( setShowTableModal(false)} /> @@ -4190,57 +4407,7 @@ export function App() { {doc && showPrintDialog && } - {stats && ( -
e.target === e.currentTarget && setStats(null)} - > -
-

{t('appWordCountTitle')}

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
{t('appStatPages')}{stats.pages}
{t('appStatWords')}{stats.words}
{t('appStatAsianChars')}{stats.asianChars}
{t('appStatNonAsianWords')}{stats.nonAsianWords}
{t('appStatCharsNoSpaces')}{stats.charsNoSpace}
{t('appStatCharsWithSpaces')}{stats.charsWithSpace}
{t('appStatParagraphs')}{stats.paragraphs}
{t('appStatLines')}{stats.lines}
-
- -
-
-
- )} + {stats && setStats(null)} />} {docPwdPrompt && (