diff --git a/LICENSE-UNICODE.txt b/LICENSE-UNICODE.txt new file mode 100644 index 0000000..72d4460 --- /dev/null +++ b/LICENSE-UNICODE.txt @@ -0,0 +1,39 @@ +UNICODE LICENSE V3 + +COPYRIGHT AND PERMISSION NOTICE + +Copyright © 1991-2026 Unicode, Inc. + +NOTICE TO USER: Carefully read the following legal agreement. BY +DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR +SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE +TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT +DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of data files and any associated documentation (the "Data Files") or +software and any associated documentation (the "Software") to deal in +the Data Files or Software without restriction, including without +limitation the rights to use, copy, modify, merge, publish, distribute, +and/or sell copies of the Data Files or Software, and to permit persons +to whom the Data Files or Software are furnished to do so, provided that +either (a) this copyright and permission notice appear with all copies of +the Data Files or Software, or (b) this copyright and permission notice +appear in associated Documentation. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF +THIRD PARTY RIGHTS. + +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE +BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL +DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR +PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS +ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THE DATA FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder shall +not be used in advertising or otherwise to promote the sale, use or +other dealings in these Data Files or Software without prior written +authorization of the copyright holder. diff --git a/NOTICE b/NOTICE index dc4dcf7..5e3319f 100644 --- a/NOTICE +++ b/NOTICE @@ -12,3 +12,14 @@ checkout. Bundled fonts and their licenses are documented in apps/docs/src/renderer/fonts/README.md. + +Unicode Character Database + +apps/pdf/src/shared/radicals.ts contains a generated mapping derived from +Unicode Character Database 17.0.0, EquivalentUnifiedIdeograph.txt +(2025-08-01): +https://www.unicode.org/Public/17.0.0/ucd/EquivalentUnifiedIdeograph.txt + +Copyright © 1991-2026 Unicode, Inc. This data is distributed under Unicode +License v3. The complete copyright and permission notice is reproduced in +LICENSE-UNICODE.txt. diff --git a/README.md b/README.md index 18136e1..1815674 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,20 @@ # GenOffice -An AI-native office suite for macOS, Windows, and Linux: word processor, -spreadsheet, presentations, PDF, and Markdown — six Electron apps sharing one -engine layer, built around AI editing as a first-class workflow rather than a -bolted-on chat box. +**The world's first full-featured open-source AI Office suite.** + +[![License: Apache-2.0](https://img.shields.io/github/license/genspark-ai/genoffice)](LICENSE) +[![Latest release](https://img.shields.io/github/v/release/genspark-ai/genoffice)](https://github.com/genspark-ai/genoffice/releases/latest) +[![Downloads](https://img.shields.io/github/downloads/genspark-ai/genoffice/total)](https://github.com/genspark-ai/genoffice/releases) +[![GitHub stars](https://img.shields.io/github/stars/genspark-ai/genoffice?style=flat)](https://github.com/genspark-ai/genoffice/stargazers) +![Platforms: macOS | Windows | Linux](https://img.shields.io/badge/platform-macOS%20%7C%20Windows%20%7C%20Linux-lightgrey) + +GenOffice is a free, open-source alternative to Microsoft Office for macOS, +Windows, and Linux, built around AI editing as a first-class workflow rather +than a bolted-on chat box. It opens and saves the real Microsoft Office +formats — Word (`.docx`), Excel (`.xlsx`), PowerPoint (`.pptx`) — and edits +PDF and Markdown too: a word processor, spreadsheet, presentation editor, +PDF editor, and Markdown editor as six Electron apps sharing one engine +layer. [![Meet GenOffice — the world's first full-featured open-source AI Office (video)](https://img.youtube.com/vi/B2pLdMX95v4/maxresdefault.jpg)](https://www.youtube.com/watch?v=B2pLdMX95v4) @@ -12,10 +23,10 @@ bolted-on chat box. ## Features - **Real PDF editing** — retype text and edit images in the page itself, original fonts preserved. -- **Byte-preserving `.docx` editing** — only what you touched changes; Word never notices. +- **Microsoft Word–compatible, byte-preserving `.docx` editing** — only what you touched changes; Word never notices. - **Word-faithful pagination** — page breaks land where Word puts them. -- **In-house spreadsheet engine** — Rust `.xlsx` sidecar, own charts, pivot tables, slicers. -- **In-house `.pptx` engine** — masters, layouts, smart guides, non-destructive crop. +- **Excel-compatible spreadsheets** — in-house engine with a Rust `.xlsx` sidecar, own charts, pivot tables, slicers. +- **PowerPoint-compatible presentations** — in-house `.pptx` engine with masters, layouts, smart guides, non-destructive crop. - **Markdown to Word, fully local** — the same OOXML engine, no Pandoc, no cloud. - **AI that edits documents** — block-level edits with snapshots and diffs, document-aware agents. - **Agent tools built in** — web/image search, image generation, media analysis. @@ -25,12 +36,14 @@ bolted-on chat box. ## Download -| Platform | Requirements | Download | -| ------------------------------- | ------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | -| **macOS** (Apple Silicon) | macOS 11+ | [GenOffice-0.6.13-arm64.dmg](https://github.com/genspark-ai/genoffice/releases/download/v0.6.13/GenOffice-0.6.13-arm64.dmg) | -| **Windows** (x64) | Windows 10+ | [GenOfficeSetup-v0.6.13.exe](https://github.com/genspark-ai/genoffice/releases/download/v0.6.13/GenOfficeSetup-v0.6.13.exe) | -| **Linux** — Debian / Ubuntu | x86_64, glibc 2.34+ (Ubuntu 22.04 or newer) | [genoffice_0.6.13_amd64.deb](https://github.com/genspark-ai/genoffice/releases/download/v0.6.13/genoffice_0.6.13_amd64.deb) | -| **Linux** — other distributions | x86_64, glibc 2.34+, FUSE 2 | [GenOffice-0.6.13.AppImage](https://github.com/genspark-ai/genoffice/releases/download/v0.6.13/GenOffice-0.6.13.AppImage) | +| Platform | Requirements | Download | +| ------------------------------------ | ----------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | +| **macOS** — Apple Silicon (arm64) | macOS 11+ | [GenOffice-0.6.101-arm64.dmg](https://github.com/genspark-ai/genoffice/releases/download/v0.6.101/GenOffice-0.6.101-arm64.dmg) | +| **macOS** — Intel (x64) | macOS 11+ | [GenOffice-0.6.101.dmg](https://github.com/genspark-ai/genoffice/releases/download/v0.6.101/GenOffice-0.6.101.dmg) | +| **Windows** (x64) | Windows 10+ | [GenOfficeSetup-v0.6.101.exe](https://github.com/genspark-ai/genoffice/releases/download/v0.6.101/GenOfficeSetup-v0.6.101.exe) | +| **Linux** — Debian / Ubuntu | x86_64, glibc 2.34+ (Ubuntu 22.04 or newer) | [genoffice_0.6.101_amd64.deb](https://github.com/genspark-ai/genoffice/releases/download/v0.6.101/genoffice_0.6.101_amd64.deb) | +| **Linux** — Fedora / RHEL / openSUSE | x86_64, glibc 2.34+ (Fedora 35+, RHEL 9+, Leap 15.6+) | [genoffice-0.6.101.x86_64.rpm](https://github.com/genspark-ai/genoffice/releases/download/v0.6.101/genoffice-0.6.101.x86_64.rpm) | +| **Linux** — other distributions | x86_64, glibc 2.34+, FUSE 2 | [GenOffice-0.6.101.AppImage](https://github.com/genspark-ai/genoffice/releases/download/v0.6.101/GenOffice-0.6.101.AppImage) | All builds come from `main`; the macOS and Windows installers are signed. Older versions are on the [Releases](https://github.com/genspark-ai/genoffice/releases) page. @@ -41,7 +54,14 @@ The deb installs with apt — it pulls in the dependencies and adds GenOffice to the applications menu: ```bash -sudo apt install ./genoffice_0.6.13_amd64.deb +sudo apt install ./genoffice_0.6.101_amd64.deb +``` + +On Fedora / RHEL-family / openSUSE, install the rpm instead: + +```bash +sudo dnf install ./genoffice-0.6.101.x86_64.rpm # Fedora / RHEL family +sudo zypper install ./genoffice-0.6.101.x86_64.rpm # openSUSE ``` The AppImage instead runs in place: install the FUSE 2 runtime @@ -49,8 +69,8 @@ The AppImage instead runs in place: install the FUSE 2 runtime make the file executable, then run it: ```bash -chmod +x GenOffice-0.6.13.AppImage -./GenOffice-0.6.13.AppImage +chmod +x GenOffice-0.6.101.AppImage +./GenOffice-0.6.101.AppImage ``` ## Apps @@ -111,7 +131,7 @@ npm run dev # all five editors + shell against Vite dev servers npm run dev:docs # a single app (same pattern works per workspace) npm run dist:mac # package macOS dmg (regenerates third-party notices) npm run dist:win # package Windows nsis installer -npm run dist:linux # package Linux AppImage + deb +npm run dist:linux # package Linux AppImage + deb + rpm ``` The sheets app additionally needs a Rust toolchain for its xlsx sidecar @@ -137,6 +157,26 @@ The same philosophy holds in sheets and slides: the original file is the source of truth, edits are applied as narrow patches, and everything the editor didn't touch survives the round trip untouched. +## FAQ + +**Is GenOffice free?** +Yes. GenOffice is free and open-source under the Apache-2.0 license — no +trial, no paid tier for the apps themselves. + +**Can GenOffice open Microsoft Word, Excel, and PowerPoint files?** +Yes. GenOffice opens and saves native `.docx`, `.xlsx`, and `.pptx` files. +Saving is byte-preserving: parts of the file you didn't touch are written +back byte-for-byte, so documents keep working in Microsoft Office. + +**Does GenOffice work offline?** +Document editing is fully local — files never leave your machine to be +opened, edited, or saved. The AI features (agents, search, image tools) sign +in to a Genspark account and need a network connection. + +**Can GenOffice edit PDF files?** +Yes — real PDF text and image editing that rewrites the page content stream +with the original fonts preserved, not cover-up annotations. + ## Security See [SECURITY.md](SECURITY.md) for the process security posture (renderer diff --git a/apps/docs/electron.vite.config.ts b/apps/docs/electron.vite.config.ts index c18419c..925d159 100644 --- a/apps/docs/electron.vite.config.ts +++ b/apps/docs/electron.vite.config.ts @@ -1,6 +1,14 @@ +import { resolve } from 'node:path' import react from '@vitejs/plugin-react' import { defineConfig, externalizeDepsPlugin } from 'electron-vite' +// Resolve workspace packages from this checkout's sources: in a git worktree +// node_modules is a symlink into the main checkout, so bare specifiers would +// silently bundle the other checkout's (possibly stale) code. +const localAlias = { + '@genoffice/docx-engine': resolve(__dirname, '../../packages/docx-engine/src/index.ts'), +} + export default defineConfig({ // Main and preload use only electron + node builtins; bundle everything so // the packaged app doesn't rely on node_modules at runtime. @@ -9,10 +17,12 @@ export default defineConfig({ // (same setup as apps/slides). main: { plugins: [externalizeDepsPlugin({ exclude: ['@genoffice/electron-utils'] })], + resolve: { alias: localAlias }, }, preload: {}, renderer: { plugins: [react()], + resolve: { alias: localAlias }, server: { // Overridable so multiple genoffice dev instances can coexist (default 5173). port: Number(process.env.DOCS_DEV_PORT) || 5173, diff --git a/apps/docs/package.json b/apps/docs/package.json index a0976b0..3eb2ff3 100644 --- a/apps/docs/package.json +++ b/apps/docs/package.json @@ -38,6 +38,7 @@ "electron-builder": "^26.0.12", "electron-vite": "^5.0.0", "jsdom": "^28.0.0", + "marked": "^17.0.6", "opentype.js": "^2.0.0", "react": "^19.2.4", "react-dom": "^19.2.4", diff --git a/apps/docs/src/main/docs-main.ts b/apps/docs/src/main/docs-main.ts index 7cf5afb..3dd8c85 100644 --- a/apps/docs/src/main/docs-main.ts +++ b/apps/docs/src/main/docs-main.ts @@ -13,6 +13,7 @@ import { basename, join } from 'node:path' import { BrowserWindow, Menu, WebContentsView, app, dialog, ipcMain, shell } from 'electron' import { appMenuLabels, + configuredDefaultSaveDir, contextMenuLabels, fetchRemoteImage, installContextMenu, @@ -20,6 +21,7 @@ import { safeExternalUrl, showOpenDialogWithMemory, showSaveDialogWithMemory, + toggleDevToolsItem, windowMenuTemplate, } from '@genoffice/electron-utils' import { createI18n, getUiLang, normalizeLang, setUiLang } from '@genoffice/i18n' @@ -1944,14 +1946,14 @@ async function openDialog(event: IpcMainInvokeEvent, options: OpenDialogOptions) } async function saveDialog(event: IpcMainInvokeEvent, options: SaveDialogOptions) { - return showSaveDialogWithMemory(dialog, dialogParent(event), options) + // before any pick is remembered, bare-name suggestions anchor in the + // configurable default save folder instead of Electron's Downloads pin + return showSaveDialogWithMemory(dialog, dialogParent(event), options, defaultSaveDir()) } -/** default folder where new files land on their first (silent) save; shared with the other editors via shell */ +/** default folder where new files land on their first (silent) save; shared with the other editors via shell. User-configurable (app-settings.json), falls back to /GenOffice. */ export function defaultSaveDir(): string { - const dir = join(app.getPath('documents'), 'GenOffice') - mkdirSync(dir, { recursive: true }) - return dir + return configuredDefaultSaveDir(app) } /** first free path for fileName inside dir: name.ext, name-2.ext, name-3.ext… */ @@ -3420,7 +3422,7 @@ export function buildDocsMenu(): void { }, { type: 'separator' }, { role: 'togglefullscreen', label: tm('menuFullscreen') }, - ...(isDev ? [{ role: 'toggleDevTools' as const }] : []), + ...(isDev ? [toggleDevToolsItem(appMenuLabels(getUiLang()))] : []), ], }, { diff --git a/apps/docs/src/renderer/App.tsx b/apps/docs/src/renderer/App.tsx index 9c15c03..f660129 100644 --- a/apps/docs/src/renderer/App.tsx +++ b/apps/docs/src/renderer/App.tsx @@ -3,6 +3,7 @@ import type { CSSProperties, MouseEvent as ReactMouseEvent } from 'react' import { EditorContent, useEditor } from '@tiptap/react' import type { Editor } from '@tiptap/core' import { DOMParser as PmDOMParser, type Mark as PmMark } from '@tiptap/pm/model' +import { markdownPasteHtml } from './editor/markdown-paste' import { BLANK_BULLET_NUM_ID, BLANK_ORDERED_NUM_ID, @@ -39,6 +40,7 @@ import { liveSections, nextLineAnchor, measureBlocks, + docGridPitchPt, type LineAnchor, pageNumbers, sliceWithLineSplit, @@ -205,6 +207,24 @@ function cleanPastedHtml(html: string): string { .replace(/]*)>\s*]*>([\s\S]*?)<\/p>\s*<\/li>/g, '$2') } +/** All runs a footnote/endnote reference may live in: paragraph runs, plus table + * cell paragraphs (incl. nested tables) — refs inside cells still print their + * note at the page bottom like Word */ +function blockNoteScanRuns(b: Block): NonNullable { + const out: NonNullable = [] + if (b.runs) out.push(...b.runs) + const walkTable = (table: NonNullable | undefined): void => { + for (const row of table?.rows ?? []) { + for (const cell of row) { + for (const p of cell.richParas ?? []) out.push(...p.runs) + for (const nested of cell.nestedTables ?? []) walkTable(nested) + } + } + } + if (b.table) walkTable(b.table) + return out +} + /** Footnote area at the top of a page gap (previous page's bottom): absolutely positioned in the content area, double-click an entry to edit */ function makeGapNotesEl( items: PageNoteItem[], @@ -596,6 +616,45 @@ export function App() { reader.readAsDataURL(imageFile) 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 + if (!html && text) { + const markdownHtml = markdownPasteHtml(text) + if (markdownHtml !== null) { + try { + // cleanPastedHtml unwraps
  • …

  • from loose lists — + // docListItem only allows inline content and would shatter them. + const dom = new window.DOMParser().parseFromString( + cleanPastedHtml(markdownHtml), + 'text/html', + ) + const parser = PmDOMParser.fromSchema(view.state.schema) + if ( + selEmpty && + $from.parent.isTextblock && + $from.parent.content.size === 0 && + $from.depth === 1 + ) { + // same wholesale replace as block HTML onto an empty paragraph + const parsed = parser.parse(dom.body) + if (parsed.content.childCount > 0) { + view.dispatch( + view.state.tr.replaceWith($from.before(1), $from.after(1), parsed.content), + ) + return true + } + } else { + view.dispatch( + view.state.tr.replaceSelection(parser.parseSlice(dom.body)).scrollIntoView(), + ) + return true + } + } catch { + /* fall back to default literal paste on parse failure */ + } + } + } return false }, }, @@ -1330,9 +1389,10 @@ export function App() { // page-bottom height (px) reserved for footnote references inside a block: same estimation model as the parity runner const footnoteExtraOf = useCallback( (b: Block): number => { - if (!b.runs || footnotes.length === 0) return 0 + const runs = blockNoteScanRuns(b) + if (runs.length === 0 || footnotes.length === 0) return 0 let extra = 0 - for (const run of b.runs) { + for (const run of runs) { if (run.noteRef?.kind !== 'footnote') continue const sec = sections.find((s) => (b.docxIndex ?? 0) <= s.lastBlockIndex)?.settings ?? section @@ -1346,6 +1406,9 @@ export function App() { [footnotes, sections, section], ) + // typed w:docGrid line pitch (pt) when every section shares one; null = no snapping + const gridPitchPt = useMemo(() => docGridPitchPt(sections), [sections]) + // single-section header/footer push-down: body top = max(marginTop, headerDist + header height) const singleHfPx = useMemo(() => { if (!section) return { headerPx: 0, footerPx: 0 } @@ -1427,8 +1490,10 @@ export function App() { for (const b of blocks) { if (b.docxIndex === undefined) continue const pb = doc.parsed.blocks.find((bl) => bl.docxIndex === b.docxIndex) - if (!pb?.runs) continue - const ids = pb.runs.filter((r) => r.noteRef?.kind === 'footnote').map((r) => r.noteRef!.id) + if (!pb) continue + const ids = blockNoteScanRuns(pb) + .filter((r) => r.noteRef?.kind === 'footnote') + .map((r) => r.noteRef!.id) if (ids.length === 0) continue const page = pageAt(slices, b.top + 0.5) - 1 const sec = sections.find((s) => b.docxIndex! <= s.lastBlockIndex)?.settings ?? section @@ -2666,6 +2731,14 @@ export function App() { {doc && liveDocCjk != null && ( )} + {doc && gridPitchPt != null && ( + // typed w:docGrid: line-height round(up) expressions snap to this pitch + + )} + {doc && section && ( + // over-wide tables may spill into the right margin (Word/LO), capped at the paper edge + + )} {/* Theme CSS comes from live state, so a Design ▸ Themes/Fonts/Colors pick shows on the page immediately instead of only in the saved file */} {doc && } @@ -3118,6 +3191,9 @@ export function App() { pageFootnotesOf={pageFootnotesOf} endnoteItems={endnoteItems} sectionHfOverride={sectionHfOverride} + clearPageGaps={() => { + if (editor) setPageGaps(editor.view, []) + }} onExportPdf={() => void exportPdf()} onClose={() => setShowPagePreview(false)} /> diff --git a/apps/docs/src/renderer/ai/AiPanel.tsx b/apps/docs/src/renderer/ai/AiPanel.tsx index a117445..bc61822 100644 --- a/apps/docs/src/renderer/ai/AiPanel.tsx +++ b/apps/docs/src/renderer/ai/AiPanel.tsx @@ -29,13 +29,7 @@ import fileVideoIcon from '../assets/file-video.png' import fileVoiceIcon from '../assets/file-voice.png' import fileDocumentIcon from '../assets/file-document.png' import fileGeneralIcon from '../assets/file-general.png' -import { IconClock, IconNewChat, IconSidebarCollapse } from '../components/icons' - -interface Snapshot { - label: string - time: string - json: PmNode -} +import { IconNewChat, IconSidebarCollapse } from '../components/icons' interface ToolActivity { name: string @@ -75,6 +69,10 @@ interface ChatEntry { loginRequired?: boolean /** tool executions performed during this assistant turn */ tools?: ToolActivity[] + /** document state before this turn's first edit — rendered as an inline roll-back action */ + snapshot?: PmNode + /** attachments consumed from the composer by this user message (read-only echo chips) */ + attachments?: AttachmentMeta[] } /** clickable starter prompts for the empty state (fill the input, do not send) — @@ -199,6 +197,44 @@ function formatAttachmentSize(bytes: number): string { : `${(bytes / 1024).toFixed(2)} KB` } +/** Read-only echo of the attachments a user message consumed from the composer + * (image previews when the file is still readable; otherwise the placeholder icon) */ +function SentAttachments({ + atts, + previews, +}: { + atts: AttachmentMeta[] + previews: Record +}) { + return ( +
    + {atts.map((a) => + ATTACHMENT_IMAGE_EXTS.has(a.ext) ? ( + + {previews[a.path] ? ( + {a.name} + ) : ( + + + + )} + + ) : ( + + + + + + {truncateCardName(a.name)} + {formatAttachmentSize(a.sizeBytes)} + + + ), + )} +
    + ) +} + /** author name on AI-generated tracked revisions (accept/reject via Review) */ export const AI_REVISION_AUTHOR = 'AI Assistant' @@ -240,7 +276,8 @@ export function AiPanel({ /** Wall-clock start of the current run, drives the elapsed badge */ const runStartedAtRef = useRef(0) const [chat, setChat] = useState([]) - const [snapshots, setSnapshots] = useState([]) + /** Past conversation restored from JSONL (read-only transcript, not fed to the model) */ + const [historicChat, setHistoricChat] = useState([]) const [trackChanges, setTrackChanges] = useState( () => localStorage.getItem(TRACK_CHANGES_KEY) === '1', ) @@ -251,8 +288,19 @@ export function AiPanel({ const [attachmentPreviews, setAttachmentPreviews] = useState>({}) /** image paths with a read already issued — one readAttachmentImage per attach, even while pending */ const previewRequestedRef = useRef(new Set()) + /** Attachments consumed by earlier sends this session: sending clears the composer, but the + files skill must keep reading them mid-run and in follow-up turns. Deduped by path + against the live composer list. */ + const sentAttachmentsRef = useRef([]) useEffect(() => { - const alive = new Set(attachments.map((a) => a.path)) + // previews cover the composer plus every image echoed on a sent/history message + // (history chips re-read the file by its stored path; a deleted file keeps the placeholder) + const wanted = [ + ...attachments, + ...chat.flatMap((e) => e.attachments ?? []), + ...historicChat.flatMap((e) => e.attachments ?? []), + ] + const alive = new Set(wanted.map((a) => a.path)) // drop previews (and request markers) of removed attachments, so memory is reclaimed and a re-attach re-reads setAttachmentPreviews((prev) => { const stale = Object.keys(prev).filter((p) => !alive.has(p)) @@ -264,7 +312,7 @@ export function AiPanel({ for (const p of previewRequestedRef.current) { if (!alive.has(p)) previewRequestedRef.current.delete(p) } - for (const a of attachments) { + for (const a of wanted) { if (!ATTACHMENT_IMAGE_EXTS.has(a.ext) || previewRequestedRef.current.has(a.path)) continue previewRequestedRef.current.add(a.path) void window.desktop.readAttachmentImage(a.path).then((r) => { @@ -277,7 +325,7 @@ export function AiPanel({ } }) } - }, [attachments]) + }, [attachments, chat, historicChat]) /** paints the strip's scrollbar thumb while the user scrolls it (cleared 800ms after the last event) */ const attachScrollFadeRef = useRef(0) const onAttachmentsScroll = (e: React.UIEvent): void => { @@ -305,8 +353,6 @@ export function AiPanel({ window.addEventListener('resize', onResize) return () => window.removeEventListener('resize', onResize) }, []) - /** Past conversation restored from JSONL (read-only transcript, not fed to the model) */ - const [historicChat, setHistoricChat] = useState([]) // bumped on selection/doc changes so the scope hint & quick actions stay fresh const [, setScopeTick] = useState(0) const logRef = useRef(null) @@ -327,6 +373,15 @@ export function AiPanel({ numIdFallbackRef.current = numIdFallback const attachmentsRef = useRef(attachments) attachmentsRef.current = attachments + /** attachments consumed by the most recent send — retry resends the same set */ + const lastAttachmentsRef = useRef([]) + /** composer attachments plus everything already sent this session (deduped by path) */ + const availableAttachments = (): AttachmentMeta[] => { + const seen = new Set() + return [...sentAttachmentsRef.current, ...attachmentsRef.current].filter((a) => + seen.has(a.path) ? false : (seen.add(a.path), true), + ) + } const trackChangesRef = useRef(trackChanges) trackChangesRef.current = trackChanges @@ -348,8 +403,11 @@ export function AiPanel({ markDocSeen(editorRef.current) } } - /** instruction of the in-flight run, labels its rollback snapshot */ + /** instruction of the in-flight run */ const instructionRef = useRef('') + /** document state before the run's first edit — attached to the turn's final + segment at run end (mid-turn segments never show the action toolbar) */ + const runSnapshotRef = useRef(null) /** last sent instruction, for one-click retry */ const lastInstructionRef = useRef('') /** Tool activity of the whole run (with args/output, accumulated across turns) — for full @@ -381,6 +439,15 @@ export function AiPanel({ isError: t.isError, output: t.output ? t.output.slice(0, TOOL_OUTPUT_MAX_CHARS) : undefined, })), + // stored metadata only: no thumbnail read for history, the chips render name/size + attachments: m.attachments + ?.filter((a) => a.path) + .map((a) => ({ + name: a.name, + path: a.path ?? '', + ext: a.ext ?? '', + sizeBytes: a.sizeBytes ?? 0, + })), })), ) // restore model context: follow-ups after reopening a file continue the previous conversation (only when the loop is idle with no history) @@ -473,7 +540,7 @@ export function AiPanel({ numIds, () => (trackChangesRef.current ? { author: AI_REVISION_AUTHOR } : undefined), ), - createFilesSkill(() => attachmentsRef.current), + createFilesSkill(availableAttachments), ]), captureSnapshot: () => editorRef.current.getJSON() as PmNode, events: { @@ -488,18 +555,8 @@ export function AiPanel({ })) }, onToolExecuted: ({ call, execution, snapshotBefore }) => { - if (snapshotBefore) { - setSnapshots((prev) => - [ - { - label: instructionRef.current.slice(0, 40), - time: new Date().toLocaleTimeString(), - json: snapshotBefore, - }, - ...prev, - ].slice(0, 20), - ) - } + // The run's first pre-edit state wins so one roll-back undoes the whole run + if (snapshotBefore && !runSnapshotRef.current) runSnapshotRef.current = snapshotBefore if (execution.mutated) { // tracking off: accept immediately (same tick, so the yellow never paints); // tracking on: revisions stay pending, handled in the Review tab @@ -551,6 +608,7 @@ export function AiPanel({ text: finalText || (last.tools?.length ? last.text : tModule('aiNoReply')), // A stop mid-tool can leave a running placeholder behind — drop it tools: last.tools?.filter((tl) => !tl.running), + snapshot: runSnapshotRef.current ?? undefined, })) setBusy(false) // App listens: a run that generated content into a never-saved document @@ -580,6 +638,7 @@ export function AiPanel({ streaming: false, error, tools: last.tools?.filter((tl) => !tl.running), + snapshot: runSnapshotRef.current ?? undefined, } } return next @@ -645,8 +704,8 @@ export function AiPanel({ /** Image attachments are read as base64 and go multimodal with this user message (≤5MB per image, max 20) */ const MAX_IMAGES_PER_MESSAGE = 20 - const collectImageAttachments = async (): Promise => { - const imageAtts = attachmentsRef.current.filter((a) => ATTACHMENT_IMAGE_EXTS.has(a.ext)) + const collectImageAttachments = async (atts: AttachmentMeta[]): Promise => { + const imageAtts = atts.filter((a) => ATTACHMENT_IMAGE_EXTS.has(a.ext)) const images: AgentImage[] = [] const failures: string[] = [] for (const att of imageAtts.slice(0, MAX_IMAGES_PER_MESSAGE)) { @@ -667,24 +726,45 @@ export function AiPanel({ return images } - const runWith = (instruction: string, displayInstruction = instruction) => { + const runWith = ( + instruction: string, + displayInstruction = instruction, + attachmentsOverride?: AttachmentMeta[], + ) => { const loop = loopRef.current if (!instruction || !loop || loop.busy) return setInput('') + // The message consumes the composer attachments: they ride along (echoed on the + // bubble, images multimodal, files via the files skill) and the composer clears. + const sentAtts = attachmentsOverride ?? attachmentsRef.current + if (!attachmentsOverride && sentAtts.length > 0) { + const seen = new Set(sentAttachmentsRef.current.map((a) => a.path)) + sentAttachmentsRef.current = [ + ...sentAttachmentsRef.current, + ...sentAtts.filter((a) => !seen.has(a.path)), + ] + setAttachments([]) + } + lastAttachmentsRef.current = sentAtts instructionRef.current = instruction lastInstructionRef.current = instruction runToolsRef.current = [] + runSnapshotRef.current = null stickToBottomRef.current = true setChat((prev) => [ ...prev, - { role: 'user', text: displayInstruction }, + { + role: 'user', + text: displayInstruction, + ...(sentAtts.length > 0 ? { attachments: sentAtts } : {}), + }, { role: 'assistant', text: '', streaming: true }, ]) runStartedAtRef.current = Date.now() setBusy(true) - persistMessage('user', instruction, undefined, attachmentsRef.current) + persistMessage('user', instruction, undefined, sentAtts) // a rejected image read must not strand the run (busy would stay true forever): degrade to a no-image send - void collectImageAttachments() + void collectImageAttachments(sentAtts) .catch((): AgentImage[] => { setAttachNotice(t('aiImagesSendFailed')) window.setTimeout(() => setAttachNotice(null), 5000) @@ -695,7 +775,8 @@ export function AiPanel({ const cancel = () => loopRef.current?.cancel() - const retry = () => runWith(lastInstructionRef.current) + const retry = () => + runWith(lastInstructionRef.current, lastInstructionRef.current, lastAttachmentsRef.current) const continueRun = () => runWith(DOCS_CONTINUE_INSTRUCTION, t('aiContinue')) @@ -703,6 +784,7 @@ export function AiPanel({ loopRef.current?.reset() setBusy(false) setChat([]) + sentAttachmentsRef.current = [] inputRef.current?.focus() } @@ -769,9 +851,13 @@ export function AiPanel({ if (!next) acceptChanges() } - const rollback = (snapshot: Snapshot) => { - editor.commands.setContent(snapshot.json as never) - setSnapshots((prev) => prev.filter((s) => s !== snapshot)) + const rollback = (entryIdx: number, snapshot: PmNode) => { + editor.commands.setContent(snapshot as never) + // The document rewound to before this turn, so this and every later + // rollback point now describe discarded futures + setChat((prev) => + prev.map((e, i) => (i >= entryIdx && e.snapshot ? { ...e, snapshot: undefined } : e)), + ) } const resizeCleanupRef = useRef<(() => void) | null>(null) @@ -871,6 +957,9 @@ export function AiPanel({ <> {historicChat.map((entry, i) => (
    + {entry.role === 'user' && entry.attachments && entry.attachments.length > 0 && ( + + )} {entry.tools && entry.tools.length > 0 && } {entry.text && }
    @@ -923,12 +1012,16 @@ export function AiPanel({ entry.role === 'assistant' && !entry.streaming && turnEnded && - !!(entry.text || entry.error) + // edits-only turns have no text but still carry the rollback point + !!(entry.text || entry.error || entry.snapshot) return (
    + {entry.role === 'user' && entry.attachments && entry.attachments.length > 0 && ( + + )} {entry.role === 'assistant' && !entry.text && entry.streaming ? ( - {/* IconRefresh glyph, restated for this 20px slot: the button CSS - stretches svgs to 20px, and the shared icon's 12px-pinned stroke - painted ~1.8px here — 1 canvas unit paints 1.25px, matching IconCopy */} + {/* 24-canvas glyph at 18px (near-full-bleed paths, sized for optical + parity with the copy icon): stroke 1.5 paints 1.125px (1:16) */} - - + + + + )} + {entry.snapshot && ( + <> + {/* hairline between reply actions (icons) and the document action (icon+label); + CSS shows it only when an icon button actually precedes it */} + + rollback(i, entry.snapshot!)} + /> + + )}
    )} {entry.turnLimit && isLast && !busy && ( @@ -1022,26 +1126,6 @@ export function AiPanel({ })} - {snapshots.length > 0 && ( -
    -
    - - {t('aiSnapshotsTitle')} -
    - {snapshots.map((s, i) => ( -
    - - {s.time} - {s.label} - - -
    - ))} -
    - )} -
    {attachNotice &&
    {attachNotice}
    } void }) { + const { t: tr } = useI18n() + return ( + + ) +} + /** Tool activity group: a single quiet summary row * that auto-opens while tools run, auto-collapses into "Worked · N steps" when they finish, * and a manual toggle that always wins. Rows inside are step rows with 1px connectors. */ diff --git a/apps/docs/src/renderer/ai/commands.ts b/apps/docs/src/renderer/ai/commands.ts index b6a002f..b87bdf3 100644 --- a/apps/docs/src/renderer/ai/commands.ts +++ b/apps/docs/src/renderer/ai/commands.ts @@ -598,6 +598,10 @@ function runSetHeadingLevel( } function runReplaceAllText(tr: Transaction, schema: Schema, cmd: ReplaceAllText): CommandResult { + // an empty needle would match at every offset without ever advancing the scan below + if (!cmd.containsText) { + return { command: 'replaceAllText', matched: 0, changed: 0, skippedProtected: 0 } + } const matchCase = cmd.matchCase !== false const needle = matchCase ? cmd.containsText : cmd.containsText.toLowerCase() const blocks = topLevelBlocks(tr.doc) diff --git a/apps/docs/src/renderer/components/ContextMenu.tsx b/apps/docs/src/renderer/components/ContextMenu.tsx index ca48d7a..3e6d4a3 100644 --- a/apps/docs/src/renderer/components/ContextMenu.tsx +++ b/apps/docs/src/renderer/components/ContextMenu.tsx @@ -1,5 +1,6 @@ import { useEffect, useRef, useState } from 'react' import type { Editor } from '@tiptap/core' +import { platformShortcuts } from '@genoffice/i18n' import { useI18n, type StringKey } from '../i18n/locale' import { fontFamiliesFor, isEastAsianFontName } from '../font-list' import { cssFontFamily } from '../line-metrics' @@ -187,7 +188,7 @@ export function EditorContextMenu({ )} - {opts.key && {opts.key}} + {opts.key && {platformShortcuts(opts.key)}} {opts.submenuKey && ›} ) diff --git a/apps/docs/src/renderer/components/PaginationPreview.tsx b/apps/docs/src/renderer/components/PaginationPreview.tsx index e523b64..94ed7f8 100644 --- a/apps/docs/src/renderer/components/PaginationPreview.tsx +++ b/apps/docs/src/renderer/components/PaginationPreview.tsx @@ -56,7 +56,27 @@ const CLONE_PRUNE_BUDGET = 150_000 /** window slack around a page (px): keeps neighbours whose floats/overflow bleed into the page */ const CLONE_PRUNE_PAD = 2000 -/** pruned clone for one page window: blocks intersecting [from-pad, to+pad] verbatim, pruned runs as spacers (exported for tests) */ +/** + * Canvas block → clone HTML. Phantom table rows (page-gap / repeated-header + * widgets) are removed and rowspans restored to their source values + * (data-base-rowspan): the canvas grows rowspans to bridge the phantom rows, + * but the clone hides/drops them, so the grown spans would swallow real rows. + */ +function cloneBlockHtml(el: HTMLElement): string { + if (!el.querySelector('tr.page-gap, tr.page-repeat-header, [data-base-rowspan]')) { + return el.outerHTML + } + const tmp = el.cloneNode(true) as HTMLElement + for (const tr of Array.from(tmp.querySelectorAll('tr.page-gap, tr.page-repeat-header'))) { + tr.remove() + } + for (const td of Array.from(tmp.querySelectorAll('[data-base-rowspan]'))) { + td.setAttribute('rowspan', td.getAttribute('data-base-rowspan')!) + } + return tmp.outerHTML +} + +/** pruned clone for one page window: blocks intersecting [from-pad, to+pad] verbatim, pruned runs as spacers */ export function prunedCloneHtml(kids: CloneChild[], from: number, to: number): string { const lo = from - CLONE_PRUNE_PAD const hi = to + CLONE_PRUNE_PAD @@ -80,9 +100,9 @@ export function prunedCloneHtml(kids: CloneChild[], from: number, to: number): s pruned = false } parts.push(c.html) - // zero markers advance the flow position too (a spacer may have been - // emitted before them); skipping them leaves `base` stale and the next - // spacer re-adds the distance already consumed, shifting content down + // zero-height markers anchor positions too: skipping them here made every + // following marker's spacer re-span the full distance from the last real + // block, inflating the clone flow (blank pages past the drift) lastKept = c } return parts.join('') @@ -127,6 +147,7 @@ export function PaginationPreview({ pageFootnotesOf, endnoteItems, sectionHfOverride, + clearPageGaps, onExportPdf, onClose, }: { @@ -150,6 +171,14 @@ export function PaginationPreview({ endnoteItems?: PageNoteItem[] /** Multi-section: unsaved per-section header/footer edit overrides (default variant) */ sectionHfOverride?: (sectionIndex: number, kind: 'header' | 'footer') => HeaderFooter | null + /** + * Clears the canvas page-gap decorations before the snapshot measure. In-table + * gap/repeated-header widgets are extra s that consume rowspan slots, so a + * vMerge-heavy table measures with collapsed columns (exploding row heights) + * while they are present; the canvas rebuilds them on its next debounced + * remeasure after the snapshot. + */ + clearPageGaps?: () => void onExportPdf: () => void onClose: () => void }) { @@ -179,6 +208,7 @@ export function PaginationPreview({ useEffect(() => { const pm = document.querySelector('.editor-scroll .ProseMirror') as HTMLElement | null if (!pm) return + clearPageGaps?.() const factor = zoom / 100 // switch the columned canvas to the single-flow measuring state (CSS columns off, width = column width), matching engine column-flow coordinates if (colFlow) pm.classList.add('measuring-columns') @@ -270,7 +300,7 @@ export function PaginationPreview({ const h = (rect.height - innerGap) / factor gapAccum += innerGap metas.push({ - html: el.outerHTML, + html: cloneBlockHtml(el), vTop, vBottom: vTop + h, mt: parseFloat(cs.marginTop) || 0, @@ -282,7 +312,7 @@ export function PaginationPreview({ setHtml('') } else { setCloneKids(null) - setHtml(pm.innerHTML) + setHtml(Array.from(pm.children, (c) => cloneBlockHtml(c as HTMLElement)).join('')) } } finally { if (colFlow) pm.classList.remove('measuring-columns') @@ -433,6 +463,7 @@ export function PaginationPreview({ '--header-dist': `${pageBox.headerDist}px`, '--footer-dist': `${pageBox.footerDist}px`, '--pv-mr': `${twipsToPx(s.marginRight)}px`, + '--pv-ml': `${twipsToPx(s.marginLeft)}px`, padding: `${mTop}px ${twipsToPx(s.marginRight)}px ${mBottom}px ${twipsToPx(s.marginLeft)}px`, background: pageColor ? `#${pageColor}` : undefined, } as React.CSSProperties @@ -443,11 +474,39 @@ export function PaginationPreview({ {watermark}
    )} + {(parts.headerImages ?? []) + .filter((img) => img.floating) + .map((img, k) => ( + // picture watermark (absolute VML shape in the header): drawn once + // per page behind the body (negative z-index; .pv-page isolates) + + ))} {parts.header && ( !img.floating)} readOnly onCommit={() => {}} pageNo={pageNoText} @@ -687,7 +746,7 @@ export function PaginationPreview({ !img.floating)} readOnly onCommit={() => {}} pageNo={pageNoText} diff --git a/apps/docs/src/renderer/components/Ribbon.tsx b/apps/docs/src/renderer/components/Ribbon.tsx index f4de764..43e5714 100644 --- a/apps/docs/src/renderer/components/Ribbon.tsx +++ b/apps/docs/src/renderer/components/Ribbon.tsx @@ -90,12 +90,8 @@ import { IconPalette, IconPaste, IconPilcrow, - IconFlipH, - IconFlipV, IconRemoveBg, IconReplacePicture, - IconRotateLeft, - IconRotateRight, IconRowDelete, IconRowInsertAbove, IconRowInsertBelow, @@ -802,9 +798,10 @@ function RibbonInner({ /** * Replace the selected image's bytes (shared by Replace Picture / remove background / crop). - * Original images (docxIndex set) swap bytes in place via the imageReplace patch: the - * drawing XML survives, so wrap/position/docxIndex — and with them the Position gallery — - * keep working. Images not yet saved (genImage) just update their pending payload. + * The original image's patch-save only supports size/alignment/wrap; swapping bytes must go + * through the genImage new-image embed branch, so docxIndex is cleared (on save the old + * block is treated as deleted, the new image is written at the same position, and + * alignment/wrap are inherited from attributes). * Display size keeps the current width; height adapts to the new image's aspect ratio. */ const applyPictureBytes = async (dataUrl: string) => { @@ -818,7 +815,6 @@ function RibbonInner({ const currentW = Number(attrs.imageWidthPx) || Math.min(natural.width, 620) const w = Math.max(1, Math.round(currentW)) const h = Math.max(1, Math.round((currentW * natural.height) / natural.width)) - const isOriginal = attrs.docxIndex !== null && attrs.docxIndex !== undefined editor .chain() .focus() @@ -826,9 +822,8 @@ function RibbonInner({ imageDataUrl: dataUrl, imageWidthPx: w, imageHeightPx: h, - ...(isOriginal - ? { imageReplace: { base64: m[2], mime: m[1] } } - : { genImage: { base64: m[2], mime: m[1], widthPx: w, heightPx: h } }), + genImage: { base64: m[2], mime: m[1], widthPx: w, heightPx: h }, + docxIndex: null, }) .run() } catch { @@ -842,30 +837,6 @@ function RibbonInner({ await applyPictureBytes(`data:${picked.mime};base64,${picked.base64}`) } - const rotatePicture = (deltaDeg: number) => { - if (!canEdit) return - const attrs = editor.getAttributes('docProtected') - if (attrs?.blockType !== 'image') return - const next = ((((Number(attrs.imageRotDeg) || 0) + deltaDeg) % 360) + 360) % 360 - editor - .chain() - .focus() - .updateAttributes('docProtected', { imageRotDeg: next || null }) - .run() - } - - const flipPicture = (axis: 'h' | 'v') => { - if (!canEdit) return - const attrs = editor.getAttributes('docProtected') - if (attrs?.blockType !== 'image') return - const key = axis === 'h' ? 'imageFlipH' : 'imageFlipV' - editor - .chain() - .focus() - .updateAttributes('docProtected', { [key]: !attrs[key] }) - .run() - } - /** Set the image display size proportionally (cm input; either side drives the other) */ const setPictureSizeCm = (dim: 'w' | 'h', cm: number) => { if (!canEdit) return @@ -1710,40 +1681,6 @@ function RibbonInner({ ))} -
    - - - - -
    {t('ribbonGroupArrange')}
    diff --git a/apps/docs/src/renderer/components/icons.tsx b/apps/docs/src/renderer/components/icons.tsx index 906deb7..7fda184 100644 --- a/apps/docs/src/renderer/components/icons.tsx +++ b/apps/docs/src/renderer/components/icons.tsx @@ -337,44 +337,6 @@ export function IconCrop(props: IconProps) { ) } -export function IconRotateRight(props: IconProps) { - return ( - - - - - ) -} - -export function IconRotateLeft(props: IconProps) { - return ( - - - - - ) -} - -export function IconFlipH(props: IconProps) { - return ( - - - - - - ) -} - -export function IconFlipV(props: IconProps) { - return ( - - - - - - ) -} - export function IconReplacePicture(props: IconProps) { return ( diff --git a/apps/docs/src/renderer/components/ribbon-format-state.ts b/apps/docs/src/renderer/components/ribbon-format-state.ts index df41689..98e3848 100644 --- a/apps/docs/src/renderer/components/ribbon-format-state.ts +++ b/apps/docs/src/renderer/components/ribbon-format-state.ts @@ -29,8 +29,6 @@ export interface RibbonFormatState { imageAlign: string | null imageWidthPx: number | null imageHeightPx: number | null - imageFlipH: boolean - imageFlipV: boolean imageHasDocxIndex: boolean textboxSelected: boolean shapeFill: string | null @@ -79,8 +77,6 @@ export const EMPTY_FORMAT_STATE: RibbonFormatState = { imageAlign: null, imageWidthPx: null, imageHeightPx: null, - imageFlipH: false, - imageFlipV: false, imageHasDocxIndex: false, textboxSelected: false, shapeFill: null, @@ -197,8 +193,6 @@ export function computeFormatState( imageAlign: str(protAttrs.imageAlign), imageWidthPx: num(protAttrs.imageWidthPx), imageHeightPx: num(protAttrs.imageHeightPx), - imageFlipH: !!protAttrs.imageFlipH, - imageFlipV: !!protAttrs.imageFlipV, imageHasDocxIndex: protAttrs.docxIndex != null, textboxSelected: Array.isArray(protAttrs.textboxes) && protAttrs.textboxes.length > 0, shapeFill: Array.isArray(protAttrs.textboxes) diff --git a/apps/docs/src/renderer/doc-style-css.ts b/apps/docs/src/renderer/doc-style-css.ts index e6a429f..b0f0456 100644 --- a/apps/docs/src/renderer/doc-style-css.ts +++ b/apps/docs/src/renderer/doc-style-css.ts @@ -2,7 +2,10 @@ import type { ParsedDocFull, StyleDisplay, ThemeColors, ThemeFonts } from '@geno import { cssDualFontFamily, cssFontFamily, + cssGridLineBase, + cssGridSpacingPt, cssLineHeight, + isCjkFontName, krLineFactor, lineHeightFactor, textHasCjk, @@ -57,17 +60,32 @@ export function docHasCjk(parsed: ParsedDocFull): boolean { * line height). Recomputed live while editing via App's liveDocCjk. */ export function docLineFactor(parsed: ParsedDocFull, hasCjk: boolean): number { + return hasCjk ? docCjkFactor(parsed) : lineHeightFactor(docBodyFont(parsed) ?? 'Calibri') +} + +/** CJK line-height factor of the document's East Asian face (feeds --doc-line-factor-cjk: + * per-paragraph script overrides resolve CJK paragraphs through this var). */ +export function docCjkFactor(parsed: ParsedDocFull): number { // Normal's EA face wins over docDefaults (a Normal declaring e.g. Noto KR must - // not fall back to the SimSun 1.3 factor). font === fontAscii means only a + // not fall back to the SimSun factor). font === fontAscii means only a // Latin slot was declared (StyleDisplay.font is EA-first) — not an EA choice. const normal = defaultParaDisplay(parsed) const normalEa = normal?.font && (normal.font !== normal.fontAscii || isKoreanFontName(normal.font)) ? normal.font : undefined - return hasCjk - ? lineHeightFactor(normalEa ?? parsed.docDefaults?.eastAsiaFont ?? 'SimSun') - : lineHeightFactor(docBodyFont(parsed) ?? 'Calibri') + if (normalEa && !normal?.eaSlotEmpty) return lineHeightFactor(normalEa) + const dd = parsed.docDefaults + if (dd?.eastAsiaFont && !dd.eaSlotEmpty) return lineHeightFactor(dd.eastAsiaFont) + // An empty EA theme slot can still use a CJK-capable Latin theme face. + // Japanese templates commonly put Yu Mincho or Yu Gothic in the Latin + // slots, and LibreOffice lays undeclared CJK out with that face. + // A Latin theme face (Calibri…) can't render CJK, so the lang backfill wins. + const themeLatin = parsed.themeFonts?.minor + if ((normal?.eaSlotEmpty || dd?.eaSlotEmpty) && themeLatin && isCjkFontName(themeLatin)) { + return lineHeightFactor(themeLatin) + } + return lineHeightFactor(normalEa ?? dd?.eastAsiaFont ?? 'SimSun') } /** the w:default="1" paragraph style's display (Word's baseline for un-styled paragraphs) */ @@ -99,6 +117,9 @@ export function docStyleCss(parsed: ParsedDocFull): string { // at parse time + live decorations in LineFactorExtension). const factor = docLineFactor(parsed, docHasCjk(parsed)) decls.push(`--doc-line-factor:${factor}`) + // CJK paragraphs resolve their per-paragraph factor through this var + // (paraLineFactorCss); value follows the document's East Asian face + decls.push(`--doc-line-factor-cjk:${docCjkFactor(parsed)}`) // Latin factor for per-paragraph overrides (blockAttrs): pure-Western paragraphs // follow the body font's real single-line metric instead of a flat 1.2 decls.push(`--doc-line-factor-latin:${lineHeightFactor(docBodyFont(parsed) ?? 'Calibri')}`) @@ -127,18 +148,20 @@ export function docStyleCss(parsed: ParsedDocFull): string { const lh = cssLineHeight(normal?.lineRule, normal?.lineRawTwips, normal?.lineSpacing) ?? cssLineHeight(dd?.lineRule, dd?.lineRawTwips, dd?.lineSpacing) - decls.push(`line-height:${lh ?? `calc(${factor} * 1)`}`) + // fallback references the var (not the resolved number) so per-paragraph + // script factors and docGrid snapping re-evaluate on each block + decls.push(`line-height:${lh ?? cssGridLineBase()}`) rules.push(`.doc-page { ${decls.join(';')} }`) // Word's fallback when neither Normal nor docDefaults declares w:spacing is 0 // (the static stylesheet's 8pt guess inflated undeclared docs, table cells worst); // declared per block so --doc-line-factor set inline on a paragraph re-evaluates // the line-height var (it wouldn't through inheritance) const blockSel = - '.doc-page p, .doc-page .doc-li, .doc-page h1, .doc-page h2, .doc-page h3, .doc-page h4, .doc-page h5, .doc-page h6' + '.doc-page p, .doc-page .doc-li, .doc-page h1, .doc-page h2, .doc-page h3, .doc-page h4, .doc-page h5, .doc-page h6, .doc-page .doc-protected-field' const blockDecls = [ - `margin-top:${((normal?.spaceBeforeTwips ?? dd?.spaceBeforeTwips ?? 0) / 20).toFixed(1)}pt`, - `margin-bottom:${((normal?.spaceAfterTwips ?? dd?.spaceAfterTwips ?? 0) / 20).toFixed(1)}pt`, - `line-height:${lh ?? `calc(${factor} * 1)`}`, + `margin-top:${cssGridSpacingPt((normal?.spaceBeforeTwips ?? dd?.spaceBeforeTwips ?? 0) / 20)}`, + `margin-bottom:${cssGridSpacingPt((normal?.spaceAfterTwips ?? dd?.spaceAfterTwips ?? 0) / 20)}`, + `line-height:${lh ?? cssGridLineBase()}`, ] rules.push(`${blockSel} { ${blockDecls.join(';')} }`) // Normal's first-line indent applies to plain body paragraphs (not lists — @@ -177,9 +200,9 @@ export function docStyleCss(parsed: ParsedDocFull): string { const ps = t.paraSpacing const decls: string[] = [] if (ps.beforeTwips !== undefined && normal?.spaceBeforeTwips === undefined) - decls.push(`margin-top:${(ps.beforeTwips / 20).toFixed(1)}pt`) + decls.push(`margin-top:${cssGridSpacingPt(ps.beforeTwips / 20)}`) if (ps.afterTwips !== undefined && normal?.spaceAfterTwips === undefined) - decls.push(`margin-bottom:${(ps.afterTwips / 20).toFixed(1)}pt`) + decls.push(`margin-bottom:${cssGridSpacingPt(ps.afterTwips / 20)}`) const psLh = cssLineHeight(ps.lineRule, ps.lineRawTwips, ps.lineSpacing) const normalLh = cssLineHeight(normal?.lineRule, normal?.lineRawTwips, normal?.lineSpacing) if (psLh && !normalLh) decls.push(`line-height:${psLh}`) @@ -211,6 +234,12 @@ export function docStyleCss(parsed: ParsedDocFull): string { : cssFontFamily(d.font) }`, ) + // style-declared EA face re-anchors the CJK line factor for its paragraphs + // (runs without their own fonts resolve --doc-line-factor-cjk through this); + // an empty-theme-slot backfill is not a document choice and stays silent + if (!d.eaSlotEmpty && (d.font !== d.fontAscii || isCjkFontName(d.font))) { + decls.push(`--doc-line-factor-cjk:${lineHeightFactor(d.font)}`) + } } else if (d.fontAscii) { decls.push(`font-family:${cssFontFamily(d.fontAscii)}`) } @@ -218,9 +247,9 @@ export function docStyleCss(parsed: ParsedDocFull): string { const styleLh = cssLineHeight(d.lineRule, d.lineRawTwips, d.lineSpacing) if (styleLh) decls.push(`line-height:${styleLh}`) if (d.spaceBeforeTwips !== undefined) - decls.push(`margin-top:${(d.spaceBeforeTwips / 20).toFixed(1)}pt`) + decls.push(`margin-top:${cssGridSpacingPt(d.spaceBeforeTwips / 20)}`) if (d.spaceAfterTwips !== undefined) - decls.push(`margin-bottom:${(d.spaceAfterTwips / 20).toFixed(1)}pt`) + decls.push(`margin-bottom:${cssGridSpacingPt(d.spaceAfterTwips / 20)}`) if (d.indentRightTwips) decls.push(`margin-inline-end:${(d.indentRightTwips / 20).toFixed(1)}pt`) if (d.indentFirstLineTwips) diff --git a/apps/docs/src/renderer/editor/convert.ts b/apps/docs/src/renderer/editor/convert.ts index a1a8e7d..6d50730 100644 --- a/apps/docs/src/renderer/editor/convert.ts +++ b/apps/docs/src/renderer/editor/convert.ts @@ -91,6 +91,7 @@ function formatAttrs(format: ParaFormat | undefined): Record { dropCap: format?.dropCap ? JSON.stringify(format.dropCap) : null, bidi: format?.bidi ?? false, autoSpace: format?.autoSpace ?? null, + snapToGrid: format?.snapToGrid ?? null, } } @@ -203,26 +204,27 @@ function blockToPmNode(block: Block, rowCapTwips: number | null = null): PmNode docxIndex: block.docxIndex, blockRevision: block.blockRevision ?? null, blockType: block.type, + styleId: block.styleId ?? null, label: block.label ?? block.type, previewText: block.previewText ?? '', imageDataUrl: block.imageDataUrl ?? null, oleProgId: block.oleProgId ?? null, imageWidthPx: block.imageWidthPx ?? null, imageHeightPx: block.imageHeightPx ?? null, + imageCrop: block.imageCrop ?? null, + imageFillRect: block.imageFillRect ?? null, imageAlign: block.imageAlign ?? null, imageWrap: block.imageWrap ?? null, imageOffsetXEmu: block.imageOffsetXEmu ?? null, imageOffsetYEmu: block.imageOffsetYEmu ?? null, imagePosH: block.imagePosH ?? null, imagePosV: block.imagePosV ?? null, - imageRotDeg: block.imageRotDeg ?? null, - imageFlipH: block.imageFlipH ?? false, - imageFlipV: block.imageFlipV ?? false, table: block.table && rowCapTwips != null ? capTableRowHeights(block.table, rowCapTwips) : (block.table ?? null), fieldDisplay: block.fieldDisplay ?? null, + diagramDisplay: block.diagramDisplay ?? null, decorative: block.decorative ?? false, ruleColorHex: block.ruleColorHex ?? null, ruleThicknessPx: block.ruleThicknessPx ?? null, @@ -743,6 +745,7 @@ function runMarks(run: Run): PmMark[] { color: run.color ?? null, sizeHalfPoints: run.sizeHalfPoints ?? null, font: run.font ?? null, + eaSlotEmpty: run.eaSlotEmpty ?? null, fontAscii: run.fontAscii ?? null, // cs chain only kicks in for complex-script text (Word's w:cs semantics) csFont: run.csFont && textHasComplexScript(run.text) ? run.csFont : null, @@ -942,16 +945,10 @@ export function pmDocToSavePlan(doc: PmNode, originalBlocks: Block[]): SavePlan chartDisplay.heightPx !== original.chartDisplay?.heightPx) ? { w: chartDisplay.widthPx, h: chartDisplay.heightPx } : null - const imageReplace = - original.type === 'image' - ? (node.attrs?.imageReplace as { base64: string; mime: string } | null) - : null - if ((imagePatch || imageReplace) && original.originalXml) { + if (imagePatch && original.originalXml) { changedCount++ - let xml = imagePatch - ? patchImageParagraphXml(original.originalXml, imagePatch) - : original.originalXml - if (imagePatch?.wrap !== undefined) { + let xml = patchImageParagraphXml(original.originalXml, imagePatch) + if (imagePatch.wrap !== undefined) { const posOffset = imagePatch.posOffsetX !== undefined && imagePatch.posOffsetY !== undefined ? { x: imagePatch.posOffsetX, y: imagePatch.posOffsetY } @@ -961,24 +958,10 @@ export function pmDocToSavePlan(doc: PmNode, originalBlocks: Block[]): SavePlan ? { h: imagePatch.posH, v: imagePatch.posV } : undefined xml = applyImageWrap(xml, imagePatch.wrap, posOffset, marginAlign) - } else if ( - imagePatch && - (imagePatch.posOffsetX !== undefined || imagePatch.posOffsetY !== undefined) - ) { + } else if (imagePatch.posOffsetX !== undefined || imagePatch.posOffsetY !== undefined) { // posOffset changed without wrap change: patchImageParagraphXml already rewrote it } - pushBlock({ - kind: 'xml', - xml, - ...(imageReplace - ? { - replaceImage: { - base64: imageReplace.base64, - mime: imageReplace.mime as NewImage['mime'], - }, - } - : {}), - }) + pushBlock({ kind: 'xml', xml }) } else if (tableTexts && original.originalXml) { changedCount++ pushBlock({ kind: 'xml', xml: patchTableCellTexts(original.originalXml, tableTexts) }) @@ -1096,9 +1079,6 @@ export function pmDocToSavePlan(doc: PmNode, originalBlocks: Block[]): SavePlan if (align) image.align = align const wrap = node.attrs.imageWrap as ImageWrap | null if (wrap) image.wrap = wrap - if (node.attrs.imageRotDeg) image.rotDeg = Number(node.attrs.imageRotDeg) - if (node.attrs.imageFlipH) image.flipH = true - if (node.attrs.imageFlipV) image.flipV = true pushBlock({ kind: 'image', image }) } else if (node.attrs?.genChart) { // in-place edits live in chartDisplay; the saved part reflects them @@ -1216,9 +1196,6 @@ function imageFromProtectedAttrs(node: PmNode): NewImage | null { if (align) image.align = align const wrap = node.attrs?.imageWrap as ImageWrap | null if (wrap) image.wrap = wrap - if (node.attrs?.imageRotDeg) image.rotDeg = Number(node.attrs.imageRotDeg) - if (node.attrs?.imageFlipH) image.flipH = true - if (node.attrs?.imageFlipV) image.flipV = true return image } @@ -1290,10 +1267,6 @@ interface ImageBlockPatch { /** margin-relative align pair (Word position-gallery presets); undefined = keep */ posH?: 'left' | 'center' | 'right' posV?: 'top' | 'center' | 'bottom' - /** rotation (deg clockwise, 0 removes) / mirror flips; undefined = keep */ - rotDeg?: number - flipH?: boolean - flipV?: boolean } /** size/align/wrap changes on an original image block; null when untouched */ @@ -1325,12 +1298,6 @@ function imagePatchOf(node: PmNode, original: Block): ImageBlockPatch | null { if (posOffsetY !== undefined && posOffsetY !== (original.imageOffsetYEmu ?? undefined)) { patch.posOffsetY = posOffsetY } - const rotDeg = node.attrs?.imageRotDeg != null ? Number(node.attrs.imageRotDeg) : 0 - if (rotDeg !== (original.imageRotDeg ?? 0)) patch.rotDeg = rotDeg - const flipH = !!node.attrs?.imageFlipH - const flipV = !!node.attrs?.imageFlipV - if (flipH !== (original.imageFlipH ?? false)) patch.flipH = flipH - if (flipV !== (original.imageFlipV ?? false)) patch.flipV = flipV const posH = (node.attrs?.imagePosH as ImageBlockPatch['posH'] | null) ?? null const posV = (node.attrs?.imagePosV as ImageBlockPatch['posV'] | null) ?? null if ( diff --git a/apps/docs/src/renderer/editor/extensions.ts b/apps/docs/src/renderer/editor/extensions.ts index 884b73d..fd590cc 100644 --- a/apps/docs/src/renderer/editor/extensions.ts +++ b/apps/docs/src/renderer/editor/extensions.ts @@ -25,8 +25,12 @@ import { import { autospaceBoundaries, autospacePadBetween, + cssGridSpacingPt, cssLineHeight, + isCjkFontName, + lineHeightFactor, paraLineFactorCss, + textHasCjk, } from '../line-metrics' import { noteMarkText } from '../note-format' import { t } from '../i18n/locale' @@ -34,6 +38,7 @@ import { ommlToMathML, patchMathTokens, type ChartDisplay, + type DiagramDisplay, type FieldDisplay, type FormulaDisplay, type NewChart, @@ -114,6 +119,8 @@ const anchorAttrs = { lineRule: { default: null as string | null }, /** Raw w:spacing w:line twips (used by atLeast/exact) */ lineRawTwips: { default: null as number | null }, + /** w:snapToGrid: false only when explicitly off (opts out of docGrid snapping) */ + snapToGrid: { default: null as boolean | null }, indentLeft: { default: null as number | null }, indentRight: { default: null as number | null }, indentFirstLine: { default: null as number | null }, @@ -159,6 +166,41 @@ function explicitStrutHalfPoints(node: { descendants?: PmNode['descendants'] }): return inherited ? null : max } +/** + * Per-paragraph --doc-line-factor value: CJK runs with a declared font take that + * font's LO-metric factor (max over runs); undeclared CJK runs keep the + * document-level CJK var; non-CJK paragraphs keep the script-based guess. + */ +function paraLineFactor(node: { + textContent?: string + descendants?: PmNode['descendants'] +}): string { + const scriptVar = paraLineFactorCss(node.textContent ?? '') + if (!node.descendants || !textHasCjk(node.textContent ?? '')) return scriptVar + let declaredMax = 0 + let undeclaredCjk = false + node.descendants((child) => { + if (!child.isText) return true + if (!textHasCjk(child.text ?? '')) return false + const mark = child.marks.find((m) => m.type.name === 'docTextStyle') + // empty-EA-theme-slot backfills keep the Word-look face but are not a + // document font choice: LO cascades such runs to the document's EA default, + // so they count as undeclared here (the doc-level var carries that factor). + // Latin-named faces likewise don't drive CJK line height — an ascii-only + // "Times New Roman" run still renders its CJK via the inherited EA font. + const family = + mark?.attrs.eaSlotEmpty === true + ? null + : ((mark?.attrs.font ?? mark?.attrs.fontAscii) as string | null | undefined) + if (family && isCjkFontName(family)) { + declaredMax = Math.max(declaredMax, lineHeightFactor(family)) + } else undeclaredCjk = true + return false + }) + if (declaredMax <= 0) return scriptVar + return undeclaredCjk ? `max(${scriptVar}, ${declaredMax})` : String(declaredMax) +} + function blockAttrs( node: { attrs: Record @@ -180,6 +222,9 @@ function blockAttrs( } const classes: string[] = [] if (node.attrs.aiChanged) classes.push('ai-changed') + // textless paragraph: table-cell CSS shrinks these to the Latin line height + // (an empty cell inheriting the CJK factor would out-grow the content cells) + if (!node.textContent) classes.push('doc-p-empty') if (node.attrs.pageBreakBefore) { classes.push('page-break-before') attrs['data-page-break-label'] = t('editorPageBreak') @@ -194,9 +239,13 @@ function blockAttrs( } // the line-height factor follows paragraph content (approximating Word's max-of-inline-fonts // line height): CJK paragraphs get the CJK factor, pure-Western ones the document's - // font-aware Latin factor (doc-style-css sets --doc-line-factor-latin per body font) + // font-aware Latin factor (doc-style-css sets --doc-line-factor-latin per body font). + // Runs that DECLARE a font override the script guess with that font's factor + // (LO probe: line height follows the requested face's metrics even when CJK + // glyphs fall through to another font — EA "Times New Roman" lays at 1.15em); + // the paragraph takes the max over its CJK runs, like Word's tallest-run rule. if (node.textContent) { - styles.push(`--doc-line-factor:${paraLineFactorCss(node.textContent)}`) + styles.push(`--doc-line-factor:${paraLineFactor(node)}`) // Word's line strut follows run sizes; without this the paragraph inherits the // body size (often larger than table-cell runs) and every line box inflates. // Shrink-only: a large run already lifts its own line, and Word sizes each @@ -206,10 +255,13 @@ function blockAttrs( } const lh = cssLineHeight( (node.attrs.lineRule as 'auto' | 'atLeast' | 'exact' | null) ?? undefined, - node.attrs.lineRawTwips ? Number(node.attrs.lineRawTwips) : undefined, + node.attrs.lineRawTwips != null ? Number(node.attrs.lineRawTwips) : undefined, node.attrs.lineSpacing ? Number(node.attrs.lineSpacing) : undefined, ) if (lh) styles.push(`line-height:${lh}`) + // w:snapToGrid=0: opt this paragraph out of docGrid line snapping (the + // round(up) expressions read the pitch var, so a local ~0 disables them) + if (node.attrs.snapToGrid === false) styles.push('--doc-grid-pitch:0.0001px') // list items already indent via padding; a margin would double-shift them. // listGeometry: drive list geometry with w:ind (--li-left text indent, --li-hang the hanging // area i.e. the number-marker width); negative text-indent is expressed by the marker box, no longer emitted directly @@ -229,9 +281,9 @@ function blockAttrs( } // explicit 0 must still emit (w:after="0" overrides the style/docDefaults margin) if (node.attrs.spaceBefore != null) - styles.push(`margin-top:${Number(node.attrs.spaceBefore) / 20}pt`) + styles.push(`margin-top:${cssGridSpacingPt(Number(node.attrs.spaceBefore) / 20)}`) if (node.attrs.spaceAfter != null) - styles.push(`margin-bottom:${Number(node.attrs.spaceAfter) / 20}pt`) + styles.push(`margin-bottom:${cssGridSpacingPt(Number(node.attrs.spaceAfter) / 20)}`) if (node.attrs.shadingFill) styles.push(`background-color:#${node.attrs.shadingFill}`) if (node.attrs.borders) { const borders = String(node.attrs.borders) @@ -299,7 +351,9 @@ export const DocNoteRef = Node.create({ class: 'doc-note-ref', title: node.attrs.kind === 'footnote' ? t('editorFootnote') : t('editorEndnote'), }, - `[${noteMarkText(node.attrs.kind as 'footnote' | 'endnote', Number(node.attrs.num) || 1)}]`, + // brackets are editor chrome (CSS ::before/::after): Word prints a bare + // superscript number, and bracket glyphs must not leak into exported text + noteMarkText(node.attrs.kind as 'footnote' | 'endnote', Number(node.attrs.num) || 1), ] }, }) @@ -704,7 +758,7 @@ function lineFactorDecos(doc: PmNode): DecorationSet { if (node.textContent) { let style = lineFactorCache.get(node) if (style === undefined) { - style = `--doc-line-factor:${paraLineFactorCss(node.textContent)}` + style = `--doc-line-factor:${paraLineFactor(node)}` const strut = explicitStrutHalfPoints(node) if (strut) style += `;--doc-strut:${strut / 2}pt;font-size:min(var(--doc-strut), 1em)` lineFactorCache.set(node, style) @@ -1050,8 +1104,13 @@ export const DocTable = Node.create({ if (node.attrs.bidiVisual) attrs.dir = 'rtl' const styles: string[] = [] if (node.attrs.widthPct) styles.push(`width:${Number(node.attrs.widthPct)}%`) - // min() keeps legacy over-wide grids on the paper instead of the gray canvas - else if (node.attrs.widthPx) styles.push(`width:min(${Number(node.attrs.widthPx)}px,100%)`) + // Over-wide grids may spill into the right page margin like Word/LO (clamping + // them to the content box narrowed every column, wrapped cell text onto extra + // lines and inflated PDF-converted documents by pages), but never past the paper + else if (node.attrs.widthPx) + styles.push( + `width:min(${Number(node.attrs.widthPx)}px,calc(100% + var(--doc-margin-right,0px)))`, + ) const pad = cellPadCss(node.attrs.cellMar as Record | null) if (pad) styles.push(`--doc-cell-pad:${pad}`) styles.push(...tableBordersCss(node.attrs.borders as TableBordersAttr | null)) @@ -1376,6 +1435,8 @@ export const DocProtected = Node.create({ docxIndex: { default: null as number | null }, blockRevision: { default: null as Record | null }, blockType: { default: 'passthrough' }, + /** w:pStyle of field/TOC paragraphs: doc style CSS (spacing/line-height) targets data-style */ + styleId: { default: null as string | null }, label: { default: '' }, previewText: { default: '' }, imageDataUrl: { default: null as string | null }, @@ -1383,6 +1444,10 @@ export const DocProtected = Node.create({ /** display size in CSS px (blockType === 'image'), editable via drag handles */ imageWidthPx: { default: null as number | null }, imageHeightPx: { default: null as number | null }, + /** source crop (a:srcRect) fractions, display-only */ + imageCrop: { default: null as { l: number; t: number; r: number; b: number } | null }, + /** fill placement (a:fillRect) fractions (negative = bleed), display-only */ + imageFillRect: { default: null as { l: number; t: number; r: number; b: number } | null }, /** paragraph alignment of the image (w:jc) */ imageAlign: { default: null as string | null }, imageWrap: { default: null as string | null }, @@ -1416,19 +1481,14 @@ export const DocProtected = Node.create({ formulaDisplay: { default: null as FormulaDisplay | null }, /** embedded chart data model; cached texts/numbers editable, structure protected */ chartDisplay: { default: null as ChartDisplay | null }, + /** display-only SmartArt degrade (precomputed diagram drawing shapes) */ + diagramDisplay: { default: null as DiagramDisplay | null }, /** self-contained OOXML fragment for editor-created content (new tables) */ genXml: { default: null as string | null }, /** new image awaiting embedding at save time */ genImage: { default: null as { base64: string; mime: string; widthPx: number; heightPx: number } | null, }, - /** picture rotation (deg clockwise, 0-359) and mirror flips (a:xfrm rot/flipH/flipV) */ - imageRotDeg: { default: null as number | null }, - imageFlipH: { default: false }, - imageFlipV: { default: false }, - /** replacement bytes for an original image (crop/background removal/replace): - * the drawing XML — and with it docxIndex, wrap and position — survives */ - imageReplace: { default: null as { base64: string; mime: string } | null }, /** new chart awaiting embedding at save time (data snapshot; edits live in chartDisplay) */ genChart: { default: null as NewChart | null }, } @@ -1517,6 +1577,72 @@ export const DocProtected = Node.create({ }, }) +/** + * SmartArt / drawing-canvas display: absolutely positioned shapes (picture + * fills, solid fills, centered texts) at the parse-resolved geometry. All + * colors are document data (theme-resolved at parse), hence inline. Canvas + * displays (lockedCanvas) keep raw-size text overflowing the scaled child + * boxes instead of clipping, like LO renders them. + */ +function diagramSpecOf(diagram: DiagramDisplay): DomSpec { + const shapeSpecs: DomSpec[] = diagram.shapes.map((s) => { + const radius = + s.prst === 'ellipse' || s.prst === 'circle' + ? '50%' + : s.prst === 'roundRect' + ? `${Math.round(Math.min(s.wPx, s.hPx) * 0.12)}px` + : '0' + const style = [ + `left:${s.xPx}px`, + `top:${s.yPx}px`, + `width:${s.wPx}px`, + `height:${s.hPx}px`, + `border-radius:${radius}`, + s.fillHex ? `background:#${s.fillHex}` : '', + s.rotDeg ? `transform:rotate(${s.rotDeg}deg)` : '', + s.fontSizePt ? `font-size:${s.fontSizePt}pt` : '', + s.textColorHex ? `color:#${s.textColorHex}` : '', + ] + .filter(Boolean) + .join(';') + const kids: DomSpec[] = [] + if (s.imageDataUrl) { + let imgStyle = 'position:absolute;left:0;top:0;width:100%;height:100%;object-fit:cover' + if (s.fillRect) { + const sw = s.wPx * (1 - s.fillRect.l - s.fillRect.r) + const sh = s.hPx * (1 - s.fillRect.t - s.fillRect.b) + imgStyle = + `position:absolute;left:${(s.fillRect.l * s.wPx).toFixed(1)}px;` + + `top:${(s.fillRect.t * s.hPx).toFixed(1)}px;` + + `width:${sw.toFixed(1)}px;height:${sh.toFixed(1)}px;max-width:none` + } + kids.push(['img', { src: s.imageDataUrl, class: 'doc-diagram-img', style: imgStyle }]) + } + if (s.texts?.length) { + kids.push(['span', { class: 'doc-diagram-text' }, s.texts.join('\n')]) + } + return ['span', { class: 'doc-diagram-shape', style }, ...kids] + }) + const spanStyle = [ + `width:${diagram.widthPx}px`, + `height:${diagram.heightPx}px`, + diagram.floating + ? `position:absolute;left:${((diagram.offsetXEmu ?? 0) / EMU_PER_PX).toFixed(1)}px;` + + `top:${((diagram.offsetYEmu ?? 0) / EMU_PER_PX).toFixed(1)}px` + : '', + ] + .filter(Boolean) + .join(';') + return [ + 'span', + { + class: `doc-diagram${diagram.canvas ? ' doc-diagram-canvas' : ''}`, + style: spanStyle, + }, + ...shapeSpecs, + ] +} + /** shared DOM spec for protected blocks (renderHTML + node view) */ function protectedDomSpec(node: PmNode): DomSpec { const { @@ -1537,6 +1663,9 @@ function protectedDomSpec(node: PmNode): DomSpec { 'data-idx': docxIndex === null ? '' : String(docxIndex), class: `doc-protected doc-protected-${blockType}`, } + // field/TOC paragraphs keep their paragraph style so document CSS + // (TOC1 spacing etc.) reaches the wrapper like any styled paragraph + if (node.attrs.styleId) attrs['data-style'] = String(node.attrs.styleId) if (node.attrs.invisibleMarker) { attrs.class += ' doc-protected-invisible' return ['div', attrs] @@ -1555,16 +1684,26 @@ function protectedDomSpec(node: PmNode): DomSpec { } if (Array.isArray(textboxes) && textboxes.length > 0) { attrs.class += ' doc-protected-textboxes' - const offsetX = node.attrs.imageOffsetXEmu - const offsetY = node.attrs.imageOffsetYEmu - if (offsetX != null || offsetY != null) { - attrs.style = - `transform:translate(${Number(offsetX ?? 0) / EMU_PER_PX}px,` + - `${Number(offsetY ?? 0) / EMU_PER_PX}px)` + const boxes = textboxes as TextboxDisplay[] + const diagram = node.attrs.diagramDisplay as DiagramDisplay | null + // every box floats at its own anchor offset (wrapNone / multi-drawing + // paragraphs): the wrapper leaves the flow like Word instead of stacking + const allFloating = boxes.every((b) => b.floating) && (!diagram || diagram.floating) + if (allFloating) { + attrs.class += ' doc-protected-floating' + } else { + const offsetX = node.attrs.imageOffsetXEmu + const offsetY = node.attrs.imageOffsetYEmu + if (offsetX != null || offsetY != null) { + attrs.style = + `transform:translate(${Number(offsetX ?? 0) / EMU_PER_PX}px,` + + `${Number(offsetY ?? 0) / EMU_PER_PX}px)` + } } - const children: DomSpec[] = (textboxes as TextboxDisplay[]).map(renderTextboxSpec) + const children: DomSpec[] = boxes.map(renderTextboxSpec) + if (diagram?.shapes?.length) children.push(diagramSpecOf(diagram)) // corner resize handle; multi-box nodes keep per-box autogrow semantics only - if ((textboxes as TextboxDisplay[]).length === 1) { + if (boxes.length === 1 && !diagram) { children.push(['span', { class: 'box-resize-handle', contenteditable: 'false' }]) } return ['div', attrs, moveHandleSpec(t('editorMoveTextbox')), ...children] @@ -1587,11 +1726,30 @@ function protectedDomSpec(node: PmNode): DomSpec { return ['div', attrs, ['span', { class: 'doc-sectbreak-label' }, String(label)]] } if (blockType === 'image' && imageDataUrl) { - const { imageWidthPx, imageHeightPx, imageAlign, imageWrap, imageRotDeg } = node.attrs + const { imageWidthPx, imageHeightPx, imageAlign, imageWrap, imageCrop, imageFillRect } = + node.attrs if (imageAlign === 'center' || imageAlign === 'right') { attrs['style'] = `text-align:${imageAlign}` } if (imageWrap) attrs.class += ` img-wrap-${String(imageWrap)}` + // no-wrap / behind-text floats: approximate the anchor position — margin + // alignment via text-align, numeric posOffset via a transform on the INNER + // wrap (the outer block's rect feeds pagination measurement, which must + // stay at the flow position; transforms leak into getBoundingClientRect) + let imgWrapTransform = '' + if (imageWrap === 'front' || imageWrap === 'behind') { + const posH = node.attrs.imagePosH + if ((posH === 'center' || posH === 'right') && !attrs['style']) { + attrs['style'] = `text-align:${String(posH)}` + } + const tx = + node.attrs.imageOffsetXEmu != null ? Number(node.attrs.imageOffsetXEmu) / EMU_PER_PX : 0 + const ty = + node.attrs.imageOffsetYEmu != null ? Number(node.attrs.imageOffsetYEmu) / EMU_PER_PX : 0 + if (tx !== 0 || ty !== 0) { + imgWrapTransform = `transform:translate(${tx.toFixed(1)}px,${ty.toFixed(1)}px)` + } + } const imgAttrs: Record = { src: String(imageDataUrl), class: 'doc-protected-img', @@ -1601,15 +1759,49 @@ function protectedDomSpec(node: PmNode): DomSpec { `width:${Number(imageWidthPx)}px;` + (imageHeightPx ? `height:${Number(imageHeightPx)}px` : 'height:auto') } - // DrawingML order: flip mirrors the source, rot turns the result - // (CSS applies right-to-left, so scale sits last) - const xf: string[] = [] - if (imageRotDeg) xf.push(`rotate(${Number(imageRotDeg)}deg)`) - if (node.attrs.imageFlipH) xf.push('scaleX(-1)') - if (node.attrs.imageFlipV) xf.push('scaleY(-1)') - if (xf.length) { + // a:srcRect source crop / a:fillRect fill placement: an overflow-hidden + // window at the declared extent over a scaled and offset image + const rect = (imageCrop ?? imageFillRect) as { + l: number + t: number + r: number + b: number + } | null + if (rect && imageWidthPx && imageHeightPx) { + const W = Number(imageWidthPx) + const H = Number(imageHeightPx) + const span = (a: number, b: number) => Math.max(0.01, 1 - a - b) + let sw: number, sh: number, dx: number, dy: number + if (imageCrop) { + // crop: the window shows the (1-l-r)×(1-t-b) slice of the source + sw = W / span(rect.l, rect.r) + sh = H / span(rect.t, rect.b) + dx = -rect.l * sw + dy = -rect.t * sh + } else { + // fillRect: the image occupies the inset (negative = bleeding) sub-rect + sw = W * (1 - rect.l - rect.r) + sh = H * (1 - rect.t - rect.b) + dx = rect.l * W + dy = rect.t * H + } imgAttrs['style'] = - `${imgAttrs['style'] ? `${imgAttrs['style']};` : ''}transform:${xf.join(' ')}` + `position:absolute;left:${dx.toFixed(1)}px;top:${dy.toFixed(1)}px;` + + `width:${sw.toFixed(1)}px;height:${sh.toFixed(1)}px;max-width:none` + return [ + 'div', + attrs, + moveHandleSpec(t('editorMoveImage')), + [ + 'span', + { + class: 'doc-img-wrap doc-img-crop', + style: `position:relative;display:inline-block;overflow:hidden;width:${W}px;height:${H}px${imgWrapTransform ? `;${imgWrapTransform}` : ''}`, + }, + ['img', imgAttrs], + ['span', { class: 'img-resize-handle' }], + ], + ] } return [ 'div', @@ -1617,7 +1809,10 @@ function protectedDomSpec(node: PmNode): DomSpec { moveHandleSpec(t('editorMoveImage')), [ 'span', - { class: 'doc-img-wrap' }, + { + class: 'doc-img-wrap', + ...(imgWrapTransform ? { style: `display:inline-block;${imgWrapTransform}` } : {}), + }, ['img', imgAttrs], ['span', { class: 'img-resize-handle' }], ], @@ -1658,6 +1853,21 @@ function protectedDomSpec(node: PmNode): DomSpec { ['span', { class: 'box-resize-handle', contenteditable: 'false' }], ] } + // SmartArt with a precomputed drawing part: absolutely positioned shapes + // (picture fills, solid fills, centered texts) at Word's resolved geometry. + // All colors are document data (theme-resolved at parse), hence inline. + const diagram = node.attrs.diagramDisplay as DiagramDisplay | null + if (diagram?.shapes?.length) { + attrs.class += ' doc-protected-diagram' + if (diagram.floating) { + attrs.class += ' doc-protected-floating' + } else if (diagram.offsetXEmu != null || diagram.offsetYEmu != null) { + attrs.style = + `transform:translate(${Number(diagram.offsetXEmu ?? 0) / EMU_PER_PX}px,` + + `${Number(diagram.offsetYEmu ?? 0) / EMU_PER_PX}px)` + } + return ['div', attrs, moveHandleSpec(t('editorMoveImage')), diagramSpecOf(diagram)] + } // Broken picture (missing rel/media): empty frame at the declared extent // with centered alt text. Frame/text colors stand in for document content // (must look identical in both themes), hence hardcoded inline. @@ -2350,11 +2560,9 @@ function imageResizePlugin(): Plugin { // CSS `zoom` scales client coordinates; divide it back out const zoomEl = document.querySelector('.doc-zoom') as HTMLElement | null const zoom = zoomEl ? parseFloat(getComputedStyle(zoomEl).zoom || '1') || 1 : 1 - // Layout-box measurements: getBoundingClientRect would include the - // rotation/flip transform, swapping width/height for 90°-rotated images - const startW = img.offsetWidth - const ratio = img.offsetHeight / Math.max(1, img.offsetWidth) - const priorStyle = img.getAttribute('style') + const startRect = img.getBoundingClientRect() + const startW = startRect.width / zoom + const ratio = startRect.height / startRect.width const startX = event.clientX const widthAt = (e: MouseEvent) => Math.max(24, startW + (e.clientX - startX) / zoom) @@ -2366,12 +2574,6 @@ function imageResizePlugin(): Plugin { const onUp = (e: MouseEvent) => { window.removeEventListener('mousemove', onMove) window.removeEventListener('mouseup', onUp) - // A plain click on the handle must not rewrite the stored size - if (Math.abs(e.clientX - startX) < 2) { - if (priorStyle === null) img.removeAttribute('style') - else img.setAttribute('style', priorStyle) - return - } const w = Math.round(widthAt(e)) const node = view.state.doc.nodeAt(pos) if (!node) return @@ -2458,10 +2660,6 @@ function floatingObjectDragPlugin(): Plugin { const visual = wrapper.querySelector( isTextbox ? '.doc-textbox' : '.doc-protected-img', ) as HTMLElement | null - // Images may already carry a rotation/flip transform: the drag translate - // must compose with it (prepended = applied in screen space) and the - // original must come back on mouseup, or the orientation vanishes - const baseTransform = visual?.style.transform ?? '' // 3px threshold keeps plain clicks (select, first click of a // double-click-to-edit) from nudging the object @@ -2471,16 +2669,13 @@ function floatingObjectDragPlugin(): Plugin { const dy = (e.clientY - startY) / zoom if (!dragging && Math.abs(dx) < 3 && Math.abs(dy) < 3) return dragging = true - if (visual) { - visual.style.transform = - `translate(${dx}px, ${dy}px)` + (baseTransform ? ` ${baseTransform}` : '') - } + if (visual) visual.style.transform = `translate(${dx}px, ${dy}px)` } const onUp = (e: MouseEvent) => { window.removeEventListener('mousemove', onMove) window.removeEventListener('mouseup', onUp) - if (visual) visual.style.transform = baseTransform + if (visual) visual.style.transform = '' const dx = (e.clientX - startX) / zoom const dy = (e.clientY - startY) / zoom diff --git a/apps/docs/src/renderer/editor/markdown-paste.ts b/apps/docs/src/renderer/editor/markdown-paste.ts new file mode 100644 index 0000000..a4fdea4 --- /dev/null +++ b/apps/docs/src/renderer/editor/markdown-paste.ts @@ -0,0 +1,52 @@ +/** + * Plain-text Markdown paste. Clipboards that carry only text/plain (fenced + * code blocks, terminals, .md files in a text editor, LLM output) lose all + * structure when pasted literally: "## Heading" keeps its hashes, "**bold**" + * its asterisks. When such text looks like Markdown, it is converted to HTML + * and inserted through the same pipeline as an HTML paste. Clipboards that + * already carry text/html never reach this path. + * + * Detection errs toward literal paste: prose that merely mentions a "#" or a + * lone "1." must not be reformatted, so conversion requires an unambiguous + * Markdown construct (heading, fence, link, emphasis, table) or a repeated + * one (several list/quote lines). + */ +import { marked } from 'marked' + +/// Constructs that essentially never appear in prose accidentally. +const STRONG_SIGNALS: readonly RegExp[] = [ + /^#{1,6}\s+\S/m, // ATX heading + /^\s{0,3}```/m, // fenced code block + /\[[^\]\n]+\]\([^\s)]+\)/, // [text](url) link + // **bold** only — the __bold__ form is indistinguishable from Python + // dunder identifiers (__init__, __name__) and would convert pasted code. + /(?:^|\W)\*\*[^*\n]+\*\*(?:\W|$)/, + /^\s{0,3}\|.+\|\s*$\n^\s{0,3}\|[\s:|-]+\|\s*$/m, // table header + separator row +] + +/// Constructs that appear in prose too; require several matching lines. +const LIST_LINE = /^\s{0,3}(?:[-*+]|\d{1,3}[.)])\s+\S/ +const QUOTE_LINE = /^\s{0,3}>\s?\S/ + +export function looksLikeMarkdown(text: string): boolean { + if (STRONG_SIGNALS.some((signal) => signal.test(text))) return true + const lines = text.split('\n') + const listLines = lines.filter((line) => LIST_LINE.test(line)).length + const quoteLines = lines.filter((line) => QUOTE_LINE.test(line)).length + return listLines >= 2 || quoteLines >= 2 +} + +/** + * HTML for a plain-text paste that looks like Markdown, or null to leave the + * default literal paste in place. The output feeds the same DOM → ProseMirror + * parse as a native HTML paste, so unknown elements degrade the same way. + */ +export function markdownPasteHtml(text: string): string | null { + const normalized = text.replace(/\r\n?/g, '\n') + if (!looksLikeMarkdown(normalized)) return null + try { + return marked.parse(normalized, { gfm: true, breaks: false, async: false }) + } catch { + return null + } +} diff --git a/apps/docs/src/renderer/editor/marks.ts b/apps/docs/src/renderer/editor/marks.ts index 86e8989..6de697d 100644 --- a/apps/docs/src/renderer/editor/marks.ts +++ b/apps/docs/src/renderer/editor/marks.ts @@ -421,6 +421,8 @@ export const TextStyleMark = Mark.create({ color: { default: null as string | null }, sizeHalfPoints: { default: null as number | null }, font: { default: null as string | null }, + // the EA face backfills an empty theme slot (line metrics follow the Latin face like LO) + eaSlotEmpty: { default: null as boolean | null }, // Latin slot (w:ascii/w:hAnsi) when it differs from the primary/eastAsia font fontAscii: { default: null as string | null }, // complex-script slot (w:cs); convert sets it only when the run text needs it diff --git a/apps/docs/src/renderer/editor/protected-render.ts b/apps/docs/src/renderer/editor/protected-render.ts index d1e85eb..f58e303 100644 --- a/apps/docs/src/renderer/editor/protected-render.ts +++ b/apps/docs/src/renderer/editor/protected-render.ts @@ -62,7 +62,9 @@ export function renderFieldSpec(field: FieldDisplay): DomSpec | null { attrs, ...num, ['span', { class: 'doc-toc-title', contenteditable: 'false' }, field.left || '\u00a0'], - ['span', { class: 'doc-toc-dots' }], + // real dot glyphs (clipped to the free width), not a border decoration: + // Word/LO leader dots are text, and exported-PDF text comparison sees them + ['span', { class: 'doc-toc-dots', contenteditable: 'false' }, '.'.repeat(220)], ['span', { class: 'doc-toc-page', contenteditable: 'false' }, field.right ?? ''], ] } @@ -170,6 +172,13 @@ export function renderChartSpec(chart: ChartDisplay): DomSpec { const SVG_NS = 'http://www.w3.org/2000/svg' +/** round up to a 1/2/5×10ⁿ "nice" axis step */ +function niceStep(target: number): number { + const pow = 10 ** Math.floor(Math.log10(Math.max(target, 1e-9))) + const n = target / pow + return (n <= 1 ? 1 : n <= 2 ? 2 : n <= 5 ? 5 : 10) * pow +} + interface ChartGeom { width: number height: number @@ -186,13 +195,18 @@ export const CHART_MAX_WIDTH_PX = 660 export function drawChartSvg(dom: HTMLElement, chart: ChartDisplay | null): void { const canvas = dom.querySelector('.doc-chart-canvas') if (!canvas || !chart?.series.length) return + // series-name legend inside the SVG: the data grid is an editing affordance + // (hidden unless the block is selected), so the printed chart must carry the + // legend itself, like Word/LibreOffice output + const legendNames = chart.series.map((s, i) => s.name ?? t('editorChartSeries', { num: i + 1 })) + const showLegend = chart.series.length > 1 || chart.series.some((s) => s.name) const geom: ChartGeom = { width: Math.min(chart.widthPx ?? 560, CHART_MAX_WIDTH_PX), height: chart.heightPx ?? 240, left: 46, right: 12, top: 12, - bottom: 26, + bottom: 26 + (showLegend ? 18 : 0), } const svg = document.createElementNS(SVG_NS, 'svg') svg.setAttribute('viewBox', `0 0 ${geom.width} ${geom.height}`) @@ -203,6 +217,31 @@ export function drawChartSvg(dom: HTMLElement, chart: ChartDisplay | null): void if (chart.kind === 'pie') drawPie(svg, chart, geom) else drawAxes(svg, chart, geom) + if (showLegend) { + const slot = geom.width / legendNames.length + legendNames.forEach((name, i) => { + const cx = slot * i + slot / 2 + svgEl(svg, 'rect', { + x: String(cx - Math.min(name.length * 3.2, slot / 2 - 14) - 12), + y: String(geom.height - 15), + width: '8', + height: '8', + fill: chartColor(i), + }) + svgEl( + svg, + 'text', + { + x: String(cx), + y: String(geom.height - 7), + class: 'doc-chart-axis-label', + 'text-anchor': 'middle', + }, + name, + ) + }) + } + canvas.replaceChildren(svg) } @@ -222,8 +261,14 @@ function svgEl( /** bar / line / area charts share the same axes and scale */ function drawAxes(svg: SVGElement, chart: ChartDisplay, geom: ChartGeom): void { const values = chart.series.flatMap((s) => s.values).filter((v): v is number => v !== null) - const max = Math.max(0, ...values) - const min = Math.min(0, ...values) + // "nice" axis bounds (1/2/5×10ⁿ step, integer-friendly labels like Word/LO) + const rawMax = Math.max(0, ...values) + const rawMin = Math.min(0, ...values) + const step = niceStep((rawMax - rawMin) / 5 || 1) + const min = Math.floor(rawMin / step) * step + // Word/LO leave headroom: the top tick sits strictly above the data maximum + let max = Math.ceil(rawMax / step) * step || step + if (rawMax > 0 && max <= rawMax + 1e-9) max += step const span = max - min || 1 const plotW = geom.width - geom.left - geom.right const plotH = geom.height - geom.top - geom.bottom @@ -232,9 +277,9 @@ function drawAxes(svg: SVGElement, chart: ChartDisplay, geom: ChartGeom): void { const slotW = plotW / cols // horizontal gridlines with value labels - const steps = 4 + const steps = Math.max(1, Math.round(span / step)) for (let i = 0; i <= steps; i++) { - const v = min + (span / steps) * i + const v = min + step * i const y = yOf(v) svgEl(svg, 'line', { x1: String(geom.left), @@ -454,14 +499,34 @@ export function textboxBoxStyle(box: TextboxDisplay): string { ) : null const waStyle = box.wordArtId ? WORDART_CSS[box.wordArtId] : undefined + // picture fill (photo boxes / a:blipFill): tiles repeat at natural size, + // stretch fills cover the whole box. Document data, hence inline. + const fillImage = box.fillImageDataUrl + ? `background-image:url("${box.fillImageDataUrl}");` + + (box.fillTile + ? 'background-repeat:repeat' + : 'background-repeat:no-repeat;background-size:100% 100%') + : '' + const transforms = [box.rotDeg ? `rotate(${box.rotDeg}deg)` : ''] + const floatPos = box.floating + ? `position:absolute;left:${((box.offsetXEmu ?? 0) / 9525).toFixed(1)}px;` + + `top:${((box.offsetYEmu ?? 0) / 9525).toFixed(1)}px` + : '' return [ geomCss ?? '', - !geomCss && box.fill ? `background:#${box.fill}` : '', + !geomCss && box.fill ? `background-color:#${box.fill}` : '', !geomCss && box.borderColor ? `border-color:#${box.borderColor}` : '', + !geomCss && box.borderColor && box.borderWidthPx ? `border-width:${box.borderWidthPx}px` : '', + !geomCss && box.borderColor && box.borderDash ? `border-style:${box.borderDash}` : '', + fillImage, + floatPos, box.widthPx ? `width:${box.widthPx}px` : '', // Word clips fixed-height (noAutofit) boxes instead of growing them box.heightPx ? `height:${box.heightPx}px` : '', `padding:${insetTop}px ${insetRight}px ${insetBottom}px ${insetLeft}px`, + transforms.filter(Boolean).length > 0 + ? `transform:${transforms.filter(Boolean).join(' ')}` + : '', waStyle?.color ? `-webkit-text-fill-color:${waStyle.color}` : '', waStyle?.stroke ? `-webkit-text-stroke:${waStyle.stroke}` : '', waStyle?.textShadow ? `text-shadow:${waStyle.textShadow}` : '', diff --git a/apps/docs/src/renderer/file-actions.ts b/apps/docs/src/renderer/file-actions.ts index 938d5c8..70fb507 100644 --- a/apps/docs/src/renderer/file-actions.ts +++ b/apps/docs/src/renderer/file-actions.ts @@ -723,6 +723,21 @@ export async function exportPdf(ctx: FileActionContext, outPath?: string): Promi if (last && last.w === w && last.h === h) last.to = i else groups.push({ w, h, from: i, to: i }) }) + // Chromium's printToPDF can non-deterministically paint later pages blank + // when one job carries hundreds of heavy pages (large table clones on + // 100+-page forms). Chunk long documents through the group-merge path so + // each print job stays small. + const PRINT_CHUNK = 40 + if (pvPages.length > 60) { + const chunked: typeof groups = [] + for (const g of groups) { + for (let s = g.from; s <= g.to; s += PRINT_CHUNK) { + chunked.push({ w: g.w, h: g.h, from: s, to: Math.min(s + PRINT_CHUNK - 1, g.to) }) + } + } + groups.length = 0 + groups.push(...chunked) + } if (groups.length > 1) { const parts: string[] = [] try { diff --git a/apps/docs/src/renderer/i18n/strings-ribbon.ts b/apps/docs/src/renderer/i18n/strings-ribbon.ts index b18a741..56e0e17 100644 --- a/apps/docs/src/renderer/i18n/strings-ribbon.ts +++ b/apps/docs/src/renderer/i18n/strings-ribbon.ts @@ -31,10 +31,6 @@ export const ribbonStrings = defineStrings({ ribbonRemoveBg: '去除背景', ribbonRemoveBgTip: '去除背景:基于颜色容差抠图(替换为透明 PNG)', ribbonCrop: '裁剪', - ribbonRotateRight: '向右旋转 90°', - ribbonRotateLeft: '向左旋转 90°', - ribbonFlipH: '水平翻转', - ribbonFlipV: '垂直翻转', ribbonCropTip: '裁剪图片(拖动手柄,Enter 确认)', ribbonCropHint: '拖动手柄或在框内拖动选择保留区域;Enter 应用,Esc 取消', ribbonReplacePicture: '替换图片', @@ -700,10 +696,6 @@ export const ribbonStrings = defineStrings({ ribbonRemoveBgTip: 'Remove background: color-tolerance cutout (replaced with a transparent PNG)', ribbonCrop: 'Crop', - ribbonRotateRight: 'Rotate Right 90°', - ribbonRotateLeft: 'Rotate Left 90°', - ribbonFlipH: 'Flip Horizontal', - ribbonFlipV: 'Flip Vertical', ribbonCropTip: 'Crop the picture (drag the handles, Enter to confirm)', ribbonCropHint: 'Drag the handles or move the box to choose the area to keep; Enter to apply, Esc to cancel', @@ -1361,10 +1353,6 @@ export const ribbonStrings = defineStrings({ ribbonRemoveBg: '背景の削除', ribbonRemoveBgTip: '背景の削除:色の許容差に基づく切り抜き(透明 PNG に置き換え)', ribbonCrop: 'トリミング', - ribbonRotateRight: '右へ90°回転', - ribbonRotateLeft: '左へ90°回転', - ribbonFlipH: '左右反転', - ribbonFlipV: '上下反転', ribbonCropTip: '画像をトリミング(ハンドルをドラッグ、Enter で確定)', ribbonCropHint: 'ハンドルをドラッグするか枠内を移動して残す範囲を選択。Enter で適用、Esc でキャンセル', @@ -2043,10 +2031,6 @@ export const ribbonStrings = defineStrings({ ribbonRemoveBg: '배경 제거', ribbonRemoveBgTip: '배경 제거: 색 허용 오차 기반 추출(투명 PNG로 대체)', ribbonCrop: '자르기', - ribbonRotateRight: '오른쪽으로 90° 회전', - ribbonRotateLeft: '왼쪽으로 90° 회전', - ribbonFlipH: '좌우 대칭', - ribbonFlipV: '상하 대칭', ribbonCropTip: '그림 자르기(핸들을 끌고 Enter 키로 확인)', ribbonCropHint: '핸들을 끌거나 상자를 이동해 유지할 영역을 선택하세요. Enter로 적용, Esc로 취소', @@ -2723,10 +2707,6 @@ export const ribbonStrings = defineStrings({ ribbonRemoveBgTip: "Supprimer l'arrière-plan : détourage par tolérance de couleur (remplacé par un PNG transparent)", ribbonCrop: 'Rogner', - ribbonRotateRight: 'Rotation 90° à droite', - ribbonRotateLeft: 'Rotation 90° à gauche', - ribbonFlipH: 'Retourner horizontalement', - ribbonFlipV: 'Retourner verticalement', ribbonCropTip: "Rogner l'image (faites glisser les poignées, Entrée pour confirmer)", ribbonCropHint: 'Faites glisser les poignées ou déplacez le cadre pour choisir la zone à conserver ; Entrée pour appliquer, Échap pour annuler', @@ -3395,10 +3375,6 @@ export const ribbonStrings = defineStrings({ ribbonRemoveBgTip: 'Hintergrund entfernen: Freistellen per Farbtoleranz (durch transparentes PNG ersetzt)', ribbonCrop: 'Zuschneiden', - ribbonRotateRight: '90° nach rechts drehen', - ribbonRotateLeft: '90° nach links drehen', - ribbonFlipH: 'Horizontal spiegeln', - ribbonFlipV: 'Vertikal spiegeln', ribbonCropTip: 'Bild zuschneiden (Ziehpunkte ziehen, Eingabetaste zum Bestätigen)', ribbonCropHint: 'Ziehpunkte ziehen oder Rahmen verschieben, um den zu behaltenden Bereich zu wählen; Eingabetaste zum Anwenden, Esc zum Abbrechen', @@ -4067,10 +4043,6 @@ export const ribbonStrings = defineStrings({ ribbonRemoveBgTip: 'Quitar fondo: recorte por tolerancia de color (reemplazado por un PNG transparente)', ribbonCrop: 'Recortar', - ribbonRotateRight: 'Girar 90° a la derecha', - ribbonRotateLeft: 'Girar 90° a la izquierda', - ribbonFlipH: 'Voltear horizontalmente', - ribbonFlipV: 'Voltear verticalmente', ribbonCropTip: 'Recortar la imagen (arrastre los controladores, Entrar para confirmar)', ribbonCropHint: 'Arrastre los controladores o mueva el cuadro para elegir el área que desea conservar; Entrar para aplicar, Esc para cancelar', @@ -4741,10 +4713,6 @@ export const ribbonStrings = defineStrings({ ribbonRemoveBg: 'เอาพื้นหลังออก', ribbonRemoveBgTip: 'เอาพื้นหลังออก: ตัดภาพตามค่าความคลาดเคลื่อนของสี (แทนที่ด้วย PNG โปร่งใส)', ribbonCrop: 'ครอบตัด', - ribbonRotateRight: 'หมุนขวา 90°', - ribbonRotateLeft: 'หมุนซ้าย 90°', - ribbonFlipH: 'พลิกแนวนอน', - ribbonFlipV: 'พลิกแนวตั้ง', ribbonCropTip: 'ครอบตัดรูปภาพ (ลากจุดจับ กด Enter เพื่อยืนยัน)', ribbonCropHint: 'ลากจุดจับหรือย้ายกรอบเพื่อเลือกพื้นที่ที่จะเก็บไว้ กด Enter เพื่อนำไปใช้ Esc เพื่อยกเลิก', @@ -5398,10 +5366,6 @@ export const ribbonStrings = defineStrings({ ribbonRemoveBgTip: 'Hapus latar belakang: pemotongan berdasarkan toleransi warna (diganti dengan PNG transparan)', ribbonCrop: 'Pangkas', - ribbonRotateRight: 'Putar Kanan 90°', - ribbonRotateLeft: 'Putar Kiri 90°', - ribbonFlipH: 'Balik Horizontal', - ribbonFlipV: 'Balik Vertikal', ribbonCropTip: 'Pangkas gambar (seret gagang, Enter untuk mengonfirmasi)', ribbonCropHint: 'Seret gagang atau pindahkan kotak untuk memilih area yang dipertahankan; Enter untuk menerapkan, Esc untuk membatalkan', @@ -6062,10 +6026,6 @@ export const ribbonStrings = defineStrings({ ribbonRemoveBg: 'Удалить фон', ribbonRemoveBgTip: 'Удалить фон: вырезание по допуску цвета (заменяется прозрачным PNG)', ribbonCrop: 'Обрезка', - ribbonRotateRight: 'Повернуть вправо на 90°', - ribbonRotateLeft: 'Повернуть влево на 90°', - ribbonFlipH: 'Отразить по горизонтали', - ribbonFlipV: 'Отразить по вертикали', ribbonCropTip: 'Обрезать рисунок (перетащите маркеры, Enter — подтвердить)', ribbonCropHint: 'Перетащите маркеры или переместите рамку, чтобы выбрать сохраняемую область; Enter — применить, Esc — отмена', @@ -6729,10 +6689,6 @@ export const ribbonStrings = defineStrings({ ribbonRemoveBg: 'إزالة الخلفية', ribbonRemoveBgTip: 'إزالة الخلفية: اقتصاص حسب تفاوت اللون (تُستبدل بصورة PNG شفافة)', ribbonCrop: 'اقتصاص', - ribbonRotateRight: 'تدوير لليمين 90 درجة', - ribbonRotateLeft: 'تدوير لليسار 90 درجة', - ribbonFlipH: 'انعكاس أفقي', - ribbonFlipV: 'انعكاس رأسي', ribbonCropTip: 'اقتصاص الصورة (اسحب المقابض، Enter للتأكيد)', ribbonCropHint: 'اسحب المقابض أو حرّك الإطار لاختيار المنطقة المراد الاحتفاظ بها؛ Enter للتطبيق وEsc للإلغاء', @@ -7387,10 +7343,6 @@ export const ribbonStrings = defineStrings({ ribbonRemoveBgTip: 'Remover plano de fundo: recorte por tolerância de cor (substituído por um PNG transparente)', ribbonCrop: 'Cortar', - ribbonRotateRight: 'Girar 90° para a direita', - ribbonRotateLeft: 'Girar 90° para a esquerda', - ribbonFlipH: 'Inverter horizontalmente', - ribbonFlipV: 'Inverter verticalmente', ribbonCropTip: 'Cortar a imagem (arraste as alças, Enter para confirmar)', ribbonCropHint: 'Arraste as alças ou mova a caixa para escolher a área a manter; Enter para aplicar, Esc para cancelar', @@ -8052,10 +8004,6 @@ export const ribbonStrings = defineStrings({ ribbonRemoveBgTip: 'Rimuovi sfondo: ritaglio in base alla tolleranza del colore (sostituito con un PNG trasparente)', ribbonCrop: 'Ritaglia', - ribbonRotateRight: 'Ruota a destra di 90°', - ribbonRotateLeft: 'Ruota a sinistra di 90°', - ribbonFlipH: 'Capovolgi orizzontalmente', - ribbonFlipV: 'Capovolgi verticalmente', ribbonCropTip: "Ritaglia l'immagine (trascina le maniglie, Invio per confermare)", ribbonCropHint: "Trascina le maniglie o sposta il riquadro per scegliere l'area da mantenere; Invio per applicare, Esc per annullare", @@ -8723,10 +8671,6 @@ export const ribbonStrings = defineStrings({ ribbonRemoveBgTip: 'Usuń tło: wycinanie na podstawie tolerancji koloru (zastąpione przezroczystym plikiem PNG)', ribbonCrop: 'Przytnij', - ribbonRotateRight: 'Obróć w prawo o 90°', - ribbonRotateLeft: 'Obróć w lewo o 90°', - ribbonFlipH: 'Odbij w poziomie', - ribbonFlipV: 'Odbij w pionie', ribbonCropTip: 'Przytnij obraz (przeciągnij uchwyty, Enter, aby potwierdzić)', ribbonCropHint: 'Przeciągnij uchwyty lub przesuń ramkę, aby wybrać obszar do zachowania; Enter, aby zastosować, Esc, aby anulować', @@ -9389,10 +9333,6 @@ export const ribbonStrings = defineStrings({ ribbonRemoveBgTip: 'Achtergrond verwijderen: uitsnijden op basis van kleurtolerantie (vervangen door een transparante PNG)', ribbonCrop: 'Bijsnijden', - ribbonRotateRight: '90° rechtsom draaien', - ribbonRotateLeft: '90° linksom draaien', - ribbonFlipH: 'Horizontaal spiegelen', - ribbonFlipV: 'Verticaal spiegelen', ribbonCropTip: 'De afbeelding bijsnijden (sleep de grepen, Enter om te bevestigen)', ribbonCropHint: 'Sleep de grepen of verplaats het kader om het te behouden gebied te kiezen; Enter om toe te passen, Esc om te annuleren', @@ -10059,10 +9999,6 @@ export const ribbonStrings = defineStrings({ ribbonRemoveBgTip: 'Alih keluar latar belakang: potongan berdasarkan toleransi warna (digantikan dengan PNG lutsinar)', ribbonCrop: 'Pangkas', - ribbonRotateRight: 'Putar Kanan 90°', - ribbonRotateLeft: 'Putar Kiri 90°', - ribbonFlipH: 'Balikkan Melintang', - ribbonFlipV: 'Balikkan Menegak', ribbonCropTip: 'Pangkas gambar (seret pemegang, Enter untuk mengesahkan)', ribbonCropHint: 'Seret pemegang atau alihkan kotak untuk memilih kawasan yang hendak dikekalkan; Enter untuk menggunakan, Esc untuk membatalkan', @@ -10724,10 +10660,6 @@ export const ribbonStrings = defineStrings({ ribbonRemoveBg: 'הסרת רקע', ribbonRemoveBgTip: 'הסרת רקע: חיתוך לפי סבילות צבע (מוחלף ב-PNG שקוף)', ribbonCrop: 'חיתוך', - ribbonRotateRight: 'סיבוב 90° ימינה', - ribbonRotateLeft: 'סיבוב 90° שמאלה', - ribbonFlipH: 'היפוך אופקי', - ribbonFlipV: 'היפוך אנכי', ribbonCropTip: 'חיתוך התמונה (גרור את הידיות, Enter לאישור)', ribbonCropHint: 'גרור את הידיות או הזז את המסגרת כדי לבחור את האזור שיישמר; Enter להחלה, Esc לביטול', @@ -11378,10 +11310,6 @@ export const ribbonStrings = defineStrings({ ribbonRemoveBgTip: 'पृष्ठभूमि हटाएँ: रंग सहनशीलता के आधार पर कटआउट (पारदर्शी PNG से बदला जाता है)', ribbonCrop: 'काट-छाँट करें', - ribbonRotateRight: '90° दाएँ घुमाएँ', - ribbonRotateLeft: '90° बाएँ घुमाएँ', - ribbonFlipH: 'क्षैतिज पलटें', - ribbonFlipV: 'लंबवत पलटें', ribbonCropTip: 'चित्र की काट-छाँट करें (हैंडल खींचें, पुष्टि के लिए Enter दबाएँ)', ribbonCropHint: 'रखे जाने वाले क्षेत्र को चुनने के लिए हैंडल खींचें या बॉक्स को हिलाएँ; लागू करने के लिए Enter, रद्द करने के लिए Esc', @@ -12044,10 +11972,6 @@ export const ribbonStrings = defineStrings({ ribbonRemoveBg: '移除背景', ribbonRemoveBgTip: '移除背景:依色彩容許度去背(取代為透明 PNG)', ribbonCrop: '裁剪', - ribbonRotateRight: '向右旋轉 90°', - ribbonRotateLeft: '向左旋轉 90°', - ribbonFlipH: '水平翻轉', - ribbonFlipV: '垂直翻轉', ribbonCropTip: '裁剪圖片(拖曳控點,Enter 確認)', ribbonCropHint: '拖曳控點或在框內拖曳以選擇保留區域;Enter 套用,Esc 取消', ribbonReplacePicture: '取代圖片', diff --git a/apps/docs/src/renderer/line-metrics.ts b/apps/docs/src/renderer/line-metrics.ts index 1afea2b..29dbd7a 100644 --- a/apps/docs/src/renderer/line-metrics.ts +++ b/apps/docs/src/renderer/line-metrics.ts @@ -100,8 +100,15 @@ const KO_FONT_RE = /malgun|맑은|batang|바탕|myeongjo|myungjo|명조|gungsuh|궁서|gulim|굴림|dotum|돋움|nanum|나눔|genoffice (sans|serif) kr|(noto|source han) (sans|serif)[^,]*\bk(r|orean)?\b/i /** - * Per-font line-height factor (based on measured Windows font metrics). - * PMingLiU/MingLiU: ~1.0em; SimSun and other Simplified fonts: ~1.3em; Western: 1.2em. + * Per-font single-spacing line-height factor, matched to the LibreOffice + * baseline on this platform (probe docx converted with soffice, one paragraph + * per family, line pitch ÷ font size measured from the PDF — 2026-08-10). + * LO lays lines out with the *substituted* macOS face's hhea metrics + * (including its line gap), which is why the CJK values are far above the + * Windows-font 1.3 that Word uses: SimSun maps to the Songti-class 1.7, + * missing GB faces to the PingFang-class 1.775, MS Mincho to the + * Hiragino-class 1.7, and Yu Mincho to 2.2667 because of its large line gap. + * SimHei, KaiTi, and PMingLiU use compact 1.0em macOS substitutes. */ export function lineHeightFactor(fontFamily: string): number { const f = fontFamily.toLowerCase() @@ -109,45 +116,59 @@ export function lineHeightFactor(fontFamily: string): number { if (f.includes('pmingliu') || f.includes('mingliu') || f.includes('細明體')) { return 1.0 } - // Korean faces: Word lays out East Asian auto line rule at winTotal × 1.3 - // (probe-verified vs Word PDFs): Malgun 1.3301 × 1.3 ≈ 1.73, Batang/Gulim 1.0 × 1.3 - if (KO_FONT_RE.test(f)) return /malgun|맑은/.test(f) ? 1.73 : 1.3 - // Noto/Source Han SC declares substitute into the SimSun class when missing - // (bundled subsets count as missing), so they take the SimSun factor - if (/^(noto|source han) (sans|serif)( cjk)? ?(sc|cn)\b/.test(f)) return 1.3 - // expanded Simplified Chinese fonts (SimSun/NSimSun/SimHei/FangSong/KaiTi/Microsoft YaHei) + // Korean faces (probe: Malgun 1.775, Batang/Gulim 1.4583) + if (KO_FONT_RE.test(f)) return /malgun|맑은/.test(f) ? 1.775 : 1.4583 + // Japanese faces: MS (P)Mincho/Gothic substitute into the Hiragino class + // (1.7); Yu Mincho/Gothic carry a very large line gap (2.2667); Meiryo 1.775 + if (/游|yu (gothic|mincho)|yugoth|yumin/.test(f)) return 2.2667 + if (/meiryo|メイリオ/.test(f)) return 1.775 + if (/mincho|明朝|ゴシック|ms (ui )?p?gothic|hiragino|osaka|kozuka|小塚|biz ud/.test(f)) return 1.7 + // Noto/Source Han SC (matches the PingFang substitution class) + if (/^noto sans sc$/.test(f)) return 1.8375 + if (/^(noto|source han) (sans|serif)( cjk)? ?(sc|cn)\b/.test(f)) return 1.775 + // Songti class (installed Songti SC / STSong) + if (f.includes('simsun') || f.includes('nsimsun') || f.includes('宋体')) return 1.7 + if (/(^|\s)(songti|stsong)\b/.test(f)) return 1.7 + if (/zhongsong|xiaobiaosong|中宋|小标宋/.test(f)) return 1.775 + // Compact macOS Heiti/Kaiti substitutes for SimHei and bare KaiTi names. + if (f.includes('黑体') || f.includes('simhei')) return 1.0 + if ((f.includes('楷体') || f.includes('kaiti')) && !/gb2312|_gbk|gbk/.test(f)) return 1.0 + // missing GB faces and other zh names substitute into the PingFang class if ( - f.includes('simsun') || - f.includes('nsimsun') || - f.includes('宋体') || - f.includes('黑体') || + f.includes('仿宋') || f.includes('fangsong') || + f.includes('楷体') || f.includes('kaiti') || + f.includes('宋') || // Song-family display faces and related variants f.includes('microsoft yahei') || f.includes('microsoftyahei') || + f.includes('雅黑') || f.includes('dengxian') || f.includes('等线') || - f.includes('simhei') || f.includes('simfang') || f.includes('simkai') ) { - return 1.3 + return 1.775 } - // Western single-line factors follow each font's hhea metrics (Word's single - // spacing): a 4% surplus per line cascades into whole-paragraph pagination - // drift, so the big Office faces get their real values. + // Traditional Chinese sans/kai faces use the PingFang TC class. + if (/jhenghei|正黑|標楷|biaukai|dfkai|kaiu/.test(f)) return 1.775 + // Western single-line factors follow each font's hhea metrics (LO probe): + // a 4% surplus per line cascades into whole-paragraph pagination drift, + // so the big Office faces get their real values. if (f.includes('times') || f.includes('liberation serif')) return 1.15 - if (f.includes('georgia')) return 1.14 + if (f.includes('georgia')) return 1.1375 if (f.includes('cambria') || f.includes('caladea')) return 1.17 - if ( - f === 'arial' || - f.startsWith('arial ') || - f.includes('helvetica') || - f.includes('liberation sans') - ) - return 1.15 + if (f.includes('helvetica')) return 1.0 + if (f === 'arial' || f.startsWith('arial ') || f.includes('liberation sans')) return 1.15 if (f.includes('calibri') || f.includes('carlito')) return 1.22 - // default (Lato, Segoe, unknown Western) + if (f.includes('tahoma')) return 1.2083 + if (f.includes('verdana')) return 1.2167 + if (f.includes('courier')) return 1.1333 + if (f.includes('consolas')) return 1.1667 + if (f.includes('century') && !f.includes('gothic')) return 1.15 + if (f.includes('book antiqua')) return 1.1 + if (f.includes('segoe')) return 1.15 + // default (Lato, unknown Western) return 1.2 } @@ -210,31 +231,28 @@ export function computeLineHeight( lineRawTwips: number | undefined, docGrid: DocGrid | undefined, ): number { - let lineH: number + // typed line grid (LO probe 2026-08-10): single/auto lines snap UP to whole + // linePitch cells BEFORE the auto multiple applies; exact/atLeast never snap + const pitchPx = + docGrid && (docGrid.type === 'lines' || docGrid.type === 'linesAndChars') && docGrid.linePitch + ? docGrid.linePitch * TWIPS_TO_PX + : 0 + const snapped = pitchPx > 0 ? Math.ceil(naturalLineH / pitchPx - 0.001) * pitchPx : naturalLineH if (lineRule === 'exact' && lineRawTwips !== undefined) { // fixed line height: use the specified value regardless of font size - lineH = lineRawTwips * TWIPS_TO_PX - } else if (lineRule === 'atLeast' && lineRawTwips !== undefined) { - // at least: max(font natural line height, specified value) - lineH = Math.max(naturalLineH, lineRawTwips * TWIPS_TO_PX) - } else if (lineRule === 'auto' && lineRawTwips !== undefined) { - // multiple: naturalLineH * (lineRawTwips / 240) - lineH = naturalLineH * (lineRawTwips / 240) - } else { - // default (no lineRule): single spacing - lineH = naturalLineH + return lineRawTwips * TWIPS_TO_PX } - - // docGrid: real Word for Mac baseline (2026-07-27, line-by-line PDF measurement of - // corpora 02/10) shows line heights are NOT rounded to linePitch — 12pt with line - // spacing 276 (1.15×) lays out at 18pt/line, not the 15.6 or 31.2 grid multiples; - // space-after is also left unrounded. The earlier round-up was tuned to LibreOffice - // behavior and halved lines-per-page for docGrid documents (7 pages vs Word's 4). - // The docGrid param stays: other semantics like lines-per-page rulers may still need it. - void docGrid - - return lineH + if (lineRule === 'atLeast' && lineRawTwips !== undefined) { + // at least: max(font natural line height, specified value), unsnapped + return Math.max(naturalLineH, lineRawTwips * TWIPS_TO_PX) + } + if (lineRule === 'auto' && lineRawTwips !== undefined) { + // multiple: snapped base × (lineRawTwips / 240) + return snapped * (lineRawTwips / 240) + } + // default (no lineRule): single spacing on the grid + return snapped } /** @@ -494,14 +512,14 @@ export function textHasHangul(text: string): boolean { /** Per-paragraph --doc-line-factor value by script (approximates Word's max-of-inline-fonts line height) */ export function paraLineFactorCss(text: string): string { - if (textHasHangul(text)) return 'var(--doc-line-factor-kr,1.3)' - if (textHasCjk(text)) return '1.3' + if (textHasHangul(text)) return 'var(--doc-line-factor-kr,1.4583)' + if (textHasCjk(text)) return 'var(--doc-line-factor-cjk,1.7)' return 'var(--doc-line-factor-latin,1.2)' } /** --doc-line-factor-kr source: the document's East Asian face when Korean, else the Batang-class default */ export function krLineFactor(fontFamily: string | undefined): number { - return fontFamily && isKoreanFontName(fontFamily) ? lineHeightFactor(fontFamily) : 1.3 + return fontFamily && isKoreanFontName(fontFamily) ? lineHeightFactor(fontFamily) : 1.4583 } export function isKoreanFontName(fontFamily: string): boolean { @@ -514,9 +532,33 @@ export function isKoreanFontName(fontFamily: string): boolean { * Line rules: auto = multiple × font natural line height; atLeast = max(natural, N); exact = N. * CSS expression: natural line height ≈ var(--doc-line-factor) (line-height factor * of the document's default Chinese font, injected by docStyleCss; default 1.2) × 1em. - * The canvas previously used a uniform lineSpacing×1.2, which made Chinese documents - * (factor 1.3) systematically too tight and dropped atLeast/exact entirely. + * + * docGrid (LO probe, 2026-08-10): in sections with a typed line grid + * (w:docGrid lines/linesAndChars) single/auto-multiple lines snap UP to a + * whole number of linePitch cells and the multiple applies AFTER snapping; + * exact and atLeast lines never snap; w:snapToGrid=0 opts a paragraph out. + * --doc-grid-pitch is set on .doc-page only for grid documents (a paragraph + * override resets it); without it round(up, X, ~0) degrades to X, so the same + * expression serves both grid and normal documents. */ +const GRID_PITCH = 'var(--doc-grid-pitch,0.0001px)' + +/** single-spacing natural line height, snapped up to the doc grid when one exists */ +export function cssGridLineBase(): string { + return `round(up, calc(var(--doc-line-factor,1.2) * 1em), ${GRID_PITCH})` +} + +/** + * Paragraph space before/after (pt) as a CSS margin value. In typed-grid + * documents LO quantizes paragraph spacing DOWN to whole grid cells (probe + + * corpus 12063517: before/after 6pt vanish on a 15.6pt grid — boundary pitch + * stays 46.8 flat); without a grid round(down, X, ~0) degrades to X. + */ +export function cssGridSpacingPt(pt: number): string { + const v = `${pt.toFixed(1)}pt` + return pt > 0 ? `round(down, ${v}, ${GRID_PITCH})` : v +} + export function cssLineHeight( lineRule: 'auto' | 'atLeast' | 'exact' | undefined, lineRawTwips: number | undefined, @@ -524,11 +566,13 @@ export function cssLineHeight( ): string | null { const FACTOR = 'var(--doc-line-factor,1.2)' if (lineRule === 'exact' && lineRawTwips) return `${(lineRawTwips / 20).toFixed(1)}pt` - if (lineRule === 'atLeast' && lineRawTwips) { + if (lineRule === 'atLeast' && lineRawTwips != null) { + // atLeast never snaps to the grid; line="0" atLeast degrades to plain natural height + if (lineRawTwips === 0) return `calc(${FACTOR} * 1em)` return `max(${(lineRawTwips / 20).toFixed(1)}pt, calc(${FACTOR} * 1em))` } const m = lineSpacing ?? (lineRule === 'auto' && lineRawTwips ? lineRawTwips / 240 : undefined) - if (m) return `calc(${FACTOR} * ${m})` + if (m) return m === 1 ? cssGridLineBase() : `calc(${cssGridLineBase()} * ${m})` return null } @@ -536,9 +580,18 @@ export function cssLineHeight( * Space-before/space-after, aligned to the grid when docGrid exists. */ export function snapSpacingToGrid(spacingTwips: number, docGrid: DocGrid | undefined): number { - // real Word baseline measurement: space-before/after are not rounded to the grid (corpus 10-cn: 240tw space-after lays out at ~8pt, the original value) - void docGrid - return spacingTwips * TWIPS_TO_PX + const px = spacingTwips * TWIPS_TO_PX + // typed line grid: LO quantizes paragraph spacing DOWN to whole grid cells + // (probe 2026-08-10: 6pt before/after vanish on a 15.6pt grid) + if ( + docGrid && + (docGrid.type === 'lines' || docGrid.type === 'linesAndChars') && + docGrid.linePitch + ) { + const pitch = docGrid.linePitch * TWIPS_TO_PX + return Math.floor(px / pitch + 0.001) * pitch + } + return px } // ─── CJK detection ─────────────────────────────────────────────────────────── @@ -624,13 +677,25 @@ export function autospaceBoundaries(text: string): number[] { /** * CJK character line-height factor (by font family). - * PMingLiU/MingLiU (compact Traditional) → 1.0: the font's lineHeight is already 1.0×, no extra boost. - * Other fonts (SimSun/SimHei/Calibri etc.) → 1.3: CJK chars render via SimSun fallback with ~1.3em line height. + * Known CJK families take their LO-probe factor (lineHeightFactor); CJK text + * inside Latin-font runs falls through LO's font fallback (~1.3 on this + * platform), so the legacy 1.3 stays as the default. */ +/** Font name plausibly covering CJK glyphs (drives whether a declared face may + * set the CJK line factor; Latin names cascade to the document's EA default). */ +export function isCjkFontName(fontFamily: string): boolean { + const f = fontFamily.toLowerCase() + return CJK_FONT_NAME_RE.test(f) || KO_FONT_RE.test(f.normalize('NFKC')) +} + +const CJK_FONT_NAME_RE = + /宋|黑|楷|仿|明|雅黑|等线|simsun|simhei|simkai|simfang|kaiti|fangsong|songti|stsong|yahei|dengxian|mingliu|jhenghei|biaukai|dfkai|kaiu|mincho|ms (ui )?p?gothic|yu gothic|ゴシック|meiryo|メイリオ|hiragino|osaka|kozuka|游|(noto|source han) (sans|serif)( cjk)? ?(sc|cn|jp|tc|kr)\b/i + function cjkLineHFactor(fontFamily: string): number { const f = fontFamily.toLowerCase() if (f.includes('pmingliu') || f.includes('mingliu')) return 1.0 if (KO_FONT_RE.test(f)) return lineHeightFactor(fontFamily) + if (CJK_FONT_NAME_RE.test(f)) return lineHeightFactor(fontFamily) return 1.3 } diff --git a/apps/docs/src/renderer/pagination.ts b/apps/docs/src/renderer/pagination.ts index 88b4526..70a4c1d 100644 --- a/apps/docs/src/renderer/pagination.ts +++ b/apps/docs/src/renderer/pagination.ts @@ -906,6 +906,26 @@ export function effectiveBottomPx(set: SectionSettings, footerPx: number): numbe return Math.max(twipsToPx(set.marginBottom), footerPx > 0 ? dist + footerPx : 0) } +/** + * Uniform typed line grid (w:docGrid type lines/linesAndChars): the pitch in + * points when EVERY section declares the same typed pitch, else null. Mixed or + * untyped docs don't snap (matches LO only for the uniform case; per-section + * pitches would need per-block plumbing, and mixed-grid docs are rare). + * The value feeds .doc-page { --doc-grid-pitch } which line-height round(up) + * expressions consume. + */ +export function docGridPitchPt(sections: SectionInfo[]): number | null { + if (sections.length === 0) return null + let pitch: number | null = null + for (const s of sections) { + const g = s.settings.docGrid + if (!g || (g.type !== 'lines' && g.type !== 'linesAndChars') || !g.linePitch) return null + if (pitch === null) pitch = g.linePitch + else if (pitch !== g.linePitch) return null + } + return pitch === null ? null : pitch / 20 +} + /** Equal-width column count of a section (w:cols w:num). * equalWidth="0" (local layout columns in PDF-converted docs, varying widths) is not modeled; treated as 1 column */ export function sectionColumns(s: SectionInfo): number { diff --git a/apps/docs/src/renderer/styles.css b/apps/docs/src/renderer/styles.css index 01162f0..85fd358 100644 --- a/apps/docs/src/renderer/styles.css +++ b/apps/docs/src/renderer/styles.css @@ -3178,6 +3178,9 @@ th.cell-rev-del { .pv-page { position: relative; + /* own stacking context: behind-text layers (picture watermarks, z-index -1) + must stay above this page's background, not sink under it */ + isolation: isolate; margin: 0 auto 24px; background: var(--docs-paper); box-shadow: var(--docs-page-shadow); @@ -3193,10 +3196,24 @@ th.cell-rev-del { overflow: hidden; } -/* clip at the paper edge, not the content box: over-wide tables bleed into the margin - like Word (keep overflow hidden — print pagination needs the box monolithic) */ +/* header picture watermark (absolute VML shape): drawn once per preview page, + behind the body text. Document content: renders identically in both themes. */ +.pv-watermark-img { + position: absolute; + z-index: -1; + pointer-events: none; +} + +/* clip at the paper edge, not the content box: over-wide tables bleed into the right + margin like Word (keep overflow hidden — print pagination needs the box monolithic). + Left side symmetrically: negative w:tblInd tables start inside the left margin, and + clipping at the content box culled their leading characters from the exported text. + The padding compensates the negative margin so the content position is unchanged — + only the clip edge moves out to the paper edge. */ .pv-page > .pv-clip { margin-right: calc(-1 * var(--pv-mr, 0px)); + margin-left: calc(-1 * var(--pv-ml, 0px)); + padding-left: var(--pv-ml, 0px); } /* column flow: regions stack vertically; narrow clipped columns sit side by side within a region */ @@ -3466,6 +3483,20 @@ th.cell-rev-del { .doc-table th { position: relative; box-sizing: border-box; + /* the w:docGrid line grid applies to the body flow only — Word/LO never snap + table-cell lines to it (grid docs' scoring tables would inflate ~50%) */ + --doc-grid-pitch: 0.0001px; +} + +/* empty paragraph in a cell: LO sizes it near the Latin single line, so it must + not out-grow the row's content cells via the inherited CJK factor */ +.doc-table td .doc-p-empty, +.doc-table th .doc-p-empty { + --doc-line-factor: var(--doc-line-factor-latin, 1.2); +} + +.doc-table td, +.doc-table th { /* undeclared borders render as none (Word's on-screen gridlines are non-printing view furniture, not part of the document); w:tblBorders drives --doc-b-* */ border-top: var(--doc-b-h, none); @@ -3662,6 +3693,22 @@ th.cell-rev-del { border-color: var(--border); } +/* floating drawings (wrapNone/front/behind anchors, or several drawings + anchored in one paragraph): the wrapper marks the anchor paragraph's flow + position but takes no flow height — each box positions absolutely at its + own offset, overlapping body text exactly like Word */ +.doc-protected.doc-protected-floating { + position: relative; + height: 0; + min-height: 0; + padding: 0; + margin: 0; + border: none; + width: 100%; + max-width: 100%; + overflow: visible; +} + .doc-protected.doc-protected-textboxes.ProseMirror-selectednode { border-color: var(--word-blue); outline: none; @@ -3812,7 +3859,11 @@ th.cell-rev-del { .doc-protected-field { border-color: transparent; background: transparent; - padding: 2px 4px; + /* no vertical padding/margin: field paragraphs (TOC entries, filled text + fields) must occupy paragraph-height boxes or pagination drifts; document + CSS (docStyleCss blockSel + [data-style]) supplies the real spacing */ + padding: 0 4px; + margin: 0; cursor: default; user-select: none; -webkit-user-select: none; @@ -3826,8 +3877,10 @@ th.cell-rev-del { display: flex; align-items: baseline; gap: 4px; - font-size: 11pt; - line-height: 1.7; + /* inherit the document's paragraph metrics: a hardcoded 11pt/1.7 line made + every TOC entry ~50% taller than Word/LO and drifted long TOCs a page+ */ + font-size: inherit; + line-height: inherit; cursor: pointer; } @@ -3856,9 +3909,11 @@ th.cell-rev-del { .doc-toc-dots { flex: 1; - border-bottom: 2px dotted var(--docs-paper-ink-mid); - transform: translateY(-3px); min-width: 24px; + overflow: hidden; + white-space: nowrap; + letter-spacing: 2px; + user-select: none; } .doc-field-pagebreak { @@ -3878,8 +3933,8 @@ th.cell-rev-del { } .doc-field-text { - font-size: 11pt; - line-height: 1.7; + font-size: inherit; + line-height: inherit; } .doc-content-editing .doc-toc-title, @@ -3993,6 +4048,18 @@ th.cell-rev-del { fill: var(--docs-paper-ink-faint); } +/* data grid is an editing affordance: visible while the chart block is + selected or in text-edit mode; the printed/preview chart shows only the plot + (Word/LO behavior) */ +.doc-protected .doc-chart-data { + display: none; +} + +.doc-protected.ProseMirror-selectednode .doc-chart-data, +.doc-protected.doc-content-editing .doc-chart-data { + display: table; +} + .doc-chart-data { border-collapse: collapse; align-self: center; @@ -4074,6 +4141,49 @@ th.cell-rev-del { white-space: pre-line; } +/* SmartArt degrade: precomputed diagram shapes at absolute positions. + Shape/text colors are document data — inline per shape, never themed. */ +.doc-diagram { + position: relative; + display: inline-block; + overflow: hidden; + max-width: 100%; + vertical-align: top; +} + +.doc-diagram-shape { + position: absolute; + overflow: hidden; + display: flex; + align-items: center; + justify-content: center; + text-align: center; + white-space: pre-line; + line-height: 1.15; +} + +.doc-diagram-text { + position: relative; + z-index: 1; + padding: 0 4px; +} + +/* drawing canvas (lockedCanvas): text keeps its raw font size and overflows + the scaled child geometry downward instead of clipping (LO behavior) */ +.doc-diagram-canvas, +.doc-diagram-canvas .doc-diagram-shape { + overflow: visible; +} + +.doc-diagram-canvas .doc-diagram-shape { + align-items: flex-start; +} + +.doc-diagram-canvas .doc-diagram-text { + word-break: break-all; + line-height: 1.2; +} + /* OLE embed degrade: the packaged preview picture + a friendly type caption */ .doc-protected-ole .doc-ole-wrap { display: block; @@ -4090,6 +4200,23 @@ th.cell-rev-del { display: block; } +/* SmartArt / drawing-canvas blocks: the shapes are the content — no chip box */ +.doc-protected-diagram { + border-color: transparent; + background: none; +} + +.doc-protected-diagram:hover { + border-color: var(--border); +} + +/* srcRect crop windows carry the declared extent inline; the float wrap's + 60% clamp must not squeeze them (Word keeps the placed size and lets the + picture reach into the margin instead) */ +.doc-protected .doc-img-crop { + max-width: none; +} + /* image blocks: no chip chrome, selection border with resize handle */ .doc-protected[data-doc-protected='image'] { border-color: transparent; @@ -5154,10 +5281,55 @@ body.docs-crop-active height: 20px; } -.ai-msg-tool-btn:hover { +.ai-msg-tool-btn:hover:not(:disabled) { background: var(--color-bg-subtle); } +.ai-msg-tool-btn:disabled { + opacity: 0.45; + cursor: default; +} + +/* Hairline before the roll-back action; hidden unless an icon action precedes it */ +.ai-rollback-sep { + display: none; + width: 1px; + height: 14px; + align-self: center; + background: var(--border); +} + +.ai-msg-tool-btn ~ .ai-rollback-sep { + display: block; +} + +/* Quiet roll-back in the message toolbar (after copy/regenerate): dim at rest, solid on hover */ +.ai-rollback-btn { + display: inline-flex; + align-items: center; + gap: 4px; + flex-shrink: 0; + height: 30px; + border: none; + background: none; + color: var(--text-dim); + font-size: 12px; + font-family: inherit; + padding: 0 8px; + border-radius: 6px; + cursor: pointer; +} + +.ai-rollback-btn:hover:not(:disabled) { + color: var(--text); + background: var(--hover); +} + +.ai-rollback-btn:disabled { + opacity: 0.5; + cursor: default; +} + .ai-msg-tool-btn:focus-visible { outline: none; box-shadow: 0 0 0 3px var(--docs-focus-ring-blue); @@ -5219,75 +5391,6 @@ body.docs-crop-active filter: brightness(0.94); } -.ai-versions { - border-top: 1px solid var(--border); - padding: 8px 14px 10px; - max-height: 150px; - overflow-y: auto; -} - -.ai-versions-title { - display: flex; - align-items: center; - gap: 5px; - font-size: 11.5px; - font-weight: 600; - color: var(--text-dim); - margin-bottom: 4px; -} - -.ai-version-row { - display: flex; - justify-content: space-between; - align-items: center; - gap: 8px; - font-size: 12px; - padding: 4px 8px; - margin: 0 -8px; - border-radius: 6px; -} - -.ai-version-row:hover { - background: var(--hover); -} - -.ai-version-label { - display: flex; - align-items: baseline; - gap: 8px; - overflow: hidden; - white-space: nowrap; - color: var(--text); - min-width: 0; -} - -.ai-version-label > :last-child { - overflow: hidden; - text-overflow: ellipsis; -} - -.ai-version-time { - flex-shrink: 0; - font-size: 11px; - color: var(--text-dim); - font-variant-numeric: tabular-nums; -} - -.ai-version-rollback { - flex-shrink: 0; - border: none; - background: none; - color: var(--word-blue); - font-size: 12px; - padding: 2px 8px; - border-radius: 5px; - cursor: pointer; -} - -.ai-version-rollback:hover { - background: var(--active-bg); -} - .ai-msg-error { margin-top: 6px; color: var(--docs-ai-error); @@ -5652,6 +5755,38 @@ body.docs-crop-active color: var(--text-muted); } +/* attachments echoed on a sent user message (read-only: no remove button, smaller thumbs) */ +.ai-msg-attachments { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin-bottom: 6px; +} + +.ai-msg-attachments .ai-attachment-thumb img { + width: 44px; + height: 44px; + border-radius: 8px; +} + +.ai-msg-attachments .ai-attachment-card { + width: auto; + max-width: 190px; + height: 44px; + background: var(--surface); +} + +.ai-msg-attachments .ai-attachment-card-icon { + width: 32px; + height: 32px; + background: var(--surface-subtle); +} + +.ai-msg-attachments .ai-attachment-card-icon img { + width: 22px; + height: 22px; +} + .ai-attachment-chip { display: inline-flex; align-items: center; @@ -6024,6 +6159,19 @@ body.docs-crop-active white-space: pre-wrap; } +/* The pagination-preview clone must lay out exactly like the editor canvas it + was measured on. ProseMirror's whitespace/ligature rules are part of that + layout: without them whitespace-only lines collapse in the clone, every + following page window drifts upward, and page-boundary content prints twice + (once clipped at a page bottom, once at the next page top). */ +.pv-content { + word-wrap: break-word; + white-space: break-spaces; + -webkit-font-variant-ligatures: none; + font-variant-ligatures: none; + font-feature-settings: 'liga' 0; +} + .ProseMirror:focus { outline: none; } @@ -6221,6 +6369,34 @@ body.docs-crop-active display: none !important; } + /* editor-only affordance chips: Word/LibreOffice print the object (or nothing), + never a type label — the label text must not leak into exported PDFs */ + .doc-protected-label { + display: none !important; + } + + /* more editor-only markers whose text leaks into the exported text layer: + transparent ink still emits glyphs into the PDF, so they must not paint at + all. visibility (not display) keeps their layout box — pagination sliced + the canvas with these boxes in the flow. */ + .doc-sectbreak-label { + visibility: hidden !important; + } + + .doc-note-ref::before, + .doc-note-ref::after { + visibility: hidden !important; + } + + /* content-control chrome: Word prints the content only, no box or alias tag */ + .has-sdt { + border-color: transparent !important; + } + + .has-sdt::before { + display: none !important; + } + .app, .workspace, .editor-scroll { @@ -6269,6 +6445,19 @@ body.docs-crop-active display: none !important; } + /* opacity:0 chrome still emits glyphs into the PDF text layer */ + .doc-move-handle { + display: none !important; + } + + /* selection highlight is UI state: the auto-selected first node must not + print a blue plate/border */ + .doc-protected.ProseMirror-selectednode { + border-color: transparent !important; + outline: none !important; + background: none !important; + } + /* continuous-flow printing still delegates to Chromium auto-pagination; canvas page gaps don't take part */ .page-gap { display: none !important; @@ -6565,6 +6754,15 @@ body.docs-crop-active cursor: default; } +/* editor-only affordance brackets around the note number; hidden when printing */ +.doc-note-ref::before { + content: '['; +} + +.doc-note-ref::after { + content: ']'; +} + .doc-note-ref.ProseMirror-selectednode { outline: 2px solid var(--word-blue); border-radius: 2px; diff --git a/apps/docs/tests/chart-edit.test.ts b/apps/docs/tests/chart-edit.test.ts index b2433d3..1fe1d7f 100644 --- a/apps/docs/tests/chart-edit.test.ts +++ b/apps/docs/tests/chart-edit.test.ts @@ -22,7 +22,7 @@ describe('embedded chart editing', () => { const chart = editor.view.dom.querySelector('.doc-protected-chart') as HTMLElement expect(chart).toBeTruthy() expect(chart.querySelector('.doc-chart-title')?.textContent).toBe('销售统计') - expect(chart.querySelectorAll('.doc-chart-svg rect').length).toBe(5) // 6 slots - 1 gap + expect(chart.querySelectorAll('.doc-chart-svg rect').length).toBe(7) // 6 slots - 1 gap + 2 legend swatches expect(chart.querySelectorAll('.doc-chart-cat').length).toBe(3) expect(chart.querySelectorAll('.doc-chart-val').length).toBe(5) expect(chart.querySelectorAll('.doc-chart-gap').length).toBe(1) diff --git a/apps/docs/tests/doc-theme-css.test.ts b/apps/docs/tests/doc-theme-css.test.ts index 9f79111..cf35d0c 100644 --- a/apps/docs/tests/doc-theme-css.test.ts +++ b/apps/docs/tests/doc-theme-css.test.ts @@ -51,30 +51,30 @@ describe('docLineFactor — CJK factor source', () => { it("Normal's declared EA face wins over docDefaults", () => { const parsed = parsedWith({ font: 'Noto Sans KR', fontAscii: 'Calibri' }, 'SimSun') - expect(docLineFactor(parsed, true)).toBe(1.3) + expect(docLineFactor(parsed, true)).toBe(1.4583) }) it('a Latin-only Normal (font === fontAscii) does not override the docDefaults EA font', () => { const parsed = parsedWith({ font: 'Calibri', fontAscii: 'Calibri' }, 'SimSun') - expect(docLineFactor(parsed, true)).toBe(1.3) + expect(docLineFactor(parsed, true)).toBe(1.7) }) it('falls back to the SimSun-class factor without any declared EA font', () => { - expect(docLineFactor(parsedWith(undefined), true)).toBe(1.3) + expect(docLineFactor(parsedWith(undefined), true)).toBe(1.7) }) it('a same-slot Korean Normal (Malgun in both slots) still wins for the kr factor', () => { ;(globalThis as { CSS?: unknown }).CSS ??= { escape: (s: string) => s } const parsed = parsedWith({ font: 'Malgun Gothic', fontAscii: 'Malgun Gothic' }, 'Batang') - expect(docStyleCss(parsed)).toContain('--doc-line-factor-kr:1.73') - expect(docLineFactor(parsed, true)).toBe(1.73) + expect(docStyleCss(parsed)).toContain('--doc-line-factor-kr:1.775') + expect(docLineFactor(parsed, true)).toBe(1.775) }) it('kr factor skips a Latin-only Normal and reads the docDefaults EA font', () => { // node test env has no CSS.escape ;(globalThis as { CSS?: unknown }).CSS ??= { escape: (s: string) => s } const parsed = parsedWith({ font: 'Calibri', fontAscii: 'Calibri' }, 'Malgun Gothic') - expect(docStyleCss(parsed)).toContain('--doc-line-factor-kr:1.73') + expect(docStyleCss(parsed)).toContain('--doc-line-factor-kr:1.775') }) }) @@ -94,8 +94,8 @@ describe('docStyleCss — paragraph spacing fallback', () => { it('declared docDefaults spacing still applies', () => { const rule = blockRule(docStyleCss(parsedWith({ spaceAfterTwips: 200, spaceBeforeTwips: 40 }))) - expect(rule).toContain('margin-top:2.0pt') - expect(rule).toContain('margin-bottom:10.0pt') + expect(rule).toContain('margin-top:round(down, 2.0pt, var(--doc-grid-pitch,0.0001px))') + expect(rule).toContain('margin-bottom:round(down, 10.0pt, var(--doc-grid-pitch,0.0001px))') }) }) diff --git a/apps/docs/tests/image-wrap.test.ts b/apps/docs/tests/image-wrap.test.ts index 2e06d0e..2428cb0 100644 --- a/apps/docs/tests/image-wrap.test.ts +++ b/apps/docs/tests/image-wrap.test.ts @@ -1,7 +1,6 @@ import { Editor } from '@tiptap/core' import { NodeSelection } from '@tiptap/pm/state' import { parseDocx, saveDocx } from '@genoffice/docx-engine' -import JSZip from 'jszip' import { describe, expect, it } from 'vitest' import { buildDocx, @@ -10,8 +9,8 @@ import { import { blocksToPmDoc, pmDocToSavePlan, type PmNode } from '../src/renderer/editor/convert' import { editorExtensions } from '../src/renderer/editor/extensions' -async function openImageDoc(bodyXml = IMAGE_PARAGRAPH_XML, extraRels?: string) { - const source = await buildDocx({ bodyXml, withImage: true, extraRels }) +async function openImageDoc() { + const source = await buildDocx({ bodyXml: IMAGE_PARAGRAPH_XML, withImage: true }) const parsed = await parseDocx(source) const editor = new Editor({ element: document.createElement('div'), @@ -89,200 +88,4 @@ describe('image wrap in the editor', () => { editor.destroy() editor2.destroy() }) - - it('rotation + flip round-trip through a:xfrm and clear cleanly', async () => { - // the minimal shared fixture has no pic:spPr; rotation lives on the pic xfrm - const withXfrm = IMAGE_PARAGRAPH_XML.replace( - '', - '' + - '', - ) - const source = await buildDocx({ bodyXml: withXfrm, withImage: true }) - const parsed = await parseDocx(source) - const editor = new Editor({ - element: document.createElement('div'), - extensions: editorExtensions, - content: blocksToPmDoc(parsed.blocks) as never, - }) - editor.view.dispatch(editor.state.tr.setSelection(NodeSelection.create(editor.state.doc, 0))) - editor.commands.updateAttributes('docProtected', { imageRotDeg: 90, imageFlipH: true }) - const plan = pmDocToSavePlan(editor.getJSON() as PmNode, parsed.blocks) - expect(plan.changedCount).toBe(1) - const saved = await saveDocx(parsed, plan.saveBlocks) - - const reparsed = await parseDocx(saved) - expect(reparsed.blocks[0].imageRotDeg).toBe(90) - expect(reparsed.blocks[0].imageFlipH).toBe(true) - expect(reparsed.blocks[0].imageFlipV).toBeUndefined() - - // untouched re-save stays byte-identical; clearing removes the attributes - const editor2 = new Editor({ - element: document.createElement('div'), - extensions: editorExtensions, - content: blocksToPmDoc(reparsed.blocks) as never, - }) - const plan2 = pmDocToSavePlan(editor2.getJSON() as PmNode, reparsed.blocks) - expect(plan2.changedCount).toBe(0) - expect(await saveDocx(reparsed, plan2.saveBlocks)).toEqual(saved) - - editor2.view.dispatch(editor2.state.tr.setSelection(NodeSelection.create(editor2.state.doc, 0))) - editor2.commands.updateAttributes('docProtected', { imageRotDeg: null, imageFlipH: false }) - const plan3 = pmDocToSavePlan(editor2.getJSON() as PmNode, reparsed.blocks) - expect(plan3.changedCount).toBe(1) - const cleared = await saveDocx(reparsed, plan3.saveBlocks) - const p3 = await parseDocx(cleared) - expect(p3.blocks[0].imageRotDeg).toBeUndefined() - expect(p3.blocks[0].imageFlipH).toBeUndefined() - expect(cleared.length).toBeGreaterThan(0) - editor.destroy() - editor2.destroy() - }) - - it('imageReplace swaps bytes in place, keeping the drawing XML and wrap', async () => { - // 1x1 transparent GIF - const GIF_B64 = 'R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7' - const { editor, parsed } = await openImageDoc() - editor.view.dispatch(editor.state.tr.setSelection(NodeSelection.create(editor.state.doc, 0))) - editor.commands.updateAttributes('docProtected', { - imageWrap: 'square-right', - imageReplace: { base64: GIF_B64, mime: 'image/gif' }, - }) - const plan = pmDocToSavePlan(editor.getJSON() as PmNode, parsed.blocks) - expect(plan.changedCount).toBe(1) - const saved = await saveDocx(parsed, plan.saveBlocks) - - const reparsed = await parseDocx(saved) - const blk = reparsed.blocks[0] - // still an original image block (docxIndex-anchored), wrap applied, new bytes served - expect(blk.type).toBe('image') - expect(blk.imageWrap).toBe('square-right') - expect(blk.imageDataUrl?.startsWith('data:image/gif;base64,')).toBe(true) - - // an untouched re-save of the reparsed doc stays byte-identical - const editor2 = new Editor({ - element: document.createElement('div'), - extensions: editorExtensions, - content: blocksToPmDoc(reparsed.blocks) as never, - }) - const plan2 = pmDocToSavePlan(editor2.getJSON() as PmNode, reparsed.blocks) - expect(plan2.changedCount).toBe(0) - expect(await saveDocx(reparsed, plan2.saveBlocks)).toEqual(saved) - editor.destroy() - editor2.destroy() - }) - - it('flip-only saves keep a Word-authored effectExtent untouched', async () => { - // Flips do not change the bounding box: Word-authored padding for shadow / - // glow effects must survive a mirror toggle byte-for-byte - const wordEffectExtent = '' - const withEffect = IMAGE_PARAGRAPH_XML.replace( - '', - `${wordEffectExtent}`, - ).replace( - '', - '' + - '', - ) - const source = await buildDocx({ bodyXml: withEffect, withImage: true }) - const parsed = await parseDocx(source) - const editor = new Editor({ - element: document.createElement('div'), - extensions: editorExtensions, - content: blocksToPmDoc(parsed.blocks) as never, - }) - editor.view.dispatch(editor.state.tr.setSelection(NodeSelection.create(editor.state.doc, 0))) - editor.commands.updateAttributes('docProtected', { imageFlipH: true }) - const plan = pmDocToSavePlan(editor.getJSON() as PmNode, parsed.blocks) - expect(plan.changedCount).toBe(1) - const saved = await saveDocx(parsed, plan.saveBlocks) - const docXml = await (await JSZip.loadAsync(saved)).file('word/document.xml')!.async('string') - expect(docXml).toContain('flipH="1"') - expect(docXml).toContain(wordEffectExtent) - editor.destroy() - }) - - it('90° rotation of a non-square image records the bounding-box overflow in effectExtent', async () => { - // 2:1 landscape picture (1828800 x 914400 EMU): turned 90° it overflows the - // unrotated footprint by (w-h)/2 = 457200 EMU on top/bottom, and needs that - // recorded in wp:effectExtent or Word crops / misplaces the drawing - const nonSquare = IMAGE_PARAGRAPH_XML.replace( - '', - '', - ).replace( - '', - '' + - '', - ) - const source = await buildDocx({ bodyXml: nonSquare, withImage: true }) - const parsed = await parseDocx(source) - const editor = new Editor({ - element: document.createElement('div'), - extensions: editorExtensions, - content: blocksToPmDoc(parsed.blocks) as never, - }) - editor.view.dispatch(editor.state.tr.setSelection(NodeSelection.create(editor.state.doc, 0))) - editor.commands.updateAttributes('docProtected', { imageRotDeg: 90 }) - const plan = pmDocToSavePlan(editor.getJSON() as PmNode, parsed.blocks) - expect(plan.changedCount).toBe(1) - const saved = await saveDocx(parsed, plan.saveBlocks) - - const zip = await JSZip.loadAsync(saved) - const docXml = await zip.file('word/document.xml')!.async('string') - // (bboxW - cx)/2 = (914400 - 1828800)/2 clamps to 0; (bboxH - cy)/2 = 457200 - expect(docXml).toContain('') - // clearing the rotation zeroes the extra space again - const reparsed = await parseDocx(saved) - const editor2 = new Editor({ - element: document.createElement('div'), - extensions: editorExtensions, - content: blocksToPmDoc(reparsed.blocks) as never, - }) - editor2.view.dispatch(editor2.state.tr.setSelection(NodeSelection.create(editor2.state.doc, 0))) - editor2.commands.updateAttributes('docProtected', { imageRotDeg: null }) - const cleared = await saveDocx( - reparsed, - pmDocToSavePlan(editor2.getJSON() as PmNode, reparsed.blocks).saveBlocks, - ) - const clearedXml = await ( - await JSZip.loadAsync(cleared) - ) - .file('word/document.xml')! - .async('string') - expect(clearedXml).toContain('') - editor.destroy() - editor2.destroy() - }) - - it('imageReplace strips a stale external r:link and svgBlip extension', async () => { - const GIF_B64 = 'R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7' - // Word "insert and link" SVG picture: the blip carries the raster fallback - // (r:embed), an external link (r:link), and the Office-2016 svgBlip extension - const linkedBody = IMAGE_PARAGRAPH_XML.replace( - '', - '' + - '' + - '' + - '', - ) - const linkRel = - '' - const { editor, parsed } = await openImageDoc(linkedBody, linkRel) - editor.view.dispatch(editor.state.tr.setSelection(NodeSelection.create(editor.state.doc, 0))) - editor.commands.updateAttributes('docProtected', { - imageReplace: { base64: GIF_B64, mime: 'image/gif' }, - }) - const plan = pmDocToSavePlan(editor.getJSON() as PmNode, parsed.blocks) - expect(plan.changedCount).toBe(1) - const saved = await saveDocx(parsed, plan.saveBlocks) - - // Word would refresh a surviving r:link from the old file, and prefers a - // surviving svgBlip over the retargeted embed — both must be gone - const zip = await JSZip.loadAsync(saved) - const docXml = await zip.file('word/document.xml')!.async('string') - expect(docXml).not.toContain('r:link') - expect(docXml).not.toContain('svgBlip') - const reparsed2 = await parseDocx(saved) - expect(reparsed2.blocks[0].imageDataUrl?.startsWith('data:image/gif;base64,')).toBe(true) - editor.destroy() - }) }) diff --git a/apps/docs/tests/line-factor-live.test.ts b/apps/docs/tests/line-factor-live.test.ts index 7816eb0..70bc6ce 100644 --- a/apps/docs/tests/line-factor-live.test.ts +++ b/apps/docs/tests/line-factor-live.test.ts @@ -33,7 +33,7 @@ const sizedParagraph = (text: string, sizeHalfPoints: number) => }) as never describe('live line-height factor decorations', () => { - it('typing CJK into a paragraph created empty switches its factor to 1.3', () => { + it('typing CJK into a paragraph created empty switches its factor to the CJK var', () => { const editor = new Editor({ element: document.createElement('div'), extensions: editorExtensions, @@ -43,7 +43,7 @@ describe('live line-height factor decorations', () => { expect(factorOf(editor)).toBe('') editor.commands.insertContentAt(1, '中文正文') - expect(factorOf(editor)).toBe('1.3') + expect(factorOf(editor)).toBe('var(--doc-line-factor-cjk,1.7)') editor.destroy() }) @@ -57,7 +57,7 @@ describe('live line-height factor decorations', () => { content: [{ type: 'docParagraph', content: [{ type: 'text', text: '中文' }] }], } as never, }) - expect(factorOf(editor)).toBe('1.3') + expect(factorOf(editor)).toBe('var(--doc-line-factor-cjk,1.7)') editor.commands.setTextSelection({ from: 1, to: 3 }) editor.commands.insertContent('latin') diff --git a/apps/docs/tests/line-metrics.test.ts b/apps/docs/tests/line-metrics.test.ts index cc62f94..30fa281 100644 --- a/apps/docs/tests/line-metrics.test.ts +++ b/apps/docs/tests/line-metrics.test.ts @@ -116,18 +116,26 @@ describe('computeLineHeight', () => { expect(h).toBeCloseTo(naturalH, 2) }) - it('docGrid lines mode: line height is not rounded (measured on real Word for Mac)', () => { - // Precise Word baseline (line-by-line from the 02/10 corpus PDFs): 12pt/1.15× - // lays out at 18pt/line, not a multiple of linePitch (15.6pt) — docGrid does not affect line height + it('docGrid lines mode: single/auto lines snap up to whole linePitch cells (LO probe)', () => { + // LO baseline (probe docx, 2026-08-10): natural 20px on a 15.6pt (20.8px) + // grid takes one cell; the auto multiple applies AFTER snapping const docGrid = { type: 'lines' as const, linePitch: 312 } const h = computeLineHeight(20, 'auto', 240, docGrid) - expect(h).toBeCloseTo(20, 2) + expect(h).toBeCloseTo(312 * (96 / 1440), 2) }) - it('docGrid lines mode: large line heights are not rounded either', () => { + it('docGrid lines mode: taller lines take more whole cells', () => { const docGrid = { type: 'lines' as const, linePitch: 300 } const h = computeLineHeight(55, 'auto', 240, docGrid) - expect(h).toBeCloseTo(55, 2) + // 300tw = 20px cell; 55px needs 3 cells = 60px + expect(h).toBeCloseTo(60, 2) + }) + + it('docGrid lines mode: exact and atLeast never snap', () => { + const docGrid = { type: 'lines' as const, linePitch: 312 } + expect(computeLineHeight(20, 'exact', 260, docGrid)).toBeCloseTo(260 * (96 / 1440), 2) + expect(computeLineHeight(20, 'atLeast', 0, docGrid)).toBeCloseTo(20, 2) + expect(computeLineHeight(20, 'atLeast', 480, docGrid)).toBeCloseTo(480 * (96 / 1440), 2) }) it('type=default does no grid rounding', () => { @@ -150,9 +158,12 @@ describe('snapSpacingToGrid', () => { expect(px).toBeCloseTo(160 * TWIPS_TO_PX, 2) }) - it('type=lines does not round either (real Word: 240tw space-after lays out at the raw 8pt)', () => { - const px = snapSpacingToGrid(160, { type: 'lines', linePitch: 312 }) - expect(px).toBeCloseTo(160 * TWIPS_TO_PX, 2) + it('type=lines quantizes spacing DOWN to whole cells (LO probe: 6pt vanishes on a 15.6pt grid)', () => { + expect(snapSpacingToGrid(160, { type: 'lines', linePitch: 312 })).toBeCloseTo(0, 2) + expect(snapSpacingToGrid(480, { type: 'lines', linePitch: 312 })).toBeCloseTo( + 312 * TWIPS_TO_PX, + 2, + ) }) }) @@ -229,8 +240,9 @@ describe('computeLineMetrics', () => { ) }) - it('docGrid does not change line height: Chinese official doc linePitch=312 (A4 page, 12pt SimSun)', () => { - // Real-Word baseline: line height is identical with or without docGrid (no snapping) + it('docGrid snaps line heights: Chinese official doc linePitch=312 (A4 page, 12pt SimSun)', () => { + // LO baseline: 12pt SimSun natural (1.7em = 27.2px) exceeds one 20.8px cell, + // so each line takes two cells before the 1.3 auto multiple applies const docGrid = { type: 'lines' as const, linePitch: 312 } const input = { runs: [{ text: '中华人民共和国', sizeHalfPoints: 24 }], // 12pt @@ -240,8 +252,13 @@ describe('computeLineMetrics', () => { } const withGrid = computeLineMetrics({ ...input, docGrid }) const without = computeLineMetrics(input) - expect(withGrid.lineHeights).toEqual(without.lineHeights) - expect(withGrid.totalHeight).toBeCloseTo(without.totalHeight, 2) + const cell = 312 * (96 / 1440) + for (const [i, h] of withGrid.lineHeights.entries()) { + expect(h).toBeCloseTo( + Math.ceil(without.lineHeights[i] / (312 / 240) / cell - 0.001) * cell * (312 / 240), + 2, + ) + } }) it('exact line-height mode: total height = lineCount × exactPx + spacing', () => { @@ -319,11 +336,15 @@ describe('lineTexts', () => { describe('cssLineHeight', () => { it('auto multiple → calc(coefficient variable × multiple)', () => { - expect(cssLineHeight('auto', 276, 1.15)).toBe('calc(var(--doc-line-factor,1.2) * 1.15)') + expect(cssLineHeight('auto', 276, 1.15)).toBe( + 'calc(round(up, calc(var(--doc-line-factor,1.2) * 1em), var(--doc-grid-pitch,0.0001px)) * 1.15)', + ) }) it('derives the multiple from auto twips when lineSpacing is absent', () => { - expect(cssLineHeight('auto', 360, undefined)).toBe('calc(var(--doc-line-factor,1.2) * 1.5)') + expect(cssLineHeight('auto', 360, undefined)).toBe( + 'calc(round(up, calc(var(--doc-line-factor,1.2) * 1em), var(--doc-grid-pitch,0.0001px)) * 1.5)', + ) }) it('exact → fixed pt', () => { @@ -488,31 +509,43 @@ describe('Korean line metrics', () => { expect(m.measure('한글날', style)).toBeCloseTo(48, 5) }) - it('Korean font line factors: Batang-class 1.3, Malgun 1.73, Noto KR 1.3', () => { - expect(lineHeightFactor('Batang')).toBe(1.3) - expect(lineHeightFactor('바탕')).toBe(1.3) - expect(lineHeightFactor('Gulim')).toBe(1.3) - expect(lineHeightFactor('Dotum')).toBe(1.3) - expect(lineHeightFactor('NanumMyeongjo')).toBe(1.3) - expect(lineHeightFactor('Malgun Gothic')).toBe(1.73) - expect(lineHeightFactor('맑은 고딕')).toBe(1.73) - expect(lineHeightFactor('Noto Sans CJK KR')).toBe(1.3) - expect(lineHeightFactor('Noto Serif KR')).toBe(1.3) - expect(lineHeightFactor('Source Han Sans K')).toBe(1.3) + it('Korean font line factors: Batang-class 1.4583, Malgun 1.775 (LO probe)', () => { + expect(lineHeightFactor('Batang')).toBe(1.4583) + expect(lineHeightFactor('바탕')).toBe(1.4583) + expect(lineHeightFactor('Gulim')).toBe(1.4583) + expect(lineHeightFactor('Dotum')).toBe(1.4583) + expect(lineHeightFactor('NanumMyeongjo')).toBe(1.4583) + expect(lineHeightFactor('Malgun Gothic')).toBe(1.775) + expect(lineHeightFactor('맑은 고딕')).toBe(1.775) + expect(lineHeightFactor('Noto Sans CJK KR')).toBe(1.4583) + expect(lineHeightFactor('Noto Serif KR')).toBe(1.4583) + expect(lineHeightFactor('Source Han Sans K')).toBe(1.4583) }) - it('Chinese/Japanese factors unchanged', () => { - expect(lineHeightFactor('SimSun')).toBe(1.3) - expect(lineHeightFactor('DengXian')).toBe(1.3) - expect(lineHeightFactor('等线')).toBe(1.3) + it('Chinese/Japanese factors follow the LO substitution probe', () => { + expect(lineHeightFactor('SimSun')).toBe(1.7) + expect(lineHeightFactor('宋体')).toBe(1.7) + expect(lineHeightFactor('DengXian')).toBe(1.775) + expect(lineHeightFactor('等线')).toBe(1.775) + expect(lineHeightFactor('仿宋_GB2312')).toBe(1.775) + expect(lineHeightFactor('黑体')).toBe(1.0) + expect(lineHeightFactor('楷体')).toBe(1.0) + expect(lineHeightFactor('楷体_GB2312')).toBe(1.775) + expect(lineHeightFactor('MS 明朝')).toBe(1.7) + expect(lineHeightFactor('MS Gothic')).toBe(1.7) + expect(lineHeightFactor('游明朝')).toBe(2.2667) + expect(lineHeightFactor('Meiryo')).toBe(1.775) expect(lineHeightFactor('PMingLiU')).toBe(1.0) + expect(lineHeightFactor('Microsoft JhengHei')).toBe(1.775) expect(lineHeightFactor('Calibri')).toBe(1.22) + expect(lineHeightFactor('Century Gothic')).toBe(1.2) }) - it('SC-variant declares take the SimSun factor (their substitution target when missing)', () => { - expect(lineHeightFactor('Noto Sans CJK SC')).toBe(1.3) - expect(lineHeightFactor('Noto Serif SC')).toBe(1.3) - expect(lineHeightFactor('Source Han Sans CN')).toBe(1.3) + it('SC-variant declares take the PingFang-class factor (their substitution target when missing)', () => { + expect(lineHeightFactor('Noto Sans CJK SC')).toBe(1.775) + expect(lineHeightFactor('Noto Serif SC')).toBe(1.775) + expect(lineHeightFactor('Source Han Sans CN')).toBe(1.775) + expect(lineHeightFactor('Noto Sans SC')).toBe(1.8375) }) it('textHasHangul separates Korean from other CJK', () => { @@ -522,15 +555,15 @@ describe('Korean line metrics', () => { }) it('paraLineFactorCss routes by script', () => { - expect(paraLineFactorCss('한국어')).toBe('var(--doc-line-factor-kr,1.3)') - expect(paraLineFactorCss('\u4e2d\u6587')).toBe('1.3') + expect(paraLineFactorCss('한국어')).toBe('var(--doc-line-factor-kr,1.4583)') + expect(paraLineFactorCss('\u4e2d\u6587')).toBe('var(--doc-line-factor-cjk,1.7)') expect(paraLineFactorCss('latin')).toBe('var(--doc-line-factor-latin,1.2)') }) it('krLineFactor follows the EA face, defaulting to Batang-class', () => { - expect(krLineFactor('Batang')).toBe(1.3) - expect(krLineFactor('맑은 고딕')).toBe(1.73) - expect(krLineFactor(undefined)).toBe(1.3) + expect(krLineFactor('Batang')).toBe(1.4583) + expect(krLineFactor('맑은 고딕')).toBe(1.775) + expect(krLineFactor(undefined)).toBe(1.4583) }) it('Korean ascii face in a dual-slot chain keeps only the literal family', () => { diff --git a/apps/docs/tests/markdown-paste.test.ts b/apps/docs/tests/markdown-paste.test.ts new file mode 100644 index 0000000..e0215be --- /dev/null +++ b/apps/docs/tests/markdown-paste.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, it } from 'vitest' + +import { looksLikeMarkdown, markdownPasteHtml } from '../src/renderer/editor/markdown-paste' + +describe('looksLikeMarkdown', () => { + it('recognizes unambiguous constructs on their own', () => { + expect(looksLikeMarkdown('## Heading\n\nBody text.')).toBe(true) + expect(looksLikeMarkdown('```js\nconsole.log(1)\n```')).toBe(true) + expect(looksLikeMarkdown('See [the docs](https://example.com) for details.')).toBe(true) + expect(looksLikeMarkdown('This is **important** to know.')).toBe(true) + expect(looksLikeMarkdown('| A | B |\n| --- | --- |\n| 1 | 2 |')).toBe(true) + }) + + it('requires repetition for list and quote markers', () => { + expect(looksLikeMarkdown('- one item only')).toBe(false) + expect(looksLikeMarkdown('- one\n- two')).toBe(true) + expect(looksLikeMarkdown('1. first\n2. second')).toBe(true) + expect(looksLikeMarkdown('> single quoted line')).toBe(false) + expect(looksLikeMarkdown('> line one\n> line two')).toBe(true) + }) + + it('does not treat Python dunder identifiers as bold markers', () => { + expect(looksLikeMarkdown('def __init__(self):\n self.__name__ = "x"')).toBe(false) + expect(looksLikeMarkdown('call __main__ before __exit__ runs')).toBe(false) + }) + + it('leaves ordinary prose alone', () => { + expect(looksLikeMarkdown('Meeting notes from Monday.\nBudget is $100.')).toBe(false) + expect(looksLikeMarkdown('Use the # channel for questions.')).toBe(false) + expect(looksLikeMarkdown('1. A single numbered sentence.')).toBe(false) + expect(looksLikeMarkdown('a * b * c = abc')).toBe(false) + }) +}) + +describe('markdownPasteHtml', () => { + it('converts headings, emphasis, lists, and code fences', () => { + const html = markdownPasteHtml('## Title\n\nSome **bold** text.\n\n- one\n- two') + expect(html).toContain('

    ') + expect(html).toContain('bold') + expect(html).toContain('
      ') + expect(html).toContain('
    • one
    • ') + const fenced = markdownPasteHtml('```\nlet x = 1\n```') + expect(fenced).toContain('
      ')
      +  })
      +
      +  it('normalizes Windows line endings before conversion', () => {
      +    const html = markdownPasteHtml('# A\r\n\r\n- x\r\n- y')
      +    expect(html).toContain('

      ') + expect(html).toContain('
    • y
    • ') + }) + + it('returns null for plain prose so the literal paste path runs', () => { + expect(markdownPasteHtml('Just an ordinary sentence.')).toBeNull() + expect(markdownPasteHtml('Line one.\nLine two.')).toBeNull() + }) + + it('converts GFM tables', () => { + const html = markdownPasteHtml('| A | B |\n| --- | --- |\n| 1 | 2 |') + expect(html).toContain('') + expect(html).toContain('') + }) +}) diff --git a/apps/docs/tests/native-table.test.ts b/apps/docs/tests/native-table.test.ts index 656abcb..90df512 100644 --- a/apps/docs/tests/native-table.test.ts +++ b/apps/docs/tests/native-table.test.ts @@ -82,6 +82,7 @@ describe('native editable tables', () => { type: 'docTextStyle', attrs: { color: '1F4E78', + eaSlotEmpty: null, sizeHalfPoints: null, font: 'Calibri', fontAscii: 'Calibri', @@ -209,7 +210,7 @@ describe('native editable tables', () => { editor.destroy() }) - it('renders legacy over-wide grids clamped to the content box', async () => { + it('renders legacy over-wide grids clamped to the paper edge (content box + right margin)', async () => { const { editor } = await openTable() const table = editor.state.doc.firstChild! editor.view.dispatch( @@ -225,7 +226,7 @@ describe('native editable tables', () => { Record, [string, Record, ...Array<[string, Record]>], ] - expect(spec[1].style).toContain('width:min(1200px,100%)') + expect(spec[1].style).toContain('width:min(1200px,calc(100% + var(--doc-margin-right,0px)))') const cols = spec[2].slice(2) as Array<[string, Record]> expect(cols.map((col) => col[1].style)).toEqual(['width:50.00%', 'width:50.00%']) editor.destroy() diff --git a/apps/docs/tests/note-format.test.ts b/apps/docs/tests/note-format.test.ts index 4cd2df4..527643d 100644 --- a/apps/docs/tests/note-format.test.ts +++ b/apps/docs/tests/note-format.test.ts @@ -31,8 +31,10 @@ describe('note numbering', () => { ], } as never, }) + // bare number/roman text: the editor-only brackets are CSS ::before/::after + // (hidden in print so they don't leak into exported PDF text) const sups = [...editor.view.dom.querySelectorAll('sup[data-note-ref]')] - expect(sups.map((s) => s.textContent)).toEqual(['[2]', '[ii]']) + expect(sups.map((s) => s.textContent)).toEqual(['2', 'ii']) editor.destroy() }) }) diff --git a/apps/markdown/src/main/markdown-main.ts b/apps/markdown/src/main/markdown-main.ts index 8a36b8d..2acb82c 100644 --- a/apps/markdown/src/main/markdown-main.ts +++ b/apps/markdown/src/main/markdown-main.ts @@ -15,6 +15,7 @@ import { } from 'electron' import type { WebContents } from 'electron' import { + configuredDefaultSaveDir, contextMenuLabels, installContextMenu, installNavigationGuard, @@ -416,7 +417,7 @@ async function resolveSaveTarget( .slice(0, 80) .trim() if (base) { - const dir = app.getPath('documents') + const dir = configuredDefaultSaveDir(app) let target = join(dir, `${base}.md`) for (let n = 1; existsSync(target); n++) target = join(dir, `${base}-${n}.md`) return target @@ -426,7 +427,7 @@ async function resolveSaveTarget( BrowserWindow.fromWebContents(e.sender) ?? BrowserWindow.getFocusedWindow() ?? undefined const defaultPath = current ? join(dirname(current), basename(current)) - : join(app.getPath('documents'), `${tm('untitledFile')}.md`) + : join(configuredDefaultSaveDir(app), `${tm('untitledFile')}.md`) const picked = await showSaveDialogWithMemory(dialog, win, { title: tm('dlgSaveTitle'), defaultPath, @@ -611,9 +612,9 @@ function registerMarkdownIpc(): void { try { const bytes = Buffer.from(request.base64, 'base64') if (request.mode === 'openInDocs') { - // silent convert next to the .md (untitled documents go to Documents) + // silent convert next to the .md (untitled documents go to the default save folder) const docPath = savePathByWc.get(e.sender.id) - const dir = docPath ? dirname(docPath) : app.getPath('documents') + const dir = docPath ? dirname(docPath) : configuredDefaultSaveDir(app) let target = join(dir, `${safeName}.docx`) for (let n = 1; existsSync(target); n++) target = join(dir, `${safeName}-${n}.docx`) await writeFile(target, bytes) @@ -622,10 +623,15 @@ function registerMarkdownIpc(): void { } const win = BrowserWindow.fromWebContents(e.sender) ?? BrowserWindow.getFocusedWindow() ?? undefined - const picked = await showSaveDialogWithMemory(dialog, win, { - defaultPath: `${safeName}.docx`, - filters: [{ name: 'Word', extensions: ['docx'] }], - }) + const picked = await showSaveDialogWithMemory( + dialog, + win, + { + defaultPath: `${safeName}.docx`, + filters: [{ name: 'Word', extensions: ['docx'] }], + }, + configuredDefaultSaveDir(app), + ) if (picked.canceled || !picked.filePath) return { ok: true, canceled: true } await writeFile(picked.filePath, bytes) return { ok: true, path: picked.filePath } @@ -648,10 +654,15 @@ function registerMarkdownIpc(): void { .trim() || tm('untitledFile') const win = BrowserWindow.fromWebContents(e.sender) ?? BrowserWindow.getFocusedWindow() ?? undefined - const picked = await showSaveDialogWithMemory(dialog, win, { - defaultPath: `${safeName}.pdf`, - filters: [{ name: 'PDF', extensions: ['pdf'] }], - }) + const picked = await showSaveDialogWithMemory( + dialog, + win, + { + defaultPath: `${safeName}.pdf`, + filters: [{ name: 'PDF', extensions: ['pdf'] }], + }, + configuredDefaultSaveDir(app), + ) if (picked.canceled || !picked.filePath) return { ok: true, canceled: true } // sheets-style: render the print HTML in a hidden scripting-disabled window const workDir = await mkdtemp(join(tmpdir(), 'genoffice-md-pdf-')) diff --git a/apps/markdown/src/renderer/App.tsx b/apps/markdown/src/renderer/App.tsx index befb8b3..81a9e6c 100644 --- a/apps/markdown/src/renderer/App.tsx +++ b/apps/markdown/src/renderer/App.tsx @@ -386,7 +386,8 @@ export default function App() { {!aiOpen && ( )} - @@ -586,7 +592,7 @@ export function AiPanel({ {snapshots.map((s, i) => (
      - + {s.time} {s.label} @@ -726,14 +732,14 @@ function ToolChipList({ tools }: { tools: ToolActivity[] }) { ) : ( - + {tool.summary} )} diff --git a/apps/markdown/src/renderer/components/Ribbon.tsx b/apps/markdown/src/renderer/components/Ribbon.tsx index 2c50c5a..863f3ad 100644 --- a/apps/markdown/src/renderer/components/Ribbon.tsx +++ b/apps/markdown/src/renderer/components/Ribbon.tsx @@ -129,7 +129,8 @@ function IconBtn({ -
      1{row.scopeLabel} + @@ -98,26 +100,40 @@ export function SlicerPanels({ const selected = new Set(slicer.selected) const filtered = selected.size < slicer.members.length return ( -
      +
      - {slicer.fieldName} + + {slicer.fieldName} + + > + ⧉ + + > + × +
      {slicer.members.map((entry) => (
      - +
      diff --git a/apps/sheets/src/renderer/TimelinePanel.tsx b/apps/sheets/src/renderer/TimelinePanel.tsx index 1878d39..f43d9bb 100644 --- a/apps/sheets/src/renderer/TimelinePanel.tsx +++ b/apps/sheets/src/renderer/TimelinePanel.tsx @@ -106,12 +106,13 @@ export function TimelinePanels({ aria-label={t('dlgTimelineAria', { name: timeline.fieldName })} >
      - + {timeline.fieldName} @@ -398,11 +451,21 @@ export function AiChatPanel({
      {(chat.length > 0 || historicChat.length > 0) && ( - )} -
      @@ -414,6 +477,9 @@ export function AiChatPanel({ <> {historicChat.map((entry, i) => (
      + {entry.role === 'user' && entry.attachments && entry.attachments.length > 0 && ( + + )} {entry.tools.length > 0 && } {entry.text && }
      @@ -438,12 +504,18 @@ export function AiChatPanel({ > {entry.role === 'user' ? ( <> + {entry.attachments && entry.attachments.length > 0 && ( + + )} {entry.text} {entry.undelivered && (
      {t('aiUndelivered')} {!aiBusy && ( - )} @@ -469,7 +541,7 @@ export function AiChatPanel({ {t('aiAutoApplied', { count: entry.autoApplied.opCount })} -
      @@ -547,7 +619,7 @@ export function AiChatPanel({ {attachmentPreviews[attachment.path] ? ( {attachment.name} @@ -559,7 +631,7 @@ export function AiChatPanel({ @@ -802,14 +875,14 @@ function ToolChipList({ tools }: { tools: readonly AiToolChip[] }): React.JSX.El ) : ( - + {tool.summary} )} diff --git a/apps/sheets/src/renderer/autofit-multi-row.ts b/apps/sheets/src/renderer/autofit-multi-row.ts new file mode 100644 index 0000000..fb39573 --- /dev/null +++ b/apps/sheets/src/renderer/autofit-multi-row.ts @@ -0,0 +1,77 @@ +/** + * Excel-style multi-row AutoFit. Univer's row-header double-click resize + * autofits only the double-clicked row (the column counterpart already walks + * the whole selection — upstream asymmetry). When the clicked row lies + * inside a multi-row full-row selection, the single-row command is cancelled + * and re-dispatched with every selected row span, so each selected row sizes + * to its own content, matching Excel. + */ +import type { IRange } from '@univerjs/core' + +import type { UniverRuntime } from './univer-state' + +export const SET_ROW_IS_AUTO_HEIGHT_COMMAND = 'sheet.command.set-worksheet-row-is-auto-height' + +/// Full-row spans: selections made from the row headers or a select-all. +function isFullRowSpan(range: IRange, columnCount: number): boolean { + return range.startColumn === 0 && range.endColumn >= columnCount - 1 +} + +/** + * Returns the replacement ranges when the command should grow to the whole + * selection, or null to leave the command untouched. Grows only when the + * command targets a single row that sits inside a full-row selection + * covering more than one row in total (Ctrl-selected disjoint spans count). + */ +export function expandAutoHeightRanges( + commandRanges: readonly IRange[], + selections: readonly IRange[], + columnCount: number, +): IRange[] | null { + if (commandRanges.length !== 1) return null + const clicked = commandRanges[0] + if (clicked === undefined || clicked.startRow !== clicked.endRow) return null + const rowSpans = selections.filter((range) => isFullRowSpan(range, columnCount)) + if ( + !rowSpans.some( + (range) => range.startRow <= clicked.startRow && clicked.startRow <= range.endRow, + ) + ) { + return null + } + const totalRows = rowSpans.reduce((sum, range) => sum + (range.endRow - range.startRow + 1), 0) + if (totalRows <= 1) return null + return rowSpans.map((range) => ({ + startRow: range.startRow, + endRow: range.endRow, + startColumn: clicked.startColumn, + endColumn: clicked.endColumn, + })) +} + +export function installMultiRowAutofit(runtime: UniverRuntime): { dispose(): void } { + let redispatching = false + return runtime.univerAPI.addEvent(runtime.univerAPI.Event.BeforeCommandExecute, (event) => { + if (redispatching || event.id !== SET_ROW_IS_AUTO_HEIGHT_COMMAND) return + const params = (event.params ?? {}) as { ranges?: IRange[] } + if (!params.ranges) return + const worksheet = runtime.univerAPI.getActiveWorkbook()?.getActiveSheet() + if (!worksheet) return + const selections = (worksheet.getSelection()?.getActiveRangeList() ?? []).map((range) => + range.getRange(), + ) + const expanded = expandAutoHeightRanges( + params.ranges, + selections, + worksheet.getSheet().getColumnCount(), + ) + if (expanded === null) return + event.cancel = true + redispatching = true + void runtime.univerAPI + .executeCommand(SET_ROW_IS_AUTO_HEIGHT_COMMAND, { ...event.params, ranges: expanded }) + .finally(() => { + redispatching = false + }) + }) +} diff --git a/apps/sheets/src/renderer/i18n/strings-app.ts b/apps/sheets/src/renderer/i18n/strings-app.ts index 81253e9..a99bb06 100644 --- a/apps/sheets/src/renderer/i18n/strings-app.ts +++ b/apps/sheets/src/renderer/i18n/strings-app.ts @@ -1032,6 +1032,10 @@ export const appStrings = defineStrings({ appGroupShow: '显示', appFormulaBar: '编辑栏', appZoomLabel: '缩放', + appFontFamilyTip: '字体', + appFontSizeTip: '字号', + appZoomIn: '放大', + appZoomOut: '缩小', appZoomSheetTitle: '缩放工作表', appResetZoom: '重置缩放', appZoomToSelection: '缩放到选定区域', @@ -2240,6 +2244,10 @@ export const appStrings = defineStrings({ appGroupShow: 'Show', appFormulaBar: 'Formula Bar', appZoomLabel: 'Zoom', + appFontFamilyTip: 'Font', + appFontSizeTip: 'Font size', + appZoomIn: 'Zoom in', + appZoomOut: 'Zoom out', appZoomSheetTitle: 'Zoom the sheet', appResetZoom: 'Reset zoom', appZoomToSelection: 'Zoom to Selection', @@ -3515,6 +3523,10 @@ export const appStrings = defineStrings({ appGroupShow: '表示', appFormulaBar: '数式バー', appZoomLabel: 'ズーム', + appFontFamilyTip: 'フォント', + appFontSizeTip: 'フォントサイズ', + appZoomIn: '拡大', + appZoomOut: '縮小', appZoomSheetTitle: 'シートをズーム', appResetZoom: 'ズームのリセット', appZoomToSelection: '選択範囲に合わせて拡大/縮小', @@ -4761,6 +4773,10 @@ export const appStrings = defineStrings({ appGroupShow: '표시', appFormulaBar: '수식 입력줄', appZoomLabel: '확대/축소', + appFontFamilyTip: '글꼴', + appFontSizeTip: '글꼴 크기', + appZoomIn: '확대', + appZoomOut: '축소', appZoomSheetTitle: '시트 확대/축소', appResetZoom: '확대/축소 다시 설정', appZoomToSelection: '선택 영역 확대/축소', @@ -6043,6 +6059,10 @@ export const appStrings = defineStrings({ appGroupShow: 'Afficher', appFormulaBar: 'Barre de formule', appZoomLabel: 'Zoom', + appFontFamilyTip: 'Police', + appFontSizeTip: 'Taille de police', + appZoomIn: 'Zoom avant', + appZoomOut: 'Zoom arrière', appZoomSheetTitle: 'Zoomer la feuille', appResetZoom: 'Réinitialiser le zoom', appZoomToSelection: 'Zoom sur la sélection', @@ -7311,6 +7331,10 @@ export const appStrings = defineStrings({ appGroupShow: 'Anzeigen', appFormulaBar: 'Bearbeitungsleiste', appZoomLabel: 'Zoom', + appFontFamilyTip: 'Schriftart', + appFontSizeTip: 'Schriftgrad', + appZoomIn: 'Vergrößern', + appZoomOut: 'Verkleinern', appZoomSheetTitle: 'Blatt zoomen', appResetZoom: 'Zoom zurücksetzen', appZoomToSelection: 'An Markierung anpassen', @@ -8568,6 +8592,10 @@ export const appStrings = defineStrings({ appGroupShow: 'Mostrar', appFormulaBar: 'Barra de fórmulas', appZoomLabel: 'Zoom', + appFontFamilyTip: 'Fuente', + appFontSizeTip: 'Tamaño de fuente', + appZoomIn: 'Acercar', + appZoomOut: 'Alejar', appZoomSheetTitle: 'Hacer zoom en la hoja', appResetZoom: 'Restablecer zoom', appZoomToSelection: 'Ampliar selección', @@ -9766,6 +9794,10 @@ export const appStrings = defineStrings({ appGroupShow: 'แสดง', appFormulaBar: 'แถบสูตร', appZoomLabel: 'ย่อ/ขยาย', + appFontFamilyTip: 'แบบอักษร', + appFontSizeTip: 'ขนาดแบบอักษร', + appZoomIn: 'ขยาย', + appZoomOut: 'ย่อ', appZoomSheetTitle: 'ย่อ/ขยายแผ่นงาน', appResetZoom: 'รีเซ็ตการย่อ/ขยาย', appZoomToSelection: 'ขยายไปยังส่วนที่เลือก', @@ -10987,6 +11019,10 @@ export const appStrings = defineStrings({ appGroupShow: 'Tampilkan', appFormulaBar: 'Bilah Rumus', appZoomLabel: 'Zoom', + appFontFamilyTip: 'Font', + appFontSizeTip: 'Ukuran font', + appZoomIn: 'Perbesar', + appZoomOut: 'Perkecil', appZoomSheetTitle: 'Zoom lembar', appResetZoom: 'Atur ulang zoom', appZoomToSelection: 'Zoom ke Pilihan', @@ -12229,6 +12265,10 @@ export const appStrings = defineStrings({ appGroupShow: 'Показать', appFormulaBar: 'Строка формул', appZoomLabel: 'Масштаб', + appFontFamilyTip: 'Шрифт', + appFontSizeTip: 'Размер шрифта', + appZoomIn: 'Увеличить', + appZoomOut: 'Уменьшить', appZoomSheetTitle: 'Масштабировать лист', appResetZoom: 'Сбросить масштаб', appZoomToSelection: 'Масштаб по выделенному', @@ -13428,6 +13468,10 @@ export const appStrings = defineStrings({ appGroupShow: 'إظهار', appFormulaBar: 'شريط الصيغة', appZoomLabel: 'تكبير/تصغير', + appFontFamilyTip: 'الخط', + appFontSizeTip: 'حجم الخط', + appZoomIn: 'تكبير', + appZoomOut: 'تصغير', appZoomSheetTitle: 'تكبير/تصغير الورقة', appResetZoom: 'إعادة تعيين التكبير/التصغير', appZoomToSelection: 'تكبير/تصغير حسب التحديد', @@ -14680,6 +14724,10 @@ export const appStrings = defineStrings({ appGroupShow: 'Mostrar', appFormulaBar: 'Barra de Fórmulas', appZoomLabel: 'Zoom', + appFontFamilyTip: 'Fonte', + appFontSizeTip: 'Tamanho da fonte', + appZoomIn: 'Ampliar', + appZoomOut: 'Reduzir', appZoomSheetTitle: 'Aplicar zoom na planilha', appResetZoom: 'Redefinir zoom', appZoomToSelection: 'Zoom na Seleção', @@ -15935,6 +15983,10 @@ export const appStrings = defineStrings({ appGroupShow: 'Mostra', appFormulaBar: 'Barra della formula', appZoomLabel: 'Zoom', + appFontFamilyTip: 'Carattere', + appFontSizeTip: 'Dimensione carattere', + appZoomIn: 'Ingrandisci', + appZoomOut: 'Riduci', appZoomSheetTitle: 'Zoom sul foglio', appResetZoom: 'Reimposta zoom', appZoomToSelection: 'Zoom sulla selezione', @@ -17186,6 +17238,10 @@ export const appStrings = defineStrings({ appGroupShow: 'Pokazywanie', appFormulaBar: 'Pasek formuły', appZoomLabel: 'Powiększenie', + appFontFamilyTip: 'Czcionka', + appFontSizeTip: 'Rozmiar czcionki', + appZoomIn: 'Powiększ', + appZoomOut: 'Pomniejsz', appZoomSheetTitle: 'Powiększ arkusz', appResetZoom: 'Resetuj powiększenie', appZoomToSelection: 'Powiększ do zaznaczenia', @@ -18444,6 +18500,10 @@ export const appStrings = defineStrings({ appGroupShow: 'Weergeven', appFormulaBar: 'Formulebalk', appZoomLabel: 'In-/uitzoomen', + appFontFamilyTip: 'Lettertype', + appFontSizeTip: 'Tekengrootte', + appZoomIn: 'Inzoomen', + appZoomOut: 'Uitzoomen', appZoomSheetTitle: 'In-/uitzoomen op het werkblad', appResetZoom: 'Zoomniveau herstellen', appZoomToSelection: 'Inzoomen op selectie', @@ -19666,6 +19726,10 @@ export const appStrings = defineStrings({ appGroupShow: 'Tunjukkan', appFormulaBar: 'Bar Formula', appZoomLabel: 'Zum', + appFontFamilyTip: 'Fon', + appFontSizeTip: 'Saiz fon', + appZoomIn: 'Zum masuk', + appZoomOut: 'Zum keluar', appZoomSheetTitle: 'Zum helaian', appResetZoom: 'Tetapkan semula zum', appZoomToSelection: 'Zum ke Pilihan', @@ -20846,6 +20910,10 @@ export const appStrings = defineStrings({ appGroupShow: 'הצגה', appFormulaBar: 'שורת הנוסחאות', appZoomLabel: 'זום', + appFontFamilyTip: 'גופן', + appFontSizeTip: 'גודל גופן', + appZoomIn: 'התקרבות', + appZoomOut: 'התרחקות', appZoomSheetTitle: 'שנה את גודל תצוגת הגיליון', appResetZoom: 'אפס זום', appZoomToSelection: 'זום לבחירה', @@ -22070,6 +22138,10 @@ export const appStrings = defineStrings({ appGroupShow: 'दिखाएँ', appFormulaBar: 'सूत्र पट्टी', appZoomLabel: 'ज़ूम', + appFontFamilyTip: 'फ़ॉन्ट', + appFontSizeTip: 'फ़ॉन्ट का आकार', + appZoomIn: 'ज़ूम इन', + appZoomOut: 'ज़ूम आउट', appZoomSheetTitle: 'शीट ज़ूम करें', appResetZoom: 'ज़ूम रीसेट करें', appZoomToSelection: 'चयन पर ज़ूम करें', @@ -23217,6 +23289,10 @@ export const appStrings = defineStrings({ appGroupShow: '顯示', appFormulaBar: '資料編輯列', appZoomLabel: '縮放', + appFontFamilyTip: '字型', + appFontSizeTip: '字型大小', + appZoomIn: '放大', + appZoomOut: '縮小', appZoomSheetTitle: '縮放工作表', appResetZoom: '重設縮放', appZoomToSelection: '縮放至選取範圍', diff --git a/apps/sheets/src/renderer/i18n/strings-dialogs.ts b/apps/sheets/src/renderer/i18n/strings-dialogs.ts index 6fb7150..6f0cef6 100644 --- a/apps/sheets/src/renderer/i18n/strings-dialogs.ts +++ b/apps/sheets/src/renderer/i18n/strings-dialogs.ts @@ -229,6 +229,8 @@ export const dialogStrings = defineStrings({ dlgFcRotDown: '向下旋转(−90°)', dlgFcRotVertical: '竖排文字', dlgFcFont: '字体', + dlgFcFontsCommon: '常用字体', + dlgFcFontsSystem: '系统字体', dlgFcSize: '字号', dlgFcBold: '加粗', dlgFcItalic: '倾斜', @@ -607,6 +609,8 @@ export const dialogStrings = defineStrings({ dlgFcRotDown: 'Rotate down (−90°)', dlgFcRotVertical: 'Vertical text', dlgFcFont: 'Font', + dlgFcFontsCommon: 'Common fonts', + dlgFcFontsSystem: 'System fonts', dlgFcSize: 'Size', dlgFcBold: 'Bold', dlgFcItalic: 'Italic', @@ -987,6 +991,8 @@ export const dialogStrings = defineStrings({ dlgFcRotDown: '下向きに回転(−90°)', dlgFcRotVertical: '縦書き', dlgFcFont: 'フォント', + dlgFcFontsCommon: 'よく使うフォント', + dlgFcFontsSystem: 'システムフォント', dlgFcSize: 'サイズ', dlgFcBold: '太字', dlgFcItalic: '斜体', @@ -1362,6 +1368,8 @@ export const dialogStrings = defineStrings({ dlgFcRotDown: '아래쪽으로 회전(−90°)', dlgFcRotVertical: '세로 쓰기', dlgFcFont: '글꼴', + dlgFcFontsCommon: '자주 쓰는 글꼴', + dlgFcFontsSystem: '시스템 글꼴', dlgFcSize: '크기', dlgFcBold: '굵게', dlgFcItalic: '기울임꼴', @@ -1745,6 +1753,8 @@ export const dialogStrings = defineStrings({ dlgFcRotDown: 'Rotation vers le bas (−90°)', dlgFcRotVertical: 'Texte vertical', dlgFcFont: 'Police', + dlgFcFontsCommon: 'Polices courantes', + dlgFcFontsSystem: 'Polices système', dlgFcSize: 'Taille', dlgFcBold: 'Gras', dlgFcItalic: 'Italique', @@ -2129,6 +2139,8 @@ export const dialogStrings = defineStrings({ dlgFcRotDown: 'Nach unten drehen (−90°)', dlgFcRotVertical: 'Vertikaler Text', dlgFcFont: 'Schriftart', + dlgFcFontsCommon: 'Gängige Schriftarten', + dlgFcFontsSystem: 'Systemschriftarten', dlgFcSize: 'Größe', dlgFcBold: 'Fett', dlgFcItalic: 'Kursiv', @@ -2511,6 +2523,8 @@ export const dialogStrings = defineStrings({ dlgFcRotDown: 'Girar hacia abajo (−90°)', dlgFcRotVertical: 'Texto vertical', dlgFcFont: 'Fuente', + dlgFcFontsCommon: 'Fuentes comunes', + dlgFcFontsSystem: 'Fuentes del sistema', dlgFcSize: 'Tamaño', dlgFcBold: 'Negrita', dlgFcItalic: 'Cursiva', @@ -2889,6 +2903,8 @@ export const dialogStrings = defineStrings({ dlgFcRotDown: 'หมุนลง (−90°)', dlgFcRotVertical: 'ข้อความแนวตั้ง', dlgFcFont: 'แบบอักษร', + dlgFcFontsCommon: 'แบบอักษรที่ใช้บ่อย', + dlgFcFontsSystem: 'แบบอักษรของระบบ', dlgFcSize: 'ขนาด', dlgFcBold: 'ตัวหนา', dlgFcItalic: 'ตัวเอียง', @@ -3270,6 +3286,8 @@ export const dialogStrings = defineStrings({ dlgFcRotDown: 'Putar ke bawah (−90°)', dlgFcRotVertical: 'Teks vertikal', dlgFcFont: 'Font', + dlgFcFontsCommon: 'Font umum', + dlgFcFontsSystem: 'Font sistem', dlgFcSize: 'Ukuran', dlgFcBold: 'Tebal', dlgFcItalic: 'Miring', @@ -3651,6 +3669,8 @@ export const dialogStrings = defineStrings({ dlgFcRotDown: 'Повернуть вниз (−90°)', dlgFcRotVertical: 'Вертикальный текст', dlgFcFont: 'Шрифт', + dlgFcFontsCommon: 'Основные шрифты', + dlgFcFontsSystem: 'Системные шрифты', dlgFcSize: 'Размер', dlgFcBold: 'Полужирный', dlgFcItalic: 'Курсив', @@ -4030,6 +4050,8 @@ export const dialogStrings = defineStrings({ dlgFcRotDown: 'استدارة لأسفل (−90°)', dlgFcRotVertical: 'نص عمودي', dlgFcFont: 'الخط', + dlgFcFontsCommon: 'الخطوط الشائعة', + dlgFcFontsSystem: 'خطوط النظام', dlgFcSize: 'الحجم', dlgFcBold: 'غامق', dlgFcItalic: 'مائل', @@ -4411,6 +4433,8 @@ export const dialogStrings = defineStrings({ dlgFcRotDown: 'Girar para baixo (−90°)', dlgFcRotVertical: 'Texto vertical', dlgFcFont: 'Fonte', + dlgFcFontsCommon: 'Fontes comuns', + dlgFcFontsSystem: 'Fontes do sistema', dlgFcSize: 'Tamanho', dlgFcBold: 'Negrito', dlgFcItalic: 'Itálico', @@ -4793,6 +4817,8 @@ export const dialogStrings = defineStrings({ dlgFcRotDown: 'Ruota verso il basso (−90°)', dlgFcRotVertical: 'Testo verticale', dlgFcFont: 'Carattere', + dlgFcFontsCommon: 'Caratteri comuni', + dlgFcFontsSystem: 'Caratteri di sistema', dlgFcSize: 'Dimensione', dlgFcBold: 'Grassetto', dlgFcItalic: 'Corsivo', @@ -5175,6 +5201,8 @@ export const dialogStrings = defineStrings({ dlgFcRotDown: 'Obróć w dół (−90°)', dlgFcRotVertical: 'Tekst pionowy', dlgFcFont: 'Czcionka', + dlgFcFontsCommon: 'Popularne czcionki', + dlgFcFontsSystem: 'Czcionki systemowe', dlgFcSize: 'Rozmiar', dlgFcBold: 'Pogrubienie', dlgFcItalic: 'Kursywa', @@ -5554,6 +5582,8 @@ export const dialogStrings = defineStrings({ dlgFcRotDown: 'Omlaag draaien (−90°)', dlgFcRotVertical: 'Verticale tekst', dlgFcFont: 'Lettertype', + dlgFcFontsCommon: 'Veelgebruikte lettertypen', + dlgFcFontsSystem: 'Systeemlettertypen', dlgFcSize: 'Grootte', dlgFcBold: 'Vet', dlgFcItalic: 'Cursief', @@ -5934,6 +5964,8 @@ export const dialogStrings = defineStrings({ dlgFcRotDown: 'Putar ke bawah (−90°)', dlgFcRotVertical: 'Teks menegak', dlgFcFont: 'Fon', + dlgFcFontsCommon: 'Fon biasa', + dlgFcFontsSystem: 'Fon sistem', dlgFcSize: 'Saiz', dlgFcBold: 'Tebal', dlgFcItalic: 'Condong', @@ -6307,6 +6339,8 @@ export const dialogStrings = defineStrings({ dlgFcRotDown: 'סיבוב למטה (−90°)', dlgFcRotVertical: 'טקסט אנכי', dlgFcFont: 'גופן', + dlgFcFontsCommon: 'גופנים נפוצים', + dlgFcFontsSystem: 'גופני מערכת', dlgFcSize: 'גודל', dlgFcBold: 'מודגש', dlgFcItalic: 'נטוי', @@ -6687,6 +6721,8 @@ export const dialogStrings = defineStrings({ dlgFcRotDown: 'नीचे घुमाएं (−90°)', dlgFcRotVertical: 'ऊर्ध्वाधर पाठ', dlgFcFont: 'फ़ॉन्ट', + dlgFcFontsCommon: 'सामान्य फ़ॉन्ट', + dlgFcFontsSystem: 'सिस्टम फ़ॉन्ट', dlgFcSize: 'आकार', dlgFcBold: 'मोटा', dlgFcItalic: 'तिरछा', @@ -7059,6 +7095,8 @@ export const dialogStrings = defineStrings({ dlgFcRotDown: '向下旋轉(−90°)', dlgFcRotVertical: '垂直文字', dlgFcFont: '字型', + dlgFcFontsCommon: '常用字型', + dlgFcFontsSystem: '系統字型', dlgFcSize: '字型大小', dlgFcBold: '粗體', dlgFcItalic: '斜體', diff --git a/apps/sheets/src/renderer/main.tsx b/apps/sheets/src/renderer/main.tsx index 89ae9ee..eb4343a 100644 --- a/apps/sheets/src/renderer/main.tsx +++ b/apps/sheets/src/renderer/main.tsx @@ -1,7 +1,9 @@ import ReactDOM from 'react-dom/client' import { htmlLang, type Lang } from '@genoffice/i18n' +import { installScreenTips } from '@genoffice/ui' import '@genoffice/ui/tokens.css' +import '@genoffice/ui/screentip.css' import '@univerjs/preset-sheets-core/lib/index.css' import { App } from './App' @@ -21,6 +23,8 @@ if (import.meta.hot) { const root = document.getElementById('root') if (!root) throw new Error('Missing application root.') +installScreenTips() + function applyTheme(theme: UiTheme): void { if (theme === 'system') document.documentElement.removeAttribute('data-theme') else document.documentElement.setAttribute('data-theme', theme) diff --git a/apps/sheets/src/renderer/print-html.ts b/apps/sheets/src/renderer/print-html.ts index cdd5f48..fe34001 100644 --- a/apps/sheets/src/renderer/print-html.ts +++ b/apps/sheets/src/renderer/print-html.ts @@ -376,7 +376,12 @@ function cellCss(style: PrintCellStyle | null, rawValue: unknown, gridlines: boo // a font name comes straight from styles.xml; anything outside the whitelist could // close the style attribute and inject markup into the exported page const family = style?.ff?.replace(/[^\p{L}\p{N} \-_.]/gu, '') - if (family) rules.push(`font-family:'${family}'`) + // fallbacks mirror the body stack: an uninstalled family (e.g. Aptos) + // must not drop to the browser's serif default in the exported page + if (family) + rules.push( + `font-family:'${family}',Calibri,'Helvetica Neue',Arial,${printCjkFonts(getLang())},sans-serif`, + ) if (style?.cl?.rgb) rules.push(`color:${cssColor(style.cl.rgb)}`) if (style?.bg?.rgb) rules.push(`background:${cssColor(style.bg.rgb)}`) const align = diff --git a/apps/sheets/src/renderer/styles.css b/apps/sheets/src/renderer/styles.css index 0d7aa71..1fb5f70 100644 --- a/apps/sheets/src/renderer/styles.css +++ b/apps/sheets/src/renderer/styles.css @@ -172,6 +172,68 @@ --ui-cjk: 'PingFang TC', 'Microsoft JhengHei'; } +/* Cell-content font aliases (document data, theme-independent): without these, + * Office sans families the OS lacks silently fall back to Chromium's serif + * default on the grid canvas; local() keeps the real font first if installed. */ +@font-face { + font-family: Aptos; + src: local('Aptos'), local('Calibri'), local('Carlito'), local('Helvetica Neue'), local('Arial'); +} + +@font-face { + font-family: Aptos; + font-weight: bold; + src: + local('Aptos Bold'), local('Calibri Bold'), local('Carlito Bold'), local('Helvetica Neue Bold'), + local('Arial Bold'); +} + +@font-face { + font-family: Aptos; + font-style: italic; + src: + local('Aptos Italic'), local('Calibri Italic'), local('Carlito Italic'), + local('Helvetica Neue Italic'), local('Arial Italic'); +} + +@font-face { + font-family: Aptos; + font-weight: bold; + font-style: italic; + src: + local('Aptos Bold Italic'), local('Calibri Bold Italic'), local('Carlito Bold Italic'), + local('Helvetica Neue Bold Italic'), local('Arial Bold Italic'); +} + +@font-face { + font-family: Calibri; + src: local('Calibri'), local('Carlito'), local('Helvetica Neue'), local('Arial'); +} + +@font-face { + font-family: Calibri; + font-weight: bold; + src: + local('Calibri Bold'), local('Carlito Bold'), local('Helvetica Neue Bold'), local('Arial Bold'); +} + +@font-face { + font-family: Calibri; + font-style: italic; + src: + local('Calibri Italic'), local('Carlito Italic'), local('Helvetica Neue Italic'), + local('Arial Italic'); +} + +@font-face { + font-family: Calibri; + font-weight: bold; + font-style: italic; + src: + local('Calibri Bold Italic'), local('Carlito Bold Italic'), local('Helvetica Neue Bold Italic'), + local('Arial Bold Italic'); +} + * { box-sizing: border-box; } @@ -498,15 +560,31 @@ textarea:disabled { height: 80px; /* Groups must never shrink below content (they would paint over each other); anything past the window edge scrolls instead. */ - overflow-x: auto; + /* `scroll`, not `auto`: styled scrollbars are classic (non-overlay), so + `scroll` keeps the 5px lane reserved even without overflow — the content + area never changes and crossing the overflow threshold cannot cause a + vertical layout jump (same reasoning as .ai-attachments). */ + overflow-x: scroll; overflow-y: hidden; - scrollbar-width: none; - padding: 6px 12px; + /* Slim visible scrollbar so mouse users can reach overflowed groups + (genspark-ai/genoffice#55). Its 5px lane is carved out of the bottom + padding, keeping the 80px band and the content area unchanged; Chromium + paints a thumb only while the row actually overflows. */ + padding: 6px 12px 1px; background: var(--surface); } .ribbon::-webkit-scrollbar { - display: none; + height: 5px; +} + +.ribbon::-webkit-scrollbar-track { + background: transparent; +} + +.ribbon::-webkit-scrollbar-thumb { + border-radius: 2.5px; + background: var(--sheets-scroll-thumb); } .ribbon-group { @@ -1024,11 +1102,13 @@ textarea:disabled { } /* View tab's stacked show/hide checkboxes (the Show group). */ -/* Home Styles group: three stacked dropdown rows. */ +/* Home Styles group: three stacked dropdown rows. Muted via color, not + * opacity — opacity spans the subtree and would render the anchored + * .menu-select-drop popups translucent. */ .styles-stack { display: grid; gap: 1px; - opacity: 0.55; + color: var(--text-secondary); } .styles-row { @@ -1233,6 +1313,13 @@ textarea:disabled { font-weight: 600; } +/* group break above the enumerated system fonts */ +.menu-select-drop button.sep-above { + border-top: 1px solid var(--border-strong); + border-radius: 0 0 4px 4px; + margin-top: 4px; +} + /* Insert tab shape gallery: grouped preview grid inside the dropdown */ .shape-gallery-drop { width: 322px; @@ -4185,6 +4272,38 @@ textarea:focus { color: var(--color-text-tertiary); } +/* attachments echoed on a sent user message (read-only: no remove button, smaller thumbs) */ +.ai-msg-attachments { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin-bottom: 6px; +} + +.ai-msg-attachments .ai-attachment-thumb img { + width: 44px; + height: 44px; + border-radius: 8px; +} + +.ai-msg-attachments .ai-attachment-card { + width: auto; + max-width: 190px; + height: 44px; + background: var(--surface); +} + +.ai-msg-attachments .ai-attachment-card-icon { + width: 32px; + height: 32px; + background: var(--surface-subtle); +} + +.ai-msg-attachments .ai-attachment-card-icon img { + width: 22px; + height: 22px; +} + .ai-attachment-chip { display: inline-flex; align-items: center; diff --git a/apps/sheets/src/renderer/system-fonts.ts b/apps/sheets/src/renderer/system-fonts.ts new file mode 100644 index 0000000..b80ef3c --- /dev/null +++ b/apps/sheets/src/renderer/system-fonts.ts @@ -0,0 +1,65 @@ +import { useCallback, useState } from 'react' + +export const DEFAULT_FONT_FAMILIES: readonly string[] = [ + 'Aptos', + 'Arial', + 'Calibri', + 'Times New Roman', + '微软雅黑', + '宋体', +] + +let cached: readonly string[] | null = null +let pending: Promise | null = null + +async function queryFamilies(): Promise { + const query = (window as { queryLocalFonts?: () => Promise<{ readonly family: string }[]> }) + .queryLocalFonts + if (!query) return [] + try { + const fonts = await query.call(window) + const families = new Set() + for (const font of fonts) { + if (font.family && !DEFAULT_FONT_FAMILIES.includes(font.family)) families.add(font.family) + } + return [...families].sort((a, b) => a.localeCompare(b)) + } catch { + return [] + } +} + +function loadSystemFontFamilies(): Promise { + if (cached) return Promise.resolve(cached) + pending ??= queryFamilies().then((families) => { + cached = families + return families + }) + return pending +} + +/// Empty until load() runs — call it from the picker's open click so the +/// Local Font Access API sees user activation; cached for the page lifetime, +/// and on failure the pickers just keep the default list. +export function useSystemFontFamilies(): { + readonly families: readonly string[] + readonly load: () => void +} { + const [families, setFamilies] = useState(cached ?? []) + const load = useCallback(() => { + void loadSystemFontFamilies().then(setFamilies) + }, []) + return { families, load } +} + +/// The echoed value stays listed even when uninstalled (document echo). +export function fontFamilyGroups( + systemFamilies: readonly string[], + echoFamily: string | null | undefined, +): { readonly common: readonly string[]; readonly system: readonly string[] } { + const known = + !echoFamily || DEFAULT_FONT_FAMILIES.includes(echoFamily) || systemFamilies.includes(echoFamily) + return { + common: known ? DEFAULT_FONT_FAMILIES : [echoFamily, ...DEFAULT_FONT_FAMILIES], + system: systemFamilies, + } +} diff --git a/apps/sheets/src/shared/desktop-api.ts b/apps/sheets/src/shared/desktop-api.ts index 4c95577..4b88518 100644 --- a/apps/sheets/src/shared/desktop-api.ts +++ b/apps/sheets/src/shared/desktop-api.ts @@ -1913,6 +1913,12 @@ export interface DesktopApi { getTheme(): Promise /** theme switched from the shell home page */ onThemeChanged(handler: (theme: UiTheme) => void): () => void + /** + * the user pressed the shell chrome (tab strip) or started dragging the + * window — no DOM event or blur reaches this view, so the shell relays the + * press for dismissing open popovers + */ + onChromePressed(handler: () => void): () => void selectWorkbook(): Promise readWorkbookRange(request: WorkbookRangeRequest): Promise readWorkbookFormulas(request: WorkbookFormulaCellsRequest): Promise diff --git a/apps/sheets/tests/autofit-multi-row.test.ts b/apps/sheets/tests/autofit-multi-row.test.ts new file mode 100644 index 0000000..4c902fb --- /dev/null +++ b/apps/sheets/tests/autofit-multi-row.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from 'vitest' + +import { expandAutoHeightRanges } from '../src/renderer/autofit-multi-row' + +const COLUMNS = 26 +const fullRows = (startRow: number, endRow: number) => ({ + startRow, + endRow, + startColumn: 0, + endColumn: COLUMNS - 1, +}) +const clicked = (row: number) => [{ startRow: row, endRow: row, startColumn: 0, endColumn: 5 }] + +describe('expandAutoHeightRanges', () => { + it('grows a single-row autofit to the full multi-row selection', () => { + expect(expandAutoHeightRanges(clicked(3), [fullRows(1, 5)], COLUMNS)).toEqual([ + { startRow: 1, endRow: 5, startColumn: 0, endColumn: 5 }, + ]) + }) + + it('covers Ctrl-selected disjoint row spans', () => { + expect(expandAutoHeightRanges(clicked(2), [fullRows(1, 2), fullRows(7, 9)], COLUMNS)).toEqual([ + { startRow: 1, endRow: 2, startColumn: 0, endColumn: 5 }, + { startRow: 7, endRow: 9, startColumn: 0, endColumn: 5 }, + ]) + }) + + it('leaves the command alone when the clicked row is outside the selection', () => { + expect(expandAutoHeightRanges(clicked(10), [fullRows(1, 5)], COLUMNS)).toBeNull() + }) + + it('leaves single-row selections and cell-range selections alone', () => { + expect(expandAutoHeightRanges(clicked(3), [fullRows(3, 3)], COLUMNS)).toBeNull() + const cellRange = { startRow: 1, endRow: 5, startColumn: 2, endColumn: 4 } + expect(expandAutoHeightRanges(clicked(3), [cellRange], COLUMNS)).toBeNull() + }) + + it('leaves multi-range or multi-row commands alone (already expanded)', () => { + const twoRanges = [...clicked(1), ...clicked(2)] + expect(expandAutoHeightRanges(twoRanges, [fullRows(1, 5)], COLUMNS)).toBeNull() + const multiRow = [{ startRow: 1, endRow: 5, startColumn: 0, endColumn: 5 }] + expect(expandAutoHeightRanges(multiRow, [fullRows(1, 5)], COLUMNS)).toBeNull() + }) +}) diff --git a/apps/sheets/tests/fixture-builder.ts b/apps/sheets/tests/fixture-builder.ts index ae4ee18..4c876b0 100644 --- a/apps/sheets/tests/fixture-builder.ts +++ b/apps/sheets/tests/fixture-builder.ts @@ -215,6 +215,159 @@ const sheetsMyWorksheet = ` const sheetsChart = `Data!$A$1:$A$2` +/// Exercises sheet removal with owned satellite parts: "Deco" carries a +/// drawing (image + chart with a color style), comments, legacy VML, and a +/// table. Options add a second drawing on the surviving sheet sharing the +/// image, a pivot-table relationship, a surviving structured reference into +/// the table, or a defined name scoped to "Deco" that uses the table. +export async function buildSatelliteSheetFixture( + options: { + sharedImage?: boolean + pivot?: boolean + tableRef?: boolean + scopedTableName?: boolean + } = {}, +): Promise { + const zip = new JSZip() + const keepFormula = options.tableRef ? 'SUM(DecoTable[Amt])3' : '' + const keepDrawing = options.sharedImage ? '' : '' + // A name scoped to Deco (localSheetId 1) dies with the sheet, so its + // structured reference into DecoTable must not block the removal. + const definedNames = options.scopedTableName + ? 'SUM(DecoTable[Amt])' + : '' + zip.file( + '[Content_Types].xml', + ` + + + + + + + + + + + ${options.sharedImage ? '' : ''} + + + + +`, + ) + zip.file('_rels/.rels', packageRelationships) + zip.file( + 'xl/workbook.xml', + ` + + + ${definedNames} +`, + ) + zip.file( + 'xl/_rels/workbook.xml.rels', + ` + + + + +`, + ) + zip.file( + 'xl/worksheets/sheet1.xml', + ` + + 1${keepFormula} + ${keepDrawing} +`, + ) + if (options.sharedImage) { + zip.file( + 'xl/worksheets/_rels/sheet1.xml.rels', + ` + + +`, + ) + zip.file( + 'xl/drawings/drawing2.xml', + '', + ) + zip.file( + 'xl/drawings/_rels/drawing2.xml.rels', + ` + + +`, + ) + } + zip.file( + 'xl/worksheets/sheet2.xml', + ` + + 57 + + + +`, + ) + zip.file( + 'xl/worksheets/_rels/sheet2.xml.rels', + ` + + + + + + ${options.pivot ? '' : ''} +`, + ) + zip.file( + 'xl/drawings/drawing1.xml', + '', + ) + zip.file( + 'xl/drawings/_rels/drawing1.xml.rels', + ` + + + +`, + ) + zip.file( + 'xl/charts/chart1.xml', + 'Deco!$A$1:$A$2', + ) + zip.file( + 'xl/charts/_rels/chart1.xml.rels', + ` + + +`, + ) + zip.file( + 'xl/charts/colors1.xml', + '', + ) + zip.file('xl/comments1.xml', kitchenSinkComments) + zip.file('xl/drawings/vmlDrawing1.vml', kitchenSinkVml) + zip.file( + 'xl/tables/table1.xml', + ` +
      `, + ) + if (options.pivot) { + zip.file( + 'xl/pivotTables/pivotTable1.xml', + '', + ) + } + zip.file('xl/media/image1.png', kitchenSinkPng) + zip.file('xl/styles.xml', styles) + return zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' }) +} + /// Exercises preservation of exotic and binary parts: theme, doc properties, /// comments + VML, a table part, frozen panes, autoFilter, PNG media, and /// printer settings. Only sheet1.xml may change when a cell is edited. diff --git a/apps/sheets/tests/xlsx-sheets.test.ts b/apps/sheets/tests/xlsx-sheets.test.ts index 3d56cfb..17344fa 100644 --- a/apps/sheets/tests/xlsx-sheets.test.ts +++ b/apps/sheets/tests/xlsx-sheets.test.ts @@ -1,21 +1,26 @@ import JSZip from 'jszip' import { describe, expect, it } from 'vitest' +import { applyCellEditsToXlsx, assertOnlyTouchedEntriesChanged } from '../src/gateway/xlsx-gateway' +import { relsPathFor, resolveRelTarget } from '../src/gateway/xlsx-drawing-add' import { - applyCellEditsToXlsx, - assertOnlyTouchedEntriesChanged, -} from '../src/gateway/xlsx-gateway' -import { - assertSheetRelsRemovable, + classifyRemovedSheetRels, + definedNamesUseToken, formatSheetQualifier, + partPathForRels, prepareClonedSheetRels, renameSheetInFormula, sanitizeClonedWorksheetXml, SheetEditError, stripPageSetupRelIds, + tableDisplayName, validateSheetName, } from '../src/gateway/xlsx-sheets' -import { buildCompatibilityFixture, buildSheetsFixture } from './fixture-builder' +import { + buildCompatibilityFixture, + buildSatelliteSheetFixture, + buildSheetsFixture, +} from './fixture-builder' async function entryText(buffer: Buffer, path: string): Promise { const zip = await JSZip.loadAsync(buffer) @@ -43,10 +48,12 @@ describe('sheet name rules', () => { describe('renameSheetInFormula', () => { it('rewrites qualified references and leaves the rest alone', () => { - expect(renameSheetInFormula('Data!A1+SUM(Data!B1:B9)+A1', 'Data', 'Numbers')) - .toBe('Numbers!A1+SUM(Numbers!B1:B9)+A1') - expect(renameSheetInFormula("'My Sheet'!$A$1&\"Data!A1\"", 'My Sheet', 'Plain')) - .toBe('Plain!$A$1&"Data!A1"') + expect(renameSheetInFormula('Data!A1+SUM(Data!B1:B9)+A1', 'Data', 'Numbers')).toBe( + 'Numbers!A1+SUM(Numbers!B1:B9)+A1', + ) + expect(renameSheetInFormula('\'My Sheet\'!$A$1&"Data!A1"', 'My Sheet', 'Plain')).toBe( + 'Plain!$A$1&"Data!A1"', + ) expect(renameSheetInFormula('Other!A1', 'Data', 'Numbers')).toBe('Other!A1') }) }) @@ -70,17 +77,19 @@ describe('sheet visibility and order save', () => { it('unhides by removing the state attribute and rejects hiding every sheet', async () => { const source = await buildSheetsFixture() - await expect(applyCellEditsToXlsx(source, [], [], [], { - renames: [], - additions: [], - removals: [], - hiddenChanges: [ - { sheetName: 'Data', hidden: true }, - { sheetName: 'Other', hidden: true }, - { sheetName: 'My Sheet', hidden: true }, - ], - order: ['Data', 'Other', 'My Sheet'], - })).rejects.toThrow(/at least one visible sheet/) + await expect( + applyCellEditsToXlsx(source, [], [], [], { + renames: [], + additions: [], + removals: [], + hiddenChanges: [ + { sheetName: 'Data', hidden: true }, + { sheetName: 'Other', hidden: true }, + { sheetName: 'My Sheet', hidden: true }, + ], + order: ['Data', 'Other', 'My Sheet'], + }), + ).rejects.toThrow(/at least one visible sheet/) }) }) @@ -117,7 +126,9 @@ describe('sheet rename save', () => { const other = await entryText(mutation.buffer, 'xl/worksheets/sheet2.xml') expect(other).toContain('Data!A1+SUM(Plain!A1:A2)') const workbook = await entryText(mutation.buffer, 'xl/workbook.xml') - expect(workbook).toContain('Plain!$A$1') + expect(workbook).toContain( + 'Plain!$A$1', + ) const spaced = await applyCellEditsToXlsx(await buildSheetsFixture(), [], [], [], { renames: [{ sheetName: 'Data', newName: 'New Data' }], @@ -130,18 +141,22 @@ describe('sheet rename save', () => { }) it('rejects duplicate and invalid names', async () => { - await expect(applyCellEditsToXlsx(await buildSheetsFixture(), [], [], [], { - renames: [{ sheetName: 'Data', newName: 'Other' }], - additions: [], - removals: [], - order: ['Other', 'Other', 'My Sheet'], - })).rejects.toThrow('same name') - await expect(applyCellEditsToXlsx(await buildSheetsFixture(), [], [], [], { - renames: [{ sheetName: 'Data', newName: 'bad[name' }], - additions: [], - removals: [], - order: ['bad[name', 'Other', 'My Sheet'], - })).rejects.toThrow('forbidden character') + await expect( + applyCellEditsToXlsx(await buildSheetsFixture(), [], [], [], { + renames: [{ sheetName: 'Data', newName: 'Other' }], + additions: [], + removals: [], + order: ['Other', 'Other', 'My Sheet'], + }), + ).rejects.toThrow('same name') + await expect( + applyCellEditsToXlsx(await buildSheetsFixture(), [], [], [], { + renames: [{ sheetName: 'Data', newName: 'bad[name' }], + additions: [], + removals: [], + order: ['bad[name', 'Other', 'My Sheet'], + }), + ).rejects.toThrow('forbidden character') }) }) @@ -201,34 +216,185 @@ describe('sheet remove save', () => { }) it('fails closed when formulas, charts, or defined names still reference the sheet', async () => { - await expect(applyCellEditsToXlsx(await buildSheetsFixture(), [], [], [], { - renames: [], - additions: [], - removals: ['My Sheet'], - order: ['Data', 'Other'], - })).rejects.toThrow('reference "My Sheet"') - await expect(applyCellEditsToXlsx(await buildSheetsFixture(), [], [], [], { - renames: [], - additions: [], - removals: ['Data'], - order: ['Other', 'My Sheet'], - })).rejects.toThrow('"Data"') + await expect( + applyCellEditsToXlsx(await buildSheetsFixture(), [], [], [], { + renames: [], + additions: [], + removals: ['My Sheet'], + order: ['Data', 'Other'], + }), + ).rejects.toThrow('reference "My Sheet"') + await expect( + applyCellEditsToXlsx(await buildSheetsFixture(), [], [], [], { + renames: [], + additions: [], + removals: ['Data'], + order: ['Other', 'My Sheet'], + }), + ).rejects.toThrow('"Data"') }) it('refuses to remove the last visible sheet', async () => { - await expect(applyCellEditsToXlsx(await buildCompatibilityFixture(), [], [], [], { - renames: [], - additions: [], - removals: ['Sheet1'], - order: [], - })).rejects.toThrow('visible sheet') + await expect( + applyCellEditsToXlsx(await buildCompatibilityFixture(), [], [], [], { + renames: [], + additions: [], + removals: ['Sheet1'], + order: [], + }), + ).rejects.toThrow('visible sheet') }) - it('refuses sheets that carry drawings or tables', () => { - const drawingRels = '' - expect(() => assertSheetRelsRemovable(drawingRels, 'Data')).toThrow(SheetEditError) - const hyperlinkRels = '' - expect(() => assertSheetRelsRemovable(hyperlinkRels, 'Data')).not.toThrow() + it('classifies removed-sheet relationships into owned, ignorable, and blocking', () => { + const rels = + '' + + '' + + '' + + '' + + '' + + '' + expect(classifyRemovedSheetRels(rels, 'Data')).toEqual([ + '../drawings/drawing1.xml', + '../comments1.xml', + ]) + const pivotRels = + '' + expect(() => classifyRemovedSheetRels(pivotRels, 'Data')).toThrow(/pivot table/) + const slicerRels = + '' + expect(() => classifyRemovedSheetRels(slicerRels, 'Data')).toThrow(SheetEditError) + }) + + it('rel-path helpers resolve targets and rels locations', () => { + expect(resolveRelTarget('xl/worksheets/sheet2.xml', '../drawings/drawing1.xml')).toBe( + 'xl/drawings/drawing1.xml', + ) + expect(resolveRelTarget('xl/worksheets/sheet2.xml', '../comments1.xml')).toBe( + 'xl/comments1.xml', + ) + expect(resolveRelTarget('xl/charts/chart1.xml', 'colors1.xml')).toBe('xl/charts/colors1.xml') + expect(relsPathFor('xl/drawings/drawing1.xml')).toBe('xl/drawings/_rels/drawing1.xml.rels') + expect(partPathForRels('xl/drawings/_rels/drawing1.xml.rels')).toBe('xl/drawings/drawing1.xml') + expect(partPathForRels('_rels/.rels')).toBe('') + expect(tableDisplayName('')).toBe( + 'DecoTable', + ) + }) + + it('definedNamesUseToken sees surviving names and skips names scoped to removed sheets', () => { + const scoped = + '' + + 'SUM(DecoTable[Amt])' + + '' + expect(definedNamesUseToken(scoped, 'DecoTable[', new Set([1]))).toBe(false) + expect(definedNamesUseToken(scoped, 'DecoTable[', new Set())).toBe(true) + const global = + '' + + 'SUM(DecoTable[Amt])' + + '' + expect(definedNamesUseToken(global, 'DecoTable[', new Set([1]))).toBe(true) + expect(definedNamesUseToken(global, 'OtherTable[', new Set())).toBe(false) + }) + + it('cascade-removes the drawings, charts, images, comments, VML, and tables the sheet owns', async () => { + const mutation = await applyCellEditsToXlsx(await buildSatelliteSheetFixture(), [], [], [], { + renames: [], + additions: [], + removals: ['Deco'], + order: ['Keep'], + }) + expect(() => assertOnlyTouchedEntriesChanged(mutation)).not.toThrow() + expect([...mutation.removedEntries].sort()).toEqual([ + 'xl/charts/_rels/chart1.xml.rels', + 'xl/charts/chart1.xml', + 'xl/charts/colors1.xml', + 'xl/comments1.xml', + 'xl/drawings/_rels/drawing1.xml.rels', + 'xl/drawings/drawing1.xml', + 'xl/drawings/vmlDrawing1.vml', + 'xl/media/image1.png', + 'xl/tables/table1.xml', + 'xl/worksheets/_rels/sheet2.xml.rels', + 'xl/worksheets/sheet2.xml', + ]) + const contentTypes = await entryText(mutation.buffer, '[Content_Types].xml') + for (const gone of [ + 'sheet2.xml', + 'drawing1.xml', + 'chart1.xml', + 'colors1.xml', + 'comments1.xml', + 'table1.xml', + ]) { + expect(contentTypes).not.toContain(gone) + } + const workbook = await entryText(mutation.buffer, 'xl/workbook.xml') + expect(workbook).not.toContain('name="Deco"') + }) + + it('keeps an image a surviving sheet still references', async () => { + const mutation = await applyCellEditsToXlsx( + await buildSatelliteSheetFixture({ sharedImage: true }), + [], + [], + [], + { renames: [], additions: [], removals: ['Deco'], order: ['Keep'] }, + ) + expect(() => assertOnlyTouchedEntriesChanged(mutation)).not.toThrow() + expect(mutation.removedEntries).not.toContain('xl/media/image1.png') + expect(mutation.removedEntries).toContain('xl/drawings/drawing1.xml') + const zip = await JSZip.loadAsync(mutation.buffer) + expect(zip.file('xl/media/image1.png')).not.toBeNull() + expect(zip.file('xl/drawings/drawing2.xml')).not.toBeNull() + }) + + it('renames another sheet in the same save as the cascade removal', async () => { + // The rename pass rewrites chart references; charts dying with the + // removed sheet are already gone from the package and must be skipped. + const mutation = await applyCellEditsToXlsx(await buildSatelliteSheetFixture(), [], [], [], { + renames: [{ sheetName: 'Keep', newName: 'Kept' }], + additions: [], + removals: ['Deco'], + order: ['Kept'], + }) + expect(() => assertOnlyTouchedEntriesChanged(mutation)).not.toThrow() + const workbook = await entryText(mutation.buffer, 'xl/workbook.xml') + expect(workbook).toContain('name="Kept"') + expect(workbook).not.toContain('name="Deco"') + expect(mutation.removedEntries).toContain('xl/charts/chart1.xml') + }) + + it('ignores a structured reference in a defined name scoped to the removed sheet', async () => { + const mutation = await applyCellEditsToXlsx( + await buildSatelliteSheetFixture({ scopedTableName: true }), + [], + [], + [], + { renames: [], additions: [], removals: ['Deco'], order: ['Keep'] }, + ) + expect(() => assertOnlyTouchedEntriesChanged(mutation)).not.toThrow() + // The scoped name dies with the sheet. + const workbook = await entryText(mutation.buffer, 'xl/workbook.xml') + expect(workbook).not.toContain('DecoRef') + }) + + it('fails closed on pivot tables and on surviving structured references into the table', async () => { + await expect( + applyCellEditsToXlsx(await buildSatelliteSheetFixture({ pivot: true }), [], [], [], { + renames: [], + additions: [], + removals: ['Deco'], + order: ['Keep'], + }), + ).rejects.toThrow(/pivot table/) + await expect( + applyCellEditsToXlsx(await buildSatelliteSheetFixture({ tableRef: true }), [], [], [], { + renames: [], + additions: [], + removals: ['Deco'], + order: ['Keep'], + }), + ).rejects.toThrow(/table "DecoTable"/) }) }) @@ -253,7 +419,9 @@ describe('sheet duplicate save', () => { const copy = await entryText(mutation.buffer, 'xl/worksheets/sheet4.xml') // Source content survives — including its formula — plus the new edit. expect(copy).toContain("'My Sheet'!A1*2") - expect(copy).toContain('copied') + expect(copy).toContain( + 'copied', + ) // The source part itself is byte-untouched. expect(mutation.touchedEntries).not.toContain('xl/worksheets/sheet1.xml') const source = await entryText(mutation.buffer, 'xl/worksheets/sheet1.xml') @@ -273,10 +441,10 @@ describe('sheet duplicate save', () => { ) zip.file( 'xl/worksheets/_rels/sheet1.xml.rels', - '' - + '' - + '' - + '', + '' + + '' + + '' + + '', ) zip.file('xl/printerSettings/printerSettings1.bin', Buffer.from([1, 2, 3])) const source = await zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' }) @@ -303,40 +471,54 @@ describe('sheet duplicate save', () => { const zip = await JSZip.loadAsync(await buildSheetsFixture()) zip.file( 'xl/worksheets/_rels/sheet1.xml.rels', - '' - + '' - + '', + '' + + '' + + '', ) const withDrawing = await zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' }) - await expect(applyCellEditsToXlsx(withDrawing, [], [], [], { - renames: [], - additions: [{ name: 'Data Copy', sourceSheetName: 'Data' }], - removals: [], - order: ['Data', 'Data Copy', 'Other', 'My Sheet'], - })).rejects.toThrow('not supported yet') + await expect( + applyCellEditsToXlsx(withDrawing, [], [], [], { + renames: [], + additions: [{ name: 'Data Copy', sourceSheetName: 'Data' }], + removals: [], + order: ['Data', 'Data Copy', 'Other', 'My Sheet'], + }), + ).rejects.toThrow('not supported yet') // "Other" carries a sheet-scoped Print_Area (localSheetId=1). - await expect(applyCellEditsToXlsx(await buildSheetsFixture(), [], [], [], { - renames: [], - additions: [{ name: 'Other Copy', sourceSheetName: 'Other' }], - removals: [], - order: ['Data', 'Other', 'Other Copy', 'My Sheet'], - })).rejects.toThrow('sheet-scoped defined names') + await expect( + applyCellEditsToXlsx(await buildSheetsFixture(), [], [], [], { + renames: [], + additions: [{ name: 'Other Copy', sourceSheetName: 'Other' }], + removals: [], + order: ['Data', 'Other', 'Other Copy', 'My Sheet'], + }), + ).rejects.toThrow('sheet-scoped defined names') }) it('clone helpers sanitize part-scoped state', () => { - expect(sanitizeClonedWorksheetXml( - '', - )).toBe('') - expect(stripPageSetupRelIds('')) - .toBe('') - const hyperlinkOnly = '' - expect(prepareClonedSheetRels(hyperlinkOnly, 'Data')) - .toEqual({ relsXml: hyperlinkOnly, droppedPrinterSettings: false }) - const printerOnly = '' - expect(prepareClonedSheetRels(printerOnly, 'Data')) - .toEqual({ relsXml: null, droppedPrinterSettings: true }) - const commentRels = '' + expect( + sanitizeClonedWorksheetXml( + '', + ), + ).toBe('') + expect( + stripPageSetupRelIds(''), + ).toBe('') + const hyperlinkOnly = + '' + expect(prepareClonedSheetRels(hyperlinkOnly, 'Data')).toEqual({ + relsXml: hyperlinkOnly, + droppedPrinterSettings: false, + }) + const printerOnly = + '' + expect(prepareClonedSheetRels(printerOnly, 'Data')).toEqual({ + relsXml: null, + droppedPrinterSettings: true, + }) + const commentRels = + '' expect(() => prepareClonedSheetRels(commentRels, 'Data')).toThrow(SheetEditError) }) }) @@ -359,9 +541,9 @@ describe('combined sheet operations', () => { const workbook = await entryText(mutation.buffer, 'xl/workbook.xml') const sheetsBlock = /([\s\S]*?)<\/sheets>/.exec(workbook)?.[1] ?? '' expect(sheetsBlock).toBe( - '' - + '' - + '', + '' + + '' + + '', ) const chart = await entryText(mutation.buffer, 'xl/charts/chart1.xml') expect(chart).toContain('Numbers!$A$1:$A$2') @@ -370,11 +552,13 @@ describe('combined sheet operations', () => { }) it('rejects an order that does not match the final sheet set', async () => { - await expect(applyCellEditsToXlsx(await buildSheetsFixture(), [], [], [], { - renames: [], - additions: [], - removals: ['Other'], - order: ['Data', 'Other', 'My Sheet'], - })).rejects.toThrow('sheet order') + await expect( + applyCellEditsToXlsx(await buildSheetsFixture(), [], [], [], { + renames: [], + additions: [], + removals: ['Other'], + order: ['Data', 'Other', 'My Sheet'], + }), + ).rejects.toThrow('sheet order') }) }) diff --git a/apps/shell/electron-builder.cjs b/apps/shell/electron-builder.cjs index a501cb2..c557486 100644 --- a/apps/shell/electron-builder.cjs +++ b/apps/shell/electron-builder.cjs @@ -14,11 +14,21 @@ * app-update.yml into the app and in-app auto-update stays disabled. */ +const { execFileSync } = require('node:child_process') const { existsSync } = require('node:fs') const { join } = require('node:path') const updateUrl = process.env.GENOFFICE_UPDATE_URL +// GENOFFICE_MAC_X64=1 — opt into packaging the Intel (x64) dmg/zip alongside +// arm64. Off by default: Intel packages must only ever ship signed with the +// company certificate (planned dual-track pipeline), so the current release +// pipeline stays arm64-only and never produces a personally-signed Intel +// artifact. The downstream layout (feed archive name, GenOffice-intel.dmg +// alias) keys off which dmgs exist, so flipping this flag is the single +// switch. +const includeMacX64 = process.env.GENOFFICE_MAC_X64 === '1' + // The gsk CLI tree below is copied verbatim from node_modules, and the // nested commander path depends on npm's current hoisting layout — fail the // build with a clear message if an install ever changes it, instead of @@ -52,6 +62,30 @@ for (const rel of [ // Runs from the beforePack hook, not at module load: gen-third-party-notices // requires this config to read extraResources, and the dist:* scripts run // notices before build:all, when the out dirs legitimately don't exist yet. +// When the mac build packages BOTH arches (GENOFFICE_MAC_X64=1) its +// extraResources entry is a single path shared by the two packs, so the +// sidecar there must be a lipo fat binary — a host-arch-only build (the plain +// `native:build` dev path) would silently ship an arm64 sidecar inside the +// Intel dmg, where every workbook open fails. Runs from beforePack, dual-arch +// mac packs only. +function assertUniversalSidecar() { + const sidecar = join(__dirname, '../sheets/native/xlsx-engine/target/release/xlsx-sidecar') + if (!existsSync(sidecar)) { + throw new Error( + `mac extraResources source missing: ${sidecar} (run "npm run native:build:universal -w @genoffice/sheets" first)`, + ) + } + const archs = execFileSync('lipo', ['-archs', sidecar], { encoding: 'utf8' }).trim().split(/\s+/) + for (const want of ['x86_64', 'arm64']) { + if (!archs.includes(want)) { + throw new Error( + `xlsx-sidecar is [${archs.join(', ')}] but both mac arch packages ship it — ` + + 'run "npm run native:build:universal -w @genoffice/sheets" before packaging mac', + ) + } + } +} + function assertModuleTreesPresent() { for (const rel of [ '../docs/out', @@ -187,7 +221,17 @@ const config = { ], npmRebuild: false, mac: { - target: ['dmg', 'zip'], + // Two separate arch packages (NOT universal): arm64 keeps the exact + // artifact names and update-feed entries it always had, x64 (opt-in via + // GENOFFICE_MAC_X64=1, see includeMacX64 above) adds Intel support with + // electron-builder's default arch-less names (GenOffice-.dmg / + // GenOffice--mac.zip). Both zips land in one latest-mac.yml and + // electron-updater picks by process.arch. Dual-arch packs ship the same + // lipo fat xlsx-sidecar (see assertUniversalSidecar above). + target: [ + { target: 'dmg', arch: includeMacX64 ? ['arm64', 'x64'] : ['arm64'] }, + { target: 'zip', arch: includeMacX64 ? ['arm64', 'x64'] : ['arm64'] }, + ], category: 'public.app-category.productivity', hardenedRuntime: true, gatekeeperAssess: false, @@ -223,13 +267,15 @@ const config = { // reverse, needs a matching `cargo build --target` first. linux: { // AppImage (self-contained, any distro) + deb (apt install, pulls in the - // GTK/NSS runtime deps). Default artifact names are kept on purpose — + // GTK/NSS runtime deps) + rpm (dnf/zypper install on Fedora / RHEL / + // openSUSE). Default artifact names are kept on purpose — // GenOffice-.AppImage / genoffice__amd64.deb — because the public // README download links and the already-published linux-v0.5.149 release // use them. target: [ { target: 'AppImage', arch: ['x64'] }, { target: 'deb', arch: ['x64'] }, + { target: 'rpm', arch: ['x64'] }, ], // deb control metadata; values match the manually published 0.5.149 deb // so apt sees the new packages as the same lineage. Homepage comes from @@ -272,12 +318,29 @@ const config = { artifactName: 'genoffice_${version}_${arch}.deb', packageName: 'genoffice', }, + // Same "@genoffice/shell" naming problem as deb: spell the artifact name + // out (${arch} expands to the rpm arch string, x86_64) and pin the rpm + // Package name so dnf/zypper treat successive releases as upgrades of the + // same package. Like deb, rpm installs run no in-app updater — users + // upgrade with `dnf install ./.rpm`. Packaging needs rpmbuild on the + // build host (the `rpm` apt package on Ubuntu; CI installs it). + // + // publish: null (explicit) keeps the rpm out of the electron-updater feed + // and off the CDN entirely: the rpm is a GitHub-Release download only, so + // latest-linux.yml keeps listing exactly what the CDN pipeline uploads + // (AppImage + deb) and the promote workflow needs no rpm alias. + rpm: { + artifactName: 'genoffice-${version}.${arch}.rpm', + packageName: 'genoffice', + publish: null, + }, nsis: { oneClick: false, allowToChangeInstallationDirectory: true, }, - beforePack: async () => { + beforePack: async (context) => { assertModuleTreesPresent() + if (context.electronPlatformName === 'darwin' && includeMacX64) assertUniversalSidecar() }, dmg: { sign: true, diff --git a/apps/shell/src/main/index.ts b/apps/shell/src/main/index.ts index a0ec81c..f9346d6 100644 --- a/apps/shell/src/main/index.ts +++ b/apps/shell/src/main/index.ts @@ -1,4 +1,4 @@ -import { spawn } from 'node:child_process' +import { execSync, spawn } from 'node:child_process' import { copyFileSync, cpSync, @@ -36,11 +36,13 @@ import menuHomeIcon1x from './assets/menu-home.png?asset' import menuHomeIcon2x from './assets/menu-home@2x.png?asset' import { createI18n, isLang, normalizeLang, setUiLang, type Lang } from '@genoffice/i18n' import { + DEFAULT_SAVE_DIR_KEY, appMenuLabels, contextMenuLabels, editMenuTemplate, installContextMenu, installNavigationGuard, + isUsableSaveDir, showOpenDialogWithMemory, showSaveDialogWithMemory, windowMenuTemplate, @@ -284,6 +286,10 @@ function currentTheme(): UiTheme { // invite link, which stays out of this repo and rotates server-side. const GENTEAM_URL = 'https://genoffice.ai/join' +// Genspark credit-usage page opened from the account menu's credits row. +// Kept main-side so the renderer never supplies the URL. +const CREDIT_USAGE_URL = 'https://www.genspark.ai/credit-usage' + const tMain = createI18n({ zh: { menuFile: '文件', @@ -335,6 +341,8 @@ const tMain = createI18n({ pdfDocxFailedMsg: '导出为 Word 失败', pdfDocxNoCliMsg: '无法登录 Genspark:缺少必需组件(gsk),请重新安装应用。', pdfDocxBusyMsg: '正在转换中,请等待当前导出完成。', + dlgPickSaveDir: '选择默认保存位置', + errSaveDirUnusable: '所选文件夹不可写,无法用作默认保存位置', }, en: { menuFile: 'File', @@ -389,6 +397,9 @@ const tMain = createI18n({ pdfDocxNoCliMsg: 'Cannot sign in to Genspark: a required component (gsk) is missing. Please reinstall the app.', pdfDocxBusyMsg: 'A Word export is already in progress. Please wait for it to finish.', + dlgPickSaveDir: 'Choose Default Save Location', + errSaveDirUnusable: + 'The selected folder is not writable and cannot be used as the default save location', }, ja: { menuFile: 'ファイル', @@ -443,6 +454,9 @@ const tMain = createI18n({ pdfDocxNoCliMsg: 'Genspark にサインインできません:必要なコンポーネント(gsk)が見つかりません。アプリを再インストールしてください。', pdfDocxBusyMsg: 'Word への書き出しが進行中です。完了までお待ちください。', + dlgPickSaveDir: '既定の保存先を選択', + errSaveDirUnusable: + '選択したフォルダーは書き込みできないため、既定の保存先として使用できません', }, ko: { menuFile: '파일', @@ -497,6 +511,8 @@ const tMain = createI18n({ pdfDocxNoCliMsg: 'Genspark에 로그인할 수 없습니다. 필수 구성 요소(gsk)가 없습니다. 앱을 다시 설치해 주세요.', pdfDocxBusyMsg: 'Word 내보내기가 이미 진행 중입니다. 완료될 때까지 기다려 주세요.', + dlgPickSaveDir: '기본 저장 위치 선택', + errSaveDirUnusable: '선택한 폴더에 쓸 수 없어 기본 저장 위치로 사용할 수 없습니다', }, fr: { menuFile: 'Fichier', @@ -551,6 +567,9 @@ const tMain = createI18n({ pdfDocxNoCliMsg: "Connexion à Genspark impossible : un composant requis (gsk) est manquant. Veuillez réinstaller l'application.", pdfDocxBusyMsg: "Un export en Word est déjà en cours. Veuillez attendre qu'il se termine.", + dlgPickSaveDir: "Choisir l'emplacement d'enregistrement par défaut", + errSaveDirUnusable: + "Le dossier sélectionné n'est pas accessible en écriture et ne peut pas servir d'emplacement d'enregistrement par défaut", }, de: { menuFile: 'Datei', @@ -605,6 +624,9 @@ const tMain = createI18n({ pdfDocxNoCliMsg: 'Anmeldung bei Genspark nicht möglich: Eine erforderliche Komponente (gsk) fehlt. Bitte installieren Sie die App neu.', pdfDocxBusyMsg: 'Ein Word-Export läuft bereits. Bitte warten Sie, bis er abgeschlossen ist.', + dlgPickSaveDir: 'Standard-Speicherort auswählen', + errSaveDirUnusable: + 'Der ausgewählte Ordner ist nicht beschreibbar und kann nicht als Standard-Speicherort verwendet werden', }, es: { menuFile: 'Archivo', @@ -659,6 +681,9 @@ const tMain = createI18n({ pdfDocxNoCliMsg: 'No se puede iniciar sesión en Genspark: falta un componente necesario (gsk). Reinstale la aplicación.', pdfDocxBusyMsg: 'Ya hay una exportación a Word en curso. Espera a que termine.', + dlgPickSaveDir: 'Elegir ubicación de guardado predeterminada', + errSaveDirUnusable: + 'La carpeta seleccionada no admite escritura y no puede usarse como ubicación de guardado predeterminada', }, th: { menuFile: 'ไฟล์', @@ -712,6 +737,8 @@ const tMain = createI18n({ pdfDocxNoCliMsg: 'ไม่สามารถลงชื่อเข้าใช้ Genspark ได้: ไม่พบคอมโพเนนต์ที่จำเป็น (gsk) โปรดติดตั้งแอปใหม่', pdfDocxBusyMsg: 'กำลังส่งออกเป็น Word อยู่ โปรดรอให้เสร็จสิ้นก่อน', + dlgPickSaveDir: 'เลือกตำแหน่งบันทึกเริ่มต้น', + errSaveDirUnusable: 'โฟลเดอร์ที่เลือกไม่สามารถเขียนได้ จึงใช้เป็นตำแหน่งบันทึกเริ่มต้นไม่ได้', }, id: { menuFile: 'File', @@ -766,6 +793,9 @@ const tMain = createI18n({ pdfDocxNoCliMsg: 'Tidak dapat masuk ke Genspark: komponen yang diperlukan (gsk) tidak ditemukan. Silakan instal ulang aplikasi.', pdfDocxBusyMsg: 'Ekspor ke Word sedang berlangsung. Harap tunggu hingga selesai.', + dlgPickSaveDir: 'Pilih Lokasi Penyimpanan Default', + errSaveDirUnusable: + 'Folder yang dipilih tidak dapat ditulis dan tidak bisa digunakan sebagai lokasi penyimpanan default', }, ru: { menuFile: 'Файл', @@ -820,6 +850,9 @@ const tMain = createI18n({ pdfDocxNoCliMsg: 'Не удаётся войти в Genspark: отсутствует необходимый компонент (gsk). Переустановите приложение.', pdfDocxBusyMsg: 'Экспорт в Word уже выполняется. Дождитесь его завершения.', + dlgPickSaveDir: 'Выбрать папку сохранения по умолчанию', + errSaveDirUnusable: + 'Выбранная папка недоступна для записи и не может использоваться как папка сохранения по умолчанию', }, ar: { menuFile: 'ملف', @@ -873,6 +906,8 @@ const tMain = createI18n({ pdfDocxNoCliMsg: 'تعذّر تسجيل الدخول إلى Genspark: المكوّن المطلوب (gsk) مفقود. يُرجى إعادة تثبيت التطبيق.', pdfDocxBusyMsg: 'يجري حاليًا تصدير إلى Word. يُرجى الانتظار حتى يكتمل.', + dlgPickSaveDir: 'اختيار موقع الحفظ الافتراضي', + errSaveDirUnusable: 'المجلد المحدد غير قابل للكتابة ولا يمكن استخدامه كموقع حفظ افتراضي', }, pt: { menuFile: 'Arquivo', @@ -927,6 +962,9 @@ const tMain = createI18n({ pdfDocxNoCliMsg: 'Não é possível iniciar sessão no Genspark: falta um componente necessário (gsk). Reinstale o aplicativo.', pdfDocxBusyMsg: 'Já há uma exportação para Word em andamento. Aguarde a conclusão.', + dlgPickSaveDir: 'Escolher local de salvamento padrão', + errSaveDirUnusable: + 'A pasta selecionada não permite gravação e não pode ser usada como local de salvamento padrão', }, it: { menuFile: 'File', @@ -981,6 +1019,9 @@ const tMain = createI18n({ pdfDocxNoCliMsg: "Impossibile accedere a Genspark: manca un componente necessario (gsk). Reinstallare l'app.", pdfDocxBusyMsg: "Un'esportazione in Word è già in corso. Attendi il completamento.", + dlgPickSaveDir: 'Scegli la posizione di salvataggio predefinita', + errSaveDirUnusable: + 'La cartella selezionata non è scrivibile e non può essere usata come posizione di salvataggio predefinita', }, pl: { menuFile: 'Plik', @@ -1035,6 +1076,9 @@ const tMain = createI18n({ pdfDocxNoCliMsg: 'Nie można zalogować się do Genspark: brakuje wymaganego komponentu (gsk). Zainstaluj aplikację ponownie.', pdfDocxBusyMsg: 'Eksport do formatu Word już trwa. Poczekaj na jego zakończenie.', + dlgPickSaveDir: 'Wybierz domyślną lokalizację zapisu', + errSaveDirUnusable: + 'Wybrany folder nie pozwala na zapis i nie może być domyślną lokalizacją zapisu', }, nl: { menuFile: 'Bestand', @@ -1089,6 +1133,9 @@ const tMain = createI18n({ pdfDocxNoCliMsg: 'Kan niet inloggen bij Genspark: een vereist onderdeel (gsk) ontbreekt. Installeer de app opnieuw.', pdfDocxBusyMsg: 'Er is al een Word-export bezig. Wacht tot deze is voltooid.', + dlgPickSaveDir: 'Standaard opslaglocatie kiezen', + errSaveDirUnusable: + 'De geselecteerde map is niet beschrijfbaar en kan niet als standaard opslaglocatie worden gebruikt', }, ms: { menuFile: 'Fail', @@ -1143,6 +1190,9 @@ const tMain = createI18n({ pdfDocxNoCliMsg: 'Tidak dapat log masuk ke Genspark: komponen yang diperlukan (gsk) tiada. Sila pasang semula aplikasi.', pdfDocxBusyMsg: 'Eksport ke Word sedang dijalankan. Sila tunggu sehingga selesai.', + dlgPickSaveDir: 'Pilih Lokasi Simpanan Lalai', + errSaveDirUnusable: + 'Folder yang dipilih tidak boleh ditulis dan tidak dapat digunakan sebagai lokasi simpanan lalai', }, he: { menuFile: 'קובץ', @@ -1194,6 +1244,9 @@ const tMain = createI18n({ pdfDocxFailedMsg: 'הייצוא כ-Word נכשל', pdfDocxNoCliMsg: 'לא ניתן להתחבר ל-Genspark: רכיב נדרש (gsk) חסר. נא להתקין מחדש את האפליקציה.', pdfDocxBusyMsg: 'ייצוא ל-Word כבר מתבצע. נא להמתין לסיומו.', + dlgPickSaveDir: 'בחירת מיקום שמירה כברירת מחדל', + errSaveDirUnusable: + 'התיקייה שנבחרה אינה ניתנת לכתיבה ולא ניתן להשתמש בה כמיקום שמירה כברירת מחדל', }, hi: { menuFile: 'फ़ाइल', @@ -1248,6 +1301,9 @@ const tMain = createI18n({ pdfDocxNoCliMsg: 'Genspark में साइन इन नहीं किया जा सकता: आवश्यक घटक (gsk) मौजूद नहीं है। कृपया ऐप को फिर से इंस्टॉल करें।', pdfDocxBusyMsg: 'Word के रूप में निर्यात पहले से चल रहा है। कृपया पूरा होने तक प्रतीक्षा करें।', + dlgPickSaveDir: 'डिफ़ॉल्ट सहेजने का स्थान चुनें', + errSaveDirUnusable: + 'चयनित फ़ोल्डर में लिखा नहीं जा सकता, इसलिए इसे डिफ़ॉल्ट सहेजने के स्थान के रूप में उपयोग नहीं किया जा सकता', }, 'zh-TW': { menuFile: '檔案', @@ -1299,6 +1355,8 @@ const tMain = createI18n({ pdfDocxFailedMsg: '匯出為 Word 失敗', pdfDocxNoCliMsg: '無法登入 Genspark:缺少必要元件(gsk),請重新安裝應用程式。', pdfDocxBusyMsg: '正在轉換中,請等待目前的匯出完成。', + dlgPickSaveDir: '選擇預設儲存位置', + errSaveDirUnusable: '所選資料夾無法寫入,無法作為預設儲存位置', }, }) @@ -1385,6 +1443,9 @@ function createShellWindow(): void { }, }) shellWindow = win + // dragging the window by the tab strip's blank (draggable) area produces no + // DOM event anywhere — will-move is the only signal to dismiss popovers + win.on('will-move', broadcastChromePressed) const manager = new TabManager( win, @@ -1713,7 +1774,9 @@ function registerHomeIpc(): void { if (!loadGenofficeAuth()) return { loggedIn: false } await proxyBootstrap const info = await gskLoginInfo() - return info ? { loggedIn: true, email: info.email } : { loggedIn: true } + return info + ? { loggedIn: true, email: info.email, creditBalance: info.creditBalance } + : { loggedIn: true } }) // login progress is streamed to the requesting renderer; the auth URL is @@ -1948,12 +2011,38 @@ function registerHomeIpc(): void { for (const wc of webContents.getAllWebContents()) wc.send('app:theme-changed', theme) }) + // effective folder where new/untitled files land; the editor mains resolve + // the same setting themselves (configuredDefaultSaveDir via docs' defaultSaveDir) + ipcMain.handle(HOME_CHANNELS.getDefaultSaveDir, (): string => defaultSaveDir()) + + ipcMain.handle(HOME_CHANNELS.pickDefaultSaveDir, async (): Promise => { + const result = await showOpenDialogWithMemory(dialog, shellWindow, { + title: tm('dlgPickSaveDir'), + defaultPath: defaultSaveDir(), + properties: ['openDirectory', 'createDirectory'], + }) + const picked = result.filePaths[0] + if (result.canceled || !picked) return null + if (!isUsableSaveDir(picked)) { + showErrorDialog(shellWindow, tm('errSaveDirUnusable'), picked) + return null + } + writeAppSetting(APP_SETTINGS_PATH(), DEFAULT_SAVE_DIR_KEY, picked) + return picked + }) + ipcMain.handle(HOME_CHANNELS.openGenTeam, () => { shell.openExternal(GENTEAM_URL).catch(() => { // no browser handler available; nothing actionable for the user here }) }) + ipcMain.handle(HOME_CHANNELS.openCreditUsage, () => { + shell.openExternal(CREDIT_USAGE_URL).catch(() => { + // no browser handler available; nothing actionable for the user here + }) + }) + const cloudProjectsStorePath = () => join(app.getPath('userData'), 'cloud-projects.json') ipcMain.handle(HOME_CHANNELS.cloudProjectsCached, () => @@ -2011,7 +2100,14 @@ const TAB_MENU_ICON: Record = { markdown: 'md', } +// tab views see neither DOM events nor a focus change when the user clicks the +// shell chrome — relay the press so open popovers in documents can dismiss +function broadcastChromePressed(): void { + for (const wc of webContents.getAllWebContents()) wc.send('app:chrome-pressed') +} + function registerTabsIpc(): void { + ipcMain.on(TABS_CHANNELS.chromePressed, broadcastChromePressed) ipcMain.handle(TABS_CHANNELS.list, () => tabManager?.list() ?? []) ipcMain.handle(TABS_CHANNELS.activate, (_event, id: string) => tabManager?.activateTab(id)) ipcMain.handle(TABS_CHANNELS.close, (_event, id: string) => tabManager?.closeTab(id)) @@ -2532,14 +2628,46 @@ registerTabsIpc() // sheets' project:resolveChat goes through the handler registered by docs-main; the sessionId reverse lookup hooks in here setSessionPathResolver(resolveSheetsSessionPath) -app.whenReady().then(() => { - const hasLock = app.requestSingleInstanceLock( - pendingLaunchPath ? { launchPath: pendingLaunchPath } : {}, - ) +/** Dev-only pid marker for the takeover below; scoped to userData like the lock itself. */ +const devPidFile = () => join(app.getPath('userData'), 'dev-instance.pid') + +app.whenReady().then(async () => { + const lockData = () => (pendingLaunchPath ? { launchPath: pendingLaunchPath } : {}) + let hasLock = app.requestSingleInstanceLock(lockData()) + if (!hasLock && !app.isPackaged) { + // Dev watch restart: electron-vite SIGTERMs the previous instance and spawns this + // one immediately. Chromium turns that SIGTERM into a graceful quit (Node's + // process.on('SIGTERM') never fires in the main process), and the quit can wedge + // in the close-confirmation flow — the zombie then keeps the single-instance lock, + // this instance quits, and electron-vite's on-close handler exits with it, killing + // the renderer dev server (blank shell window until a manual dev restart). + // The previous instance is doomed either way: kill it and take over the lock. + try { + const oldPid = Number(readFileSync(devPidFile(), 'utf-8').trim()) + if (Number.isFinite(oldPid) && oldPid > 0 && oldPid !== process.pid) { + // pid-recycling guard: only kill if that pid is still an Electron process + const cmd = execSync(`ps -o command= -p ${oldPid}`).toString() + if (cmd.includes('Electron')) process.kill(oldPid, 'SIGKILL') + } + } catch { + // no previous instance recorded / already gone (ps exits non-zero) + } + for (let i = 0; i < 20 && !hasLock; i++) { + await new Promise((r) => setTimeout(r, 150)) + hasLock = app.requestSingleInstanceLock(lockData()) + } + } if (!hasLock) { app.quit() return } + if (!app.isPackaged) { + try { + writeFileSync(devPidFile(), String(process.pid)) + } catch { + // best-effort: without the marker the next restart just retries the lock + } + } proxyBootstrap = installMainProcessProxy() app.setAccessibilitySupportEnabled(true) diff --git a/apps/shell/src/main/update-window.ts b/apps/shell/src/main/update-window.ts index 5dd6b8b..16e72b5 100644 --- a/apps/shell/src/main/update-window.ts +++ b/apps/shell/src/main/update-window.ts @@ -14,6 +14,7 @@ interface UpdateActions { onDownload: () => void onInstall: () => void onLater: () => void + onOpenDownload: () => void } let updateWin: BrowserWindow | null = null @@ -31,6 +32,7 @@ function registerIpc(): void { ipcMain.handle(UPDATE_CHANNELS.download, () => actions?.onDownload()) ipcMain.handle(UPDATE_CHANNELS.install, () => actions?.onInstall()) ipcMain.handle(UPDATE_CHANNELS.later, () => actions?.onLater()) + ipcMain.handle(UPDATE_CHANNELS.openDownload, () => actions?.onOpenDownload()) } export function showUpdateWindow( @@ -84,6 +86,10 @@ export function showUpdateWindow( } } +export function isUpdateWindowOpen(): boolean { + return updateWin !== null && !updateWin.isDestroyed() +} + export function pushUpdateState(patch: Partial): void { if (!currentState) return currentState = { ...currentState, ...patch } diff --git a/apps/shell/src/main/updater.ts b/apps/shell/src/main/updater.ts index 55dc9a2..5e1ad3a 100644 --- a/apps/shell/src/main/updater.ts +++ b/apps/shell/src/main/updater.ts @@ -1,10 +1,15 @@ -import { app } from 'electron' +import { app, shell } from 'electron' import type { BrowserWindow } from 'electron' import { autoUpdater } from 'electron-updater' import type { UpdateInfo } from 'electron-updater' import { createI18n, getUiLang, htmlLang } from '@genoffice/i18n' import type { UpdateChannel, UpdateUiState, UpdateUiStrings } from '../shared/update-api' -import { closeUpdateWindow, pushUpdateState, showUpdateWindow } from './update-window' +import { + closeUpdateWindow, + isUpdateWindowOpen, + pushUpdateState, + showUpdateWindow, +} from './update-window' /** * Full-package auto-update over the generic provider (Azure CDN). @@ -39,6 +44,8 @@ const tUpd = createI18n({ updDownloading: '正在下载更新…', updFailed: '更新下载失败,请检查网络后重试。', updRetry: '重试', + updManual: '自动更新失败,请从下载页面获取最新版本并手动安装。', + updOpenDownload: '前往下载页面', }, en: { updTitle: 'Software Update', @@ -51,6 +58,9 @@ const tUpd = createI18n({ updDownloading: 'Downloading update…', updFailed: 'Update download failed. Check your network and try again.', updRetry: 'Retry', + updManual: + 'Automatic update failed. Please get the latest version from the download page and install it manually.', + updOpenDownload: 'Open Download Page', }, ja: { updTitle: 'ソフトウェアアップデート', @@ -63,6 +73,9 @@ const tUpd = createI18n({ updDownloading: 'アップデートをダウンロード中…', updFailed: 'ダウンロードに失敗しました。ネットワークを確認して再試行してください。', updRetry: '再試行', + updManual: + '自動更新に失敗しました。ダウンロードページから最新バージョンを取得して手動でインストールしてください。', + updOpenDownload: 'ダウンロードページを開く', }, ko: { updTitle: '소프트웨어 업데이트', @@ -75,6 +88,9 @@ const tUpd = createI18n({ updDownloading: '업데이트 다운로드 중…', updFailed: '업데이트 다운로드에 실패했습니다. 네트워크를 확인한 후 다시 시도하세요.', updRetry: '다시 시도', + updManual: + '자동 업데이트에 실패했습니다. 다운로드 페이지에서 최신 버전을 받아 직접 설치해 주세요.', + updOpenDownload: '다운로드 페이지 열기', }, fr: { updTitle: 'Mise à jour logicielle', @@ -87,6 +103,9 @@ const tUpd = createI18n({ updDownloading: 'Téléchargement de la mise à jour…', updFailed: 'Échec du téléchargement. Vérifiez votre réseau et réessayez.', updRetry: 'Réessayer', + updManual: + 'La mise à jour automatique a échoué. Téléchargez la dernière version depuis la page de téléchargement et installez-la manuellement.', + updOpenDownload: 'Ouvrir la page de téléchargement', }, de: { updTitle: 'Softwareaktualisierung', @@ -100,6 +119,9 @@ const tUpd = createI18n({ updFailed: 'Download fehlgeschlagen. Prüfen Sie Ihre Netzwerkverbindung und versuchen Sie es erneut.', updRetry: 'Erneut versuchen', + updManual: + 'Automatisches Update fehlgeschlagen. Laden Sie die neueste Version von der Download-Seite herunter und installieren Sie sie manuell.', + updOpenDownload: 'Download-Seite öffnen', }, es: { updTitle: 'Actualización de software', @@ -112,6 +134,9 @@ const tUpd = createI18n({ updDownloading: 'Descargando la actualización…', updFailed: 'Error al descargar. Compruebe su red e inténtelo de nuevo.', updRetry: 'Reintentar', + updManual: + 'La actualización automática falló. Descargue la última versión desde la página de descargas e instálela manualmente.', + updOpenDownload: 'Abrir página de descargas', }, th: { updTitle: 'อัปเดตซอฟต์แวร์', @@ -123,6 +148,9 @@ const tUpd = createI18n({ updDownloading: 'กำลังดาวน์โหลดอัปเดต…', updFailed: 'ดาวน์โหลดไม่สำเร็จ โปรดตรวจสอบเครือข่ายแล้วลองอีกครั้ง', updRetry: 'ลองอีกครั้ง', + updManual: + 'การอัปเดตอัตโนมัติล้มเหลว โปรดดาวน์โหลดเวอร์ชันล่าสุดจากหน้าดาวน์โหลดแล้วติดตั้งด้วยตนเอง', + updOpenDownload: 'เปิดหน้าดาวน์โหลด', }, id: { updTitle: 'Pembaruan Perangkat Lunak', @@ -135,6 +163,9 @@ const tUpd = createI18n({ updDownloading: 'Mengunduh pembaruan…', updFailed: 'Unduhan gagal. Periksa jaringan Anda dan coba lagi.', updRetry: 'Coba Lagi', + updManual: + 'Pembaruan otomatis gagal. Silakan unduh versi terbaru dari halaman unduhan dan pasang secara manual.', + updOpenDownload: 'Buka Halaman Unduhan', }, ru: { updTitle: 'Обновление программы', @@ -147,6 +178,9 @@ const tUpd = createI18n({ updDownloading: 'Загрузка обновления…', updFailed: 'Не удалось загрузить обновление. Проверьте сеть и повторите попытку.', updRetry: 'Повторить', + updManual: + 'Автоматическое обновление не удалось. Скачайте последнюю версию со страницы загрузки и установите её вручную.', + updOpenDownload: 'Открыть страницу загрузки', }, ar: { updTitle: 'تحديث البرنامج', @@ -158,6 +192,8 @@ const tUpd = createI18n({ updDownloading: 'جارٍ تنزيل التحديث…', updFailed: 'فشل تنزيل التحديث. تحقق من الشبكة وحاول مرة أخرى.', updRetry: 'إعادة المحاولة', + updManual: 'فشل التحديث التلقائي. يرجى تنزيل أحدث إصدار من صفحة التنزيل وتثبيته يدويًا.', + updOpenDownload: 'فتح صفحة التنزيل', }, pt: { updTitle: 'Atualização de Software', @@ -170,6 +206,9 @@ const tUpd = createI18n({ updDownloading: 'Baixando a atualização…', updFailed: 'Falha no download. Verifique sua rede e tente novamente.', updRetry: 'Tentar novamente', + updManual: + 'A atualização automática falhou. Baixe a versão mais recente na página de download e instale manualmente.', + updOpenDownload: 'Abrir página de download', }, it: { updTitle: 'Aggiornamento software', @@ -182,6 +221,9 @@ const tUpd = createI18n({ updDownloading: "Download dell'aggiornamento…", updFailed: 'Download non riuscito. Controlla la rete e riprova.', updRetry: 'Riprova', + updManual: + "Aggiornamento automatico non riuscito. Scarica l'ultima versione dalla pagina di download e installala manualmente.", + updOpenDownload: 'Apri pagina di download', }, pl: { updTitle: 'Aktualizacja oprogramowania', @@ -194,6 +236,9 @@ const tUpd = createI18n({ updDownloading: 'Pobieranie aktualizacji…', updFailed: 'Pobieranie nie powiodło się. Sprawdź sieć i spróbuj ponownie.', updRetry: 'Spróbuj ponownie', + updManual: + 'Automatyczna aktualizacja nie powiodła się. Pobierz najnowszą wersję ze strony pobierania i zainstaluj ją ręcznie.', + updOpenDownload: 'Otwórz stronę pobierania', }, nl: { updTitle: 'Software-update', @@ -206,6 +251,9 @@ const tUpd = createI18n({ updDownloading: 'Update wordt gedownload…', updFailed: 'Download mislukt. Controleer uw netwerk en probeer het opnieuw.', updRetry: 'Opnieuw proberen', + updManual: + 'Automatische update mislukt. Download de nieuwste versie via de downloadpagina en installeer deze handmatig.', + updOpenDownload: 'Downloadpagina openen', }, ms: { updTitle: 'Kemas Kini Perisian', @@ -218,6 +266,9 @@ const tUpd = createI18n({ updDownloading: 'Memuat turun kemas kini…', updFailed: 'Muat turun gagal. Semak rangkaian anda dan cuba lagi.', updRetry: 'Cuba Lagi', + updManual: + 'Kemas kini automatik gagal. Sila muat turun versi terkini dari halaman muat turun dan pasang secara manual.', + updOpenDownload: 'Buka Halaman Muat Turun', }, he: { updTitle: 'עדכון תוכנה', @@ -229,6 +280,8 @@ const tUpd = createI18n({ updDownloading: 'מוריד את העדכון…', updFailed: 'ההורדה נכשלה. בדוק את הרשת ונסה שוב.', updRetry: 'נסה שוב', + updManual: 'העדכון האוטומטי נכשל. הורד את הגרסה העדכנית מדף ההורדות והתקן אותה ידנית.', + updOpenDownload: 'פתח את דף ההורדות', }, hi: { updTitle: 'सॉफ़्टवेयर अपडेट', @@ -241,6 +294,9 @@ const tUpd = createI18n({ updDownloading: 'अपडेट डाउनलोड हो रहा है…', updFailed: 'डाउनलोड विफल रहा। अपना नेटवर्क जाँचें और पुनः प्रयास करें।', updRetry: 'पुनः प्रयास करें', + updManual: + 'स्वचालित अपडेट विफल रहा। कृपया डाउनलोड पृष्ठ से नवीनतम संस्करण प्राप्त करें और मैन्युअल रूप से इंस्टॉल करें।', + updOpenDownload: 'डाउनलोड पृष्ठ खोलें', }, 'zh-TW': { updTitle: '軟體更新', @@ -252,12 +308,22 @@ const tUpd = createI18n({ updDownloading: '正在下載更新…', updFailed: '更新下載失敗,請檢查網路後重試。', updRetry: '重試', + updManual: '自動更新失敗,請從下載頁面取得最新版本並手動安裝。', + updOpenDownload: '前往下載頁面', }, }) const FIRST_CHECK_DELAY_MS = 15_000 const RECHECK_INTERVAL_MS = 4 * 60 * 60 * 1000 +// After this many failed download/apply attempts for the same version the +// dialog stops offering "retry" and guides the user to a manual download +// instead. Covers permanently broken update paths — most importantly a +// code-signing identity (Apple Team ID) change, which Squirrel.Mac rejects +// on every retry while the error looks like a download failure to the user. +const MANUAL_FALLBACK_AFTER = 2 +const DOWNLOAD_PAGE_URL = 'https://github.com/genspark-ai/genoffice/releases/latest' + let started = false // version the user declined this session — don't nag again until next launch let dismissedVersion: string | null = null @@ -287,6 +353,8 @@ function uiStrings(): UpdateUiStrings { downloading: tUpd(lang, 'updDownloading'), failed: tUpd(lang, 'updFailed'), retry: tUpd(lang, 'updRetry'), + manualDesc: tUpd(lang, 'updManual'), + openDownload: tUpd(lang, 'updOpenDownload'), } } @@ -347,13 +415,27 @@ export function initAutoUpdater( autoUpdater.disableDifferentialDownload = true let latestSeenVersion: string | null = null + // consecutive failed attempts for latestSeenVersion; a download can fail + // through the downloadUpdate() rejection OR only through the 'error' event + // (macOS: Squirrel.Mac reports signature/apply failures natively), so both + // paths funnel into failDownload() and the in-flight flag dedupes them + let failedAttempts = 0 + let downloadInFlight = false + + const failDownload = (): void => { + if (!downloadInFlight) return + downloadInFlight = false + failedAttempts += 1 + pushUpdateState({ phase: failedAttempts >= MANUAL_FALLBACK_AFTER ? 'manual' : 'error' }) + } const actions = { onDownload: () => { + downloadInFlight = true pushUpdateState({ phase: 'downloading', percent: 0 }) autoUpdater.downloadUpdate().catch((err) => { log('download failed:', err?.message ?? err) - pushUpdateState({ phase: 'error' }) + failDownload() }) }, onInstall: () => { @@ -365,18 +447,29 @@ export function initAutoUpdater( dismissedVersion = latestSeenVersion closeUpdateWindow() }, + onOpenDownload: () => { + void shell.openExternal(DOWNLOAD_PAGE_URL) + }, } autoUpdater.on('error', (err) => { // network failures during background checks are expected; only surface // when the user is watching a download log('error:', err?.message ?? err) + failDownload() }) autoUpdater.on('update-available', (info: UpdateInfo) => { if (info.version === dismissedVersion) return + const sameVersionRecheck = info.version === latestSeenVersion + if (!sameVersionRecheck) failedAttempts = 0 latestSeenVersion = info.version log('update available:', info.version) + // a periodic recheck resolving to the version the open dialog already + // shows must not reset its phase to 'available' — that would wipe an + // in-progress download or a terminal 'manual' fallback back to the + // "Update Now" offer + if (sameVersionRecheck && isUpdateWindowOpen()) return showUpdateWindow(getWindow(), initialState(info.version), actions) }) @@ -386,6 +479,8 @@ export function initAutoUpdater( autoUpdater.on('update-downloaded', (info: UpdateInfo) => { log('downloaded:', info.version) + downloadInFlight = false + failedAttempts = 0 pushUpdateState({ phase: 'downloaded', percent: 100 }) }) @@ -421,6 +516,9 @@ function initFakeUpdate(getWindow: () => BrowserWindow | null, version: string): if (timer) clearInterval(timer) closeUpdateWindow() }, + onOpenDownload: () => { + log('[fake] open download page requested') + }, } setTimeout(() => showUpdateWindow(getWindow(), initialState(version), actions), 1500) } diff --git a/apps/shell/src/preload/index.ts b/apps/shell/src/preload/index.ts index af54f49..8ee45d3 100644 --- a/apps/shell/src/preload/index.ts +++ b/apps/shell/src/preload/index.ts @@ -167,6 +167,14 @@ const homeApi: HomeApi = { throw new Error('Invalid theme.') await ipcRenderer.invoke(HOME_CHANNELS.setTheme, theme) }, + async getDefaultSaveDir() { + const result: unknown = await ipcRenderer.invoke(HOME_CHANNELS.getDefaultSaveDir) + return typeof result === 'string' ? result : '' + }, + async pickDefaultSaveDir() { + const result: unknown = await ipcRenderer.invoke(HOME_CHANNELS.pickDefaultSaveDir) + return typeof result === 'string' && result ? result : null + }, onThemeChanged(handler) { const listener = (_event: Electron.IpcRendererEvent, theme: unknown) => { if (theme === 'light' || theme === 'dark' || theme === 'system') handler(theme) @@ -177,6 +185,9 @@ const homeApi: HomeApi = { async openGenTeam() { await ipcRenderer.invoke(HOME_CHANNELS.openGenTeam) }, + async openCreditUsage() { + await ipcRenderer.invoke(HOME_CHANNELS.openCreditUsage) + }, async cloudProjectsCached() { const result: unknown = await ipcRenderer.invoke(HOME_CHANNELS.cloudProjectsCached) return asCloudProjectsSnapshot(result) @@ -269,6 +280,9 @@ const tabsApi: TabsApi = { ipcRenderer.on(TABS_CHANNELS.changed, listener) return () => ipcRenderer.removeListener(TABS_CHANNELS.changed, listener) }, + notifyChromePressed() { + ipcRenderer.send(TABS_CHANNELS.chromePressed) + }, } contextBridge.exposeInMainWorld('aiOfficeTabs', tabsApi) diff --git a/apps/shell/src/preload/update.ts b/apps/shell/src/preload/update.ts index 07dec87..7056bd0 100644 --- a/apps/shell/src/preload/update.ts +++ b/apps/shell/src/preload/update.ts @@ -17,6 +17,9 @@ const api: UpdateWindowApi = { later() { void ipcRenderer.invoke(UPDATE_CHANNELS.later) }, + openDownload() { + void ipcRenderer.invoke(UPDATE_CHANNELS.openDownload) + }, onState(handler) { const listener = (_event: IpcRendererEvent, state: UpdateUiState) => handler(state) ipcRenderer.on(UPDATE_CHANNELS.changed, listener) diff --git a/apps/shell/src/renderer/src/Home.tsx b/apps/shell/src/renderer/src/Home.tsx index da4b788..06798fb 100644 --- a/apps/shell/src/renderer/src/Home.tsx +++ b/apps/shell/src/renderer/src/Home.tsx @@ -18,6 +18,7 @@ import type { import { fileCountKey, visiblePageCount } from './counts' import { useI18n } from './locale' import type { I18n, StringKey } from './locale' +import { SettingsModal } from './SettingsModal' declare global { interface Window { @@ -210,7 +211,7 @@ function ProjectPanel({ projects, selectedId, onSelect, onRefresh }: ProjectPane {t('projects')} - {waiting && authUrl && ( - <> - - - - )} - - )} -
      -
      - - {langFly && ( -
      - {LANG_OPTIONS.map((opt) => ( - - ))} -
      - )} -
      -
      - - {themeFly && ( -
      - {THEME_OPTIONS.map((opt) => ( - - ))} -
      - )} -
      -
      - - {chanFly && ( -
      - {CHANNEL_OPTIONS.map((opt) => ( - - ))} -
      - )} -
      - {appVersion && ( -
      - - {t('versionLabel')} - {appVersion} -
      - )} - {loggedIn && ( - - )} -
      + {settingsOpen && ( + setSettingsOpen(false)} + onLogin={() => { + setSettingsOpen(false) + startLogin() + }} + onLogout={doLogout} + /> )} - {!menuOpen && waiting && authUrl && ( + {!settingsOpen && waiting && authUrl && (
      ) @@ -1261,7 +783,7 @@ function CloudProjectsView() {
    • + +
      + +
      + {section === 'account' && ( + <> +

      {t('setSecAccount')}

      + + {loggedIn && ( + void window.aiOffice.openCreditUsage?.()} + > + {t('setViewUsage')} + + } + /> + )} +
      + {loggedIn ? ( + + ) : ( + <> + {loginWaiting && loginUrl && ( + <> + + + + )} + + + )} +
      + + )} + {section === 'general' && ( + <> +

      {t('setSecGeneral')}

      +
      +
      + +
      + +
      +
      +
      + +
      + +
      + + {t('setChange')} + + } + /> + + )} + {section === 'about' && ( + <> +

      {t('setSecAbout')}

      + +
      +
      + +
      + +
      + + )} +
      +
      + + + ) +} diff --git a/apps/shell/src/renderer/src/TabBar.tsx b/apps/shell/src/renderer/src/TabBar.tsx index 448cad1..2752093 100644 --- a/apps/shell/src/renderer/src/TabBar.tsx +++ b/apps/shell/src/renderer/src/TabBar.tsx @@ -159,6 +159,14 @@ export function TabBar() { return window.aiOfficeTabs.onChanged(setTabs) }, []) + // document tabs are sibling WebContentsViews: they see neither this press + // nor a focus change, so relay it for them to dismiss open popovers + useEffect(() => { + const notify = (): void => window.aiOfficeTabs.notifyChromePressed?.() + document.addEventListener('pointerdown', notify, true) + return () => document.removeEventListener('pointerdown', notify, true) + }, []) + // if the dragged tab is closed mid-drag (e.g. Cmd+W) its element unmounts // and pointerup/pointercancel never fire — clear the drag state ourselves useEffect(() => { @@ -311,6 +319,7 @@ export function TabBar() { )} @@ -2523,7 +2576,7 @@ export function App() {
      setCurrent((c) => Math.min(c + 1, slides.length - 1))} > @@ -2557,7 +2610,7 @@ export function App() {
      { setCurrent(i) @@ -2630,7 +2683,7 @@ export function App() {
      { setCurrent(i) @@ -2747,7 +2800,7 @@ export function App() {
      ) @@ -1583,12 +1693,22 @@ export function AiPanel({
      {chat.length > 0 && ( - )} {onCollapse && ( - )} @@ -1601,6 +1721,9 @@ export function AiPanel({ <> {historicChat.map((entry, i) => (
      + {entry.role === 'user' && entry.attachments && entry.attachments.length > 0 && ( + + )} {entry.tools && entry.tools.length > 0 && } {entry.text && }
      @@ -1653,12 +1776,16 @@ export function AiPanel({ entry.role === 'assistant' && !entry.streaming && turnEnded && - !!(entry.text || entry.error) + // edits-only turns have no text but still carry the rollback point + (!!(entry.text || entry.error) || entry.snapshotId != null) return (
      + {entry.role === 'user' && entry.attachments && entry.attachments.length > 0 && ( + + )} {entry.role === 'assistant' && !entry.text && entry.streaming ? ( - + {/* 24-canvas glyph at 18px (near-full-bleed paths, sized for optical + parity with the copy icon): stroke 1.5 paints 1.125px (1:16) */} + + + + + + )} + {entry.snapshotId != null && ( + <> + {/* hairline between reply actions (icons) and the document action (icon+label); + CSS shows it only when an icon button actually precedes it */} + + void rollback(entry.snapshotId!)} + /> + + )}
      )} {clarifyAnswers @@ -1752,30 +1906,6 @@ export function AiPanel({ )}
      - {snapshots.length > 0 && ( -
      -
      - - {t('aiSnapshotsTitle')} -
      - {snapshots.map((s) => ( -
      - - {s.time} - {s.label} - - -
      - ))} -
      - )} - {activeClarify ? ( /* Docked in the composer slot with the composer's own outer spacing */
      @@ -1802,7 +1932,7 @@ export function AiPanel({
      {attachments.map((a) => ATTACHMENT_IMAGE_EXTS.has(a.ext) ? ( - + {attachmentPreviews[a.path] ? ( {a.name} ) : ( @@ -1813,7 +1943,7 @@ export function AiPanel({ ) : ( - + @@ -1840,7 +1970,7 @@ export function AiPanel({ @@ -1896,7 +2027,7 @@ export function AiPanel({ @@ -2115,6 +2246,31 @@ function StepIcon({ status }: { status: 'running' | 'done' | 'error' }) { ) } +/** Quiet roll-back action in the message toolbar: restores the deck to before the run's edits */ +function RollbackButton({ disabled, onClick }: { disabled: boolean; onClick: () => void }) { + const { t: tr } = useI18n() + return ( + + ) +} + /** Tool activity group: a single quiet summary row * that auto-opens while tools run, auto-collapses into "Worked · N steps" when they finish, * and a manual toggle that always wins. Rows inside are step rows with 1px connectors. */ @@ -2170,14 +2326,14 @@ function ToolChipList({ tools }: { tools: ToolActivity[] }) { ) : ( - + {tool.summary} )} @@ -2321,7 +2477,7 @@ function DeckProgressCard({ progress }: { progress: DeckProgressSnapshot }) { {`${t('aiPageN', { n: i + 1 })}${p.title ? '·' + p.title : ''}`} {p.status === 'error' && p.error && ( - + {p.error} )} diff --git a/apps/slides/src/renderer/arrange-actions.ts b/apps/slides/src/renderer/arrange-actions.ts index 6df76b2..cf638c6 100644 --- a/apps/slides/src/renderer/arrange-actions.ts +++ b/apps/slides/src/renderer/arrange-actions.ts @@ -207,6 +207,79 @@ export async function flipSelected(ctx: ActionCtx, axis: 'h' | 'v'): Promise { + const items: Array<{ + sourceId: string + box: { x: number; y: number; w: number; h: number; rotationDeg: number } + groupId?: string + }> = [] + for (const id of ctx.selectedIds) { + const found = ctx.findNodeCtx(id) + if (!found) continue + const { node, groupId } = found + const isConnector = + (node.type === 'shape' || node.type === 'text') && !!(node as { line?: unknown }).line + if (isConnector) continue + const b = node.box + const deg = b.rotationDeg ?? 0 + // Konva transform order is translate(origin) → rotate → scale(flip): the local center + // lands at origin + R(θ)·S·(w/2, h/2). Track where it goes under the old and new + // angles and shift the origin by the difference (the flip part of the origin cancels). + const vx = (b.flipH ? -1 : 1) * (b.w / 2) + const vy = (b.flipV ? -1 : 1) * (b.h / 2) + const orbit = (angleDeg: number) => { + const t = (angleDeg * Math.PI) / 180 + return { x: vx * Math.cos(t) - vy * Math.sin(t), y: vx * Math.sin(t) + vy * Math.cos(t) } + } + const p0 = orbit(deg) + const p1 = orbit(deg + deltaDeg) + items.push({ + sourceId: id, + box: { + x: b.x + p0.x - p1.x, + y: b.y + p0.y - p1.y, + w: b.w, + h: b.h, + rotationDeg: (((deg + deltaDeg) % 360) + 360) % 360, + }, + ...(groupId ? { groupId } : {}), + }) + } + if (!items.length) return + // Top-level elements batch into one IPC so a multi-rotate is a single undo step; + // in-group children keep the per-element path (the batch op has no group support) + if (items.every((it) => !it.groupId)) { + const updated = await window.slidesApi.batchEditTransform({ + slideIndex: ctx.current, + fitWidthPx: FIT_WIDTH, + items: items.map((it) => ({ + sourceId: it.sourceId, + xPx: it.box.x, + yPx: it.box.y, + wPx: it.box.w, + hPx: it.box.h, + rotationDeg: it.box.rotationDeg, + })), + }) + if (updated) { + ctx.applySlide(ctx.current, updated) + ctx.setDirty(true) + } + return + } + for (const it of items) { + await ctx.onTransform(it.sourceId, it.box, undefined, it.groupId) + } +} + export async function eraseInk(ctx: ActionCtx, sourceIds: string[]): Promise { for (const id of sourceIds) { const updated = await window.slidesApi.deleteElement({ slideIndex: ctx.current, sourceId: id }) diff --git a/apps/slides/src/renderer/assets/icon-crop.png b/apps/slides/src/renderer/assets/icon-crop.png new file mode 100644 index 0000000..05dcdb3 Binary files /dev/null and b/apps/slides/src/renderer/assets/icon-crop.png differ diff --git a/apps/slides/src/renderer/components/AnimatedSlide.tsx b/apps/slides/src/renderer/components/AnimatedSlide.tsx index 3ac517a..f88950e 100644 --- a/apps/slides/src/renderer/components/AnimatedSlide.tsx +++ b/apps/slides/src/renderer/components/AnimatedSlide.tsx @@ -227,7 +227,7 @@ export function AnimPreviewOverlay({ }, [player.playing, player.pending, player.advance, onDone]) // eslint-disable-line react-hooks/exhaustive-deps return ( -
      +
      void } -export function AnimationPane({ slideIndex, items, selected, onSelect, onMove, onDelete, onPreview, onCollapse }: Props) { +export function AnimationPane({ + slideIndex, + items, + selected, + onSelect, + onMove, + onDelete, + onPreview, + onCollapse, +}: Props) { const { t } = useI18n() // Step numbering: onClick increments; withPrev/afterPrev share the previous entry's number (0 = auto-play) const stepNos: number[] = [] @@ -68,10 +77,21 @@ export function AnimationPane({ slideIndex, items, selected, onSelect, onMove, o
      {t('paneAnimTitle', { n: slideIndex + 1 })}
      - -
      @@ -89,10 +109,10 @@ export function AnimationPane({ slideIndex, items, selected, onSelect, onMove, o key={i} className={`anim-row anim-${animClassOf(it.effect)} ${selected === i ? 'selected' : ''}`} onClick={() => onSelect(selected === i ? -1 : i)} - title={`${t(TRIGGER_KEY[it.trigger])} · ${t('paneAnimSeconds', { sec: (it.durationMs / 1000).toFixed(2) })}${it.delayMs ? ` · ${t('paneAnimDelaySeconds', { sec: (it.delayMs / 1000).toFixed(2) })}` : ''}`} + data-tip={`${t(TRIGGER_KEY[it.trigger])} · ${t('paneAnimSeconds', { sec: (it.durationMs / 1000).toFixed(2) })}${it.delayMs ? ` · ${t('paneAnimDelaySeconds', { sec: (it.delayMs / 1000).toFixed(2) })}` : ''}`} > {stepNos[i] || ''} - + {TRIGGER_GLYPH[it.trigger]} @@ -103,13 +123,27 @@ export function AnimationPane({ slideIndex, items, selected, onSelect, onMove, o e.stopPropagation()}> - - - diff --git a/apps/slides/src/renderer/components/ChartDataDialog.tsx b/apps/slides/src/renderer/components/ChartDataDialog.tsx index 7c3ad24..72f15c8 100644 --- a/apps/slides/src/renderer/components/ChartDataDialog.tsx +++ b/apps/slides/src/renderer/components/ChartDataDialog.tsx @@ -28,11 +28,15 @@ export function ChartDataDialog({ init, onConfirm, onClose }: Props) { const [vals, setVals] = useState(() => { const rows = init.categories.length || 1 const sers = init.series.length ? init.series : [{ name: '', values: [] as number[] }] - return sers.map((s) => Array.from({ length: rows }, (_, i) => (s.values[i] != null ? String(s.values[i]) : ''))) + return sers.map((s) => + Array.from({ length: rows }, (_, i) => (s.values[i] != null ? String(s.values[i]) : '')), + ) }) const setVal = (si: number, ci: number, v: string) => - setVals((prev) => prev.map((row, i) => (i === si ? row.map((x, j) => (j === ci ? v : x)) : row))) + setVals((prev) => + prev.map((row, i) => (i === si ? row.map((x, j) => (j === ci ? v : x)) : row)), + ) const addCategory = () => { setCats((c) => [...c, t('paneChartCategoryN', { n: c.length + 1 })]) @@ -76,10 +80,16 @@ export function ChartDataDialog({ init, onConfirm, onClose }: Props) { {names.map((name, si) => (
    • ))} @@ -100,10 +114,16 @@ export function ChartDataDialog({ init, onConfirm, onClose }: Props) { diff --git a/apps/slides/src/renderer/components/CommentsPane.tsx b/apps/slides/src/renderer/components/CommentsPane.tsx index a2f8ad7..b80aafa 100644 --- a/apps/slides/src/renderer/components/CommentsPane.tsx +++ b/apps/slides/src/renderer/components/CommentsPane.tsx @@ -23,10 +23,22 @@ interface Props { function fmtDt(dt: string, locale: string): string { const d = new Date(dt) if (Number.isNaN(d.getTime())) return dt - return d.toLocaleString(locale, { month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit' }) + return d.toLocaleString(locale, { + month: 'numeric', + day: 'numeric', + hour: '2-digit', + minute: '2-digit', + }) } -export function CommentsPane({ slideIndex, comments, focusNonce, onAdd, onDelete, onCollapse }: Props) { +export function CommentsPane({ + slideIndex, + comments, + focusNonce, + onAdd, + onDelete, + onCollapse, +}: Props) { const { t, dateLocale } = useI18n() const [draft, setDraft] = useState('') const inputRef = useRef(null) @@ -47,7 +59,12 @@ export function CommentsPane({ slideIndex, comments, focusNonce, onAdd, onDelete
      {t('paneCommentsTitle', { n: slideIndex + 1 })}
      -
      @@ -69,7 +86,12 @@ export function CommentsPane({ slideIndex, comments, focusNonce, onAdd, onDelete {c.author} {c.dt && {fmtDt(c.dt, dateLocale)}} -
      diff --git a/apps/slides/src/renderer/components/ContextMenu.tsx b/apps/slides/src/renderer/components/ContextMenu.tsx index e2e4001..a21fdab 100644 --- a/apps/slides/src/renderer/components/ContextMenu.tsx +++ b/apps/slides/src/renderer/components/ContextMenu.tsx @@ -3,6 +3,7 @@ * Items that are null render as separators. */ import React, { useEffect, useLayoutEffect, useRef, useState } from 'react' +import { platformShortcuts } from '@genoffice/i18n' export interface CtxItem { label: string @@ -76,7 +77,8 @@ export function ContextMenu({ x, y, items, onClose }: Props) { key={c} className={`ctx-swatch ${c === 'none' ? 'ctx-swatch-none' : ''}`} style={c === 'none' ? undefined : { background: c }} - title={c} + data-tip={c} + aria-label={c} onClick={() => { onClose() item.onSwatch?.(c) @@ -98,7 +100,7 @@ export function ContextMenu({ x, y, items, onClose }: Props) { }} > {item.label} - {item.hint && {item.hint}} + {item.hint && {platformShortcuts(item.hint)}} ), )} diff --git a/apps/slides/src/renderer/components/CustomShowDialog.tsx b/apps/slides/src/renderer/components/CustomShowDialog.tsx index 372c5c3..7e35b2a 100644 --- a/apps/slides/src/renderer/components/CustomShowDialog.tsx +++ b/apps/slides/src/renderer/components/CustomShowDialog.tsx @@ -39,7 +39,11 @@ export function CustomShowDialog({ } const addShow = () => { - const show: CustomShow = { id: newShowId(), name: t('paneCsdDefaultName', { n: shows.length + 1 }), slideIndices: [] } + const show: CustomShow = { + id: newShowId(), + name: t('paneCsdDefaultName', { n: shows.length + 1 }), + slideIndices: [], + } onChange([...shows, show]) setSelId(show.id) } @@ -84,7 +88,9 @@ export function CustomShowDialog({ > {s.name} - {t('paneCsdPageCount', { n: s.slideIndices.filter((i) => i < slideCount).length })} + {t('paneCsdPageCount', { + n: s.slideIndices.filter((i) => i < slideCount).length, + })} ))} @@ -113,7 +119,11 @@ export function CustomShowDialog({
      {Array.from({ length: slideCount }, (_, i) => ( ))} @@ -122,20 +132,28 @@ export function CustomShowDialog({
      {t('paneCsdOrder')}
      - {selIndices.length === 0 &&
      {t('paneCsdOrderEmpty')}
      } + {selIndices.length === 0 && ( +
      {t('paneCsdOrderEmpty')}
      + )} {selIndices.map((slideIdx, posInShow) => (
      {posInShow + 1}. {t('paneCsdSlideN', { n: slideIdx + 1 })} - @@ -152,7 +170,11 @@ export function CustomShowDialog({
      -
      diff --git a/apps/slides/src/renderer/components/FindReplaceDialog.tsx b/apps/slides/src/renderer/components/FindReplaceDialog.tsx index f3f6ebe..b43dc6b 100644 --- a/apps/slides/src/renderer/components/FindReplaceDialog.tsx +++ b/apps/slides/src/renderer/components/FindReplaceDialog.tsx @@ -134,7 +134,7 @@ export function FindReplaceDialog({
      e.key === 'Escape' && onClose()}>
      {t('paneFrTitle')} -
      diff --git a/apps/slides/src/renderer/components/FormatPane.tsx b/apps/slides/src/renderer/components/FormatPane.tsx index b3569a9..1d9e76e 100644 --- a/apps/slides/src/renderer/components/FormatPane.tsx +++ b/apps/slides/src/renderer/components/FormatPane.tsx @@ -197,7 +197,12 @@ export function FormatPane({
      {t('paneFormatTitle')}
      -
      @@ -248,7 +253,7 @@ export function FormatPane({ diff --git a/apps/slides/src/renderer/components/PasteOptionsFloater.tsx b/apps/slides/src/renderer/components/PasteOptionsFloater.tsx index 990bde8..3e501ad 100644 --- a/apps/slides/src/renderer/components/PasteOptionsFloater.tsx +++ b/apps/slides/src/renderer/components/PasteOptionsFloater.tsx @@ -51,7 +51,8 @@ export function PasteOptionsFloater({ mode, onSelect, onDismiss }: Props) { @@ -354,12 +354,12 @@ export function PresenterView({ className="pv-top-btn" disabled={!hasAudience} onClick={() => void window.slidesApi.presenterSwap()} - title={hasAudience ? t('panePresenterSwapTip') : t('panePresenterNoSecond')} + data-tip={hasAudience ? t('panePresenterSwapTip') : t('panePresenterNoSecond')} > ⇄ {t('panePresenterSwap')} {onUseSlideShow && ( - )} @@ -369,13 +369,14 @@ export function PresenterView({
      - + {fmtElapsed(elapsed)} @@ -385,12 +386,13 @@ export function PresenterView({ setElapsed(0) setPaused(false) }} - title={t('panePresenterRestart')} + data-tip={t('panePresenterRestart')} + aria-label={t('panePresenterRestart')} > ↻
      - + {clock}
      @@ -414,7 +416,7 @@ export function PresenterView({ states={player.states} /> - {black &&
      } + {black &&
      }
      )}
      @@ -423,14 +425,16 @@ export function PresenterView({ @@ -438,14 +442,16 @@ export function PresenterView({ className="pv-tool-btn" disabled={strokes.length === 0} onClick={clearInk} - title={t('panePresenterEraseInk')} + data-tip={t('panePresenterEraseInk')} + aria-label={t('panePresenterEraseInk')} > ⌫ @@ -455,7 +461,8 @@ export function PresenterView({ className="pv-round" disabled={!ended && pos === 0} onClick={prev} - title={t('panePresenterPrevTip')} + data-tip={t('panePresenterPrevTip')} + aria-label={t('panePresenterPrevTip')} > ‹ @@ -467,7 +474,12 @@ export function PresenterView({
      -
      @@ -491,14 +503,14 @@ export function PresenterView({ @@ -514,7 +526,7 @@ export function PresenterView({ setEnded(false) goTo(i, false) }} - title={t('panePresenterFilmSlideN', { n: i + 1 })} + data-tip={t('panePresenterFilmSlideN', { n: i + 1 })} >
      diff --git a/apps/slides/src/renderer/components/Ribbon.tsx b/apps/slides/src/renderer/components/Ribbon.tsx index 72059c3..362375d 100644 --- a/apps/slides/src/renderer/components/Ribbon.tsx +++ b/apps/slides/src/renderer/components/Ribbon.tsx @@ -67,7 +67,6 @@ import { IconTransRandom, IconAnimStar, IconAnimNone, - IconCrop, IconPageBorders, IconNoneX, IconPathRight, @@ -80,6 +79,7 @@ import { import iconSpelling from '../assets/icon-spelling.png' import iconTranslate from '../assets/icon-translate.png' import iconTransparency from '../assets/icon-transparency.png' +import iconCrop from '../assets/icon-crop.png' import { ChartTypeDialog } from './ChartTypeDialog' import { BIG, @@ -655,7 +655,7 @@ function TableToggleBtn({ @@ -698,7 +698,7 @@ function RbCheck({
      )} - {/* onMouseDown+preventDefault like the format buttons: keep contentEditable focus so undo/redo reaches the active text edit. onClick with detail===0 covers keyboard activation (Enter/Space emit only click). */} -
      )} {rehearseMode && rehearse && ( -
      +
      ⏱ {formatClock(rehearseCurMs)} {t('paneShowRehearseTotal', { time: formatClock(rehearseTotalMs) })} diff --git a/apps/slides/src/renderer/components/icons.tsx b/apps/slides/src/renderer/components/icons.tsx index c13e27f..c3dd824 100644 --- a/apps/slides/src/renderer/components/icons.tsx +++ b/apps/slides/src/renderer/components/icons.tsx @@ -1039,17 +1039,29 @@ export function IconGear(props: IconProps) { } /** collapse the right sidebar: panel outline + arrow pushing into it */ -export function IconSidebarCollapse(props: IconProps) { +/** Collapse glyph for RIGHT-docked panes (Format/Animation/Comments) — exact mirror of + * IconSidebarCollapseLeft so both sides share the Sheets-parity look (16-canvas, + * 1.2/1.3 stroke), self-contained for the same pinned-stroke reason. */ +export function IconSidebarCollapse({ size = 24 }: IconProps) { return ( - - - - - + + + + + ) } -/** Mirror of IconSidebarCollapse for the LEFT-docked AI panel (right panes keep the original). +/** Mirror of IconSidebarCollapse for the LEFT-docked AI panel. * Sheets-parity glyph (16-canvas, 1.2/1.3 stroke), self-contained so the shared * Svg wrapper's 24-canvas pinned stroke doesn't alter its weight. */ export function IconSidebarCollapseLeft({ size = 24 }: IconProps) { diff --git a/apps/slides/src/renderer/components/ribbon-shared.tsx b/apps/slides/src/renderer/components/ribbon-shared.tsx index 0bca289..b4a0333 100644 --- a/apps/slides/src/renderer/components/ribbon-shared.tsx +++ b/apps/slides/src/renderer/components/ribbon-shared.tsx @@ -153,7 +153,7 @@ export function LayoutList({ key={lay.path} className="rb-layout-item" onClick={() => onPick(lay.path)} - title={name} + data-tip={name} >
      {lay.placeholders.map((ph, i) => ( @@ -241,7 +241,7 @@ export function Group({
      - setNames((n) => n.map((x, i) => (i === si ? e.target.value : x)))} /> + + setNames((n) => n.map((x, i) => (i === si ? e.target.value : x))) + } + />
      -
      - setCats((c) => c.map((x, i) => (i === ci ? e.target.value : x)))} /> + + setCats((c) => c.map((x, i) => (i === ci ? e.target.value : x))) + } + />
      -