Sync snapshot (2026-08-10) (#80)
- Improve DOCX rendering fidelity, pagination, image handling, and Markdown paste - Expand PDF text editing with paragraph reflow, style preservation, and more reliable text matching - Harden XLSX sheet deletion, localized date formats, multi-row autofit, charts, and system font support - Add inline AI turn rollback and sent-attachment visibility across editors - Add Office-style ScreenTips and refine ribbons, dialogs, menus, and themes - Improve Slides cropping, rotate and flip tools, printing, animations, and editing workflows - Add shell settings, configurable save locations, account credits, and update recovery guidance - Add Intel macOS and RPM download support and refresh public documentation Co-authored-by: GenOffice <merrick-2002@users.noreply.github.com>
This commit is contained in:
co-authored by
GenOffice
parent
fd33934dab
commit
7023e635bd
@@ -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.
|
||||
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
[](https://github.com/genspark-ai/genoffice/releases/latest)
|
||||
[](https://github.com/genspark-ai/genoffice/releases)
|
||||
[](https://github.com/genspark-ai/genoffice/stargazers)
|
||||

|
||||
|
||||
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.
|
||||
|
||||
[](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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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 <Documents>/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()))] : []),
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -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(/<li([^>]*)>\s*<p[^>]*>([\s\S]*?)<\/p>\s*<\/li>/g, '<li$1>$2</li>')
|
||||
}
|
||||
|
||||
/** 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<Block['runs']> {
|
||||
const out: NonNullable<Block['runs']> = []
|
||||
if (b.runs) out.push(...b.runs)
|
||||
const walkTable = (table: NonNullable<Block['table']> | 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 <li><p>…</p></li> 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 && (
|
||||
<style>{`.doc-page { --doc-line-factor:${docLineFactor(doc.parsed, liveDocCjk)} }`}</style>
|
||||
)}
|
||||
{doc && gridPitchPt != null && (
|
||||
// typed w:docGrid: line-height round(up) expressions snap to this pitch
|
||||
<style>{`.doc-page { --doc-grid-pitch:${gridPitchPt}pt }`}</style>
|
||||
)}
|
||||
{doc && section && (
|
||||
// over-wide tables may spill into the right margin (Word/LO), capped at the paper edge
|
||||
<style>{`.doc-page { --doc-margin-right:${twipsToPx(section.marginRight)}px }`}</style>
|
||||
)}
|
||||
{/* 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 && <style>{docThemeCss(themeFonts, themeColors, !!docBodyFont(doc.parsed))}</style>}
|
||||
@@ -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)}
|
||||
/>
|
||||
|
||||
@@ -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<string, string>
|
||||
}) {
|
||||
return (
|
||||
<div className="ai-msg-attachments">
|
||||
{atts.map((a) =>
|
||||
ATTACHMENT_IMAGE_EXTS.has(a.ext) ? (
|
||||
<span key={a.path} className="ai-attachment-thumb" title={a.name}>
|
||||
{previews[a.path] ? (
|
||||
<img src={previews[a.path]} alt={a.name} />
|
||||
) : (
|
||||
<span className="ai-attachment-thumb-pending" aria-hidden>
|
||||
<img src={fileImageIcon} alt="" />
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
) : (
|
||||
<span key={a.path} className="ai-attachment-card" title={a.name}>
|
||||
<span className="ai-attachment-card-icon">
|
||||
<AttachmentCardIcon ext={a.ext} />
|
||||
</span>
|
||||
<span className="ai-attachment-card-meta">
|
||||
<span className="ai-attachment-card-name">{truncateCardName(a.name)}</span>
|
||||
<span className="ai-attachment-card-size">{formatAttachmentSize(a.sizeBytes)}</span>
|
||||
</span>
|
||||
</span>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 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<ChatEntry[]>([])
|
||||
const [snapshots, setSnapshots] = useState<Snapshot[]>([])
|
||||
/** Past conversation restored from JSONL (read-only transcript, not fed to the model) */
|
||||
const [historicChat, setHistoricChat] = useState<ChatEntry[]>([])
|
||||
const [trackChanges, setTrackChanges] = useState(
|
||||
() => localStorage.getItem(TRACK_CHANGES_KEY) === '1',
|
||||
)
|
||||
@@ -251,8 +288,19 @@ export function AiPanel({
|
||||
const [attachmentPreviews, setAttachmentPreviews] = useState<Record<string, string>>({})
|
||||
/** image paths with a read already issued — one readAttachmentImage per attach, even while pending */
|
||||
const previewRequestedRef = useRef(new Set<string>())
|
||||
/** 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<AttachmentMeta[]>([])
|
||||
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<HTMLDivElement>): 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<ChatEntry[]>([])
|
||||
// bumped on selection/doc changes so the scope hint & quick actions stay fresh
|
||||
const [, setScopeTick] = useState(0)
|
||||
const logRef = useRef<HTMLDivElement>(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<AttachmentMeta[]>([])
|
||||
/** composer attachments plus everything already sent this session (deduped by path) */
|
||||
const availableAttachments = (): AttachmentMeta[] => {
|
||||
const seen = new Set<string>()
|
||||
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<PmNode | null>(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<AgentImage[]> => {
|
||||
const imageAtts = attachmentsRef.current.filter((a) => ATTACHMENT_IMAGE_EXTS.has(a.ext))
|
||||
const collectImageAttachments = async (atts: AttachmentMeta[]): Promise<AgentImage[]> => {
|
||||
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) => (
|
||||
<div key={`h${i}`} className={`ai-msg ai-msg-${entry.role} ai-msg-historic`}>
|
||||
{entry.role === 'user' && entry.attachments && entry.attachments.length > 0 && (
|
||||
<SentAttachments atts={entry.attachments} previews={attachmentPreviews} />
|
||||
)}
|
||||
{entry.tools && entry.tools.length > 0 && <ToolChipList tools={entry.tools} />}
|
||||
{entry.text && <Markdown text={entry.text} />}
|
||||
</div>
|
||||
@@ -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 (
|
||||
<div
|
||||
key={i}
|
||||
className={`ai-msg ai-msg-${entry.role}${entry.role === 'assistant' && entry.streaming ? ' ai-msg-streaming' : ''}`}
|
||||
>
|
||||
{entry.role === 'user' && entry.attachments && entry.attachments.length > 0 && (
|
||||
<SentAttachments atts={entry.attachments} previews={attachmentPreviews} />
|
||||
)}
|
||||
{entry.role === 'assistant' && !entry.text && entry.streaming ? (
|
||||
<span className="ai-typing-row">
|
||||
<AiTypingIndicator
|
||||
@@ -991,25 +1084,36 @@ export function AiPanel({
|
||||
aria-label={t('aiRegenerateTitle')}
|
||||
data-tip={t('aiRegenerateTitle')}
|
||||
>
|
||||
{/* 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) */}
|
||||
<svg
|
||||
width="20"
|
||||
height="20"
|
||||
viewBox="0 0 16 16"
|
||||
style={{ width: 18, height: 18 }}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1"
|
||||
strokeWidth="1.5"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
aria-hidden
|
||||
>
|
||||
<path d="M 12.68 6.65 a 4.86 4.86 0 0 0 -9 -1.08 M 3.32 9.35 a 4.86 4.86 0 0 0 9 1.08" />
|
||||
<path d="M 12.95 3.05 v 2.7 h -2.7 M 3.05 12.95 v -2.7 h 2.7" />
|
||||
<path d="M3.68881 9.85339C4.1791 8.0054 5.28205 6.30704 6.9459 5.09101C10.8046 2.27085 16.2188 3.11279 19.0389 6.97147C19.7242 7.90904 20.1932 8.93842 20.4553 10.0001" />
|
||||
<path d="M2.00452 8.46411L2.87229 10.7059C2.96814 10.9535 3.24658 11.0765 3.4942 10.9807L5.73594 10.1129" />
|
||||
<path d="M20.3308 14.4908C19.8405 16.3388 18.7376 18.0372 17.0738 19.2532C13.215 22.0734 7.80083 21.2314 4.98071 17.3728C4.22167 16.3342 3.72792 15.183 3.48686 13.9999" />
|
||||
<path d="M22.0151 15.8801L21.1474 13.6384C21.0515 13.3908 20.7731 13.2677 20.5255 13.3636L18.2837 14.2314" />
|
||||
</svg>
|
||||
</button>
|
||||
)}
|
||||
{entry.snapshot && (
|
||||
<>
|
||||
{/* hairline between reply actions (icons) and the document action (icon+label);
|
||||
CSS shows it only when an icon button actually precedes it */}
|
||||
<span className="ai-rollback-sep" aria-hidden />
|
||||
<RollbackButton
|
||||
disabled={busy}
|
||||
onClick={() => rollback(i, entry.snapshot!)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{entry.turnLimit && isLast && !busy && (
|
||||
@@ -1022,26 +1126,6 @@ export function AiPanel({
|
||||
})}
|
||||
</div>
|
||||
|
||||
{snapshots.length > 0 && (
|
||||
<div className="ai-versions">
|
||||
<div className="ai-versions-title">
|
||||
<IconClock size={12} />
|
||||
{t('aiSnapshotsTitle')}
|
||||
</div>
|
||||
{snapshots.map((s, i) => (
|
||||
<div key={i} className="ai-version-row">
|
||||
<span className="ai-version-label" title={s.label}>
|
||||
<span className="ai-version-time">{s.time}</span>
|
||||
{s.label}
|
||||
</span>
|
||||
<button className="ai-version-rollback" onClick={() => rollback(s)}>
|
||||
{t('aiRollback')}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="ai-composer">
|
||||
{attachNotice && <div className="ai-attach-notice">{attachNotice}</div>}
|
||||
<AiComposer
|
||||
@@ -1204,6 +1288,31 @@ function StepIcon({ status }: { status: 'running' | 'done' | 'error' }) {
|
||||
)
|
||||
}
|
||||
|
||||
/** Quiet roll-back action in the message toolbar: restores the document to before the run's edits */
|
||||
function RollbackButton({ disabled, onClick }: { disabled: boolean; onClick: () => void }) {
|
||||
const { t: tr } = useI18n()
|
||||
return (
|
||||
<button type="button" className="ai-rollback-btn" disabled={disabled} onClick={onClick}>
|
||||
{/* 24-canvas glyph at 18px (optical parity with the toolbar icons): stroke 1.5 paints 1.125px (1:16) */}
|
||||
<svg
|
||||
width="18"
|
||||
height="18"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
aria-hidden
|
||||
>
|
||||
<path d="M5.91026 4L2.5 7.14791L5.91026 10.8205" />
|
||||
<path d="M3.96154 7.41028H15.1636C18.5169 7.41028 21.3646 10.1484 21.4953 13.5C21.6334 17.0416 18.707 20.0769 15.1636 20.0769H6.88384" />
|
||||
</svg>
|
||||
{tr('aiRollback')}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
/** 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. */
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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({
|
||||
<IconSparkle size={10} />
|
||||
</span>
|
||||
)}
|
||||
{opts.key && <span className="ctx-key">{opts.key}</span>}
|
||||
{opts.key && <span className="ctx-key">{platformShortcuts(opts.key)}</span>}
|
||||
{opts.submenuKey && <span className="ctx-arrow">›</span>}
|
||||
</button>
|
||||
)
|
||||
|
||||
@@ -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 <tr>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}
|
||||
</div>
|
||||
)}
|
||||
{(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)
|
||||
<img
|
||||
key={`wm${k}`}
|
||||
className="pv-watermark-img"
|
||||
src={img.dataUrl}
|
||||
alt=""
|
||||
aria-hidden="true"
|
||||
style={{
|
||||
left:
|
||||
img.posH === 'center'
|
||||
? '50%'
|
||||
: img.posH === 'right'
|
||||
? undefined
|
||||
: twipsToPx(s.marginLeft),
|
||||
right: img.posH === 'right' ? twipsToPx(s.marginRight) : undefined,
|
||||
top: img.posV === 'center' ? '50%' : img.posV === 'bottom' ? undefined : mTop,
|
||||
bottom: img.posV === 'bottom' ? mBottom : undefined,
|
||||
transform: `translate(${img.posH === 'center' ? '-50%' : '0'}, ${img.posV === 'center' ? '-50%' : '0'})`,
|
||||
...(img.widthPx ? { width: img.widthPx } : {}),
|
||||
...(img.heightPx ? { height: img.heightPx } : {}),
|
||||
...(img.washout ? { filter: 'brightness(1.6) contrast(0.35)' } : {}),
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
{parts.header && (
|
||||
<HeaderFooterArea
|
||||
kind="header"
|
||||
value={parts.header}
|
||||
images={parts.headerImages}
|
||||
images={parts.headerImages?.filter((img) => !img.floating)}
|
||||
readOnly
|
||||
onCommit={() => {}}
|
||||
pageNo={pageNoText}
|
||||
@@ -687,7 +746,7 @@ export function PaginationPreview({
|
||||
<HeaderFooterArea
|
||||
kind="footer"
|
||||
value={parts.footer}
|
||||
images={parts.footerImages}
|
||||
images={parts.footerImages?.filter((img) => !img.floating)}
|
||||
readOnly
|
||||
onCommit={() => {}}
|
||||
pageNo={pageNoText}
|
||||
|
||||
@@ -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({
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="table-tool-row">
|
||||
<button
|
||||
className="table-tool-button"
|
||||
disabled={!canEdit}
|
||||
title={t('ribbonRotateRight')}
|
||||
onClick={() => rotatePicture(90)}
|
||||
>
|
||||
<IconRotateRight />
|
||||
</button>
|
||||
<button
|
||||
className="table-tool-button"
|
||||
disabled={!canEdit}
|
||||
title={t('ribbonRotateLeft')}
|
||||
onClick={() => rotatePicture(-90)}
|
||||
>
|
||||
<IconRotateLeft />
|
||||
</button>
|
||||
<button
|
||||
className={fs.imageFlipH ? 'table-tool-button active' : 'table-tool-button'}
|
||||
disabled={!canEdit}
|
||||
title={t('ribbonFlipH')}
|
||||
onClick={() => flipPicture('h')}
|
||||
>
|
||||
<IconFlipH />
|
||||
</button>
|
||||
<button
|
||||
className={fs.imageFlipV ? 'table-tool-button active' : 'table-tool-button'}
|
||||
disabled={!canEdit}
|
||||
title={t('ribbonFlipV')}
|
||||
onClick={() => flipPicture('v')}
|
||||
>
|
||||
<IconFlipV />
|
||||
</button>
|
||||
</div>
|
||||
<div className="ribbon-group-label">{t('ribbonGroupArrange')}</div>
|
||||
</div>
|
||||
<div className="ribbon-sep" />
|
||||
|
||||
@@ -337,44 +337,6 @@ export function IconCrop(props: IconProps) {
|
||||
)
|
||||
}
|
||||
|
||||
export function IconRotateRight(props: IconProps) {
|
||||
return (
|
||||
<Svg {...props}>
|
||||
<path d="M 12.4 6.2 a 4.6 4.6 0 1 0 0.6 3.3" />
|
||||
<path d="M 12.7 3.2 v 3 h -3" />
|
||||
</Svg>
|
||||
)
|
||||
}
|
||||
|
||||
export function IconRotateLeft(props: IconProps) {
|
||||
return (
|
||||
<Svg {...props}>
|
||||
<path d="M 3.6 6.2 a 4.6 4.6 0 1 1 -0.6 3.3" />
|
||||
<path d="M 3.3 3.2 v 3 h 3" />
|
||||
</Svg>
|
||||
)
|
||||
}
|
||||
|
||||
export function IconFlipH(props: IconProps) {
|
||||
return (
|
||||
<Svg {...props}>
|
||||
<path d="M 8 2.6 v 10.8" strokeDasharray="1.7 1.5" />
|
||||
<path d="M 6 5.2 L 2.6 8 L 6 10.8 Z" />
|
||||
<path d="M 10 5.2 L 13.4 8 L 10 10.8 Z" fill="currentColor" />
|
||||
</Svg>
|
||||
)
|
||||
}
|
||||
|
||||
export function IconFlipV(props: IconProps) {
|
||||
return (
|
||||
<Svg {...props}>
|
||||
<path d="M 2.6 8 h 10.8" strokeDasharray="1.7 1.5" />
|
||||
<path d="M 5.2 6 L 8 2.6 L 10.8 6 Z" />
|
||||
<path d="M 5.2 10 L 8 13.4 L 10.8 10 Z" fill="currentColor" />
|
||||
</Svg>
|
||||
)
|
||||
}
|
||||
|
||||
export function IconReplacePicture(props: IconProps) {
|
||||
return (
|
||||
<Svg {...props}>
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -91,6 +91,7 @@ function formatAttrs(format: ParaFormat | undefined): Record<string, unknown> {
|
||||
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 (
|
||||
|
||||
@@ -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<string, unknown>
|
||||
@@ -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<string, number> | 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<string, string> | 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<string, string> = {
|
||||
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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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<HTMLElement>('.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}` : '',
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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: '取代圖片',
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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))')
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -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(
|
||||
'</pic:blipFill></pic:pic>',
|
||||
'</pic:blipFill><pic:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="914400" cy="914400"/></a:xfrm>' +
|
||||
'<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr></pic:pic>',
|
||||
)
|
||||
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 = '<wp:effectExtent l="9525" t="19050" r="28575" b="38100"/>'
|
||||
const withEffect = IMAGE_PARAGRAPH_XML.replace(
|
||||
'<wp:extent cx="914400" cy="914400"/>',
|
||||
`<wp:extent cx="914400" cy="914400"/>${wordEffectExtent}`,
|
||||
).replace(
|
||||
'</pic:blipFill></pic:pic>',
|
||||
'</pic:blipFill><pic:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="914400" cy="914400"/></a:xfrm>' +
|
||||
'<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr></pic:pic>',
|
||||
)
|
||||
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(
|
||||
'<wp:extent cx="914400" cy="914400"/>',
|
||||
'<wp:extent cx="1828800" cy="914400"/>',
|
||||
).replace(
|
||||
'</pic:blipFill></pic:pic>',
|
||||
'</pic:blipFill><pic:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="1828800" cy="914400"/></a:xfrm>' +
|
||||
'<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr></pic:pic>',
|
||||
)
|
||||
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('<wp:effectExtent l="0" t="457200" r="0" b="457200"/>')
|
||||
// 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('<wp:effectExtent l="0" t="0" r="0" b="0"/>')
|
||||
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(
|
||||
'<a:blip r:embed="rId10"/>',
|
||||
'<a:blip r:embed="rId10" r:link="rId11">' +
|
||||
'<a:extLst><a:ext uri="{96DAC541-7B7A-43D3-8B79-37D633B846F1}">' +
|
||||
'<asvg:svgBlip xmlns:asvg="http://schemas.microsoft.com/office/drawing/2016/SVG/main" r:embed="rId10"/>' +
|
||||
'</a:ext></a:extLst></a:blip>',
|
||||
)
|
||||
const linkRel =
|
||||
'<Relationship Id="rId11" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="file:///C:/old.png" TargetMode="External"/>'
|
||||
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()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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('<h2>')
|
||||
expect(html).toContain('<strong>bold</strong>')
|
||||
expect(html).toContain('<ul>')
|
||||
expect(html).toContain('<li>one</li>')
|
||||
const fenced = markdownPasteHtml('```\nlet x = 1\n```')
|
||||
expect(fenced).toContain('<pre><code>')
|
||||
})
|
||||
|
||||
it('normalizes Windows line endings before conversion', () => {
|
||||
const html = markdownPasteHtml('# A\r\n\r\n- x\r\n- y')
|
||||
expect(html).toContain('<h1>')
|
||||
expect(html).toContain('<li>y</li>')
|
||||
})
|
||||
|
||||
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('<table>')
|
||||
expect(html).toContain('<td>1</td>')
|
||||
})
|
||||
})
|
||||
@@ -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, string>,
|
||||
[string, Record<string, string>, ...Array<[string, Record<string, string>]>],
|
||||
]
|
||||
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<string, string>]>
|
||||
expect(cols.map((col) => col[1].style)).toEqual(['width:50.00%', 'width:50.00%'])
|
||||
editor.destroy()
|
||||
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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-'))
|
||||
|
||||
@@ -386,7 +386,8 @@ export default function App() {
|
||||
{!aiOpen && (
|
||||
<button
|
||||
className="ai-rail"
|
||||
title={t('aiOpenAssistant')}
|
||||
data-tip={t('aiOpenAssistant')}
|
||||
aria-label={t('aiOpenAssistant')}
|
||||
onClick={() => setAiOpen(true)}
|
||||
>
|
||||
<GensparkMark size={22} />
|
||||
@@ -402,19 +403,27 @@ export default function App() {
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div className="editor-scroll" ref={scrollRef}>
|
||||
<div className="doc-page">
|
||||
{fmOpen && <FrontmatterPanel value={fmText} onChange={onFrontmatterChange} />}
|
||||
<EditorContent editor={editor} />
|
||||
<div className="app-content">
|
||||
<div className="editor-scroll" ref={scrollRef}>
|
||||
<div className="doc-page">
|
||||
{fmOpen && <FrontmatterPanel value={fmText} onChange={onFrontmatterChange} />}
|
||||
<EditorContent editor={editor} />
|
||||
</div>
|
||||
</div>
|
||||
<footer className="status-bar">
|
||||
<div className="status-left">
|
||||
{fileName && <span className="status-item status-file">{fileName}</span>}
|
||||
</div>
|
||||
<div className="status-right">
|
||||
{statusText && (
|
||||
<span className={`status-save status-${saveState}`}>{statusText}</span>
|
||||
)}
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
<SlashMenu ref={slashMenuRef} state={slashState} onDismiss={() => setSlashState(null)} />
|
||||
<TableMenu editor={editor} scrollRef={scrollRef} />
|
||||
<div className="status-bar">
|
||||
{fileName && <span className="status-file">{fileName}</span>}
|
||||
{statusText && <span className={`status-save status-${saveState}`}>{statusText}</span>}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -441,12 +441,18 @@ export function AiPanel({
|
||||
setBusy(false)
|
||||
setChat([])
|
||||
}}
|
||||
title={t('aiNewChat')}
|
||||
data-tip={t('aiNewChat')}
|
||||
aria-label={t('aiNewChat')}
|
||||
>
|
||||
<IconNewChat />
|
||||
</button>
|
||||
)}
|
||||
<button className="ai-header-btn" onClick={onCollapse} title={t('aiCollapsePanel')}>
|
||||
<button
|
||||
className="ai-header-btn"
|
||||
onClick={onCollapse}
|
||||
data-tip={t('aiCollapsePanel')}
|
||||
aria-label={t('aiCollapsePanel')}
|
||||
>
|
||||
<IconCollapse />
|
||||
</button>
|
||||
</div>
|
||||
@@ -586,7 +592,7 @@ export function AiPanel({
|
||||
</div>
|
||||
{snapshots.map((s, i) => (
|
||||
<div key={i} className="ai-version-row">
|
||||
<span className="ai-version-label" title={s.label}>
|
||||
<span className="ai-version-label" data-tip={s.label}>
|
||||
<span className="ai-version-time">{s.time}</span>
|
||||
{s.label}
|
||||
</span>
|
||||
@@ -726,14 +732,14 @@ function ToolChipList({ tools }: { tools: ToolActivity[] }) {
|
||||
<button
|
||||
type="button"
|
||||
className="ai-step-title clickable"
|
||||
title={tool.name}
|
||||
data-tip={tool.name}
|
||||
aria-expanded={isOpen}
|
||||
onClick={() => toggle(j)}
|
||||
>
|
||||
{tool.summary}
|
||||
</button>
|
||||
) : (
|
||||
<span className="ai-step-title" title={tool.name}>
|
||||
<span className="ai-step-title" data-tip={tool.name}>
|
||||
{tool.summary}
|
||||
</span>
|
||||
)}
|
||||
|
||||
@@ -129,7 +129,8 @@ function IconBtn({
|
||||
<button
|
||||
type="button"
|
||||
className={`rb-btn${active ? ' active' : ''}`}
|
||||
title={title}
|
||||
data-tip={title}
|
||||
aria-label={title}
|
||||
disabled={disabled}
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={onClick}
|
||||
@@ -225,7 +226,8 @@ export function Ribbon({
|
||||
<button
|
||||
type="button"
|
||||
className="qa-btn"
|
||||
title={t('save')}
|
||||
data-tip={t('save')}
|
||||
aria-label={t('save')}
|
||||
disabled={off || !dirty}
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={onSave}
|
||||
@@ -235,7 +237,8 @@ export function Ribbon({
|
||||
<button
|
||||
type="button"
|
||||
className="qa-btn"
|
||||
title={t('undo')}
|
||||
data-tip={t('undo')}
|
||||
aria-label={t('undo')}
|
||||
disabled={off || !state?.canUndo}
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => editor?.chain().focus().undo().run()}
|
||||
@@ -245,14 +248,15 @@ export function Ribbon({
|
||||
<button
|
||||
type="button"
|
||||
className="qa-btn"
|
||||
title={t('redo')}
|
||||
data-tip={t('redo')}
|
||||
aria-label={t('redo')}
|
||||
disabled={off || !state?.canRedo}
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => editor?.chain().focus().redo().run()}
|
||||
>
|
||||
<IconRedo size={16} />
|
||||
</button>
|
||||
<label className={`autosave-toggle${autoSave ? ' on' : ''}`} title={t('autoSaveTip')}>
|
||||
<label className={`autosave-toggle${autoSave ? ' on' : ''}`} data-tip={t('autoSaveTip')}>
|
||||
<span className="autosave-knob" />
|
||||
<span className="autosave-text">{t('autoSave')}</span>
|
||||
<input
|
||||
@@ -269,7 +273,7 @@ export function Ribbon({
|
||||
<button
|
||||
type="button"
|
||||
className={`rb-big ai-entry${aiOpen ? ' active' : ''}`}
|
||||
title={t('aiOpenAssistant')}
|
||||
data-tip={t('aiOpenAssistant')}
|
||||
disabled={disabled}
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={onToggleAi}
|
||||
@@ -284,7 +288,7 @@ export function Ribbon({
|
||||
key={kind}
|
||||
type="button"
|
||||
className="rb-big ai-entry"
|
||||
title={t(prompt)}
|
||||
data-tip={t(btn)}
|
||||
disabled={off || state?.empty}
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => onAiPreset(t(prompt))}
|
||||
|
||||
@@ -4,7 +4,11 @@ import App from './App'
|
||||
import { LocaleProvider } from './i18n/locale'
|
||||
import type { UiTheme } from '../shared/ipc'
|
||||
import '@genoffice/ui/tokens.css'
|
||||
import '@genoffice/ui/screentip.css'
|
||||
import './styles.css'
|
||||
import { installScreenTips } from '@genoffice/ui'
|
||||
|
||||
installScreenTips()
|
||||
|
||||
function applyTheme(theme: UiTheme): void {
|
||||
if (theme === 'system') document.documentElement.removeAttribute('data-theme')
|
||||
|
||||
@@ -1514,36 +1514,6 @@ body {
|
||||
box-shadow: 0 0 0 3px var(--md-focus-ring-blue);
|
||||
}
|
||||
|
||||
/* Tooltip: dark pill under the button, 0.3s hover delay */
|
||||
.ai-msg-tool-btn::after {
|
||||
content: attr(data-tip);
|
||||
position: absolute;
|
||||
top: 100%;
|
||||
left: 50%;
|
||||
translate: -50% 0;
|
||||
margin-top: 6px;
|
||||
padding: 4px 8px;
|
||||
background: var(--color-btn-primary);
|
||||
color: var(--color-btn-primary-text);
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 4px 6px var(--md-shadow-soft);
|
||||
white-space: nowrap;
|
||||
pointer-events: none;
|
||||
opacity: 0;
|
||||
visibility: hidden;
|
||||
transition: opacity 0.15s ease;
|
||||
transition-delay: 0s;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.ai-msg-tool-btn:hover::after {
|
||||
opacity: 1;
|
||||
visibility: visible;
|
||||
transition-delay: 0.3s;
|
||||
}
|
||||
|
||||
.ai-msg-tool-btn:active {
|
||||
filter: brightness(0.88);
|
||||
transform: scale(0.98);
|
||||
@@ -2000,44 +1970,6 @@ body {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* fast tooltip: dark pill under the button (icon-only buttons need a quick label) */
|
||||
.tm-btn[data-tip]::after,
|
||||
.md-gutter-btn[data-tip]::after {
|
||||
content: attr(data-tip);
|
||||
position: absolute;
|
||||
top: 100%;
|
||||
left: 50%;
|
||||
translate: -50% 0;
|
||||
margin-top: 8px;
|
||||
padding: 4px 8px;
|
||||
background: var(--color-btn-primary);
|
||||
color: var(--color-btn-primary-text);
|
||||
font-size: 12px;
|
||||
line-height: 1.4;
|
||||
border-radius: 8px;
|
||||
box-shadow: var(--md-tip-shadow);
|
||||
white-space: nowrap;
|
||||
pointer-events: none;
|
||||
opacity: 0;
|
||||
visibility: hidden;
|
||||
transition: opacity 0.15s ease;
|
||||
transition-delay: 0s;
|
||||
z-index: 50;
|
||||
}
|
||||
|
||||
.tm-btn[data-tip]:hover::after {
|
||||
opacity: 1;
|
||||
visibility: visible;
|
||||
transition-delay: 0.15s;
|
||||
}
|
||||
|
||||
/* the gutter is passed on the way to other targets — show its hint a bit later */
|
||||
.md-gutter-btn[data-tip]:hover::after {
|
||||
opacity: 1;
|
||||
visibility: visible;
|
||||
transition-delay: 0.45s;
|
||||
}
|
||||
|
||||
.tm-btn:hover {
|
||||
background: var(--hover);
|
||||
}
|
||||
|
||||
+582
-67
@@ -5,6 +5,7 @@ import { findSystemFont, isTruetype } from './font-locate'
|
||||
import { identityCffCharset, subsetTtf } from './font-subset'
|
||||
import { pdfiumWasmPath } from './wasm-path'
|
||||
import type { TextEditFailure, TextEditInput, TextEditValidation } from '../shared/ipc'
|
||||
import { foldRadicals } from '../shared/radicals'
|
||||
import { chainLayers } from '../shared/x-layers'
|
||||
|
||||
export const FPDF_PAGEOBJ_TEXT = 1
|
||||
@@ -16,6 +17,7 @@ export interface Pdfium {
|
||||
HEAPU8: Uint8Array
|
||||
HEAP32: Int32Array
|
||||
HEAPF32: Float32Array
|
||||
HEAPF64: Float64Array
|
||||
_malloc(size: number): number
|
||||
_free(ptr: number): void
|
||||
_PDFiumExt_Init(): void
|
||||
@@ -31,6 +33,10 @@ export interface Pdfium {
|
||||
_FPDF_GetPageCount(doc: number): number
|
||||
_FPDFText_LoadPage(page: number): number
|
||||
_FPDFText_ClosePage(textPage: number): void
|
||||
_FPDFText_CountChars(textPage: number): number
|
||||
_FPDFText_GetTextObject(textPage: number, index: number): number
|
||||
_FPDFText_GetLooseCharBox(textPage: number, index: number, rect: number): number
|
||||
_FPDFText_GetCharOrigin(textPage: number, index: number, x: number, y: number): number
|
||||
_FPDFText_LoadFont(doc: number, data: number, size: number, fontType: number, cid: number): number
|
||||
_FPDFText_SetText(textObj: number, text: number): number
|
||||
_FPDFPage_CountObjects(page: number): number
|
||||
@@ -107,7 +113,14 @@ export function loadPdfium(): Promise<Pdfium> {
|
||||
const raw = readFileSync(pdfiumWasmPath())
|
||||
// Exact slice: Buffer.buffer may be a shared pool larger than the file
|
||||
const wasmBinary = raw.buffer.slice(raw.byteOffset, raw.byteOffset + raw.byteLength)
|
||||
const wrapped = await init({ wasmBinary })
|
||||
// thisProgram: emscripten synthesizes an environ whose `_` entry defaults
|
||||
// to process.argv[1] and writes it through ASCII-asserting stringToAscii,
|
||||
// so a non-ASCII path in argv — a CJK checkout running vitest, or a
|
||||
// document path handed to the packaged app by a file association —
|
||||
// aborts the runtime at first use. Every other synthetic entry is a
|
||||
// hardcoded ASCII constant; a fixed ASCII program name defuses the
|
||||
// only variable one.
|
||||
const wrapped = await init({ wasmBinary, thisProgram: 'genoffice-pdf' })
|
||||
const m = ('pdfium' in wrapped ? wrapped.pdfium : wrapped) as Pdfium
|
||||
m._PDFiumExt_Init()
|
||||
return m
|
||||
@@ -238,11 +251,13 @@ export function listEditFonts(): string[] {
|
||||
return Object.keys(EDIT_FONT_PATHS).filter((id) => loadEditFont(id) !== null)
|
||||
}
|
||||
|
||||
/** Whitespace-insensitive, NFKC-folded comparison key. pdf.js and pdfium disagree on
|
||||
compatibility codepoints — some fonts' cmaps yield Kangxi radicals (U+2F00 block)
|
||||
where pdfium extracts unified ideographs — and on synthesized spaces; both engines'
|
||||
text must land on the same key or every whole-line match fails on such documents. */
|
||||
export const norm = (s: string) => s.normalize('NFKC').replace(/\s+/g, '')
|
||||
/** Whitespace-insensitive, radical- and NFKC-folded comparison key. pdf.js and pdfium
|
||||
disagree on compatibility codepoints — some fonts' cmaps yield radical-block
|
||||
codepoints (Kangxi U+2F00, which NFKC decomposes, and the Radicals Supplement
|
||||
U+2E80, which it does not) where pdfium extracts unified ideographs — and on
|
||||
synthesized spaces; both engines' text must land on the same key or every
|
||||
whole-line match fails on such documents. */
|
||||
export const norm = (s: string) => foldRadicals(s).normalize('NFKC').replace(/\s+/g, '')
|
||||
|
||||
/** NFKC-fold `raw` keeping maps from each folded unit back to its source char's start
|
||||
and end index. Whitespace runs collapse to one ' ' unit when keepSpaces, else
|
||||
@@ -266,7 +281,7 @@ export function foldMap(
|
||||
inWs = true
|
||||
} else {
|
||||
inWs = false
|
||||
for (const u of ch.normalize('NFKC')) {
|
||||
for (const u of foldRadicals(ch).normalize('NFKC')) {
|
||||
if (/\s/.test(u)) continue
|
||||
units.push(u)
|
||||
idx.push(i)
|
||||
@@ -629,10 +644,10 @@ const joinX = (objs: PageTextObj[]) =>
|
||||
.map((o) => o.text)
|
||||
.join('')
|
||||
|
||||
/** Joined text in visual reading order — rows top→bottom (≥50% vertical overlap joins
|
||||
/** Objects in visual reading order — rows top→bottom (≥50% vertical overlap joins
|
||||
a row), x within each row. How a multi-line paragraph edit reads its lines; plain
|
||||
x-order interleaves them and stream order is not guaranteed. */
|
||||
function joinRows(objs: PageTextObj[]): string {
|
||||
function readingOrder(objs: PageTextObj[]): PageTextObj[] {
|
||||
const sorted = [...objs].sort((a, b) => b.bounds[3] - a.bounds[3])
|
||||
const rows: PageTextObj[][] = []
|
||||
for (const o of sorted) {
|
||||
@@ -648,7 +663,91 @@ function joinRows(objs: PageTextObj[]): string {
|
||||
row.push(o)
|
||||
} else rows.push([o])
|
||||
}
|
||||
return rows.map(joinX).join('')
|
||||
return rows.flatMap((row) => [...row].sort((a, b) => a.bounds[0] - b.bounds[0]))
|
||||
}
|
||||
|
||||
const joinRows = (objs: PageTextObj[]): string =>
|
||||
readingOrder(objs)
|
||||
.map((o) => o.text)
|
||||
.join('')
|
||||
|
||||
/**
|
||||
* Text-first rescue: the rect is only a hint here, not a filter. The renderer's rect
|
||||
* comes from pdf.js layout boxes, which can sit a few points inside the engine's ink
|
||||
* bounds — on a line built from many text objects the edge objects then fail the
|
||||
* primary path's ≥50%-containment test and the whole-line join never equals oldText.
|
||||
* Instead, order every object merely touching a slightly padded rect by reading order,
|
||||
* search their joined folded units for oldText's units, and pick the occurrence whose
|
||||
* union bounds best overlap the edit rect (disambiguates repeated text; bleed from
|
||||
* neighboring lines falls outside the occurrence and is skipped naturally). The match
|
||||
* may start or end mid-object — the uncovered head/tail of the edge objects is kept
|
||||
* verbatim around the replacement, like the single-container fragment path.
|
||||
*/
|
||||
function matchByText(objects: PageTextObj[], edit: TextEditInput): PlannedMatch | null {
|
||||
const target = foldMap(edit.oldText)
|
||||
if (target.units.length === 0) return null
|
||||
const pad = Math.max(2, edit.fontSize * 0.2)
|
||||
const r: Rect = [edit.rect[0] - pad, edit.rect[1] - pad, edit.rect[2] + pad, edit.rect[3] + pad]
|
||||
const touching = readingOrder(objects.filter((o) => overlapArea(o.bounds, r) > 0))
|
||||
if (touching.length === 0) return null
|
||||
const joined = touching.map((o) => o.text).join('')
|
||||
const eng = foldMap(joined)
|
||||
// Which object each folded unit came from, plus each object's raw span in `joined`
|
||||
// (per-object folds concatenate to the joined fold: folding is per-character)
|
||||
const objAt: number[] = []
|
||||
const rawStartOf: number[] = []
|
||||
const rawEndOf: number[] = []
|
||||
let rawOff = 0
|
||||
for (const [i, o] of touching.entries()) {
|
||||
rawStartOf.push(rawOff)
|
||||
rawOff += o.text.length
|
||||
rawEndOf.push(rawOff)
|
||||
for (let k = foldMap(o.text).units.length; k > 0; k--) objAt.push(i)
|
||||
}
|
||||
let best: { at: number; score: number } | null = null
|
||||
let at = indexOfUnits(eng.units, target.units)
|
||||
while (at >= 0) {
|
||||
const endU = at + target.units.length - 1
|
||||
const set = touching.slice(objAt[at]!, objAt[endU]! + 1)
|
||||
const b = matchBounds(set)
|
||||
const score = overlapArea(b, edit.rect) / Math.max((b[2] - b[0]) * (b[3] - b[1]), 1e-6)
|
||||
if (score > 0 && (!best || score > best.score)) best = { at, score }
|
||||
const next = indexOfUnits(eng.units.slice(at + 1), target.units)
|
||||
at = next < 0 ? -1 : at + 1 + next
|
||||
}
|
||||
if (!best) return null
|
||||
const endU = best.at + target.units.length - 1
|
||||
const set = touching.slice(objAt[best.at]!, objAt[endU]! + 1)
|
||||
// Raw text the matched objects contribute, and the matched stretch inside it
|
||||
const setStart = rawStartOf[objAt[best.at]!]!
|
||||
const setEnd = rawEndOf[objAt[endU]!]!
|
||||
const setRaw = joined.slice(setStart, setEnd)
|
||||
const rawStart = eng.idx[best.at]!
|
||||
// End of the last matched unit, not the next unit's start: the gap between them is
|
||||
// boundary whitespace belonging to the untouched suffix (see the container path)
|
||||
const rawEnd = eng.end[endU]!
|
||||
const whole = norm(setRaw) === norm(edit.oldText)
|
||||
if (whole) {
|
||||
return {
|
||||
matches: set,
|
||||
newText:
|
||||
edit.lineLeading !== undefined
|
||||
? mergeEngineCodepoints(setRaw, edit.oldText, edit.newText)
|
||||
: spliceIntoEngine(setRaw, edit.oldText, edit.newText),
|
||||
whole: true,
|
||||
}
|
||||
}
|
||||
// Paragraph rebuilds position their lines at the block corner (origin/lineLeading);
|
||||
// apply strips those overrides from fragment matches, which would rebuild the block
|
||||
// at the anchor and drag the edge objects' surrounding text into the block run.
|
||||
// Fail closed like before instead of degrading the layout silently.
|
||||
if (edit.origin !== undefined || edit.lineLeading !== undefined) return null
|
||||
const fragment = spliceIntoEngine(joined.slice(rawStart, rawEnd), edit.oldText, edit.newText)
|
||||
return {
|
||||
matches: set,
|
||||
newText: joined.slice(setStart, rawStart) + fragment + joined.slice(rawEnd, setEnd),
|
||||
whole: false,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -658,8 +757,10 @@ function joinRows(objs: PageTextObj[]): string {
|
||||
* granularity mismatches (pdf.js splits one PDF text object into several spans at column
|
||||
* gaps / kerning breaks): a single object containing most of the rect gets the fragment
|
||||
* spliced into its text — the whole object is then rewritten, so surrounding text
|
||||
* survives with the new content. All comparisons are NFKC-folded (norm) and the
|
||||
* replacement is spliced against the engine's own text to keep unedited codepoints.
|
||||
* survives with the new content. Last resort is matchByText: a text-first search over
|
||||
* objects merely touching the rect, rescuing rects that clip edge objects below the
|
||||
* containment threshold. All comparisons are NFKC-folded (norm) and the replacement
|
||||
* is spliced against the engine's own text to keep unedited codepoints.
|
||||
*/
|
||||
function matchEdit(objects: PageTextObj[], edit: TextEditInput): PlannedMatch | { reason: string } {
|
||||
// A replacement with no printable characters would remove the matched run and insert
|
||||
@@ -712,6 +813,8 @@ function matchEdit(objects: PageTextObj[], edit: TextEditInput): PlannedMatch |
|
||||
}
|
||||
}
|
||||
}
|
||||
const rescued = matchByText(objects, edit)
|
||||
if (rescued) return rescued
|
||||
return { reason: 'the edited text could not be located on the page' }
|
||||
}
|
||||
|
||||
@@ -898,6 +1001,87 @@ export function plannedCharColors(
|
||||
return out.some((c) => c !== null) ? out : null
|
||||
}
|
||||
|
||||
/** Per-code-unit fill colors of `targetText` inherited from the matched objects.
|
||||
The rebuild removes and repaints every matched object, so colors an earlier
|
||||
edit saved into the run (selection colors = one object per color) must ride
|
||||
along or the next edit silently flattens them to the anchor color. Alignment
|
||||
is by folded unit rank: the planned text keeps the engine's units for the
|
||||
unchanged head and tail, so common prefix/suffix units pair 1:1 with the
|
||||
engine's and inherit their object's color; the edited middle stays null (the
|
||||
base color, or the user's explicit runs overlaid by the caller). null when
|
||||
the matches all share one fill — nothing worth preserving. */
|
||||
function matchCharColors(
|
||||
m: Pdfium,
|
||||
matches: PageTextObj[],
|
||||
targetText: string,
|
||||
): (Rgb | null)[] | null {
|
||||
if (matches.length < 2) return null
|
||||
const colPtr = m._malloc(16)
|
||||
const byKey = new Map<string, Rgb>()
|
||||
const colorOf = new Map<PageTextObj, Rgb | null>()
|
||||
try {
|
||||
for (const t of matches) {
|
||||
if (!m._FPDFPageObj_GetFillColor(t.obj, colPtr, colPtr + 4, colPtr + 8, colPtr + 12)) {
|
||||
colorOf.set(t, null)
|
||||
continue
|
||||
}
|
||||
const rgb = [0, 4, 8].map((off) => m.HEAPU8[colPtr + off]!) as unknown as Rgb
|
||||
const key = rgb.join(',')
|
||||
// Canonical instance per RGB so segmentLine's reference grouping merges
|
||||
// adjacent same-color spans that came from different objects
|
||||
const c = byKey.get(key) ?? rgb
|
||||
byKey.set(key, c)
|
||||
colorOf.set(t, c)
|
||||
}
|
||||
} finally {
|
||||
m._free(colPtr)
|
||||
}
|
||||
if (byKey.size <= 1) return null
|
||||
const engUnits: string[] = []
|
||||
const engColors: (Rgb | null)[] = []
|
||||
for (const t of readingOrder(matches)) {
|
||||
const units = foldMap(t.text).units
|
||||
const c = colorOf.get(t) ?? null
|
||||
for (const u of units) {
|
||||
engUnits.push(u)
|
||||
engColors.push(c)
|
||||
}
|
||||
}
|
||||
const tgt = foldMap(targetText)
|
||||
let p = 0
|
||||
const maxP = Math.min(tgt.units.length, engUnits.length)
|
||||
while (p < maxP && tgt.units[p] === engUnits[p]) p++
|
||||
let s = 0
|
||||
const maxS = maxP - p
|
||||
while (s < maxS && tgt.units[tgt.units.length - 1 - s] === engUnits[engUnits.length - 1 - s]) s++
|
||||
const shift = engUnits.length - tgt.units.length
|
||||
const out: (Rgb | null)[] = new Array<Rgb | null>(targetText.length).fill(null)
|
||||
let any = false
|
||||
for (let u = 0; u < tgt.units.length; u++) {
|
||||
const c = u < p ? engColors[u]! : u >= tgt.units.length - s ? engColors[u + shift]! : null
|
||||
if (!c) continue
|
||||
for (let k = tgt.idx[u]!; k < tgt.end[u]!; k++) out[k] = c
|
||||
any = true
|
||||
}
|
||||
return any ? out : null
|
||||
}
|
||||
|
||||
/** User selection colors overlaid on the run's own preserved colors; whitespace
|
||||
joins the preceding char's segment (it carries no ink of its own). */
|
||||
function overlayColors(
|
||||
base: (Rgb | null)[] | null,
|
||||
over: (Rgb | null)[] | null,
|
||||
text: string,
|
||||
): (Rgb | null)[] | null {
|
||||
if (!base) return over
|
||||
const out = [...base]
|
||||
if (over) for (let k = 0; k < out.length; k++) if (over[k]) out[k] = over[k]!
|
||||
for (let k = 1; k < out.length; k++) {
|
||||
if (out[k] === null && text[k] !== '\n' && /\s/.test(text[k]!)) out[k] = out[k - 1]!
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
interface LineSeg {
|
||||
text: string
|
||||
color: Rgb | null
|
||||
@@ -942,6 +1126,124 @@ function segmentLine(
|
||||
return segs
|
||||
}
|
||||
|
||||
/** One original text object the rebuild keeps (translated, not redrawn) */
|
||||
interface KeepPlanObj {
|
||||
src: PageTextObj
|
||||
/** Code-unit range in newText this object's characters cover */
|
||||
startK: number
|
||||
endK: number
|
||||
/** Advance width in page units (sum of the chars' loose boxes) */
|
||||
advW: number
|
||||
/** Original baseline origin of the first char (page space) */
|
||||
origX: number
|
||||
origY: number
|
||||
/** Fill override for the whole object; null = keep its own fill */
|
||||
color: Rgb | null
|
||||
}
|
||||
|
||||
/** Signal to abandon the object-preserving build and fall back to a full redraw */
|
||||
class PreserveAbort extends Error {}
|
||||
|
||||
/**
|
||||
* Which matched objects can survive the rebuild untouched. A full redraw flattens
|
||||
* mixed weights/faces into one located font — unrecoverable for Chrome-print docs
|
||||
* whose per-glyph Type3 fonts carry no metadata to even detect bold from. So align
|
||||
* the objects against the rebuilt text by folded unit rank and keep every object
|
||||
* whose characters all sit in the unchanged head/tail and land on one output line;
|
||||
* kept objects are merely translated, only the edited middle is redrawn. Geometry
|
||||
* comes from the pre-edit text page (char → object, loose-box advances).
|
||||
*/
|
||||
function buildKeepPlan(
|
||||
m: Pdfium,
|
||||
textPage: number,
|
||||
matches: PageTextObj[],
|
||||
newText: string,
|
||||
charColors: (Rgb | null)[] | null,
|
||||
newColor: Rgb | undefined,
|
||||
): KeepPlanObj[] | null {
|
||||
const charsOf = new Map<number, number[]>(matches.map((t) => [t.obj, []]))
|
||||
const total = m._FPDFText_CountChars(textPage)
|
||||
for (let i = 0; i < total; i++) {
|
||||
charsOf.get(m._FPDFText_GetTextObject(textPage, i))?.push(i)
|
||||
}
|
||||
const rectPtr = m._malloc(16)
|
||||
const xPtr = m._malloc(8)
|
||||
const yPtr = m._malloc(8)
|
||||
try {
|
||||
const ordered = readingOrder(matches)
|
||||
const engUnits: string[] = []
|
||||
const unitCount: number[] = []
|
||||
const geo: ({ origX: number; origY: number; advW: number } | null)[] = []
|
||||
for (const t of ordered) {
|
||||
const chars = charsOf.get(t.obj) ?? []
|
||||
let g: { origX: number; origY: number; advW: number } | null = null
|
||||
// The object's page chars must correspond 1:1 to its extracted codepoints,
|
||||
// or advance/origin attribution would silently drift
|
||||
if (chars.length > 0 && chars.length === [...t.text].length) {
|
||||
let advW = 0
|
||||
for (const ci of chars) {
|
||||
if (!m._FPDFText_GetLooseCharBox(textPage, ci, rectPtr)) {
|
||||
advW = NaN
|
||||
break
|
||||
}
|
||||
advW += m.HEAPF32[(rectPtr >> 2) + 2]! - m.HEAPF32[rectPtr >> 2]!
|
||||
}
|
||||
if (Number.isFinite(advW) && m._FPDFText_GetCharOrigin(textPage, chars[0]!, xPtr, yPtr)) {
|
||||
g = { origX: m.HEAPF64[xPtr >> 3]!, origY: m.HEAPF64[yPtr >> 3]!, advW }
|
||||
}
|
||||
}
|
||||
geo.push(g)
|
||||
const units = foldMap(t.text).units
|
||||
unitCount.push(units.length)
|
||||
engUnits.push(...units)
|
||||
}
|
||||
const tgt = foldMap(newText)
|
||||
let p = 0
|
||||
const maxP = Math.min(tgt.units.length, engUnits.length)
|
||||
while (p < maxP && tgt.units[p] === engUnits[p]) p++
|
||||
let s = 0
|
||||
const maxS = maxP - p
|
||||
while (s < maxS && tgt.units[tgt.units.length - 1 - s] === engUnits[engUnits.length - 1 - s])
|
||||
s++
|
||||
const shift = engUnits.length - tgt.units.length
|
||||
const out: KeepPlanObj[] = []
|
||||
let a = 0
|
||||
let prevEnd = -1
|
||||
for (const [oi, t] of ordered.entries()) {
|
||||
const b = a + unitCount[oi]!
|
||||
const g = geo[oi]
|
||||
const inPrefix = b <= p
|
||||
const inSuffix = a >= engUnits.length - s
|
||||
if (g && b > a && (inPrefix || inSuffix)) {
|
||||
const ua = inPrefix ? a : a - shift
|
||||
const startK = tgt.idx[ua]!
|
||||
const endK = tgt.end[(inPrefix ? b : b - shift) - 1]!
|
||||
if (startK >= prevEnd && endK > startK && !newText.slice(startK, endK).includes('\n')) {
|
||||
// Fill override must be uniform across the object, or it needs a split
|
||||
let color: Rgb | null | undefined = newColor ?? null
|
||||
if (!newColor && charColors) {
|
||||
color = charColors[startK] ?? null
|
||||
for (let k = startK + 1; k < endK; k++) {
|
||||
if ((charColors[k] ?? null) !== color) {
|
||||
color = undefined
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if (color !== undefined) {
|
||||
out.push({ src: t, startK, endK, advW: g.advW, origX: g.origX, origY: g.origY, color })
|
||||
prevEnd = endK
|
||||
}
|
||||
}
|
||||
}
|
||||
a = b
|
||||
}
|
||||
return out.length > 0 ? out : null
|
||||
} finally {
|
||||
for (const ptr of [rectPtr, xPtr, yPtr]) m._free(ptr)
|
||||
}
|
||||
}
|
||||
|
||||
async function rebuildRun(
|
||||
m: Pdfium,
|
||||
doc: number,
|
||||
@@ -949,6 +1251,7 @@ async function rebuildRun(
|
||||
edit: TextEditInput,
|
||||
matches: PageTextObj[],
|
||||
newText: string,
|
||||
textPage: number,
|
||||
): Promise<boolean> {
|
||||
const anchor = matches.reduce((a, b) => (b.bounds[0] < a.bounds[0] ? b : a))
|
||||
const matPtr = m._malloc(24)
|
||||
@@ -984,35 +1287,93 @@ async function rebuildRun(
|
||||
? ([0, 4, 8, 12].map((off) => m.HEAPU8[colPtr + off]!) as [number, number, number, number])
|
||||
: [0, 0, 0, 255]
|
||||
|
||||
const fontBytes = await rebuildFontBytes(m, anchor.font, edit, newText)
|
||||
const fontPtr = m._malloc(fontBytes.length)
|
||||
m.HEAPU8.set(fontBytes, fontPtr)
|
||||
const font = m._FPDFText_LoadFont(
|
||||
doc,
|
||||
fontPtr,
|
||||
fontBytes.length,
|
||||
isTruetype(fontBytes) ? FPDF_FONT_TRUETYPE : FPDF_FONT_TYPE1,
|
||||
1,
|
||||
)
|
||||
m._free(fontPtr)
|
||||
if (!font) throw new Error('FPDFText_LoadFont failed')
|
||||
// Colors already in the matched run survive underneath the user's selection
|
||||
// colors; an explicit whole-edit newColor means "repaint uniformly" and wins.
|
||||
const keepColors = edit.newColor ? null : matchCharColors(m, matches, newText)
|
||||
const charColors = overlayColors(keepColors, plannedCharColors(edit, newText), newText)
|
||||
|
||||
// Object-preserving mode. Explicit face/size/style overrides mean "restyle
|
||||
// everything" and take the full-redraw path; so does a rotated/skewed matrix
|
||||
// (the cursor walk below only models horizontal text).
|
||||
const styleOverride =
|
||||
edit.newFontSize !== undefined || edit.newFont !== undefined || edit.newBold || edit.newItalic
|
||||
const axisAligned =
|
||||
Math.abs(matrix[1]!) < 1e-4 && Math.abs(matrix[2]!) < 1e-4 && matrix[0]! > 0 && matrix[3]! > 0
|
||||
const keeps =
|
||||
!styleOverride && axisAligned
|
||||
? buildKeepPlan(m, textPage, matches, newText, charColors, edit.newColor)
|
||||
: null
|
||||
// Subset the rebuild font to the non-kept text only: requiring coverage for
|
||||
// kept glyphs (e.g. Type3 PUA codepoints) would fail edits that never touch them
|
||||
const redrawOnly = (): string => {
|
||||
if (!keeps) return newText
|
||||
const parts: string[] = []
|
||||
let k = 0
|
||||
for (const kp of [...keeps].sort((a, b) => a.startK - b.startK)) {
|
||||
parts.push(newText.slice(k, kp.startK))
|
||||
k = kp.endK
|
||||
}
|
||||
parts.push(newText.slice(k))
|
||||
return parts.join('')
|
||||
}
|
||||
|
||||
let font = 0
|
||||
let usedTruetype = true
|
||||
const loadRebuild = async (text: string) => {
|
||||
const fontBytes = await rebuildFontBytes(m, anchor.font, edit, text.trim() ? text : 'x')
|
||||
const fontPtr = m._malloc(fontBytes.length)
|
||||
m.HEAPU8.set(fontBytes, fontPtr)
|
||||
font = m._FPDFText_LoadFont(
|
||||
doc,
|
||||
fontPtr,
|
||||
fontBytes.length,
|
||||
isTruetype(fontBytes) ? FPDF_FONT_TRUETYPE : FPDF_FONT_TYPE1,
|
||||
1,
|
||||
)
|
||||
m._free(fontPtr)
|
||||
if (!font) throw new Error('FPDFText_LoadFont failed')
|
||||
usedTruetype = isTruetype(fontBytes)
|
||||
}
|
||||
await loadRebuild(keeps ? redrawOnly() : newText)
|
||||
|
||||
// Advance of one codepoint in em units, measured from the font object the new
|
||||
// text objects draw with (same unicode→charcode mapping FPDFText_SetText uses)
|
||||
const advanceEm = (cp: number): number | null =>
|
||||
m._FPDFFont_GetGlyphWidth(font, cp, 1, widthPtr) ? m.HEAPF32[widthPtr >> 2]! : null
|
||||
|
||||
// One text object per line — several per line when selection-level colors split
|
||||
// it — stepping down one leading along the matrix's "down" direction (text space
|
||||
// (0,-gap) mapped through [a b c d]) from the anchor baseline (or the edit's
|
||||
// explicit origin — paragraph edits anchor at the block corner). All new objects
|
||||
// are built before anything is removed, so a failure here leaves the page
|
||||
// untouched (the edit is then skipped, not half-applied).
|
||||
const charColors = plannedCharColors(edit, newText)
|
||||
const lineHeight = edit.lineLeading ?? fontSize * LINE_GAP
|
||||
const [baseX, baseY] = edit.origin ?? [matrix[4]!, matrix[5]!]
|
||||
const newObjs: number[] = []
|
||||
try {
|
||||
const moves: { obj: number; dx: number; dy: number; color: Rgb | null }[] = []
|
||||
// Per new object: the kept object preceding it in text order (0 = none), so
|
||||
// redrawn fragments can be inserted next to their kept neighbors — otherwise
|
||||
// stream-order extraction (copy/paste, pdftotext) reads jumbled text
|
||||
const segAnchors: number[] = []
|
||||
let lastKeptObj = 0
|
||||
|
||||
const makeSeg = (text: string, x: number, y: number, segColor: Rgb | null) => {
|
||||
const newObj = m._FPDFPageObj_CreateTextObj(doc, font, fontSize)
|
||||
const textPtr = utf16Ptr(m, text)
|
||||
const ok = m._FPDFText_SetText(newObj, textPtr)
|
||||
m._free(textPtr)
|
||||
if (!ok) {
|
||||
m._FPDFPageObj_Destroy(newObj)
|
||||
throw new Error('FPDFText_SetText failed on rebuilt object')
|
||||
}
|
||||
const lineMatrix = [...matrix]
|
||||
lineMatrix[4] = x
|
||||
lineMatrix[5] = y
|
||||
m.HEAPF32.set(lineMatrix, matPtr >> 2)
|
||||
m._FPDFPageObj_SetMatrix(newObj, matPtr)
|
||||
const c = segColor ? [segColor[0], segColor[1], segColor[2], 255] : color
|
||||
m._FPDFPageObj_SetFillColor(newObj, c[0]!, c[1]!, c[2]!, c[3]!)
|
||||
newObjs.push(newObj)
|
||||
segAnchors.push(lastKeptObj)
|
||||
}
|
||||
|
||||
// Full redraw: one text object per line (several when selection colors split
|
||||
// it), stepping down one leading per line from the anchor baseline or origin
|
||||
const buildRedraw = () => {
|
||||
let lineStart = 0
|
||||
for (const [lineIdx, line] of newText.split('\n').entries()) {
|
||||
const lineColors = charColors ? charColors.slice(lineStart, lineStart + line.length) : null
|
||||
@@ -1021,48 +1382,159 @@ async function rebuildRun(
|
||||
const drop = lineIdx * lineHeight
|
||||
for (const seg of segmentLine(line, lineColors, advanceEm)) {
|
||||
if (!seg.text) continue
|
||||
const newObj = m._FPDFPageObj_CreateTextObj(doc, font, fontSize)
|
||||
const textPtr = utf16Ptr(m, seg.text)
|
||||
const ok = m._FPDFText_SetText(newObj, textPtr)
|
||||
m._free(textPtr)
|
||||
if (!ok) {
|
||||
m._FPDFPageObj_Destroy(newObj)
|
||||
throw new Error('FPDFText_SetText failed on rebuilt object')
|
||||
}
|
||||
// Segment offset is a text-space advance: map it through the matrix's x axis
|
||||
const segX = seg.xEm * fontSize
|
||||
const lineMatrix = [...matrix]
|
||||
lineMatrix[4] =
|
||||
baseX + (edit.lineXOffsets?.[lineIdx] ?? 0) + matrix[0]! * segX - matrix[2]! * drop
|
||||
lineMatrix[5] = baseY + matrix[1]! * segX - matrix[3]! * drop
|
||||
m.HEAPF32.set(lineMatrix, matPtr >> 2)
|
||||
m._FPDFPageObj_SetMatrix(newObj, matPtr)
|
||||
const c = seg.color ? [seg.color[0], seg.color[1], seg.color[2], 255] : color
|
||||
m._FPDFPageObj_SetFillColor(newObj, c[0]!, c[1]!, c[2]!, c[3]!)
|
||||
newObjs.push(newObj)
|
||||
makeSeg(
|
||||
seg.text,
|
||||
baseX + (edit.lineXOffsets?.[lineIdx] ?? 0) + matrix[0]! * segX - matrix[2]! * drop,
|
||||
baseY + matrix[1]! * segX - matrix[3]! * drop,
|
||||
seg.color,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Preserving build: walk each output line with a page-space cursor — kept
|
||||
// objects become translations to the cursor, edited stretches are drawn with
|
||||
// the rebuild font. Consecutive kept objects carry their ORIGINAL spacing, so
|
||||
// untouched (even justified) text keeps its exact layout.
|
||||
const buildPreserved = (plan: KeepPlanObj[]) => {
|
||||
const sorted = [...plan].sort((a, b) => a.startK - b.startK)
|
||||
let ki = 0
|
||||
let lineStart = 0
|
||||
// Advances/leadings are text-space (Tf) values; map through the matrix's
|
||||
// axis scales to walk in page space (scale 1 for origin edits)
|
||||
const emToPage = fontSize * matrix[0]!
|
||||
const advOf = (ch: string): number => {
|
||||
const a = advanceEm(ch.codePointAt(0)!)
|
||||
if (a !== null) return a * emToPage
|
||||
if (/\s/.test(ch)) return emToPage * 0.28
|
||||
throw new PreserveAbort()
|
||||
}
|
||||
for (const [lineIdx, line] of newText.split('\n').entries()) {
|
||||
const lineEnd = lineStart + line.length
|
||||
const baseline = baseY - lineIdx * lineHeight * matrix[3]!
|
||||
let cursor = baseX + (edit.lineXOffsets?.[lineIdx] ?? 0)
|
||||
let prev: { keep: KeepPlanObj; placedX: number } | null = null
|
||||
let k = lineStart
|
||||
while (k < lineEnd) {
|
||||
const keep = ki < sorted.length && sorted[ki]!.startK === k ? sorted[ki]! : null
|
||||
if (keep) {
|
||||
if (
|
||||
prev &&
|
||||
Math.abs(keep.origY - prev.keep.origY) < 0.5 &&
|
||||
keep.origX > prev.keep.origX &&
|
||||
/^\s*$/.test(newText.slice(prev.keep.endK, keep.startK))
|
||||
) {
|
||||
cursor = prev.placedX + (keep.origX - prev.keep.origX)
|
||||
}
|
||||
moves.push({
|
||||
obj: keep.src.obj,
|
||||
dx: cursor - keep.origX,
|
||||
dy: baseline - keep.origY,
|
||||
color: keep.color,
|
||||
})
|
||||
lastKeptObj = keep.src.obj
|
||||
prev = { keep, placedX: cursor }
|
||||
cursor += keep.advW
|
||||
k = keep.endK
|
||||
ki++
|
||||
continue
|
||||
}
|
||||
const runEnd = ki < sorted.length ? Math.min(sorted[ki]!.startK, lineEnd) : lineEnd
|
||||
if (runEnd <= k) throw new PreserveAbort()
|
||||
const runText = newText.slice(k, runEnd)
|
||||
if (runText.trim()) {
|
||||
const runColors = charColors ? charColors.slice(k, runEnd) : null
|
||||
for (const seg of segmentLine(runText, runColors, advanceEm)) {
|
||||
if (!seg.text.trim()) continue
|
||||
makeSeg(seg.text, cursor + seg.xEm * emToPage, baseline, seg.color)
|
||||
}
|
||||
prev = null
|
||||
}
|
||||
for (const ch of runText) cursor += advOf(ch)
|
||||
k = runEnd
|
||||
}
|
||||
lineStart = lineEnd + 1
|
||||
}
|
||||
if (ki !== sorted.length) throw new PreserveAbort()
|
||||
}
|
||||
|
||||
// All new objects are built before anything is removed or moved, so a failure
|
||||
// here leaves the page untouched (the edit is then skipped, not half-applied).
|
||||
try {
|
||||
if (keeps) {
|
||||
try {
|
||||
buildPreserved(keeps)
|
||||
} catch (err) {
|
||||
if (!(err instanceof PreserveAbort)) throw err
|
||||
for (const o of newObjs) m._FPDFPageObj_Destroy(o)
|
||||
newObjs.length = 0
|
||||
moves.length = 0
|
||||
segAnchors.length = 0
|
||||
lastKeptObj = 0
|
||||
// The redraw-only subset lacks the kept glyphs; the fallback draws them
|
||||
await loadRebuild(newText)
|
||||
buildRedraw()
|
||||
}
|
||||
} else {
|
||||
buildRedraw()
|
||||
}
|
||||
} catch (err) {
|
||||
for (const o of newObjs) m._FPDFPageObj_Destroy(o)
|
||||
throw err
|
||||
}
|
||||
|
||||
for (const t of matches) {
|
||||
const kept = new Set(moves.map((v) => v.obj))
|
||||
for (const v of moves) {
|
||||
m._FPDFPageObj_GetMatrix(v.obj, matPtr)
|
||||
m.HEAPF32[(matPtr >> 2) + 4] += v.dx
|
||||
m.HEAPF32[(matPtr >> 2) + 5] += v.dy
|
||||
m._FPDFPageObj_SetMatrix(v.obj, matPtr)
|
||||
if (v.color) m._FPDFPageObj_SetFillColor(v.obj, v.color[0]!, v.color[1]!, v.color[2]!, 255)
|
||||
}
|
||||
const removed = matches.filter((t) => !kept.has(t.obj))
|
||||
for (const t of removed) {
|
||||
m._FPDFPage_RemoveObject(page, t.obj)
|
||||
m._FPDFPageObj_Destroy(t.obj)
|
||||
}
|
||||
// Insert where the removed run began. The anchor (leftmost on the page) is not
|
||||
// necessarily the lowest object index, and every removal below an index shifts it,
|
||||
// so the only post-removal position that is still valid is the run's minimum index.
|
||||
const insertAt = Math.min(...matches.map((t) => t.index))
|
||||
for (const [i, newObj] of newObjs.entries()) {
|
||||
if (m._FPDFPage_InsertObjectAtIndex) {
|
||||
m._FPDFPage_InsertObjectAtIndex(page, newObj, insertAt + i)
|
||||
} else {
|
||||
m._FPDFPage_InsertObject(page, newObj)
|
||||
if (kept.size > 0 && newObjs.length > 0 && m._FPDFPage_InsertObjectAtIndex) {
|
||||
// Keep the content stream in reading order: each redrawn fragment goes right
|
||||
// after its kept predecessor (anchorless fragments lead the run). Indices are
|
||||
// post-removal; groups insert back-to-front so earlier anchors stay valid.
|
||||
const idxOf = new Map<number, number>()
|
||||
const count = m._FPDFPage_CountObjects(page)
|
||||
for (let i = 0; i < count; i++) idxOf.set(m._FPDFPage_GetObject(page, i), i)
|
||||
const runStart = Math.min(
|
||||
...matches.filter((t) => kept.has(t.obj)).map((t) => idxOf.get(t.obj) ?? 0),
|
||||
)
|
||||
const groups: { at: number; objs: number[] }[] = []
|
||||
for (const [i, newObj] of newObjs.entries()) {
|
||||
const anchor = segAnchors[i]!
|
||||
const at = anchor && idxOf.has(anchor) ? idxOf.get(anchor)! + 1 : runStart
|
||||
const g = groups[groups.length - 1]
|
||||
if (g && g.at === at) g.objs.push(newObj)
|
||||
else groups.push({ at, objs: [newObj] })
|
||||
}
|
||||
groups.sort((a, b) => b.at - a.at)
|
||||
for (const g of groups) {
|
||||
for (const [j, newObj] of g.objs.entries()) {
|
||||
m._FPDFPage_InsertObjectAtIndex(page, newObj, g.at + j)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Full redraw: insert where the removed run began — the run's minimum index
|
||||
// is the only position still valid after the removals shift everything else
|
||||
const insertAt = removed.length > 0 ? Math.min(...removed.map((t) => t.index)) : -1
|
||||
for (const [i, newObj] of newObjs.entries()) {
|
||||
if (insertAt >= 0 && m._FPDFPage_InsertObjectAtIndex) {
|
||||
m._FPDFPage_InsertObjectAtIndex(page, newObj, insertAt + i)
|
||||
} else {
|
||||
m._FPDFPage_InsertObject(page, newObj)
|
||||
}
|
||||
}
|
||||
}
|
||||
return !isTruetype(fontBytes)
|
||||
return !usedTruetype
|
||||
} finally {
|
||||
for (const p of [matPtr, sizePtr, colPtr, widthPtr]) m._free(p)
|
||||
}
|
||||
@@ -1242,7 +1714,8 @@ async function applyTextEditsInner(
|
||||
m._free(textPtr)
|
||||
if (!ok) throw new Error('FPDFText_SetText failed')
|
||||
} else {
|
||||
embeddedCff = (await rebuildRun(m, doc, page, eff, matches, newText)) || embeddedCff
|
||||
embeddedCff =
|
||||
(await rebuildRun(m, doc, page, eff, matches, newText, textPage)) || embeddedCff
|
||||
}
|
||||
applied++
|
||||
} catch (err) {
|
||||
@@ -1299,6 +1772,7 @@ async function validateTextEditsInner(
|
||||
continue
|
||||
}
|
||||
const textPage = m._FPDFText_LoadPage(page)
|
||||
const colPtr = m._malloc(16)
|
||||
try {
|
||||
const objects = collectTextObjects(m, page, textPage)
|
||||
for (const e of pageEdits) {
|
||||
@@ -1312,12 +1786,53 @@ async function validateTextEditsInner(
|
||||
// rect's x-span there and take only the ink's vertical extent.
|
||||
const b = matchBounds(res.matches)
|
||||
const whole = norm(res.matches.map((t) => t.text).join('')) === norm(e.oldText)
|
||||
// Colors an earlier edit saved into the run, in oldText offsets: whole
|
||||
// matches share oldText's folded units, so ranks map straight across.
|
||||
// Editors seed their selection-color state from these so the colors
|
||||
// show while editing and the commit repaints them explicitly.
|
||||
const kept = whole ? matchCharColors(m, res.matches, e.oldText) : null
|
||||
const runs: { start: number; end: number; c: Rgb }[] = []
|
||||
if (kept) {
|
||||
for (let k = 0; k < kept.length; k++) {
|
||||
const c = kept[k]
|
||||
if (!c) continue
|
||||
const last = runs[runs.length - 1]
|
||||
if (last && last.end === k && last.c === c) last.end = k + 1
|
||||
else runs.push({ start: k, end: k + 1, c })
|
||||
}
|
||||
}
|
||||
// Base ink of the run (first object in reading order), so the editor can
|
||||
// display the document's actual color even when the run is uniform
|
||||
const first = readingOrder(res.matches)[0]!
|
||||
const baseColor = m._FPDFPageObj_GetFillColor(
|
||||
first.obj,
|
||||
colPtr,
|
||||
colPtr + 4,
|
||||
colPtr + 8,
|
||||
colPtr + 12,
|
||||
)
|
||||
? ([m.HEAPU8[colPtr]!, m.HEAPU8[colPtr + 4]!, m.HEAPU8[colPtr + 8]!] as [
|
||||
number,
|
||||
number,
|
||||
number,
|
||||
])
|
||||
: undefined
|
||||
results[indexOf.get(e)!] = {
|
||||
reason: null,
|
||||
bounds: whole ? b : [e.rect[0], b[1], e.rect[2], b[3]],
|
||||
colorRuns:
|
||||
runs.length > 0
|
||||
? runs.map((r) => ({
|
||||
start: r.start,
|
||||
end: r.end,
|
||||
color: [r.c[0], r.c[1], r.c[2]] as [number, number, number],
|
||||
}))
|
||||
: undefined,
|
||||
baseColor,
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
m._free(colPtr)
|
||||
m._FPDFText_ClosePage(textPage)
|
||||
m._FPDF_ClosePage(page)
|
||||
}
|
||||
@@ -1363,17 +1878,17 @@ export function verifyTextEdits(
|
||||
// compatibility ideograph U+F900 extracts as U+8C48) — the glyph on the page is
|
||||
// right, only the reverse mapping differs, and that must not abort the save
|
||||
const canon = (s: string) => norm(s.normalize('NFC'))
|
||||
const pageText = canon(
|
||||
collectTextObjects(m, page, textPage)
|
||||
.map((o) => o.text)
|
||||
.join(''),
|
||||
)
|
||||
const objects = collectTextObjects(m, page, textPage)
|
||||
const pageText = canon(objects.map((o) => o.text).join(''))
|
||||
// The object-preserving rebuild can leave a reflowed line contiguous
|
||||
// only visually, not in stream order — accept either
|
||||
const visualText = canon(joinRows(objects))
|
||||
for (const newText of texts) {
|
||||
// Every non-empty line must be extractable (rebuilt runs are one object per line)
|
||||
const missing = newText
|
||||
.split('\n')
|
||||
.map(canon)
|
||||
.filter((l) => l.length > 0 && !pageText.includes(l))
|
||||
.filter((l) => l.length > 0 && !pageText.includes(l) && !visualText.includes(l))
|
||||
if (missing.length > 0) {
|
||||
const snippet = missing[0]!.slice(0, 20)
|
||||
failures.push({
|
||||
|
||||
+504
-88
File diff suppressed because it is too large
Load Diff
@@ -432,7 +432,8 @@ export function DrawLayer({
|
||||
key={d.id}
|
||||
className={`pdf-note-pin${d.id === selectedId ? ' pdf-note-pin-selected' : ''}`}
|
||||
style={{ left: vx, top: vy - 20, background: cssRgb(note.color) }}
|
||||
title={`${note.contents}\n\n${selectTitle}`}
|
||||
data-tip={`${note.contents}\n\n${selectTitle}`}
|
||||
aria-label={`${note.contents}\n\n${selectTitle}`}
|
||||
onClick={(e) => onSelect(d.id, e.clientX, e.clientY)}
|
||||
>
|
||||
<svg
|
||||
|
||||
@@ -261,7 +261,7 @@ export function ImageEditLayer({
|
||||
key={e.id}
|
||||
className={`pdf-imgedit-del${sel ? ' pdf-imgedit-selected' : ''}`}
|
||||
style={css(e.input.oldRect)}
|
||||
title={editHint}
|
||||
data-tip={editHint}
|
||||
onClick={(ev) => {
|
||||
ev.stopPropagation()
|
||||
onSelectEdit(e.id, ev.clientX, ev.clientY)
|
||||
@@ -291,7 +291,7 @@ export function ImageEditLayer({
|
||||
className={`pdf-imgedit-img${sel ? ' pdf-imgedit-selected' : ''}`}
|
||||
src={`data:image/png;base64,${src}`}
|
||||
style={ghostStyle(target, e.input.rect, turns)}
|
||||
title={editHint}
|
||||
data-tip={editHint}
|
||||
alt=""
|
||||
draggable={false}
|
||||
{...pointerProps(target, e.input.rect)}
|
||||
@@ -305,7 +305,7 @@ export function ImageEditLayer({
|
||||
key={e.id}
|
||||
className={`pdf-imgedit-ghostbox${sel ? ' pdf-imgedit-selected' : ''}`}
|
||||
style={dragStyle(target, e.input.rect)}
|
||||
title={editHint}
|
||||
data-tip={editHint}
|
||||
{...pointerProps(target, e.input.rect)}
|
||||
/>,
|
||||
)
|
||||
@@ -341,7 +341,7 @@ export function ImageEditLayer({
|
||||
key={key}
|
||||
className={`pdf-imgedit-hit${key === selectedKey ? ' pdf-imgedit-selected' : ''}`}
|
||||
style={dragStyle(target, ref.rect)}
|
||||
title={editHint}
|
||||
data-tip={editHint}
|
||||
{...pointerProps(target, ref.rect)}
|
||||
/>,
|
||||
)
|
||||
|
||||
@@ -62,7 +62,7 @@ export function LinkLayer({
|
||||
className="pdf-link"
|
||||
style={pdfRectToCss(geom, l.rect, scale)}
|
||||
href={l.url ?? '#'}
|
||||
title={l.url}
|
||||
data-tip={l.url}
|
||||
target={l.url ? '_blank' : undefined}
|
||||
rel="noreferrer"
|
||||
onClick={(e) => {
|
||||
|
||||
@@ -9,24 +9,44 @@ export interface OutlineNode {
|
||||
items?: OutlineNode[]
|
||||
}
|
||||
|
||||
function Item({ node, depth, onGo }: { node: OutlineNode; depth: number; onGo: (n: OutlineNode) => void }): ReactElement {
|
||||
function Item({
|
||||
node,
|
||||
depth,
|
||||
onGo,
|
||||
}: {
|
||||
node: OutlineNode
|
||||
depth: number
|
||||
onGo: (n: OutlineNode) => void
|
||||
}): ReactElement {
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
className="pdf-outline-item"
|
||||
style={{ paddingLeft: 10 + depth * 14, fontWeight: node.bold ? 600 : 400, fontStyle: node.italic ? 'italic' : undefined }}
|
||||
title={node.title}
|
||||
style={{
|
||||
paddingLeft: 10 + depth * 14,
|
||||
fontWeight: node.bold ? 600 : 400,
|
||||
fontStyle: node.italic ? 'italic' : undefined,
|
||||
}}
|
||||
data-tip={node.title}
|
||||
onClick={() => onGo(node)}
|
||||
>
|
||||
{node.title}
|
||||
</button>
|
||||
{node.items?.map((c, i) => <Item key={i} node={c} depth={depth + 1} onGo={onGo} />)}
|
||||
{node.items?.map((c, i) => (
|
||||
<Item key={i} node={c} depth={depth + 1} onGo={onGo} />
|
||||
))}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
/** Outline (bookmark) tree: click jumps to internal destinations; url entries open external links */
|
||||
export function OutlinePanel({ outline, onGoToDest }: { outline: OutlineNode[]; onGoToDest: (dest: unknown) => void }): ReactElement {
|
||||
export function OutlinePanel({
|
||||
outline,
|
||||
onGoToDest,
|
||||
}: {
|
||||
outline: OutlineNode[]
|
||||
onGoToDest: (dest: unknown) => void
|
||||
}): ReactElement {
|
||||
const onGo = (n: OutlineNode) => {
|
||||
if (n.url) window.open(n.url, '_blank')
|
||||
else if (n.dest != null) onGoToDest(n.dest)
|
||||
|
||||
@@ -25,7 +25,9 @@ function fmtPdfDate(raw?: string): string {
|
||||
}
|
||||
|
||||
const fmtSize = (bytes: number): string =>
|
||||
bytes >= 1 << 20 ? `${(bytes / (1 << 20)).toFixed(1)} MB` : `${Math.max(1, Math.round(bytes / 1024))} KB`
|
||||
bytes >= 1 << 20
|
||||
? `${(bytes / (1 << 20)).toFixed(1)} MB`
|
||||
: `${Math.max(1, Math.round(bytes / 1024))} KB`
|
||||
|
||||
/** Document properties: first four fields are editable and become unsaved changes; the rest are read-only */
|
||||
export function PropertiesDialog({
|
||||
@@ -86,7 +88,7 @@ export function PropertiesDialog({
|
||||
const row = (label: string, value: string): ReactElement => (
|
||||
<div className="pdf-prop-row">
|
||||
<span>{label}</span>
|
||||
<em title={value}>{value || '—'}</em>
|
||||
<em data-tip={value}>{value || '—'}</em>
|
||||
</div>
|
||||
)
|
||||
|
||||
|
||||
@@ -305,12 +305,18 @@ export function AiPanel({
|
||||
setBusy(false)
|
||||
setChat([])
|
||||
}}
|
||||
title={t('aiNewChat')}
|
||||
data-tip={t('aiNewChat')}
|
||||
aria-label={t('aiNewChat')}
|
||||
>
|
||||
<IconNewChat />
|
||||
</button>
|
||||
)}
|
||||
<button className="ai-header-btn" onClick={onCollapse} title={t('aiCollapsePanel')}>
|
||||
<button
|
||||
className="ai-header-btn"
|
||||
onClick={onCollapse}
|
||||
data-tip={t('aiCollapsePanel')}
|
||||
aria-label={t('aiCollapsePanel')}
|
||||
>
|
||||
<IconCollapse />
|
||||
</button>
|
||||
</div>
|
||||
@@ -492,14 +498,14 @@ function ToolChipList({ tools }: { tools: ToolActivity[] }) {
|
||||
<button
|
||||
type="button"
|
||||
className="ai-step-title clickable"
|
||||
title={tool.name}
|
||||
data-tip={tool.name}
|
||||
aria-expanded={isOpen}
|
||||
onClick={() => toggle(j)}
|
||||
>
|
||||
{tool.summary}
|
||||
</button>
|
||||
) : (
|
||||
<span className="ai-step-title" title={tool.name}>
|
||||
<span className="ai-step-title" data-tip={tool.name}>
|
||||
{tool.summary}
|
||||
</span>
|
||||
)}
|
||||
|
||||
@@ -4,7 +4,11 @@ import App from './App'
|
||||
import { LocaleProvider } from './i18n/locale'
|
||||
import type { UiTheme } from '../shared/ipc'
|
||||
import '@genoffice/ui/tokens.css'
|
||||
import '@genoffice/ui/screentip.css'
|
||||
import './styles.css'
|
||||
import { installScreenTips } from '@genoffice/ui'
|
||||
|
||||
installScreenTips()
|
||||
|
||||
function applyTheme(theme: UiTheme): void {
|
||||
if (theme === 'system') document.documentElement.removeAttribute('data-theme')
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
--pdf-statusbar-border: #e1e4e8;
|
||||
--pdf-statusbar-hover: rgb(0 0 0 / 8%);
|
||||
--pdf-swatch-ring: rgb(0 0 0 / 15%);
|
||||
--pdf-scroll-thumb: rgb(0 0 0 / 25%);
|
||||
|
||||
/* content-side constants: pages are paper, page overlays sit on paper —
|
||||
* these never follow the theme */
|
||||
@@ -88,6 +89,7 @@
|
||||
--pdf-statusbar-border: #3a3a3a;
|
||||
--pdf-statusbar-hover: rgb(255 255 255 / 10%);
|
||||
--pdf-swatch-ring: rgb(255 255 255 / 30%);
|
||||
--pdf-scroll-thumb: rgb(255 255 255 / 28%);
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
@@ -108,6 +110,7 @@
|
||||
--pdf-statusbar-border: #3a3a3a;
|
||||
--pdf-statusbar-hover: rgb(255 255 255 / 10%);
|
||||
--pdf-swatch-ring: rgb(255 255 255 / 30%);
|
||||
--pdf-scroll-thumb: rgb(255 255 255 / 28%);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -279,16 +282,33 @@ button {
|
||||
/* band metrics shared with the docs/slides ribbons (PowerPoint parity) */
|
||||
padding: 6px 12px;
|
||||
/* HARD-fixed height like docs/slides: the ribbon height stays constant, and a
|
||||
narrow window scrolls the row inside the ribbon (invisible scrollbar) instead
|
||||
of squeezing the band */
|
||||
narrow window scrolls the row inside the ribbon instead of squeezing the
|
||||
band */
|
||||
height: 80px;
|
||||
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;
|
||||
/* 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-bottom: 1px;
|
||||
}
|
||||
|
||||
.ribbon-body::-webkit-scrollbar {
|
||||
display: none;
|
||||
height: 5px;
|
||||
}
|
||||
|
||||
.ribbon-body::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.ribbon-body::-webkit-scrollbar-thumb {
|
||||
border-radius: 2.5px;
|
||||
background: var(--pdf-scroll-thumb);
|
||||
}
|
||||
|
||||
.ribbon-group {
|
||||
@@ -1958,11 +1978,20 @@ button {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 2;
|
||||
/* The layer spans the whole page, but only real link rectangles should take
|
||||
pointer input; otherwise every page containing one link blocks text clicks. */
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.pdf-link {
|
||||
position: absolute;
|
||||
border-radius: 2px;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
/* Text editing owns page clicks, including text covered by link annotations. */
|
||||
.pdf-editing-text .pdf-link {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.pdf-link:hover {
|
||||
|
||||
@@ -68,6 +68,18 @@ const dominant = (pairs: [size: number, weight: number][]): number => {
|
||||
return best
|
||||
}
|
||||
|
||||
/** Estimated width of a line's first wrap-unit: CJK breaks after any character
|
||||
(one em, two with a kinsoku pull-down), Latin carries the whole word to the
|
||||
next line. 0.6 em per Latin char errs high on purpose so a ragged wrap
|
||||
before a wide word never reads as a paragraph end. */
|
||||
function firstTokenWidth(text: string, fs: number): number {
|
||||
const t = text.trimStart()
|
||||
if (!t) return 0
|
||||
if (/^[\u2e80-\u9fff\uf900-\ufaff]/.test(t)) return fs * 2
|
||||
const token = /^\S+/.exec(t)![0]
|
||||
return token.length * fs * 0.6
|
||||
}
|
||||
|
||||
const buildLine = (seg: Frag[]): BlockLine => {
|
||||
let text = ''
|
||||
let x1 = Infinity
|
||||
@@ -177,6 +189,41 @@ export function groupPageBlocks(entry: PageEntry): TextBlock[] {
|
||||
} else open.push({ lines: [ln], leads: [] })
|
||||
}
|
||||
|
||||
// Split after paragraph-final short lines: adjacent paragraphs that share
|
||||
// leading, font size and x-extent (labeled footer paragraphs, stacked body
|
||||
// paragraphs, list items) are indistinguishable by leading alone. A real wrap
|
||||
// leaves at most the next line's first wrap-unit unfilled, so an internal
|
||||
// line falling shorter than that is a paragraph end, not a wrapped line.
|
||||
// Left-set text only: centered/right-set lines are ragged on the right by design.
|
||||
for (let i = open.length - 1; i >= 0; i--) {
|
||||
const p = open[i]!
|
||||
if (p.lines.length < 2) continue
|
||||
let x1 = Infinity
|
||||
let x2 = -Infinity
|
||||
for (const l of p.lines) {
|
||||
x1 = Math.min(x1, l.rect[0])
|
||||
x2 = Math.max(x2, l.rect[2])
|
||||
}
|
||||
const fs = dominant(p.lines.map((l) => [l.fontSize, l.rect[2] - l.rect[0]]))
|
||||
if (inferAlign(p.lines, x1, x2, fs) !== 'left') continue
|
||||
const parts: Para[] = []
|
||||
let cur: Para = { lines: [p.lines[0]!], leads: [] }
|
||||
for (let j = 1; j < p.lines.length; j++) {
|
||||
const prev = p.lines[j - 1]!
|
||||
const ln = p.lines[j]!
|
||||
const shortfall = x2 - prev.rect[2]
|
||||
if (shortfall > firstTokenWidth(ln.text, ln.fontSize) + ln.fontSize * 1.5) {
|
||||
parts.push(cur)
|
||||
cur = { lines: [ln], leads: [] }
|
||||
} else {
|
||||
cur.leads.push(p.leads[j - 1]!)
|
||||
cur.lines.push(ln)
|
||||
}
|
||||
}
|
||||
parts.push(cur)
|
||||
if (parts.length > 1) open.splice(i, 1, ...parts)
|
||||
}
|
||||
|
||||
// Re-split where an internal gap is an outlier against the paragraph's own
|
||||
// (lower-)median leading: the generous bootstrap can glue a stray same-size
|
||||
// line (a heading, a list row) to the paragraph below, but real paragraphs
|
||||
|
||||
@@ -12,6 +12,9 @@ export interface LineGroup {
|
||||
rect: { left: number; top: number; right: number; bottom: number }
|
||||
/** Line text left-to-right, a space synthesized at visible gaps between runs */
|
||||
text: string
|
||||
/** Offset of each span's text inside `text` (accounts for synthesized spaces),
|
||||
so a DOM selection endpoint maps to a `text` offset */
|
||||
starts: number[]
|
||||
/** Width-weighted dominant span height (client px) — the line's effective font size,
|
||||
so one oversized glyph doesn't inflate the whole rebuilt line */
|
||||
fontHeight: number
|
||||
@@ -27,7 +30,13 @@ const rotated = (el: HTMLElement) => {
|
||||
export function groupLineSpans(anchor: HTMLElement): LineGroup {
|
||||
const single = (): LineGroup => {
|
||||
const r = anchor.getBoundingClientRect()
|
||||
return { spans: [anchor], rect: r, text: anchor.textContent ?? '', fontHeight: r.height }
|
||||
return {
|
||||
spans: [anchor],
|
||||
rect: r,
|
||||
text: anchor.textContent ?? '',
|
||||
starts: [0],
|
||||
fontHeight: r.height,
|
||||
}
|
||||
}
|
||||
const layer = anchor.closest('.textLayer')
|
||||
if (!layer || rotated(anchor)) return single()
|
||||
@@ -74,6 +83,7 @@ export function groupLineSpans(anchor: HTMLElement): LineGroup {
|
||||
const group = mine.slice(lo, hi + 1)
|
||||
|
||||
let text = ''
|
||||
const starts: number[] = []
|
||||
let left = Infinity
|
||||
let top = Infinity
|
||||
let right = -Infinity
|
||||
@@ -84,6 +94,7 @@ export function groupLineSpans(anchor: HTMLElement): LineGroup {
|
||||
const t = c.el.textContent ?? ''
|
||||
if (prev && c.r.left - prev.r.right > ar.height * 0.15 && !/\s$/.test(text) && !/^\s/.test(t))
|
||||
text += ' '
|
||||
starts.push(text.length)
|
||||
text += t
|
||||
prev = c
|
||||
left = Math.min(left, c.r.left)
|
||||
@@ -100,5 +111,11 @@ export function groupLineSpans(anchor: HTMLElement): LineGroup {
|
||||
bestW = w
|
||||
fontHeight = h
|
||||
}
|
||||
return { spans: group.map((c) => c.el), rect: { left, top, right, bottom }, text, fontHeight }
|
||||
return {
|
||||
spans: group.map((c) => c.el),
|
||||
rect: { left, top, right, bottom },
|
||||
text,
|
||||
starts,
|
||||
fontHeight,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
metrics are the project's source of truth for text width (hb wasm mismeasures
|
||||
AAT faces). */
|
||||
|
||||
import { foldRadicals } from '../shared/radicals'
|
||||
|
||||
const CJK = /[⺀-〿-ヿㇰ-ㇿ㐀-䶿一-鿿豈--가-]/
|
||||
|
||||
/** Must not start a line: closing brackets/quotes, CJK and Latin sentence punctuation */
|
||||
@@ -120,6 +122,119 @@ export function wrapText(
|
||||
return lines.length > 0 ? lines : ['']
|
||||
}
|
||||
|
||||
/** pdf.js sometimes extracts CJK through a font cmap that yields radical-block
|
||||
codepoints (U+2E80-2FDF, e.g. U+2F83 for U+81EA, U+2EE6 for U+9E1F) where the page
|
||||
really draws unified ideographs — and PDFium extracts those. Fold each radical to
|
||||
its unified equivalent (visually identical) so block drafts edit and write back
|
||||
real ideographs: retained radical variants between two folded edits would
|
||||
otherwise reach the rebuild font as undrawable characters. NFKC alone is not
|
||||
enough — the Radicals Supplement (U+2E80-2EFF) has no decompositions — so this
|
||||
goes through the shared RADICAL_EQUIV table first. */
|
||||
export function unifyRadicals(s: string): string {
|
||||
// Gate covers everything foldRadicals maps (radical blocks AND CJK Strokes
|
||||
// U+31C0-31E3) — the engine folds strokes too, so both sides must agree
|
||||
return /[\u2e80-\u2fdf\u31c0-\u31e3]/.test(s)
|
||||
? foldRadicals(s).replace(/[\u2e80-\u2fdf]/g, (ch) => ch.normalize('NFKC'))
|
||||
: s
|
||||
}
|
||||
|
||||
/** Non-whitespace code units of `s` (radical-folded) with their original indices —
|
||||
splice matching must ignore synthesized/joined spaces and radical variants.
|
||||
Folds are pushed unit by unit (an astral fold becomes two surrogate entries
|
||||
sharing one original index), so an unfolded needle aligns with an
|
||||
already-folded haystack that carries the surrogates as separate units. */
|
||||
function nonSpaceMap(s: string): { chars: string[]; idx: number[] } {
|
||||
const chars: string[] = []
|
||||
const idx: number[] = []
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
if (/\s/.test(s[i]!)) continue
|
||||
const folded = unifyRadicals(s[i]!)
|
||||
for (let k = 0; k < folded.length; k++) {
|
||||
chars.push(folded[k]!)
|
||||
idx.push(i)
|
||||
}
|
||||
}
|
||||
return { chars, idx }
|
||||
}
|
||||
|
||||
const indexOfSub = (hay: string[], needle: string[], from: number): number => {
|
||||
if (needle.length === 0) return -1
|
||||
outer: for (let i = Math.max(0, from); i + needle.length <= hay.length; i++) {
|
||||
for (let j = 0; j < needle.length; j++) if (hay[i + j] !== needle[j]) continue outer
|
||||
return i
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
/** Fold pending line edits into a block's joined paragraph text: each edit's
|
||||
oldText is located whitespace-insensitively (line joins differ in synthesized
|
||||
spaces) and replaced by its newText as committed. `hint` is the edit's rough
|
||||
non-space offset within the block (from the edited line's position), used to
|
||||
prefer the right occurrence when a paragraph repeats itself. Returns null when
|
||||
any oldText cannot be found or two edits overlap — the caller then keeps the
|
||||
unfolded behavior. */
|
||||
export function spliceBlockText(
|
||||
blockText: string,
|
||||
edits: { oldText: string; newText: string; hint?: number }[],
|
||||
): string | null {
|
||||
const hay = nonSpaceMap(blockText)
|
||||
const ranges: { start: number; end: number; newText: string }[] = []
|
||||
for (const e of edits) {
|
||||
const needle = nonSpaceMap(e.oldText).chars
|
||||
// From the hinted line start first; a crossing-span oldText that begins on the
|
||||
// previous line (or a stale hint) falls back to the first occurrence anywhere
|
||||
let at = indexOfSub(hay.chars, needle, e.hint ?? 0)
|
||||
if (at < 0) at = indexOfSub(hay.chars, needle, 0)
|
||||
if (at < 0) return null
|
||||
ranges.push({
|
||||
start: hay.idx[at]!,
|
||||
end: hay.idx[at + needle.length - 1]! + 1,
|
||||
newText: unifyRadicals(e.newText),
|
||||
})
|
||||
}
|
||||
ranges.sort((a, b) => a.start - b.start)
|
||||
for (let i = 1; i < ranges.length; i++) {
|
||||
if (ranges[i]!.start < ranges[i - 1]!.end) return null
|
||||
}
|
||||
let out = ''
|
||||
let pos = 0
|
||||
for (const r of ranges) {
|
||||
out += blockText.slice(pos, r.start) + r.newText
|
||||
pos = r.end
|
||||
}
|
||||
return out + blockText.slice(pos)
|
||||
}
|
||||
|
||||
/** Map a [start,end) code-unit range of one visual line's raw text to the offsets of
|
||||
the same characters inside the block's joined paragraph text. Whitespace differs
|
||||
between the two (line joins synthesize/drop spaces, the DOM line synthesizes gap
|
||||
spaces), so alignment goes through the folded non-space sequences, like
|
||||
spliceBlockText. A range covering only whitespace collapses to a caret. null =
|
||||
the line cannot be located inside the block text. */
|
||||
export function mapLineRangeToBlock(
|
||||
blockText: string,
|
||||
lineText: string,
|
||||
start: number,
|
||||
end: number,
|
||||
): [number, number] | null {
|
||||
const hay = nonSpaceMap(blockText)
|
||||
const needle = nonSpaceMap(lineText)
|
||||
if (needle.chars.length === 0) return null
|
||||
const at = indexOfSub(hay.chars, needle.chars, 0)
|
||||
if (at < 0) return null
|
||||
// Non-space ranks of the line covered by [start,end)
|
||||
let k1 = 0
|
||||
while (k1 < needle.idx.length && needle.idx[k1]! < start) k1++
|
||||
let k2 = k1
|
||||
while (k2 < needle.idx.length && needle.idx[k2]! < end) k2++
|
||||
if (k1 >= k2) {
|
||||
const caret =
|
||||
k1 < needle.idx.length ? hay.idx[at + k1]! : hay.idx[at + needle.chars.length - 1]! + 1
|
||||
return [caret, caret]
|
||||
}
|
||||
return [hay.idx[at + k1]!, hay.idx[at + k2 - 1]! + 1]
|
||||
}
|
||||
|
||||
/** Join a block's extracted lines back into one logical paragraph string: a space at
|
||||
Latin boundaries, nothing between CJK (their hard breaks carry no space) */
|
||||
export function joinBlockLines(lines: string[]): string {
|
||||
@@ -134,5 +249,5 @@ export function joinBlockLines(lines: string[]): string {
|
||||
}
|
||||
out += t
|
||||
}
|
||||
return out
|
||||
return unifyRadicals(out)
|
||||
}
|
||||
|
||||
@@ -158,6 +158,14 @@ export interface TextEditValidation {
|
||||
edit rect is a pdf.js layout box (font metrics); glyph ink can poke out of it, so the
|
||||
preview cover must use the engine's real bounds or remnants of the old run show through */
|
||||
bounds?: [number, number, number, number]
|
||||
/** Fill colors the matched objects already draw with (earlier saved selection colors),
|
||||
as [start,end) ranges into oldText. Present only when the match spans differently
|
||||
colored objects. Editors seed their selection-color state from these so existing
|
||||
colors show while editing and survive the rebuild. */
|
||||
colorRuns?: { start: number; end: number; color: [number, number, number] }[]
|
||||
/** Base fill color of the matched run (its first object in reading order), for
|
||||
display while editing — a uniformly colored run has no colorRuns to seed from */
|
||||
baseColor?: [number, number, number]
|
||||
}
|
||||
|
||||
/** Curated fonts selectable for rebuilt text runs. Single-face .ttf on every platform we
|
||||
|
||||
@@ -0,0 +1,370 @@
|
||||
/** CJK radical/stroke codepoint -> equivalent unified ideograph, generated from
|
||||
Unicode UCD 17.0.0 EquivalentUnifiedIdeograph.txt (2025-08-01):
|
||||
https://www.unicode.org/Public/17.0.0/ucd/EquivalentUnifiedIdeograph.txt
|
||||
Licensed under Unicode License v3; see LICENSE-UNICODE.txt.
|
||||
pdf.js sometimes extracts text through a font cmap that yields radical-block
|
||||
codepoints (U+2E80-2FDF, and occasionally CJK strokes U+31C0-31E3) where the
|
||||
page really draws the unified character - PDFium extracts the real one. NFKC
|
||||
only decomposes the Kangxi block (U+2F00-2FD5); the Radicals Supplement has no
|
||||
decompositions at all, so both processes fold through this table before
|
||||
comparing or writing text back. */
|
||||
export const RADICAL_EQUIV: Record<string, string> = {
|
||||
'\u2e81': '\u5382',
|
||||
'\u2e82': '\u4e5b',
|
||||
'\u2e83': '\u4e5a',
|
||||
'\u2e84': '\u4e59',
|
||||
'\u2e85': '\u4ebb',
|
||||
'\u2e86': '\u5182',
|
||||
'\u2e87': '\u{20628}',
|
||||
'\u2e88': '\u5200',
|
||||
'\u2e89': '\u5202',
|
||||
'\u2e8a': '\u535c',
|
||||
'\u2e8b': '\u353e',
|
||||
'\u2e8c': '\u5c0f',
|
||||
'\u2e8d': '\u5c0f',
|
||||
'\u2e8e': '\u5140',
|
||||
'\u2e8f': '\u5c23',
|
||||
'\u2e90': '\u5c22',
|
||||
'\u2e91': '\u{21bc2}',
|
||||
'\u2e92': '\u5df3',
|
||||
'\u2e93': '\u5e7a',
|
||||
'\u2e94': '\u5f51',
|
||||
'\u2e95': '\u{2b739}',
|
||||
'\u2e96': '\u5fc4',
|
||||
'\u2e97': '\u5fc3',
|
||||
'\u2e98': '\u624c',
|
||||
'\u2e99': '\u6535',
|
||||
'\u2e9b': '\u65e1',
|
||||
'\u2e9c': '\u65e5',
|
||||
'\u2e9d': '\u6708',
|
||||
'\u2e9e': '\u6b7a',
|
||||
'\u2e9f': '\u6bcd',
|
||||
'\u2ea0': '\u6c11',
|
||||
'\u2ea1': '\u6c35',
|
||||
'\u2ea2': '\u6c3a',
|
||||
'\u2ea3': '\u706c',
|
||||
'\u2ea4': '\u722b',
|
||||
'\u2ea5': '\u722b',
|
||||
'\u2ea6': '\u4e2c',
|
||||
'\u2ea7': '\u725b',
|
||||
'\u2ea8': '\u72ad',
|
||||
'\u2ea9': '\u738b',
|
||||
'\u2eaa': '\u{24d14}',
|
||||
'\u2eab': '\u76ee',
|
||||
'\u2eac': '\u793a',
|
||||
'\u2ead': '\u793b',
|
||||
'\u2eae': '\u{25ad7}',
|
||||
'\u2eaf': '\u7cf9',
|
||||
'\u2eb0': '\u7e9f',
|
||||
'\u2eb1': '\u7f53',
|
||||
'\u2eb2': '\u7f52',
|
||||
'\u2eb3': '\u34c1',
|
||||
'\u2eb4': '\u5197',
|
||||
'\u2eb5': '\u{2626b}',
|
||||
'\u2eb6': '\u7f8a',
|
||||
'\u2eb7': '\u{2634c}',
|
||||
'\u2eb8': '\u{2634b}',
|
||||
'\u2eb9': '\u8002',
|
||||
'\u2eba': '\u8080',
|
||||
'\u2ebb': '\u807f',
|
||||
'\u2ebc': '\u8089',
|
||||
'\u2ebd': '\u{26951}',
|
||||
'\u2ebe': '\u8279',
|
||||
'\u2ebf': '\u8279',
|
||||
'\u2ec0': '\u8279',
|
||||
'\u2ec1': '\u864e',
|
||||
'\u2ec2': '\u8864',
|
||||
'\u2ec3': '\u8980',
|
||||
'\u2ec4': '\u897f',
|
||||
'\u2ec5': '\u89c1',
|
||||
'\u2ec6': '\u89d2',
|
||||
'\u2ec7': '\u{278b2}',
|
||||
'\u2ec8': '\u8ba0',
|
||||
'\u2ec9': '\u8d1d',
|
||||
'\u2eca': '\u{27fb7}',
|
||||
'\u2ecb': '\u8f66',
|
||||
'\u2ecc': '\u8fb6',
|
||||
'\u2ecd': '\u8fb6',
|
||||
'\u2ece': '\u8fb6',
|
||||
'\u2ecf': '\u9091',
|
||||
'\u2ed0': '\u9485',
|
||||
'\u2ed1': '\u9577',
|
||||
'\u2ed2': '\u9578',
|
||||
'\u2ed3': '\u957f',
|
||||
'\u2ed4': '\u95e8',
|
||||
'\u2ed5': '\u{28e0f}',
|
||||
'\u2ed6': '\u961d',
|
||||
'\u2ed7': '\u96e8',
|
||||
'\u2ed8': '\u9752',
|
||||
'\u2ed9': '\u97e6',
|
||||
'\u2eda': '\u9875',
|
||||
'\u2edb': '\u98ce',
|
||||
'\u2edc': '\u98de',
|
||||
'\u2edd': '\u98df',
|
||||
'\u2ede': '\u{2967f}',
|
||||
'\u2edf': '\u98e0',
|
||||
'\u2ee0': '\u9963',
|
||||
'\u2ee1': '\u{29810}',
|
||||
'\u2ee2': '\u9a6c',
|
||||
'\u2ee3': '\u9aa8',
|
||||
'\u2ee4': '\u9b3c',
|
||||
'\u2ee5': '\u9c7c',
|
||||
'\u2ee6': '\u9e1f',
|
||||
'\u2ee7': '\u5364',
|
||||
'\u2ee8': '\u9ea6',
|
||||
'\u2ee9': '\u9ec4',
|
||||
'\u2eea': '\u9efe',
|
||||
'\u2eeb': '\u6589',
|
||||
'\u2eec': '\u9f50',
|
||||
'\u2eed': '\u6b6f',
|
||||
'\u2eee': '\u9f7f',
|
||||
'\u2eef': '\u7adc',
|
||||
'\u2ef0': '\u9f99',
|
||||
'\u2ef1': '\u9f9c',
|
||||
'\u2ef2': '\u4e80',
|
||||
'\u2ef3': '\u9f9f',
|
||||
'\u2f00': '\u4e00',
|
||||
'\u2f01': '\u4e28',
|
||||
'\u2f02': '\u4e36',
|
||||
'\u2f03': '\u4e3f',
|
||||
'\u2f04': '\u4e59',
|
||||
'\u2f05': '\u4e85',
|
||||
'\u2f06': '\u4e8c',
|
||||
'\u2f07': '\u4ea0',
|
||||
'\u2f08': '\u4eba',
|
||||
'\u2f09': '\u513f',
|
||||
'\u2f0a': '\u5165',
|
||||
'\u2f0b': '\u516b',
|
||||
'\u2f0c': '\u5182',
|
||||
'\u2f0d': '\u5196',
|
||||
'\u2f0e': '\u51ab',
|
||||
'\u2f0f': '\u51e0',
|
||||
'\u2f10': '\u51f5',
|
||||
'\u2f11': '\u5200',
|
||||
'\u2f12': '\u529b',
|
||||
'\u2f13': '\u52f9',
|
||||
'\u2f14': '\u5315',
|
||||
'\u2f15': '\u531a',
|
||||
'\u2f16': '\u5338',
|
||||
'\u2f17': '\u5341',
|
||||
'\u2f18': '\u535c',
|
||||
'\u2f19': '\u5369',
|
||||
'\u2f1a': '\u5382',
|
||||
'\u2f1b': '\u53b6',
|
||||
'\u2f1c': '\u53c8',
|
||||
'\u2f1d': '\u53e3',
|
||||
'\u2f1e': '\u56d7',
|
||||
'\u2f1f': '\u571f',
|
||||
'\u2f20': '\u58eb',
|
||||
'\u2f21': '\u5902',
|
||||
'\u2f22': '\u590a',
|
||||
'\u2f23': '\u5915',
|
||||
'\u2f24': '\u5927',
|
||||
'\u2f25': '\u5973',
|
||||
'\u2f26': '\u5b50',
|
||||
'\u2f27': '\u5b80',
|
||||
'\u2f28': '\u5bf8',
|
||||
'\u2f29': '\u5c0f',
|
||||
'\u2f2a': '\u5c22',
|
||||
'\u2f2b': '\u5c38',
|
||||
'\u2f2c': '\u5c6e',
|
||||
'\u2f2d': '\u5c71',
|
||||
'\u2f2e': '\u5ddb',
|
||||
'\u2f2f': '\u5de5',
|
||||
'\u2f30': '\u5df1',
|
||||
'\u2f31': '\u5dfe',
|
||||
'\u2f32': '\u5e72',
|
||||
'\u2f33': '\u5e7a',
|
||||
'\u2f34': '\u5e7f',
|
||||
'\u2f35': '\u5ef4',
|
||||
'\u2f36': '\u5efe',
|
||||
'\u2f37': '\u5f0b',
|
||||
'\u2f38': '\u5f13',
|
||||
'\u2f39': '\u5f50',
|
||||
'\u2f3a': '\u5f61',
|
||||
'\u2f3b': '\u5f73',
|
||||
'\u2f3c': '\u5fc3',
|
||||
'\u2f3d': '\u6208',
|
||||
'\u2f3e': '\u6236',
|
||||
'\u2f3f': '\u624b',
|
||||
'\u2f40': '\u652f',
|
||||
'\u2f41': '\u6534',
|
||||
'\u2f42': '\u6587',
|
||||
'\u2f43': '\u6597',
|
||||
'\u2f44': '\u65a4',
|
||||
'\u2f45': '\u65b9',
|
||||
'\u2f46': '\u65e0',
|
||||
'\u2f47': '\u65e5',
|
||||
'\u2f48': '\u66f0',
|
||||
'\u2f49': '\u6708',
|
||||
'\u2f4a': '\u6728',
|
||||
'\u2f4b': '\u6b20',
|
||||
'\u2f4c': '\u6b62',
|
||||
'\u2f4d': '\u6b79',
|
||||
'\u2f4e': '\u6bb3',
|
||||
'\u2f4f': '\u6bcb',
|
||||
'\u2f50': '\u6bd4',
|
||||
'\u2f51': '\u6bdb',
|
||||
'\u2f52': '\u6c0f',
|
||||
'\u2f53': '\u6c14',
|
||||
'\u2f54': '\u6c34',
|
||||
'\u2f55': '\u706b',
|
||||
'\u2f56': '\u722a',
|
||||
'\u2f57': '\u7236',
|
||||
'\u2f58': '\u723b',
|
||||
'\u2f59': '\u723f',
|
||||
'\u2f5a': '\u7247',
|
||||
'\u2f5b': '\u7259',
|
||||
'\u2f5c': '\u725b',
|
||||
'\u2f5d': '\u72ac',
|
||||
'\u2f5e': '\u7384',
|
||||
'\u2f5f': '\u7389',
|
||||
'\u2f60': '\u74dc',
|
||||
'\u2f61': '\u74e6',
|
||||
'\u2f62': '\u7518',
|
||||
'\u2f63': '\u751f',
|
||||
'\u2f64': '\u7528',
|
||||
'\u2f65': '\u7530',
|
||||
'\u2f66': '\u758b',
|
||||
'\u2f67': '\u7592',
|
||||
'\u2f68': '\u7676',
|
||||
'\u2f69': '\u767d',
|
||||
'\u2f6a': '\u76ae',
|
||||
'\u2f6b': '\u76bf',
|
||||
'\u2f6c': '\u76ee',
|
||||
'\u2f6d': '\u77db',
|
||||
'\u2f6e': '\u77e2',
|
||||
'\u2f6f': '\u77f3',
|
||||
'\u2f70': '\u793a',
|
||||
'\u2f71': '\u79b8',
|
||||
'\u2f72': '\u79be',
|
||||
'\u2f73': '\u7a74',
|
||||
'\u2f74': '\u7acb',
|
||||
'\u2f75': '\u7af9',
|
||||
'\u2f76': '\u7c73',
|
||||
'\u2f77': '\u7cf8',
|
||||
'\u2f78': '\u7f36',
|
||||
'\u2f79': '\u7f51',
|
||||
'\u2f7a': '\u7f8a',
|
||||
'\u2f7b': '\u7fbd',
|
||||
'\u2f7c': '\u8001',
|
||||
'\u2f7d': '\u800c',
|
||||
'\u2f7e': '\u8012',
|
||||
'\u2f7f': '\u8033',
|
||||
'\u2f80': '\u807f',
|
||||
'\u2f81': '\u8089',
|
||||
'\u2f82': '\u81e3',
|
||||
'\u2f83': '\u81ea',
|
||||
'\u2f84': '\u81f3',
|
||||
'\u2f85': '\u81fc',
|
||||
'\u2f86': '\u820c',
|
||||
'\u2f87': '\u821b',
|
||||
'\u2f88': '\u821f',
|
||||
'\u2f89': '\u826e',
|
||||
'\u2f8a': '\u8272',
|
||||
'\u2f8b': '\u8278',
|
||||
'\u2f8c': '\u864d',
|
||||
'\u2f8d': '\u866b',
|
||||
'\u2f8e': '\u8840',
|
||||
'\u2f8f': '\u884c',
|
||||
'\u2f90': '\u8863',
|
||||
'\u2f91': '\u897e',
|
||||
'\u2f92': '\u898b',
|
||||
'\u2f93': '\u89d2',
|
||||
'\u2f94': '\u8a00',
|
||||
'\u2f95': '\u8c37',
|
||||
'\u2f96': '\u8c46',
|
||||
'\u2f97': '\u8c55',
|
||||
'\u2f98': '\u8c78',
|
||||
'\u2f99': '\u8c9d',
|
||||
'\u2f9a': '\u8d64',
|
||||
'\u2f9b': '\u8d70',
|
||||
'\u2f9c': '\u8db3',
|
||||
'\u2f9d': '\u8eab',
|
||||
'\u2f9e': '\u8eca',
|
||||
'\u2f9f': '\u8f9b',
|
||||
'\u2fa0': '\u8fb0',
|
||||
'\u2fa1': '\u8fb5',
|
||||
'\u2fa2': '\u9091',
|
||||
'\u2fa3': '\u9149',
|
||||
'\u2fa4': '\u91c6',
|
||||
'\u2fa5': '\u91cc',
|
||||
'\u2fa6': '\u91d1',
|
||||
'\u2fa7': '\u9577',
|
||||
'\u2fa8': '\u9580',
|
||||
'\u2fa9': '\u961c',
|
||||
'\u2faa': '\u96b6',
|
||||
'\u2fab': '\u96b9',
|
||||
'\u2fac': '\u96e8',
|
||||
'\u2fad': '\u9751',
|
||||
'\u2fae': '\u975e',
|
||||
'\u2faf': '\u9762',
|
||||
'\u2fb0': '\u9769',
|
||||
'\u2fb1': '\u97cb',
|
||||
'\u2fb2': '\u97ed',
|
||||
'\u2fb3': '\u97f3',
|
||||
'\u2fb4': '\u9801',
|
||||
'\u2fb5': '\u98a8',
|
||||
'\u2fb6': '\u98db',
|
||||
'\u2fb7': '\u98df',
|
||||
'\u2fb8': '\u9996',
|
||||
'\u2fb9': '\u9999',
|
||||
'\u2fba': '\u99ac',
|
||||
'\u2fbb': '\u9aa8',
|
||||
'\u2fbc': '\u9ad8',
|
||||
'\u2fbd': '\u9adf',
|
||||
'\u2fbe': '\u9b25',
|
||||
'\u2fbf': '\u9b2f',
|
||||
'\u2fc0': '\u9b32',
|
||||
'\u2fc1': '\u9b3c',
|
||||
'\u2fc2': '\u9b5a',
|
||||
'\u2fc3': '\u9ce5',
|
||||
'\u2fc4': '\u9e75',
|
||||
'\u2fc5': '\u9e7f',
|
||||
'\u2fc6': '\u9ea5',
|
||||
'\u2fc7': '\u9ebb',
|
||||
'\u2fc8': '\u9ec3',
|
||||
'\u2fc9': '\u9ecd',
|
||||
'\u2fca': '\u9ed1',
|
||||
'\u2fcb': '\u9ef9',
|
||||
'\u2fcc': '\u9efd',
|
||||
'\u2fcd': '\u9f0e',
|
||||
'\u2fce': '\u9f13',
|
||||
'\u2fcf': '\u9f20',
|
||||
'\u2fd0': '\u9f3b',
|
||||
'\u2fd1': '\u9f4a',
|
||||
'\u2fd2': '\u9f52',
|
||||
'\u2fd3': '\u9f8d',
|
||||
'\u2fd4': '\u9f9c',
|
||||
'\u2fd5': '\u9fa0',
|
||||
'\u31c6': '\u{200cc}',
|
||||
'\u31cf': '\u4e40',
|
||||
'\u31d0': '\u4e00',
|
||||
'\u31d1': '\u4e28',
|
||||
'\u31d2': '\u4e3f',
|
||||
'\u31d3': '\u4e3f',
|
||||
'\u31d4': '\u4e36',
|
||||
'\u31d5': '\u{200cd}',
|
||||
'\u31d6': '\u4e5b',
|
||||
'\u31d7': '\u{200ca}',
|
||||
'\u31d8': '\u{200ce}',
|
||||
'\u31d9': '\u{2010c}',
|
||||
'\u31da': '\u4e85',
|
||||
'\u31db': '\u{21fe8}',
|
||||
'\u31dc': '\u{200cb}',
|
||||
'\u31dd': '\u4e40',
|
||||
'\u31de': '\u{200d1}',
|
||||
'\u31df': '\u4e5a',
|
||||
'\u31e0': '\u4e59',
|
||||
'\u31e1': '\u{2010e}',
|
||||
}
|
||||
|
||||
const RADICAL_RE = /[\u2e80-\u2fdf\u31c0-\u31e3]/
|
||||
|
||||
/** Fold radical-block codepoints to the unified ideographs they stand in for;
|
||||
other characters pass through untouched. */
|
||||
export function foldRadicals(s: string): string {
|
||||
return RADICAL_RE.test(s)
|
||||
? s.replace(/[\u2e80-\u2fdf\u31c0-\u31e3]/g, (ch) => RADICAL_EQUIV[ch] ?? ch)
|
||||
: s
|
||||
}
|
||||
@@ -155,6 +155,51 @@ describe('groupPageBlocks', () => {
|
||||
expect(blocks[0]!.lines).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('splits adjacent labeled paragraphs at a paragraph-final short line', () => {
|
||||
// Footer-box style: two labeled paragraphs, same leading and font size; the
|
||||
// first ends in a line far shorter than the shared extent, so the next line
|
||||
// starts a new paragraph even though leading alone cannot tell them apart
|
||||
const blocks = groupPageBlocks(
|
||||
page([
|
||||
{
|
||||
t: '\u6570\u636e\u6765\u6e90\uff1a\u5e74\u62a5\u53ca\u5b63\u5ea6\u4e1a\u7ee9\u516c\u544a\u62ab\u9732\u6587\u4ef6',
|
||||
x: 50,
|
||||
y: 700,
|
||||
w: 400,
|
||||
h: 10,
|
||||
},
|
||||
{
|
||||
t: '\u516c\u5f00\u5e02\u573a\u884c\u60c5\u6570\u636e\u3002',
|
||||
x: 50,
|
||||
y: 681,
|
||||
w: 90,
|
||||
h: 10,
|
||||
},
|
||||
{
|
||||
t: '\u514d\u8d23\u58f0\u660e\uff1a\u672c\u62a5\u544a\u4ec5\u4f9b\u7814\u7a76\u53c2\u8003\u4e0d\u6784\u6210\u6295\u8d44\u5efa\u8bae',
|
||||
x: 50,
|
||||
y: 662,
|
||||
w: 400,
|
||||
h: 10,
|
||||
},
|
||||
]),
|
||||
)
|
||||
expect(blocks.map((b) => b.lines.length)).toEqual([2, 1])
|
||||
})
|
||||
|
||||
it('keeps a ragged wrap that the next word explains (no paragraph-end split)', () => {
|
||||
// Line 1 ends 60pt short, but the next line starts with a 10-char word
|
||||
// (~72pt at 12pt): the wrap is forced, not a paragraph boundary
|
||||
const blocks = groupPageBlocks(
|
||||
page([
|
||||
{ t: 'ragged text before a', x: 50, y: 700, w: 160, h: 12 },
|
||||
{ t: 'wideworddd continues here', x: 50, y: 686, w: 220, h: 12 },
|
||||
{ t: 'and ends.', x: 50, y: 672, w: 70, h: 12 },
|
||||
]),
|
||||
)
|
||||
expect(blocks).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('tolerates a first-line indent', () => {
|
||||
const blocks = groupPageBlocks(
|
||||
page([{ t: 'indented', x: 62, y: 700, w: 188, h: 12 }, bodyLine('flush left line', 686)]),
|
||||
@@ -170,7 +215,9 @@ describe('groupPageBlocks', () => {
|
||||
w: 12,
|
||||
h: 12,
|
||||
}))
|
||||
const blocks = groupPageBlocks(page([...glyphs, bodyLine('第二行第二行第二行', 686)]))
|
||||
const blocks = groupPageBlocks(
|
||||
page([...glyphs, { t: '\u7b2c\u4e8c\u884c\u7b2c\u4e8c\u884c', x: 50, y: 686, w: 72, h: 12 }]),
|
||||
)
|
||||
expect(blocks).toHaveLength(1)
|
||||
expect(blocks[0]!.lines[0]!.text).toBe('一丁丂七丄丅')
|
||||
})
|
||||
|
||||
@@ -487,8 +487,12 @@ describe('block edits (paragraph rebuild)', () => {
|
||||
lineLeading: 18,
|
||||
},
|
||||
])
|
||||
// The object-preserving rebuild keeps the original objects side by side on the
|
||||
// merged line; compare per-baseline text so extraction granularity doesn't matter
|
||||
const lines = await extractLines(out)
|
||||
expect(lines.map((l) => l.str)).toEqual([
|
||||
const byY = new Map()
|
||||
for (const l of lines) byY.set(l.y, (byY.get(l.y) ?? '') + l.str)
|
||||
expect([...byY.values()].map((s) => s.replace(/\s+/g, ' ').trim())).toEqual([
|
||||
'first line of text second line follows',
|
||||
'third line ends here',
|
||||
])
|
||||
@@ -813,3 +817,206 @@ describe('validateTextEdits', () => {
|
||||
expect(miss!.bounds).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('text-first rescue (multi-object lines)', () => {
|
||||
/** Lines whose every word is its own PDF text object on a shared baseline — the
|
||||
granularity Chrome/Word exports use. Word gaps are positional (no space chars
|
||||
inside the objects), so the joined engine text carries no spaces. */
|
||||
async function makeWordLines(
|
||||
lines: { words: string[]; y: number }[],
|
||||
): Promise<{ bytes: Uint8Array; extents: { left: number; right: number }[] }> {
|
||||
const doc = await PDFDocument.create()
|
||||
const page = doc.addPage([595, 842])
|
||||
const font = await doc.embedFont(StandardFonts.Helvetica)
|
||||
const size = 14
|
||||
const extents: { left: number; right: number }[] = []
|
||||
for (const { words, y } of lines) {
|
||||
let x = 50
|
||||
let right = 50
|
||||
for (const w of words) {
|
||||
page.drawText(w, { x, y, size, font })
|
||||
right = x + font.widthOfTextAtSize(w, size)
|
||||
x = right + font.widthOfTextAtSize(' ', size)
|
||||
}
|
||||
extents.push({ left: 50, right })
|
||||
}
|
||||
return { bytes: await doc.save({ useObjectStreams: false }), extents }
|
||||
}
|
||||
|
||||
const stripped = (s: string) => s.replace(/\s+/g, '')
|
||||
|
||||
it('rescues a whole-line edit whose rect clips the edge objects', async () => {
|
||||
if (!existsSync('/System/Library/Fonts/Supplemental/Arial Unicode.ttf')) return
|
||||
const words = ['Use', 'it', 'to', 'cover', 'your', 'entire', 'phone', 'bill']
|
||||
const { bytes, extents } = await makeWordLines([{ words, y: 700 }])
|
||||
const { left, right } = extents[0]!
|
||||
// The rect starts inside 'Use' and ends inside 'bill': the primary path's
|
||||
// ≥50%-containment filter drops both edge objects and the line never matched
|
||||
const rect: [number, number, number, number] = [left + 18, 696, right - 14, 716]
|
||||
const out = await applyAll(bytes, [
|
||||
{
|
||||
pageIndex: 0,
|
||||
rect,
|
||||
oldText: words.join(' '),
|
||||
newText: 'Use it to pay your whole phone bill',
|
||||
fontSize: 14,
|
||||
},
|
||||
])
|
||||
expect(stripped(await extractText(out))).toBe('Useittopayyourwholephonebill')
|
||||
})
|
||||
|
||||
it('rescues a style-only recolor with a clipped rect (screenshot scenario)', async () => {
|
||||
if (!existsSync('/System/Library/Fonts/Supplemental/Arial Unicode.ttf')) return
|
||||
const { chainPdfium, loadPdfium, withDocument } = await import('../src/main/text-edit')
|
||||
const words = ['Use', 'it', 'to', 'cover', 'your', 'phone', 'bill']
|
||||
const { bytes, extents } = await makeWordLines([{ words, y: 700 }])
|
||||
const { left, right } = extents[0]!
|
||||
const oldText = words.join(' ')
|
||||
const out = await applyAll(bytes, [
|
||||
{
|
||||
pageIndex: 0,
|
||||
rect: [left + 18, 696, right - 12, 716],
|
||||
oldText,
|
||||
newText: oldText,
|
||||
fontSize: 14,
|
||||
newColor: [255, 0, 0],
|
||||
},
|
||||
])
|
||||
expect(stripped(await extractText(out))).toBe(stripped(oldText))
|
||||
// Every text object on the page is repainted red
|
||||
const m = await loadPdfium()
|
||||
const colors = await chainPdfium(() =>
|
||||
withDocument(m, out, async (doc) => {
|
||||
const page = m._FPDF_LoadPage(doc, 0)
|
||||
const colPtr = m._malloc(16)
|
||||
const found: [number, number, number][] = []
|
||||
try {
|
||||
const count = m._FPDFPage_CountObjects(page)
|
||||
for (let i = 0; i < count; i++) {
|
||||
const obj = m._FPDFPage_GetObject(page, i)
|
||||
if (m._FPDFPageObj_GetType(obj) !== 1) continue
|
||||
m._FPDFPageObj_GetFillColor(obj, colPtr, colPtr + 4, colPtr + 8, colPtr + 12)
|
||||
found.push([m.HEAPU8[colPtr]!, m.HEAPU8[colPtr + 4]!, m.HEAPU8[colPtr + 8]!])
|
||||
}
|
||||
return found
|
||||
} finally {
|
||||
m._free(colPtr)
|
||||
m._FPDF_ClosePage(page)
|
||||
}
|
||||
}),
|
||||
)
|
||||
expect(colors.length).toBeGreaterThan(0)
|
||||
for (const c of colors) expect(c).toEqual([255, 0, 0])
|
||||
})
|
||||
|
||||
it('picks the occurrence nearest the rect when the same text repeats', async () => {
|
||||
if (!existsSync('/System/Library/Fonts/Supplemental/Arial Unicode.ttf')) return
|
||||
const words = ['Repeated', 'footer', 'line']
|
||||
const { bytes, extents } = await makeWordLines([
|
||||
{ words, y: 700 },
|
||||
{ words, y: 680 },
|
||||
])
|
||||
const { left, right } = extents[1]!
|
||||
// Clipped rect around the LOWER copy; the padded candidate set still touches the
|
||||
// upper copy, so the score must pick the right occurrence
|
||||
const out = await applyAll(bytes, [
|
||||
{
|
||||
pageIndex: 0,
|
||||
rect: [left + 20, 676, right - 8, 696],
|
||||
oldText: words.join(' '),
|
||||
newText: 'Repeated footer EDIT',
|
||||
fontSize: 14,
|
||||
},
|
||||
])
|
||||
const { getDocument } = await import('pdfjs-dist/legacy/build/pdf.mjs')
|
||||
const doc = await getDocument({ data: out.slice(), useSystemFonts: true }).promise
|
||||
try {
|
||||
const content = await (await doc.getPage(1)).getTextContent()
|
||||
const byLine = new Map<number, string>()
|
||||
for (const i of content.items) {
|
||||
if (!('str' in i) || !i.str.trim()) continue
|
||||
const y = Math.round(i.transform[5]!)
|
||||
byLine.set(y, (byLine.get(y) ?? '') + i.str)
|
||||
}
|
||||
expect(stripped(byLine.get(700) ?? '')).toBe('Repeatedfooterline')
|
||||
expect(stripped(byLine.get(680) ?? '')).toBe('RepeatedfooterEDIT')
|
||||
} finally {
|
||||
await doc.loadingTask.destroy()
|
||||
}
|
||||
})
|
||||
|
||||
it('rescues an edit ending mid-object, keeping the object tail verbatim', async () => {
|
||||
if (!existsSync('/System/Library/Fonts/Supplemental/Arial Unicode.ttf')) return
|
||||
// Three objects; the edit covers the first two and only 'Plus,' of the third —
|
||||
// like a text-layer line group stopping before the rest of the engine's run
|
||||
const doc = await PDFDocument.create()
|
||||
const page = doc.addPage([595, 842])
|
||||
const font = await doc.embedFont(StandardFonts.Helvetica)
|
||||
const parts = ['Use it to cover', 'your entire phone.', 'Plus, free shipping']
|
||||
let x = 50
|
||||
const starts: number[] = []
|
||||
for (const p of parts) {
|
||||
starts.push(x)
|
||||
page.drawText(p, { x, y: 700, size: 14, font })
|
||||
x += font.widthOfTextAtSize(`${p} `, 14)
|
||||
}
|
||||
const bytes = await doc.save({ useObjectStreams: false })
|
||||
const rectRight = starts[2]! + font.widthOfTextAtSize('Plus,', 14) + 2
|
||||
const out = await applyAll(bytes, [
|
||||
{
|
||||
pageIndex: 0,
|
||||
rect: [45, 696, rectRight, 716],
|
||||
oldText: 'Use it to cover your entire phone. Plus,',
|
||||
newText: 'Use it to cover your entire phone. Anyway,',
|
||||
fontSize: 14,
|
||||
},
|
||||
])
|
||||
expect(stripped(await extractText(out))).toBe('Useittocoveryourentirephone.Anyway,freeshipping')
|
||||
})
|
||||
|
||||
it('fails closed for a paragraph rescue that would end mid-object', async () => {
|
||||
// A block edit (origin/lineLeading set) may only rescue a WHOLE match: apply
|
||||
// strips the layout overrides from fragment matches, which would rebuild the
|
||||
// paragraph at the anchor and pull the edge object's tail into the block run
|
||||
const doc = await PDFDocument.create()
|
||||
const page = doc.addPage([595, 842])
|
||||
const font = await doc.embedFont(StandardFonts.Helvetica)
|
||||
const parts = ['Use it to cover', 'your entire phone.', 'Plus, free shipping']
|
||||
let x = 50
|
||||
const starts: number[] = []
|
||||
for (const p of parts) {
|
||||
starts.push(x)
|
||||
page.drawText(p, { x, y: 700, size: 14, font })
|
||||
x += font.widthOfTextAtSize(`${p} `, 14)
|
||||
}
|
||||
const bytes = await doc.save({ useObjectStreams: false })
|
||||
const rectRight = starts[2]! + font.widthOfTextAtSize('Plus,', 14) + 2
|
||||
const results = await validateTextEdits(bytes, [
|
||||
{
|
||||
pageIndex: 0,
|
||||
rect: [45, 696, rectRight, 716],
|
||||
oldText: 'Use it to cover your entire phone. Plus,',
|
||||
newText: 'Use it to cover\nyour entire phone. Anyway,',
|
||||
fontSize: 14,
|
||||
origin: [50, 700],
|
||||
lineLeading: 17,
|
||||
},
|
||||
])
|
||||
expect(results[0]!.reason).toMatch(/could not be located/)
|
||||
})
|
||||
|
||||
it('still reports unlocatable text instead of matching elsewhere', async () => {
|
||||
const { bytes, extents } = await makeWordLines([{ words: ['Only', 'this', 'line'], y: 700 }])
|
||||
const { left, right } = extents[0]!
|
||||
const results = await validateTextEdits(bytes, [
|
||||
{
|
||||
pageIndex: 0,
|
||||
rect: [left, 696, right, 716],
|
||||
oldText: 'Entirely different words',
|
||||
newText: 'X',
|
||||
fontSize: 14,
|
||||
},
|
||||
])
|
||||
expect(results[0]!.reason).toMatch(/could not be located/)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
// @vitest-environment jsdom
|
||||
import { beforeAll, describe, expect, it, vi } from 'vitest'
|
||||
import { joinBlockLines, wrapText } from '../src/renderer/text-wrap'
|
||||
import {
|
||||
joinBlockLines,
|
||||
mapLineRangeToBlock,
|
||||
spliceBlockText,
|
||||
wrapText,
|
||||
} from '../src/renderer/text-wrap'
|
||||
|
||||
// jsdom has no canvas: stub measureText with a fixed per-char width (0.5×font size
|
||||
// for ASCII, 1× for others — the CJK em-square convention)
|
||||
@@ -67,3 +72,141 @@ describe('joinBlockLines', () => {
|
||||
expect(joinBlockLines(['uses pdf.js', '提取文本'])).toBe('uses pdf.js 提取文本')
|
||||
})
|
||||
})
|
||||
|
||||
describe('spliceBlockText', () => {
|
||||
it('folds one line edit into the paragraph', () => {
|
||||
expect(
|
||||
spliceBlockText('alpha beta gamma delta', [{ oldText: 'gamma', newText: 'gamma123' }]),
|
||||
).toBe('alpha beta gamma123 delta')
|
||||
})
|
||||
|
||||
it('matches whitespace-insensitively (line joins differ in synthesized spaces)', () => {
|
||||
// The block joins with a space, the DOM line grouping produced none
|
||||
expect(
|
||||
spliceBlockText('the quick brown fox jumps', [
|
||||
{ oldText: 'quick brown fox', newText: 'lazy dog' },
|
||||
]),
|
||||
).toBe('the lazy dog jumps')
|
||||
})
|
||||
|
||||
it('folds several non-overlapping edits by document order', () => {
|
||||
expect(
|
||||
spliceBlockText('abcdefghij', [
|
||||
{ oldText: 'hi', newText: '8_9' },
|
||||
{ oldText: 'bc', newText: '2_3' },
|
||||
]),
|
||||
).toBe('a2_3defg8_9j')
|
||||
})
|
||||
|
||||
it('uses the hint to pick the right occurrence of a repeated line', () => {
|
||||
expect(spliceBlockText('samesame', [{ oldText: 'same', newText: 'X', hint: 4 }])).toBe('sameX')
|
||||
})
|
||||
|
||||
it('returns null when an oldText is not in the block', () => {
|
||||
expect(spliceBlockText('abc', [{ oldText: 'de', newText: 'x' }])).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null when two edits overlap', () => {
|
||||
expect(
|
||||
spliceBlockText('abcde', [
|
||||
{ oldText: 'abc', newText: 'a' },
|
||||
{ oldText: 'cd', newText: 'b' },
|
||||
]),
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('unifies radical-block codepoints on both sides (pdf.js cmap quirk)', () => {
|
||||
// pdf.js extracted Kangxi radicals (U+2F83/U+2F17 for U+81EA/U+5341); the
|
||||
// block text and the folded result must carry the real unified ideographs
|
||||
// PDFium extracts and fonts can draw
|
||||
expect(joinBlockLines(['\u2f83\u5efa\u5b89\u2f17\u4e09\u5e74'])).toBe(
|
||||
'\u81ea\u5efa\u5b89\u5341\u4e09\u5e74',
|
||||
)
|
||||
expect(
|
||||
spliceBlockText('\u81ea\u5efa\u5b89\u5341\u4e09\u5e74\u81f3\u5609\u5e73\u4e94\u5e74', [
|
||||
{
|
||||
oldText: '\u2f83\u5efa\u5b89\u2f17\u4e09\u5e74',
|
||||
newText: '\u2f83\u5efa\u5b89\u2f17\u4e09\u5e74X',
|
||||
},
|
||||
]),
|
||||
).toBe('\u81ea\u5efa\u5b89\u5341\u4e09\u5e74X\u81f3\u5609\u5e73\u4e94\u5e74')
|
||||
})
|
||||
|
||||
it('unifies Radicals Supplement codepoints that NFKC cannot decompose', () => {
|
||||
// U+2EE6 (C-simplified bird) and U+2ECB (C-simplified cart) have no NFKC
|
||||
// decomposition; only the shared RADICAL_EQUIV table folds them to the
|
||||
// unified ideographs (U+9E1F, U+8F66) PDFium extracts
|
||||
expect(joinBlockLines(['\u83dc\u2ee6\u4e0e\u2ecb\u8f86'])).toBe(
|
||||
'\u83dc\u9e1f\u4e0e\u8f66\u8f86',
|
||||
)
|
||||
expect(
|
||||
spliceBlockText('\u83dc\u9e1f\u4e0e\u8f66\u8f86', [
|
||||
{ oldText: '\u83dc\u2ee6', newText: '\u83dc\u2ee6X' },
|
||||
]),
|
||||
).toBe('\u83dc\u9e1fX\u4e0e\u8f66\u8f86')
|
||||
})
|
||||
|
||||
it('folds CJK Strokes even when no radical-block char is present', () => {
|
||||
// U+31CF (stroke) folds to U+4E40; the gate must not require U+2E80-2FDF
|
||||
expect(joinBlockLines(['\u31cfX'])).toBe('\u4e40X')
|
||||
expect(spliceBlockText('\u4e40X rest', [{ oldText: '\u31cfX', newText: 'Y' }])).toBe('Y rest')
|
||||
})
|
||||
|
||||
it('aligns an unfolded radical against an already-folded astral ideograph', () => {
|
||||
// U+2E87 folds to U+20628 (supplementary plane, two UTF-16 units): the
|
||||
// haystack carries the surrogates as separate units, the needle folds
|
||||
// one radical into both — unit-level entries keep the ranks aligned
|
||||
expect(spliceBlockText('\u{20628}\u5b50', [{ oldText: '\u2e87', newText: 'X' }])).toBe(
|
||||
'X\u5b50',
|
||||
)
|
||||
})
|
||||
|
||||
it('an edit spanning a visual line break still folds (crossing spans)', () => {
|
||||
// oldText mixes the tail of line 1 and the head of line 2, carrying the
|
||||
// join space the block text does not have at that position
|
||||
expect(
|
||||
spliceBlockText('headtail nexttext rest', [
|
||||
{ oldText: 'tail next', newText: 'tail next123' },
|
||||
]),
|
||||
).toBe('headtail next123text rest')
|
||||
})
|
||||
})
|
||||
|
||||
describe('mapLineRangeToBlock', () => {
|
||||
it('maps a mid-line range to block offsets', () => {
|
||||
// block = two joined lines; select "bravo" on line 1
|
||||
const block = 'alpha bravo charlie delta'
|
||||
expect(mapLineRangeToBlock(block, 'alpha bravo charlie', 6, 11)).toEqual([6, 11])
|
||||
})
|
||||
|
||||
it('ignores whitespace differences between DOM line and joined text', () => {
|
||||
// DOM line synthesizes a double space the block text does not have
|
||||
const block = 'alpha bravo charlie'
|
||||
expect(mapLineRangeToBlock(block, 'alpha bravo', 7, 12)).toEqual([6, 11])
|
||||
})
|
||||
|
||||
it('locates a later line inside the block', () => {
|
||||
const block = '\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b'
|
||||
// line 2 of the paragraph: chars 5..8; select its middle two
|
||||
expect(mapLineRangeToBlock(block, '\u4e94\u516d\u4e03\u516b', 1, 3)).toEqual([5, 7])
|
||||
})
|
||||
|
||||
it('folds radical variants like the splice matcher', () => {
|
||||
// DOM line carries U+2EE6 where the block text has the unified U+9E1F
|
||||
expect(mapLineRangeToBlock('\u83dc\u9e1f\u4e0e', '\u83dc\u2ee6\u4e0e', 1, 2)).toEqual([1, 2])
|
||||
})
|
||||
|
||||
it('maps across an astral fold without losing unit alignment', () => {
|
||||
// line has the radical U+2E87 (1 unit), block has its fold U+20628 (2 units)
|
||||
expect(mapLineRangeToBlock('\u{20628}\u5b50', '\u2e87\u5b50', 0, 1)).toEqual([0, 2])
|
||||
expect(mapLineRangeToBlock('\u{20628}\u5b50', '\u2e87\u5b50', 1, 2)).toEqual([2, 3])
|
||||
})
|
||||
|
||||
it('collapses a whitespace-only range to a caret', () => {
|
||||
expect(mapLineRangeToBlock('alpha bravo', 'alpha bravo', 5, 6)).toEqual([6, 6])
|
||||
})
|
||||
|
||||
it('returns null when the line is not in the block', () => {
|
||||
expect(mapLineRangeToBlock('alpha bravo', 'zulu yankee', 0, 4)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -50,7 +50,7 @@ The current PoC intentionally supports a narrower write set:
|
||||
|
||||
- Sheet duplication (fully-loaded workbooks, or sheets created this session): the tab context menu's Copy journals a `duplicate-sheet` op; the save clones the source worksheet part verbatim (tabSelected stripped), replays the source's unsaved edits captured at copy time, and appends the copy's own edits. Hyperlink relationships clone with the part; printerSettings relationships are dropped (with their `pageSetup` r:id). Sources carrying drawings, tables, comments, or pivots, and sources with sheet-scoped defined names, fail closed. Duplicate-of-duplicate chains resolve to the original file part.
|
||||
|
||||
- Sheet management (works on streamed large files too): rename — the workbook.xml entry plus every qualified reference (other sheets' `<f>`/CF/DV formulas, defined-name bodies, chart `c:f` series, internal hyperlink anchors) rewrite together, with Excel quoting rules for the new name; add — a blank worksheet part with its content-type override and relationship, inserted at its on-screen tab position, immediately editable (values, styles, and row/column ops journal into the new part); remove — the part, its rels, its content-type override, and its relationship are dropped, defined names scoped to the sheet die with it, surviving `localSheetId` scopes and the active tab renumber. Removal fails closed while any surviving formula, chart, or defined name references the sheet, when the sheet carries drawings/tables/comments, or when no visible sheet would remain. Adding or removing sheets invalidates calcChain, which is dropped for Excel to rebuild.
|
||||
- Sheet management (works on streamed large files too): rename — the workbook.xml entry plus every qualified reference (other sheets' `<f>`/CF/DV formulas, defined-name bodies, chart `c:f` series, internal hyperlink anchors) rewrite together, with Excel quoting rules for the new name; add — a blank worksheet part with its content-type override and relationship, inserted at its on-screen tab position, immediately editable (values, styles, and row/column ops journal into the new part); remove — the part, its rels, its content-type override, and its relationship are dropped, along with the satellite parts the sheet owns (drawings with their images and charts, legacy VML, comments, threaded comments, tables — each with its own rels and content-type override; media still referenced from a surviving sheet's drawing is kept), defined names scoped to the sheet die with it, surviving `localSheetId` scopes and the active tab renumber. Removal fails closed while any surviving formula, chart, or defined name references the sheet (structured references into the sheet's tables included), when the sheet carries a pivot table or an unrecognized part, or when no visible sheet would remain. Adding or removing sheets invalidates calcChain, which is dropped for Excel to rebuild.
|
||||
|
||||
- Whole-row moves (drag a selected row's header; fully loaded sheets only): journaled as a move operation modeled as two adjacent row blocks swapping places — a bijection, so nothing is deleted and no reference ever turns into #REF!. The save relocates the `<row>` elements themselves (heights, hidden flags, outline levels, and cell styles travel with their rows, sheetData is re-sorted ascending) and remaps every reference through the swap: same-sheet and cross-sheet formulas, defined names, chart series, merges, CF/DV ranges, hyperlinks, drawing anchors (judged as from/to pairs), and table refs. Ranges fully inside a moved block move with it; ranges outside or spanning the blocks stay put; anything partially overlapping fails the save closed (shared/array formula anchors, table header/totals rows, and torn drawing anchors included). Undo arrives as the inverse move and cancels the journal pair. Column moves remain blocked.
|
||||
- Row heights, column widths, autofit resets, and hidden rows/columns (every load mode, including sheets with tables or charts — sizing shifts nothing): journaled as ordered axis-attribute operations and replayed into row `ht`/`customHeight`/`hidden` attributes and split-preserving `<cols>` rewrites. Clear Formats / Clear All reset cells to the default xf (`s="0"`); a format applied after a clear derives from the default style.
|
||||
|
||||
@@ -417,6 +417,14 @@ impl WorkbookSessions {
|
||||
}
|
||||
|
||||
pub fn open(&mut self, path: &Path) -> Result<WorkbookMetadata, SidecarError> {
|
||||
self.open_with_locale(path, "zh")
|
||||
}
|
||||
|
||||
pub fn open_with_locale(
|
||||
&mut self,
|
||||
path: &Path,
|
||||
locale: &str,
|
||||
) -> Result<WorkbookMetadata, SidecarError> {
|
||||
let canonical_path = path.canonicalize()?;
|
||||
let file = File::open(&canonical_path)?;
|
||||
let mut archive = ZipArchive::new(file)?;
|
||||
@@ -498,7 +506,8 @@ impl WorkbookSessions {
|
||||
"Workbook contains no readable worksheets.".into(),
|
||||
));
|
||||
}
|
||||
let (styles, dxf_styles) = visuals::read_styles(&mut archive, &color_context)?;
|
||||
let (styles, dxf_styles) =
|
||||
visuals::read_styles(&mut archive, &color_context, locale)?;
|
||||
// Value-less cells are kept when their xf paints something visible
|
||||
// (fill/border) or differs from the default xf in number format,
|
||||
// font or alignment — formatting a user's future input inherits (#169).
|
||||
@@ -3005,13 +3014,13 @@ mod tests {
|
||||
<fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills>
|
||||
<borders count="1"><border/></borders>
|
||||
<cellStyleXfs count="1"><xf/></cellStyleXfs>
|
||||
<cellXfs count="4"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/><xf numFmtId="58" applyNumberFormat="1"/><xf numFmtId="44" applyNumberFormat="1"/><xf numFmtId="57" applyNumberFormat="1"/></cellXfs>
|
||||
<cellXfs count="6"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/><xf numFmtId="58" applyNumberFormat="1"/><xf numFmtId="44" applyNumberFormat="1"/><xf numFmtId="57" applyNumberFormat="1"/><xf numFmtId="27" applyNumberFormat="1"/><xf numFmtId="30" applyNumberFormat="1"/></cellXfs>
|
||||
</styleSheet>"#,
|
||||
),
|
||||
(
|
||||
"xl/worksheets/sheet1.xml",
|
||||
r#"<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
|
||||
<sheetData><row r="1"><c r="A1" s="1"><v>46230</v></c></row></sheetData>
|
||||
<sheetData><row r="1"><c r="A1" s="1"><v>46230</v></c><c r="B1" s="4"><v>45651</v></c><c r="C1" s="5"><v>45343</v></c></row></sheetData>
|
||||
</worksheet>"#,
|
||||
),
|
||||
]);
|
||||
@@ -3027,6 +3036,18 @@ mod tests {
|
||||
Some(r#"_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)"#),
|
||||
);
|
||||
assert_eq!(format(3), Some("yyyy/m/d"));
|
||||
|
||||
// Locale-reserved ids must follow the UI locale. In Portuguese (and
|
||||
// other day-first locales), id 58 is a full date rather than the
|
||||
// zh-CN month/day pattern that previously leaked into every workbook.
|
||||
let mut portuguese_sessions = WorkbookSessions::new();
|
||||
let portuguese = portuguese_sessions.open_with_locale(&path, "pt").unwrap();
|
||||
let portuguese_format =
|
||||
|index: usize| portuguese.styles[index].number_format.as_deref();
|
||||
assert_eq!(portuguese_format(1), Some("d/m/yyyy"));
|
||||
assert_eq!(portuguese_format(3), Some("yyyy/m/d"));
|
||||
assert_eq!(portuguese_format(4), Some("d/m/yyyy"));
|
||||
assert_eq!(portuguese_format(5), Some("d/m/yyyy"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -11,11 +11,17 @@ use xlsx_sidecar::{CellRange, SidecarError, WorkbookSessions};
|
||||
|
||||
const PROTOCOL_VERSION: u8 = 1;
|
||||
|
||||
fn default_locale() -> String {
|
||||
"zh".to_owned()
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(tag = "command", rename_all = "snake_case")]
|
||||
enum Command {
|
||||
Open {
|
||||
path: PathBuf,
|
||||
#[serde(default = "default_locale")]
|
||||
locale: String,
|
||||
},
|
||||
ReadRange {
|
||||
#[serde(rename = "sessionId")]
|
||||
@@ -160,7 +166,9 @@ fn handle_line(
|
||||
|
||||
let request_id = request.request_id;
|
||||
let result = match request.command {
|
||||
Command::Open { path } => sessions.open(&path).and_then(to_json_value),
|
||||
Command::Open { path, locale } => sessions
|
||||
.open_with_locale(&path, &locale)
|
||||
.and_then(to_json_value),
|
||||
Command::ReadRange {
|
||||
session_id,
|
||||
sheet_id,
|
||||
|
||||
@@ -285,6 +285,7 @@ pub struct ColorContext {
|
||||
pub fn read_styles(
|
||||
archive: &mut ZipArchive<File>,
|
||||
colors: &ColorContext,
|
||||
locale: &str,
|
||||
) -> Result<(Vec<CellStyle>, Vec<CellStyle>), SidecarError> {
|
||||
let Some(xml) = read_optional_xml(archive, "xl/styles.xml")? else {
|
||||
return Ok((vec![CellStyle::default()], Vec::new()));
|
||||
@@ -354,7 +355,9 @@ pub fn read_styles(
|
||||
custom_formats
|
||||
.get(&(id as u32))
|
||||
.cloned()
|
||||
.or_else(|| builtin_number_format(id as u32).map(ToOwned::to_owned))
|
||||
.or_else(|| {
|
||||
builtin_number_format(id as u32, locale).map(ToOwned::to_owned)
|
||||
})
|
||||
});
|
||||
let alignment = xf.children().find(|child| child.has_tag_name("alignment"));
|
||||
CellStyle {
|
||||
@@ -1602,12 +1605,12 @@ fn media_type_for_path(path: &str) -> Option<&'static str> {
|
||||
/// falls back to General (which would surface raw date serials, #numFmt58).
|
||||
///
|
||||
/// Locale-reserved ranges carry no formatCode in styles.xml — the reader is
|
||||
/// expected to know them:
|
||||
/// - 27-36 / 50-58: East-Asian date/time formats. The same id means a
|
||||
/// different pattern per locale (zh/ja/ko/zh-TW) and the file does not
|
||||
/// record which; we resolve with the zh-CN table since every locale's
|
||||
/// variant is a date/time of the same shape, and zh Excel/WPS files are
|
||||
/// the ones we actually receive. The zh AM/PM token (U+4E0A/U+4E0B
|
||||
/// expected to resolve them for its current locale:
|
||||
/// - 27-36 / 50-58: locale-dependent date/time formats. The same id means a
|
||||
/// different pattern per locale and the file does not record which. CJK
|
||||
/// locales use the zh-CN-compatible table below; other locales use their
|
||||
/// local full short-date pattern so a CJK month/day format cannot leak into
|
||||
/// a European workbook and discard its year. The zh AM/PM token (U+4E0A/U+4E0B
|
||||
/// U+5348) is not understood by the renderer's numfmt, so 34/35/55/56
|
||||
/// render as 24-hour. Escapes: U+5E74 year, U+6708 month, U+65E5 day,
|
||||
/// U+65F6 hour, U+5206 minute, U+79D2 second.
|
||||
@@ -1615,7 +1618,14 @@ fn media_type_for_path(path: &str) -> Option<&'static str> {
|
||||
/// locale-defined and unrecorded.
|
||||
/// - 59-81: th-TH; numfmt has no Thai digit/era tokens, so these map to
|
||||
/// Arabic-digit equivalents (Buddhist-era years render as Gregorian).
|
||||
fn builtin_number_format(id: u32) -> Option<&'static str> {
|
||||
fn builtin_number_format(id: u32, locale: &str) -> Option<&'static str> {
|
||||
if matches!(
|
||||
id,
|
||||
27 | 28 | 29 | 30 | 31 | 36 | 50 | 51 | 52 | 53 | 54 | 57 | 58
|
||||
) && !matches!(locale, "zh" | "zh-TW" | "ja" | "ko")
|
||||
{
|
||||
return Some(locale_short_date_format(locale));
|
||||
}
|
||||
match id {
|
||||
0 => Some("General"),
|
||||
1 => Some("0"),
|
||||
@@ -1681,6 +1691,15 @@ fn builtin_number_format(id: u32) -> Option<&'static str> {
|
||||
}
|
||||
}
|
||||
|
||||
fn locale_short_date_format(locale: &str) -> &'static str {
|
||||
match locale {
|
||||
"en" => "m/d/yyyy",
|
||||
"de" | "pl" | "ru" => "d.m.yyyy",
|
||||
"nl" => "d-m-yyyy",
|
||||
_ => "d/m/yyyy",
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
"dev:renderer": "vite --config vite.renderer.config.ts",
|
||||
"build": "npm run native:build && electron-vite build",
|
||||
"native:build": "cargo build --release --manifest-path native/xlsx-engine/Cargo.toml --config native/xlsx-engine/.cargo/config.toml",
|
||||
"native:build:universal": "node scripts/build-sidecar-universal.mjs",
|
||||
"native:test": "cargo test --manifest-path native/xlsx-engine/Cargo.toml --config native/xlsx-engine/.cargo/config.toml",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "npm run native:test && npm run native:build && vitest run",
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env node
|
||||
// Build the xlsx-sidecar as a macOS universal (fat) binary for release
|
||||
// packaging: compile both Apple targets and lipo-merge them into
|
||||
// native/xlsx-engine/target/release/xlsx-sidecar — the exact path the shell's
|
||||
// electron-builder mac extraResources reads, so the host-arch dev build and
|
||||
// this fat release build are interchangeable at packaging time. Both mac
|
||||
// arch packages (arm64 + x64) ship the same fat sidecar.
|
||||
//
|
||||
// Dev builds stay on plain `native:build` (host arch only, no extra rustup
|
||||
// targets required); this script is only called by the release packaging
|
||||
// paths (root dist:mac and mac-build.yml). It needs both targets installed:
|
||||
// rustup target add x86_64-apple-darwin aarch64-apple-darwin
|
||||
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { mkdirSync } from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
function fatal(msg) {
|
||||
console.error(`[sidecar-universal] ERROR: ${msg}`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
if (process.platform !== 'darwin') fatal('macOS only (needs lipo)')
|
||||
|
||||
// cargo resolves --config relative to the cwd, not --manifest-path (see the
|
||||
// note in native/xlsx-engine/.cargo/config.toml), so run from apps/sheets
|
||||
// exactly like the native:build script does.
|
||||
const sheetsDir = join(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const TARGETS = ['x86_64-apple-darwin', 'aarch64-apple-darwin']
|
||||
|
||||
for (const target of TARGETS) {
|
||||
console.log(`[sidecar-universal] cargo build --target ${target}`)
|
||||
execFileSync(
|
||||
'cargo',
|
||||
[
|
||||
'build',
|
||||
'--release',
|
||||
'--manifest-path',
|
||||
'native/xlsx-engine/Cargo.toml',
|
||||
'--config',
|
||||
'native/xlsx-engine/.cargo/config.toml',
|
||||
'--target',
|
||||
target,
|
||||
],
|
||||
{ cwd: sheetsDir, stdio: 'inherit' },
|
||||
)
|
||||
}
|
||||
|
||||
const outDir = join(sheetsDir, 'native/xlsx-engine/target/release')
|
||||
mkdirSync(outDir, { recursive: true })
|
||||
const out = join(outDir, 'xlsx-sidecar')
|
||||
execFileSync(
|
||||
'lipo',
|
||||
[
|
||||
'-create',
|
||||
...TARGETS.map((t) => join(sheetsDir, 'native/xlsx-engine/target', t, 'release/xlsx-sidecar')),
|
||||
'-output',
|
||||
out,
|
||||
],
|
||||
{ stdio: 'inherit' },
|
||||
)
|
||||
|
||||
const archs = execFileSync('lipo', ['-archs', out], { encoding: 'utf8' }).trim()
|
||||
if (!archs.includes('x86_64') || !archs.includes('arm64')) {
|
||||
fatal(`merge produced "${archs}" — expected x86_64 + arm64`)
|
||||
}
|
||||
console.log(`[sidecar-universal] ${out} (${archs})`)
|
||||
@@ -43,16 +43,20 @@ import {
|
||||
addWorksheetRelationship,
|
||||
applySheetPlanToWorkbookXml,
|
||||
assertNoSheetScopedDefinedNames,
|
||||
assertSheetRelsRemovable,
|
||||
buildWorksheetPartXml,
|
||||
chartReferencesSheet,
|
||||
classifyRemovedSheetRels,
|
||||
definedNamesReferenceSheet,
|
||||
definedNamesUseToken,
|
||||
maxRelationshipId,
|
||||
maxSheetIdInWorkbook,
|
||||
parseRelationships,
|
||||
parseSheetElements,
|
||||
partPathForRels,
|
||||
prepareClonedSheetRels,
|
||||
removePartOverride,
|
||||
removeRelationshipById,
|
||||
removeWorksheetOverride,
|
||||
tableDisplayName,
|
||||
renameSheetReferencesInChart,
|
||||
renameSheetReferencesInDefinedNames,
|
||||
renameSheetReferencesInWorksheet,
|
||||
@@ -1166,6 +1170,68 @@ async function applySheetPlanToPackage(
|
||||
(path) => path.startsWith('xl/charts/') && path.endsWith('.xml'),
|
||||
)
|
||||
|
||||
// Satellite parts owned by the removed sheets — drawings with their images
|
||||
// and charts, legacy VML, comments, tables — die with the sheet. The
|
||||
// closure walks each owned part's own relationships; unsupported sheet
|
||||
// relationships (pivot tables, slicers) fail closed inside
|
||||
// classifyRemovedSheetRels.
|
||||
const removalRelsPaths = new Map<string, string>()
|
||||
const ownedPartsByRemoval = new Map<string, ReadonlySet<string>>()
|
||||
const removedOwnedParts = new Set<string>()
|
||||
for (const removal of plan.removals) {
|
||||
const removalPath = removalPaths.get(removal) ?? ''
|
||||
const relsPath = relsPathFor(removalPath)
|
||||
removalRelsPaths.set(removal, relsPath)
|
||||
const owned = new Set<string>()
|
||||
if (await pkg.has(relsPath)) {
|
||||
const targets = classifyRemovedSheetRels(await pkg.readText(relsPath), removal)
|
||||
const queue = targets.map((target) => resolveRelTarget(removalPath, target))
|
||||
while (queue.length > 0) {
|
||||
const part = queue.pop() as string
|
||||
if (owned.has(part) || !(await pkg.has(part))) continue
|
||||
owned.add(part)
|
||||
const childRelsPath = relsPathFor(part)
|
||||
if (!(await pkg.has(childRelsPath))) continue
|
||||
owned.add(childRelsPath)
|
||||
for (const entry of parseRelationships(await pkg.readText(childRelsPath))) {
|
||||
if (!entry.external) queue.push(resolveRelTarget(part, entry.target))
|
||||
}
|
||||
}
|
||||
}
|
||||
ownedPartsByRemoval.set(removal, owned)
|
||||
for (const part of owned) removedOwnedParts.add(part)
|
||||
}
|
||||
|
||||
// A part in the closure may also be referenced from a part that survives —
|
||||
// an image placed on two sheets shares one xl/media entry. Walk every
|
||||
// surviving rels part and pull such targets (with their own subtrees) back
|
||||
// out of the removal set.
|
||||
const dyingRelsParts = new Set([
|
||||
...removalRelsPaths.values(),
|
||||
...[...removedOwnedParts].filter((part) => part.endsWith('.rels')),
|
||||
])
|
||||
const keepQueue: string[] = []
|
||||
for (const relsPath of packagePaths) {
|
||||
if (!relsPath.endsWith('.rels') || dyingRelsParts.has(relsPath)) continue
|
||||
const owner = partPathForRels(relsPath)
|
||||
if (removedPathSet.has(owner)) continue
|
||||
for (const entry of parseRelationships(await pkg.readText(relsPath))) {
|
||||
if (entry.external) continue
|
||||
const target = resolveRelTarget(owner, entry.target)
|
||||
if (removedOwnedParts.has(target)) keepQueue.push(target)
|
||||
}
|
||||
}
|
||||
while (keepQueue.length > 0) {
|
||||
const part = keepQueue.pop() as string
|
||||
if (!removedOwnedParts.delete(part)) continue
|
||||
const childRelsPath = relsPathFor(part)
|
||||
if (removedOwnedParts.delete(childRelsPath)) {
|
||||
for (const entry of parseRelationships(await pkg.readText(childRelsPath))) {
|
||||
if (!entry.external) keepQueue.push(resolveRelTarget(part, entry.target))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Removals fail closed while every reference to the sheet is still intact.
|
||||
const removedLocalIds = new Set(
|
||||
originalNames.flatMap((name, index) => (plan.removals.includes(name) ? [index] : [])),
|
||||
@@ -1187,6 +1253,9 @@ async function applySheetPlanToPackage(
|
||||
}
|
||||
}
|
||||
for (const chartPath of chartPaths) {
|
||||
// Charts dying with a removed sheet chart that sheet's own data; only
|
||||
// surviving charts can hold a genuinely dangling reference.
|
||||
if (removedOwnedParts.has(chartPath)) continue
|
||||
if (chartReferencesSheet(await pkg.readText(chartPath), removal)) {
|
||||
throw new SheetEditError(
|
||||
`A chart reads its data from "${removal}" — deleting it is not allowed.`,
|
||||
@@ -1198,15 +1267,40 @@ async function applySheetPlanToPackage(
|
||||
`A workbook defined name references "${removal}" — deleting it is not allowed.`,
|
||||
)
|
||||
}
|
||||
const removalPath = removalPaths.get(removal) ?? ''
|
||||
const relsPath = removalPath.replace(/^(xl\/worksheets\/)([^/]+)$/, '$1_rels/$2.rels')
|
||||
if (await pkg.has(relsPath)) {
|
||||
assertSheetRelsRemovable(await pkg.readText(relsPath), removal)
|
||||
pkg.remove(relsPath)
|
||||
// Structured references (DecoTable[Amount]) into a removed table are not
|
||||
// sheet-qualified, so the sheet-name checks above cannot catch them.
|
||||
for (const part of ownedPartsByRemoval.get(removal) ?? []) {
|
||||
if (!removedOwnedParts.has(part) || !/^xl\/tables\/[^/]+\.xml$/.test(part)) continue
|
||||
const name = tableDisplayName(await pkg.readText(part))
|
||||
if (name === undefined) continue
|
||||
const needle = `${name}[`
|
||||
for (const path of survivingWorksheetPaths) {
|
||||
const referenced = (await pkg.canPatch(path))
|
||||
? (await pkg.readText(path)).includes(needle)
|
||||
: await pkg.containsText(path, needle)
|
||||
if (referenced) {
|
||||
throw new SheetEditError(
|
||||
`Another sheet's formulas use table "${name}" on "${removal}" — deleting it is not allowed.`,
|
||||
)
|
||||
}
|
||||
}
|
||||
// Defined names scoped to a removed sheet die with it (matching the
|
||||
// sheet-name check above), so only surviving names can block.
|
||||
if (definedNamesUseToken(workbookXml, needle, removedLocalIds)) {
|
||||
throw new SheetEditError(
|
||||
`A workbook defined name uses table "${name}" on "${removal}" — deleting it is not allowed.`,
|
||||
)
|
||||
}
|
||||
}
|
||||
pkg.remove(removalPath)
|
||||
}
|
||||
|
||||
for (const removal of plan.removals) {
|
||||
const relsPath = removalRelsPaths.get(removal) ?? ''
|
||||
if (await pkg.has(relsPath)) pkg.remove(relsPath)
|
||||
pkg.remove(removalPaths.get(removal) ?? '')
|
||||
}
|
||||
for (const part of removedOwnedParts) pkg.remove(part)
|
||||
|
||||
// Renames rewrite every qualified reference in the surviving parts.
|
||||
for (const rename of plan.renames) {
|
||||
for (const path of survivingWorksheetPaths) {
|
||||
@@ -1227,6 +1321,9 @@ async function applySheetPlanToPackage(
|
||||
}
|
||||
}
|
||||
for (const chartPath of chartPaths) {
|
||||
// Charts cascade-deleted with a removed sheet are already gone from the
|
||||
// package by this point — reading them would throw.
|
||||
if (removedOwnedParts.has(chartPath)) continue
|
||||
const xml = await pkg.readText(chartPath)
|
||||
const renamed = renameSheetReferencesInChart(xml, rename.sheetName, rename.newName)
|
||||
if (renamed !== xml) {
|
||||
@@ -1260,7 +1357,10 @@ async function applySheetPlanToPackage(
|
||||
const originalContentTypes = await pkg.readText(contentTypesPath)
|
||||
let contentTypesXml = originalContentTypes
|
||||
for (const removal of plan.removals) {
|
||||
contentTypesXml = removeWorksheetOverride(contentTypesXml, removalPaths.get(removal) ?? '')
|
||||
contentTypesXml = removePartOverride(contentTypesXml, removalPaths.get(removal) ?? '')
|
||||
}
|
||||
for (const part of removedOwnedParts) {
|
||||
contentTypesXml = removePartOverride(contentTypesXml, part)
|
||||
}
|
||||
for (const addition of additions) {
|
||||
contentTypesXml = addWorksheetOverride(contentTypesXml, addition.path)
|
||||
|
||||
@@ -396,7 +396,10 @@ export function addWorksheetOverride(contentTypesXml: string, partPath: string):
|
||||
return contentTypesXml.replace('</Types>', () => `${override}</Types>`)
|
||||
}
|
||||
|
||||
export function removeWorksheetOverride(contentTypesXml: string, partPath: string): string {
|
||||
/// Removes the [Content_Types].xml Override for any part path (worksheets,
|
||||
/// drawings, charts, comments, tables). Parts covered by a Default extension
|
||||
/// mapping have no Override; the call is a no-op for them.
|
||||
export function removePartOverride(contentTypesXml: string, partPath: string): string {
|
||||
return contentTypesXml.replace(
|
||||
new RegExp(`<Override\\b[^>]*PartName="/${escapeRegExp(partPath)}"[^>]*/>\\s*`),
|
||||
'',
|
||||
@@ -422,20 +425,93 @@ export function removeRelationshipById(relationshipsXml: string, relationshipId:
|
||||
)
|
||||
}
|
||||
|
||||
/// Relationship types a worksheet may carry and still be deletable: the
|
||||
/// target either dies with the sheet (hyperlinks) or survives as a harmless
|
||||
/// orphan (printer settings). Drawings, charts, tables, comments, and pivots
|
||||
/// would leave dangling references, so their sheets fail closed.
|
||||
const REMOVABLE_RELATIONSHIP_TYPES = /\/(hyperlink|printerSettings)"/
|
||||
/// Relationship types whose targets never block a sheet removal: hyperlink
|
||||
/// targets are external (or workbook-internal anchors that die with the
|
||||
/// sheet's part), and printer settings survive as harmless orphans.
|
||||
const IGNORABLE_SHEET_RELATIONSHIP_TYPES = /\/(?:hyperlink|printerSettings)$/
|
||||
|
||||
export function assertSheetRelsRemovable(relsXml: string, sheetName: string): void {
|
||||
for (const match of relsXml.matchAll(/<Relationship\b[^>]*?\bType="([^"]+)"[^>]*?\/>/g)) {
|
||||
if (!REMOVABLE_RELATIONSHIP_TYPES.test(`${match[1]}"`)) {
|
||||
throw new SheetEditError(
|
||||
`Sheet "${sheetName}" carries charts, images, tables, or comments — deleting it is not supported yet.`,
|
||||
)
|
||||
}
|
||||
/// Relationship types whose targets are owned by the sheet: drawings (with
|
||||
/// their images and charts), legacy VML, comments, threaded comments, form
|
||||
/// control properties, tables, and a sheet-background image are anchored on
|
||||
/// exactly one sheet, so they are cascade-deleted with it.
|
||||
const OWNED_SHEET_RELATIONSHIP_TYPES =
|
||||
/\/(?:drawing|vmlDrawing|comments|threadedComment|ctrlProp|table|image)$/
|
||||
|
||||
export interface ParsedRelationship {
|
||||
readonly id: string | undefined
|
||||
readonly type: string
|
||||
readonly target: string
|
||||
readonly external: boolean
|
||||
}
|
||||
|
||||
export function parseRelationships(relsXml: string): ParsedRelationship[] {
|
||||
const entries: ParsedRelationship[] = []
|
||||
for (const match of relsXml.matchAll(/<Relationship\b[^>]*?\/>/g)) {
|
||||
const element = match[0]
|
||||
const type = readAttribute(element, 'Type')
|
||||
const target = readAttribute(element, 'Target')
|
||||
if (type === undefined || target === undefined) continue
|
||||
entries.push({
|
||||
id: readAttribute(element, 'Id'),
|
||||
type: decodeAttribute(type),
|
||||
target: decodeAttribute(target),
|
||||
external: readAttribute(element, 'TargetMode') === 'External',
|
||||
})
|
||||
}
|
||||
return entries
|
||||
}
|
||||
|
||||
/// Inverse of xlsx-drawing-add's relsPathFor; the package-level "_rels/.rels"
|
||||
/// maps to "".
|
||||
export function partPathForRels(relsPath: string): string {
|
||||
return relsPath.replace(/(^|\/)_rels\/([^/]*)\.rels$/, '$1$2')
|
||||
}
|
||||
|
||||
/// Returns the (unresolved) targets of a removed sheet's owned satellite
|
||||
/// parts, for the caller to cascade-delete. Relationships that never block a
|
||||
/// removal are skipped; anything else — pivot tables, slicers, OLE objects —
|
||||
/// fails closed rather than leave dangling references for Excel to repair.
|
||||
export function classifyRemovedSheetRels(relsXml: string, sheetName: string): string[] {
|
||||
const owned: string[] = []
|
||||
for (const entry of parseRelationships(relsXml)) {
|
||||
if (entry.external || IGNORABLE_SHEET_RELATIONSHIP_TYPES.test(entry.type)) continue
|
||||
if (OWNED_SHEET_RELATIONSHIP_TYPES.test(entry.type)) {
|
||||
owned.push(entry.target)
|
||||
continue
|
||||
}
|
||||
const kind = /\/pivotTable$/.test(entry.type)
|
||||
? 'a pivot table'
|
||||
: `a part this build cannot delete safely (${entry.type})`
|
||||
throw new SheetEditError(
|
||||
`Sheet "${sheetName}" carries ${kind} — deleting it is not supported yet.`,
|
||||
)
|
||||
}
|
||||
return owned
|
||||
}
|
||||
|
||||
/// displayName of the table defined in a table part — the token surviving
|
||||
/// formulas would use in structured references (Table1[Amount]).
|
||||
export function tableDisplayName(tableXml: string): string | undefined {
|
||||
const openTag = /<table\b[^>]*>/.exec(tableXml)?.[0]
|
||||
if (!openTag) return undefined
|
||||
const name = readAttribute(openTag, 'displayName') ?? readAttribute(openTag, 'name')
|
||||
return name === undefined ? undefined : decodeAttribute(name)
|
||||
}
|
||||
|
||||
/// True when a defined name that survives the removal mentions the token
|
||||
/// (a structured-reference prefix like "DecoTable["). Names scoped to a
|
||||
/// removed sheet die with it and never block.
|
||||
export function definedNamesUseToken(
|
||||
workbookXml: string,
|
||||
token: string,
|
||||
removedLocalIds: ReadonlySet<number>,
|
||||
): boolean {
|
||||
for (const match of workbookXml.matchAll(/<definedName\b([^>]*)>([\s\S]*?)<\/definedName>/g)) {
|
||||
const localId = readAttribute(`<definedName${match[1] ?? ''}/>`, 'localSheetId')
|
||||
if (localId !== undefined && removedLocalIds.has(Number(localId))) continue
|
||||
if (decodeEntities(match[2] ?? '').includes(token)) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/// DefinedNames scoped to a removed sheet are dropped with it, so their
|
||||
|
||||
@@ -36,6 +36,7 @@ import type {
|
||||
import { z } from 'zod'
|
||||
import {
|
||||
appMenuLabels,
|
||||
configuredDefaultSaveDir,
|
||||
contextMenuLabels,
|
||||
installContextMenu,
|
||||
installNavigationGuard,
|
||||
@@ -1076,7 +1077,14 @@ async function openFileDialog(event: IpcMainInvokeEvent, options: OpenDialogOpti
|
||||
}
|
||||
|
||||
async function saveFileDialog(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,
|
||||
configuredDefaultSaveDir(app),
|
||||
)
|
||||
}
|
||||
|
||||
/** register a tab's webContents/client pair and wire up cleanup on teardown */
|
||||
@@ -2619,7 +2627,7 @@ async function openWorkbookSession(
|
||||
csvImport?: boolean,
|
||||
): Promise<WorkbookFile> {
|
||||
const [opened, digest] = await Promise.all([
|
||||
client.open(path).then((result) => sidecarOpenResultSchema.parse(result)),
|
||||
client.open(path, getUiLang()).then((result) => sidecarOpenResultSchema.parse(result)),
|
||||
sha256File(path),
|
||||
])
|
||||
sessions.set(opened.sessionId, {
|
||||
|
||||
@@ -32,8 +32,8 @@ export class XlsxSidecarClient {
|
||||
|
||||
constructor(private readonly binaryPath: string) {}
|
||||
|
||||
async open(path: string): Promise<unknown> {
|
||||
return this.request({ command: 'open', path })
|
||||
async open(path: string, locale = 'zh'): Promise<unknown> {
|
||||
return this.request({ command: 'open', path, locale })
|
||||
}
|
||||
|
||||
async readRange(input: {
|
||||
@@ -67,10 +67,7 @@ export class XlsxSidecarClient {
|
||||
return this.request({ command: 'read_media', ...input })
|
||||
}
|
||||
|
||||
async convertWorkbook(input: {
|
||||
path: string
|
||||
targetPath: string
|
||||
}): Promise<unknown> {
|
||||
async convertWorkbook(input: { path: string; targetPath: string }): Promise<unknown> {
|
||||
return this.request({ command: 'convert_workbook', ...input }, ARCHIVE_TIMEOUT_MS)
|
||||
}
|
||||
|
||||
|
||||
@@ -53,6 +53,11 @@ const desktopApi: DesktopApi = {
|
||||
ipcRenderer.on('app:theme-changed', listener)
|
||||
return () => ipcRenderer.removeListener('app:theme-changed', listener)
|
||||
},
|
||||
onChromePressed(handler) {
|
||||
const listener = () => handler()
|
||||
ipcRenderer.on('app:chrome-pressed', listener)
|
||||
return () => ipcRenderer.removeListener('app:chrome-pressed', listener)
|
||||
},
|
||||
async selectWorkbook() {
|
||||
const result: unknown = await ipcRenderer.invoke(IPC_CHANNELS.selectWorkbook)
|
||||
return result === null ? null : parseWorkbookFile(result)
|
||||
|
||||
@@ -234,6 +234,7 @@ import { installCellFilenameFunction } from './cell-function'
|
||||
import { installFormulaLexerFix } from './formula-lexer-fix'
|
||||
import { installSheetRenameFix } from './sheet-rename-fix'
|
||||
import { installSelectionWrapGuard } from './selection-wrap-fix'
|
||||
import { installMultiRowAutofit } from './autofit-multi-row'
|
||||
import { installCopyMaterialize } from './copy-materialize'
|
||||
import { applyUniverLocale } from './univer-locales'
|
||||
import { installRuleDetail } from './univer-rule-detail'
|
||||
@@ -590,6 +591,16 @@ export function App(): React.JSX.Element {
|
||||
const [attachNotice, setAttachNotice] = useState<string | null>(null)
|
||||
const attachmentsRef = useRef(attachments)
|
||||
attachmentsRef.current = attachments
|
||||
/** 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. */
|
||||
const sentAttachmentsRef = useRef<readonly AttachmentMeta[]>([])
|
||||
/** composer attachments plus everything already sent this session (deduped by path) */
|
||||
const availableAttachments = (): AttachmentMeta[] => {
|
||||
const seen = new Set<string>()
|
||||
return [...sentAttachmentsRef.current, ...attachmentsRef.current].filter((a) =>
|
||||
seen.has(a.path) ? false : (seen.add(a.path), true),
|
||||
)
|
||||
}
|
||||
/** Synchronous re-entrancy guard between runAgent trigger and loop.run
|
||||
* (loop.busy is still false while attachment images load asynchronously) */
|
||||
const runStartingRef = useRef(false)
|
||||
@@ -720,6 +731,19 @@ export function App(): React.JSX.Element {
|
||||
...(t.name ? { name: t.name } : {}),
|
||||
...(t.output ? { output: t.output.slice(0, 2000) } : {}),
|
||||
})) ?? [],
|
||||
// stored metadata only: no thumbnail read for history, the chips render name/size
|
||||
...(m.attachments && m.attachments.length > 0
|
||||
? {
|
||||
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 the file continue the
|
||||
@@ -741,6 +765,7 @@ export function App(): React.JSX.Element {
|
||||
input?: string
|
||||
output?: string
|
||||
}>,
|
||||
attachments?: readonly AttachmentMeta[],
|
||||
) => {
|
||||
const ids = chatRefIdsRef.current
|
||||
const api = (window as Window & { projectApi?: typeof window.projectApi }).projectApi
|
||||
@@ -754,6 +779,16 @@ export function App(): React.JSX.Element {
|
||||
...(tools && tools.length > 0
|
||||
? { tools: tools.map((t) => ({ ...t, name: t.name ?? '' })) }
|
||||
: {}),
|
||||
...(attachments && attachments.length > 0
|
||||
? {
|
||||
attachments: attachments.map((a) => ({
|
||||
name: a.name,
|
||||
path: a.path,
|
||||
ext: a.ext,
|
||||
sizeBytes: a.sizeBytes,
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
})
|
||||
.catch(() => {
|
||||
/* silent */
|
||||
@@ -796,7 +831,7 @@ export function App(): React.JSX.Element {
|
||||
systemSuffix: aiLangDirective,
|
||||
skill: composeSkills('sheets+files', '', [
|
||||
createWorkbookSkill(sheetsSkillDeps()),
|
||||
createFilesSkill(() => attachmentsRef.current),
|
||||
createFilesSkill(availableAttachments),
|
||||
createSearchSkill(),
|
||||
]),
|
||||
// guide loading adds a tool round; the default 8 cuts off multi-step work
|
||||
@@ -965,8 +1000,8 @@ export function App(): React.JSX.Element {
|
||||
/** Image attachments read as base64 and sent multimodal with this user message
|
||||
* (≤5MB each, max 20; same structure as docs/slides) */
|
||||
const MAX_IMAGES_PER_MESSAGE = 20
|
||||
async function collectImageAttachments(): Promise<AgentImage[]> {
|
||||
const imageAtts = attachmentsRef.current.filter((a) => ATTACHMENT_IMAGE_EXTS.has(a.ext))
|
||||
async function collectImageAttachments(atts: readonly AttachmentMeta[]): Promise<AgentImage[]> {
|
||||
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)) {
|
||||
@@ -987,7 +1022,7 @@ export function App(): React.JSX.Element {
|
||||
return images
|
||||
}
|
||||
|
||||
function runAgent(instruction: string): void {
|
||||
function runAgent(instruction: string, sentAttachments: readonly AttachmentMeta[]): void {
|
||||
const loop = agentLoopRef.current
|
||||
if (!instruction.trim() || !loop || loop.busy || runStartingRef.current) return
|
||||
runStartingRef.current = true
|
||||
@@ -997,7 +1032,7 @@ export function App(): React.JSX.Element {
|
||||
setAiBusy(true)
|
||||
setMessage(t('appAiThinking'))
|
||||
appendChat({ role: 'assistant', text: '', tools: [], streaming: true })
|
||||
void collectImageAttachments()
|
||||
void collectImageAttachments(sentAttachments)
|
||||
.then((images) => {
|
||||
runStartingRef.current = false
|
||||
loop.run(instruction, images)
|
||||
@@ -1048,6 +1083,7 @@ export function App(): React.JSX.Element {
|
||||
setAiBusy(false)
|
||||
setChat([])
|
||||
setHistoricChat([])
|
||||
sentAttachmentsRef.current = []
|
||||
setPreview(null)
|
||||
lazyPreviewRef.current = null
|
||||
setMessage(t('appNewConversation'))
|
||||
@@ -1231,6 +1267,8 @@ export function App(): React.JSX.Element {
|
||||
const sheetRenameFixDisposable = installSheetRenameFix()
|
||||
// Arrow keys stop at the sheet edge instead of wrapping to the far side.
|
||||
const selectionWrapGuardDisposable = installSelectionWrapGuard(runtime)
|
||||
// Row-header double-click autofits every selected row, like Excel.
|
||||
const multiRowAutofitDisposable = installMultiRowAutofit(runtime)
|
||||
// Empty-value formula results (IFERROR/IF/CHOOSE over blank refs)
|
||||
// display as 0 like Excel.
|
||||
const nullResultDisposable = installFormulaNullResultFix(runtime)
|
||||
@@ -2045,6 +2083,7 @@ export function App(): React.JSX.Element {
|
||||
formulaLexerFixDisposable.dispose()
|
||||
sheetRenameFixDisposable.dispose()
|
||||
selectionWrapGuardDisposable.dispose()
|
||||
multiRowAutofitDisposable.dispose()
|
||||
nullResultDisposable.dispose()
|
||||
copyMaterializeDisposable.dispose()
|
||||
ruleDetailDisposable()
|
||||
@@ -2075,18 +2114,40 @@ export function App(): React.JSX.Element {
|
||||
}
|
||||
}, [])
|
||||
|
||||
function handleSend(overrideInstruction?: string): void {
|
||||
function handleSend(
|
||||
overrideInstruction?: string,
|
||||
overrideAttachments?: readonly AttachmentMeta[],
|
||||
): void {
|
||||
const instruction = (overrideInstruction ?? prompt).trim()
|
||||
if (!instruction || aiBusy) return
|
||||
runToolsRef.current = []
|
||||
appendChat({ role: 'user', text: instruction, tools: [] })
|
||||
persistChatMessage('user', instruction)
|
||||
// The message consumes the composer attachments: they ride along (echoed on the
|
||||
// bubble, images multimodal, files via the files skill) and the composer clears.
|
||||
// Retry passes the failed message's original set instead.
|
||||
const sentAtts = overrideAttachments ?? attachmentsRef.current
|
||||
const agentConfigured = isAgentConfigured()
|
||||
appendChat({
|
||||
role: 'user',
|
||||
text: instruction,
|
||||
tools: [],
|
||||
...(sentAtts.length > 0 ? { attachments: sentAtts } : {}),
|
||||
})
|
||||
persistChatMessage('user', instruction, undefined, sentAtts)
|
||||
if (!overrideInstruction) setPrompt('')
|
||||
// the deterministic path consumes the composer too — the bubble already echoes the set
|
||||
if (!overrideAttachments && 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([])
|
||||
}
|
||||
// real LLM configured → let the agent read context and propose operations;
|
||||
// otherwise fall back to the local, deterministic regex planner
|
||||
// (kept for offline use and for the fixed micro-DSL it still supports).
|
||||
if (isAgentConfigured()) {
|
||||
runAgent(instruction)
|
||||
if (agentConfigured) {
|
||||
runAgent(instruction, sentAtts)
|
||||
return
|
||||
}
|
||||
const outcome = runDeterministicPlan(instruction)
|
||||
|
||||
@@ -150,7 +150,7 @@ export function ChartFormatPane({
|
||||
<div className="chart-format-pane">
|
||||
<header>
|
||||
<span>{t('appFormatHeader', { target: elementLabel(t, element, chart) })}</span>
|
||||
<button title={t('appClose')} onClick={onClose}>
|
||||
<button data-tip={t('appClose')} aria-label={t('appClose')} onClick={onClose}>
|
||||
✕
|
||||
</button>
|
||||
</header>
|
||||
@@ -513,21 +513,24 @@ export function SelectDataDialog({
|
||||
/>
|
||||
<span>
|
||||
<button
|
||||
title={t('appMoveUp')}
|
||||
data-tip={t('appMoveUp')}
|
||||
aria-label={t('appMoveUp')}
|
||||
disabled={index === 0}
|
||||
onClick={() => moveRow(index, -1)}
|
||||
>
|
||||
↑
|
||||
</button>
|
||||
<button
|
||||
title={t('appMoveDown')}
|
||||
data-tip={t('appMoveDown')}
|
||||
aria-label={t('appMoveDown')}
|
||||
disabled={index === rows.length - 1}
|
||||
onClick={() => moveRow(index, 1)}
|
||||
>
|
||||
↓
|
||||
</button>
|
||||
<button
|
||||
title={t('appRemoveSeries')}
|
||||
data-tip={t('appRemoveSeries')}
|
||||
aria-label={t('appRemoveSeries')}
|
||||
onClick={() =>
|
||||
setRows((previous) => previous.filter((_, at) => at !== index))
|
||||
}
|
||||
|
||||
@@ -119,7 +119,13 @@ export function EquationDialog({
|
||||
{PRESETS.map((preset) => {
|
||||
const rendered = mathmlOf(preset)
|
||||
return (
|
||||
<button key={preset} type="button" title={preset} onClick={() => setLatex(preset)}>
|
||||
<button
|
||||
key={preset}
|
||||
type="button"
|
||||
data-tip={preset}
|
||||
aria-label={preset}
|
||||
onClick={() => setLatex(preset)}
|
||||
>
|
||||
{rendered !== null && 'mathml' in rendered && (
|
||||
<span dangerouslySetInnerHTML={{ __html: rendered.mathml }} />
|
||||
)}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -20,6 +20,7 @@ import {
|
||||
} from './numfmt-dialog'
|
||||
|
||||
import type { SelectionFormat } from './selection-format'
|
||||
import { fontFamilyGroups, useSystemFontFamilies } from './system-fonts'
|
||||
|
||||
/// Excel's Format Cells dialog (⌘1), scoped to what the save pipeline can
|
||||
/// persist today: number format, alignment, font, border, fill, and
|
||||
@@ -95,7 +96,6 @@ const DECIMAL_CATEGORIES: readonly NumfmtCategory[] = [
|
||||
'scientific',
|
||||
]
|
||||
|
||||
const FONT_FAMILIES = ['Aptos', 'Arial', 'Calibri', 'Times New Roman', '微软雅黑', '宋体']
|
||||
const FONT_SIZES = ['9', '10', '11', '12', '14', '16', '18', '22', '26']
|
||||
/// OOXML ST_BorderStyle names offered by the line-style picker; the
|
||||
/// journal maps them 1:1 to Univer BorderStyleTypes and back to the file.
|
||||
@@ -166,10 +166,10 @@ export function FormatCellsDialog({
|
||||
)
|
||||
const negativeSample = -Math.abs(typeof sample === 'number' ? sample : 1234.56)
|
||||
|
||||
const familyOptions =
|
||||
!draft.family || FONT_FAMILIES.includes(draft.family)
|
||||
? FONT_FAMILIES
|
||||
: [draft.family, ...FONT_FAMILIES]
|
||||
const { families: systemFontFamilies, load: loadSystemFonts } = useSystemFontFamilies()
|
||||
// the dialog opens from a click, so activation is still live here
|
||||
useEffect(() => loadSystemFonts(), [loadSystemFonts])
|
||||
const fontGroups = fontFamilyGroups(systemFontFamilies, draft.family)
|
||||
const sizeOptions =
|
||||
!draft.size || FONT_SIZES.includes(draft.size)
|
||||
? FONT_SIZES
|
||||
@@ -419,9 +419,18 @@ export function FormatCellsDialog({
|
||||
{t('dlgFcFont')}
|
||||
<select value={draft.family} onChange={(e) => set('family', e.target.value)}>
|
||||
<option value="">{t('dlgFcUnchanged')}</option>
|
||||
{familyOptions.map((f) => (
|
||||
<option key={f}>{f}</option>
|
||||
))}
|
||||
<optgroup label={t('dlgFcFontsCommon')}>
|
||||
{fontGroups.common.map((f) => (
|
||||
<option key={f}>{f}</option>
|
||||
))}
|
||||
</optgroup>
|
||||
{fontGroups.system.length > 0 && (
|
||||
<optgroup label={t('dlgFcFontsSystem')}>
|
||||
{fontGroups.system.map((f) => (
|
||||
<option key={f}>{f}</option>
|
||||
))}
|
||||
</optgroup>
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
|
||||
@@ -58,7 +58,7 @@ export function GoToDialog({
|
||||
<li key={entry.name}>
|
||||
<button
|
||||
type="button"
|
||||
title={t('dlgGoToNameHint', { ref: entry.ref })}
|
||||
data-tip={t('dlgGoToNameHint', { ref: entry.ref })}
|
||||
onClick={() => setReference(entry.name)}
|
||||
onDoubleClick={() => go(entry.name)}
|
||||
>
|
||||
@@ -69,13 +69,17 @@ export function GoToDialog({
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<p className="dialog-note">
|
||||
{t('dlgGoToNote')}
|
||||
</p>
|
||||
{error && <p className="dialog-note dialog-error" role="alert">{error}</p>}
|
||||
<p className="dialog-note">{t('dlgGoToNote')}</p>
|
||||
{error && (
|
||||
<p className="dialog-note dialog-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
<div className="dialog-actions">
|
||||
<button className="secondary" onClick={onClose}>{t('dlgCancel')}</button>
|
||||
<button className="secondary" onClick={onClose}>
|
||||
{t('dlgCancel')}
|
||||
</button>
|
||||
<button
|
||||
className="primary-action"
|
||||
disabled={reference.trim() === ''}
|
||||
|
||||
@@ -16,12 +16,20 @@ export interface HeaderFooterResult {
|
||||
}
|
||||
|
||||
type SectionKey =
|
||||
| 'header-left' | 'header-center' | 'header-right'
|
||||
| 'footer-left' | 'footer-center' | 'footer-right'
|
||||
| 'header-left'
|
||||
| 'header-center'
|
||||
| 'header-right'
|
||||
| 'footer-left'
|
||||
| 'footer-center'
|
||||
| 'footer-right'
|
||||
|
||||
const SECTION_KEYS: readonly SectionKey[] = [
|
||||
'header-left', 'header-center', 'header-right',
|
||||
'footer-left', 'footer-center', 'footer-right',
|
||||
'header-left',
|
||||
'header-center',
|
||||
'header-right',
|
||||
'footer-left',
|
||||
'footer-center',
|
||||
'footer-right',
|
||||
]
|
||||
|
||||
const SECTION_LABELS: Record<SectionKey, StringKey> = {
|
||||
@@ -110,7 +118,9 @@ export function HeaderFooterDialog({
|
||||
if (element) inputs.current.set(key, element)
|
||||
else inputs.current.delete(key)
|
||||
}}
|
||||
onFocus={() => { focusedKey.current = key }}
|
||||
onFocus={() => {
|
||||
focusedKey.current = key
|
||||
}}
|
||||
onChange={(event) => {
|
||||
const next = event.target.value
|
||||
setValues((prev) => ({ ...prev, [key]: next }))
|
||||
@@ -123,7 +133,7 @@ export function HeaderFooterDialog({
|
||||
<button
|
||||
key={field.code}
|
||||
className="secondary"
|
||||
title={t('dlgHfInsertCode', { code: field.code })}
|
||||
data-tip={t('dlgHfInsertCode', { code: field.code })}
|
||||
onMouseDown={(event) => event.preventDefault()}
|
||||
onClick={() => insertCode(field.code)}
|
||||
>
|
||||
@@ -131,22 +141,30 @@ export function HeaderFooterDialog({
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<p className="dialog-note dialog-span">
|
||||
{t('dlgHfNote')}
|
||||
</p>
|
||||
<p className="dialog-note dialog-span">{t('dlgHfNote')}</p>
|
||||
</div>
|
||||
{error && <p className="dialog-note" role="alert">{error}</p>}
|
||||
{error && (
|
||||
<p className="dialog-note" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<div className="dialog-actions">
|
||||
<button className="secondary" onClick={onClose}>{t('dlgCancel')}</button>
|
||||
<button className="secondary" onClick={onClose}>
|
||||
{t('dlgCancel')}
|
||||
</button>
|
||||
<button
|
||||
className="primary-action"
|
||||
onClick={() => {
|
||||
const failure = onApply({
|
||||
header: toParts(
|
||||
values['header-left'], values['header-center'], values['header-right'],
|
||||
values['header-left'],
|
||||
values['header-center'],
|
||||
values['header-right'],
|
||||
),
|
||||
footer: toParts(
|
||||
values['footer-left'], values['footer-center'], values['footer-right'],
|
||||
values['footer-left'],
|
||||
values['footer-center'],
|
||||
values['footer-right'],
|
||||
),
|
||||
})
|
||||
setError(failure)
|
||||
|
||||
@@ -100,7 +100,8 @@ export function IconsDialog({
|
||||
aria-checked={candidate === color}
|
||||
className={candidate === color ? 'active' : ''}
|
||||
style={{ background: candidate }}
|
||||
title={candidate}
|
||||
data-tip={candidate}
|
||||
aria-label={candidate}
|
||||
onClick={() => setColor(candidate)}
|
||||
/>
|
||||
))}
|
||||
@@ -126,7 +127,8 @@ export function IconsDialog({
|
||||
key={entry.name}
|
||||
type="button"
|
||||
disabled={busy}
|
||||
title={entry.name}
|
||||
data-tip={entry.name}
|
||||
aria-label={entry.name}
|
||||
onClick={() => pick(entry.icon, entry.name)}
|
||||
>
|
||||
<entry.icon />
|
||||
|
||||
@@ -100,7 +100,8 @@ export function NameManagerDialog({
|
||||
<td>{row.scopeLabel}</td>
|
||||
<td>
|
||||
<button
|
||||
title={t('dlgNmDeleteName')}
|
||||
data-tip={t('dlgNmDeleteName')}
|
||||
aria-label={t('dlgNmDeleteName')}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
run({ kind: 'remove', name: row.name, scopeSheetId: row.scopeSheetId })
|
||||
|
||||
@@ -250,7 +250,7 @@ export function PivotDialog({
|
||||
))}
|
||||
</select>
|
||||
<select
|
||||
title={t('dlgPivotGrouping')}
|
||||
data-tip={t('dlgPivotGrouping')}
|
||||
value={groupingSelectValue(fieldGroupings[fieldIdx])}
|
||||
onChange={(event) => setFieldGrouping(fieldIdx, event.target.value)}
|
||||
>
|
||||
@@ -263,7 +263,7 @@ export function PivotDialog({
|
||||
{fieldGroupings[fieldIdx]?.kind === 'range' && (
|
||||
<input
|
||||
type="number"
|
||||
title={t('dlgPivotRangeStep')}
|
||||
data-tip={t('dlgPivotRangeStep')}
|
||||
className="cell-input"
|
||||
style={{ width: 64 }}
|
||||
min={1}
|
||||
@@ -278,7 +278,7 @@ export function PivotDialog({
|
||||
/>
|
||||
)}
|
||||
<select
|
||||
title={t('dlgPivotLabelFilter')}
|
||||
data-tip={t('dlgPivotLabelFilter')}
|
||||
value={labelFilters[fieldIdx]?.op ?? ''}
|
||||
onChange={(event) => {
|
||||
const op = event.target.value as PivotLabelFilterOption['op'] | ''
|
||||
@@ -298,7 +298,7 @@ export function PivotDialog({
|
||||
{labelFilters[fieldIdx] && (
|
||||
<input
|
||||
type="text"
|
||||
title={t('dlgPivotLabelFilterText')}
|
||||
data-tip={t('dlgPivotLabelFilterText')}
|
||||
className="cell-input"
|
||||
placeholder={t('dlgPivotFilterTextPlaceholder')}
|
||||
style={{ width: 76 }}
|
||||
@@ -317,7 +317,8 @@ export function PivotDialog({
|
||||
className="secondary"
|
||||
style={{ padding: '1px 6px' }}
|
||||
disabled={i === 0}
|
||||
title={t('dlgPivotMoveUp')}
|
||||
data-tip={t('dlgPivotMoveUp')}
|
||||
aria-label={t('dlgPivotMoveUp')}
|
||||
onClick={() => moveAxisField(setAxis, i, -1)}
|
||||
>
|
||||
↑
|
||||
@@ -327,7 +328,8 @@ export function PivotDialog({
|
||||
className="secondary"
|
||||
style={{ padding: '1px 6px' }}
|
||||
disabled={i === indices.length - 1}
|
||||
title={t('dlgPivotMoveDown')}
|
||||
data-tip={t('dlgPivotMoveDown')}
|
||||
aria-label={t('dlgPivotMoveDown')}
|
||||
onClick={() => moveAxisField(setAxis, i, 1)}
|
||||
>
|
||||
↓
|
||||
@@ -337,7 +339,8 @@ export function PivotDialog({
|
||||
type="button"
|
||||
className="secondary"
|
||||
style={{ padding: '1px 6px' }}
|
||||
title={t('dlgPivotRemoveLevel')}
|
||||
data-tip={t('dlgPivotRemoveLevel')}
|
||||
aria-label={t('dlgPivotRemoveLevel')}
|
||||
onClick={() => removeAxisField(setAxis, i)}
|
||||
>
|
||||
✕
|
||||
@@ -471,7 +474,7 @@ export function PivotDialog({
|
||||
</>
|
||||
)}
|
||||
<select
|
||||
title={t('dlgPivotShowAs')}
|
||||
data-tip={t('dlgPivotShowAs')}
|
||||
value={spec.showDataAs ?? ''}
|
||||
onChange={(event) => {
|
||||
const v = event.target.value as PivotShowDataAsOption | ''
|
||||
@@ -486,7 +489,7 @@ export function PivotDialog({
|
||||
))}
|
||||
</select>
|
||||
<select
|
||||
title={t('dlgPivotValueFilter')}
|
||||
data-tip={t('dlgPivotValueFilter')}
|
||||
value={valueFilters[i]?.op ?? ''}
|
||||
onChange={(event) => {
|
||||
const op = event.target.value as PivotValueFilterOption['op'] | ''
|
||||
@@ -508,7 +511,7 @@ export function PivotDialog({
|
||||
{valueFilters[i]?.op === 'top' && (
|
||||
<input
|
||||
type="number"
|
||||
title={t('dlgPivotTopNCount')}
|
||||
data-tip={t('dlgPivotTopNCount')}
|
||||
className="cell-input"
|
||||
style={{ width: 52 }}
|
||||
min={1}
|
||||
@@ -522,7 +525,7 @@ export function PivotDialog({
|
||||
{valueFilters[i]?.op === 'greaterThan' && (
|
||||
<input
|
||||
type="number"
|
||||
title={t('dlgPivotGreaterThanValue')}
|
||||
data-tip={t('dlgPivotGreaterThanValue')}
|
||||
className="cell-input"
|
||||
style={{ width: 64 }}
|
||||
value={valueFilters[i].from ?? 0}
|
||||
@@ -536,7 +539,7 @@ export function PivotDialog({
|
||||
<>
|
||||
<input
|
||||
type="number"
|
||||
title={t('dlgPivotBetweenFrom')}
|
||||
data-tip={t('dlgPivotBetweenFrom')}
|
||||
className="cell-input"
|
||||
style={{ width: 56 }}
|
||||
value={valueFilters[i].from ?? 0}
|
||||
@@ -550,7 +553,7 @@ export function PivotDialog({
|
||||
/>
|
||||
<input
|
||||
type="number"
|
||||
title={t('dlgPivotBetweenTo')}
|
||||
data-tip={t('dlgPivotBetweenTo')}
|
||||
className="cell-input"
|
||||
style={{ width: 56 }}
|
||||
value={valueFilters[i].to ?? 100}
|
||||
@@ -605,7 +608,7 @@ export function PivotDialog({
|
||||
placeholder={t('dlgPivotTargetPlaceholder')}
|
||||
value={targetCell}
|
||||
disabled={mode === 'edit'}
|
||||
title={mode === 'edit' ? t('dlgPivotTargetLocked') : undefined}
|
||||
data-tip={mode === 'edit' ? t('dlgPivotTargetLocked') : undefined}
|
||||
onChange={(event) => setTargetCell(event.target.value.toUpperCase())}
|
||||
style={{ width: 80 }}
|
||||
/>
|
||||
|
||||
@@ -83,7 +83,7 @@ export function ScreenshotDialog({
|
||||
type="button"
|
||||
disabled={capturingId !== null}
|
||||
className={capturingId === source.id ? 'capturing' : ''}
|
||||
title={source.name}
|
||||
data-tip={source.name}
|
||||
onClick={() => capture(source.id)}
|
||||
>
|
||||
{source.thumbnail !== '' && <img src={source.thumbnail} alt="" draggable={false} />}
|
||||
|
||||
@@ -70,7 +70,9 @@ export function SlicerFieldPicker({
|
||||
))}
|
||||
</div>
|
||||
<div className="dialog-actions">
|
||||
<button className="secondary" onClick={onClose}>{t('dlgCancel')}</button>
|
||||
<button className="secondary" onClick={onClose}>
|
||||
{t('dlgCancel')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -98,26 +100,40 @@ export function SlicerPanels({
|
||||
const selected = new Set(slicer.selected)
|
||||
const filtered = selected.size < slicer.members.length
|
||||
return (
|
||||
<section key={slicer.id} className="slicer-panel" aria-label={t('dlgSlicerAria', { name: slicer.fieldName })}>
|
||||
<section
|
||||
key={slicer.id}
|
||||
className="slicer-panel"
|
||||
aria-label={t('dlgSlicerAria', { name: slicer.fieldName })}
|
||||
>
|
||||
<header>
|
||||
<span className="slicer-title" title={slicer.pivotPath}>{slicer.fieldName}</span>
|
||||
<span className="slicer-title" data-tip={slicer.pivotPath}>
|
||||
{slicer.fieldName}
|
||||
</span>
|
||||
<button
|
||||
className="slicer-clear"
|
||||
title={t('dlgSlicerClear')}
|
||||
data-tip={t('dlgSlicerClear')}
|
||||
aria-label={t('dlgSlicerClear')}
|
||||
disabled={!filtered}
|
||||
onClick={() => onSelectAll(slicer.id)}
|
||||
>⧉</button>
|
||||
>
|
||||
⧉
|
||||
</button>
|
||||
<button
|
||||
className="slicer-close"
|
||||
title={t('dlgSlicerRemove')}
|
||||
data-tip={t('dlgSlicerRemove')}
|
||||
aria-label={t('dlgSlicerRemove')}
|
||||
onClick={() => onRemove(slicer.id)}
|
||||
>×</button>
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</header>
|
||||
<div className="slicer-members">
|
||||
{slicer.members.map((entry) => (
|
||||
<button
|
||||
key={entry.member}
|
||||
className={selected.has(entry.member) ? 'slicer-member selected' : 'slicer-member'}
|
||||
className={
|
||||
selected.has(entry.member) ? 'slicer-member selected' : 'slicer-member'
|
||||
}
|
||||
onClick={() => onToggle(slicer.id, entry.member)}
|
||||
>
|
||||
{entry.label}
|
||||
|
||||
@@ -25,39 +25,149 @@ const SYMBOL_CATEGORIES: readonly {
|
||||
{
|
||||
labelKey: 'dlgSymbolCatCurrency',
|
||||
symbols: [
|
||||
'€', '£', '¥', '¢', '₩', '₽', '₹', '©', '®', '™',
|
||||
'§', '¶', '†', '‡', '•', '…', '°', '‰', '№', '¿',
|
||||
'€',
|
||||
'£',
|
||||
'¥',
|
||||
'¢',
|
||||
'₩',
|
||||
'₽',
|
||||
'₹',
|
||||
'©',
|
||||
'®',
|
||||
'™',
|
||||
'§',
|
||||
'¶',
|
||||
'†',
|
||||
'‡',
|
||||
'•',
|
||||
'…',
|
||||
'°',
|
||||
'‰',
|
||||
'№',
|
||||
'¿',
|
||||
],
|
||||
},
|
||||
{
|
||||
labelKey: 'dlgSymbolCatMath',
|
||||
symbols: [
|
||||
'±', '×', '÷', '≠', '≈', '≤', '≥', '∞', '√', '∑',
|
||||
'∏', '∫', '∂', '∆', 'π', 'µ', '∈', '∉', '⊂', '⊃',
|
||||
'∩', '∪', '∀', '∃', '∅', '∝', '∴', '∵', '⊥', '∥',
|
||||
'±',
|
||||
'×',
|
||||
'÷',
|
||||
'≠',
|
||||
'≈',
|
||||
'≤',
|
||||
'≥',
|
||||
'∞',
|
||||
'√',
|
||||
'∑',
|
||||
'∏',
|
||||
'∫',
|
||||
'∂',
|
||||
'∆',
|
||||
'π',
|
||||
'µ',
|
||||
'∈',
|
||||
'∉',
|
||||
'⊂',
|
||||
'⊃',
|
||||
'∩',
|
||||
'∪',
|
||||
'∀',
|
||||
'∃',
|
||||
'∅',
|
||||
'∝',
|
||||
'∴',
|
||||
'∵',
|
||||
'⊥',
|
||||
'∥',
|
||||
],
|
||||
},
|
||||
{
|
||||
labelKey: 'dlgSymbolCatArrows',
|
||||
symbols: [
|
||||
'←', '→', '↑', '↓', '↔', '↕', '⇐', '⇒', '⇑', '⇓',
|
||||
'⇔', '↗', '↘', '↙', '↖', '↩', '↪', '⇄', '⇅', '↦',
|
||||
'←',
|
||||
'→',
|
||||
'↑',
|
||||
'↓',
|
||||
'↔',
|
||||
'↕',
|
||||
'⇐',
|
||||
'⇒',
|
||||
'⇑',
|
||||
'⇓',
|
||||
'⇔',
|
||||
'↗',
|
||||
'↘',
|
||||
'↙',
|
||||
'↖',
|
||||
'↩',
|
||||
'↪',
|
||||
'⇄',
|
||||
'⇅',
|
||||
'↦',
|
||||
],
|
||||
},
|
||||
{
|
||||
labelKey: 'dlgSymbolCatGreek',
|
||||
symbols: [
|
||||
'α', 'β', 'γ', 'δ', 'ε', 'ζ', 'η', 'θ', 'λ', 'μ',
|
||||
'π', 'ρ', 'σ', 'τ', 'φ', 'χ', 'ψ', 'ω', 'Α', 'Β',
|
||||
'Γ', 'Δ', 'Θ', 'Λ', 'Σ', 'Φ', 'Ω',
|
||||
'α',
|
||||
'β',
|
||||
'γ',
|
||||
'δ',
|
||||
'ε',
|
||||
'ζ',
|
||||
'η',
|
||||
'θ',
|
||||
'λ',
|
||||
'μ',
|
||||
'π',
|
||||
'ρ',
|
||||
'σ',
|
||||
'τ',
|
||||
'φ',
|
||||
'χ',
|
||||
'ψ',
|
||||
'ω',
|
||||
'Α',
|
||||
'Β',
|
||||
'Γ',
|
||||
'Δ',
|
||||
'Θ',
|
||||
'Λ',
|
||||
'Σ',
|
||||
'Φ',
|
||||
'Ω',
|
||||
],
|
||||
},
|
||||
{
|
||||
labelKey: 'dlgSymbolCatMisc',
|
||||
symbols: [
|
||||
'★', '☆', '●', '○', '◆', '◇', '■', '□', '▲', '△',
|
||||
'▼', '▽', '✓', '✗', '☑', '☐', '♠', '♣', '♥', '♦',
|
||||
'♪', '♫', '☀', '☁', '☂', '☎',
|
||||
'★',
|
||||
'☆',
|
||||
'●',
|
||||
'○',
|
||||
'◆',
|
||||
'◇',
|
||||
'■',
|
||||
'□',
|
||||
'▲',
|
||||
'△',
|
||||
'▼',
|
||||
'▽',
|
||||
'✓',
|
||||
'✗',
|
||||
'☑',
|
||||
'☐',
|
||||
'♠',
|
||||
'♣',
|
||||
'♥',
|
||||
'♦',
|
||||
'♪',
|
||||
'♫',
|
||||
'☀',
|
||||
'☁',
|
||||
'☂',
|
||||
'☎',
|
||||
],
|
||||
},
|
||||
]
|
||||
@@ -99,7 +209,7 @@ export function SymbolDialog({
|
||||
<button
|
||||
key={symbol}
|
||||
type="button"
|
||||
title={t('dlgSymbolInsertHint', { symbol })}
|
||||
data-tip={t('dlgSymbolInsertHint', { symbol })}
|
||||
onClick={() => onInsert(symbol)}
|
||||
>
|
||||
{symbol}
|
||||
@@ -109,7 +219,9 @@ export function SymbolDialog({
|
||||
<p className="dialog-note">{t('dlgSymbolNote')}</p>
|
||||
</section>
|
||||
<div className="dialog-actions">
|
||||
<button className="secondary" onClick={onClose}>{t('dlgClose')}</button>
|
||||
<button className="secondary" onClick={onClose}>
|
||||
{t('dlgClose')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -106,12 +106,13 @@ export function TimelinePanels({
|
||||
aria-label={t('dlgTimelineAria', { name: timeline.fieldName })}
|
||||
>
|
||||
<header>
|
||||
<span className="slicer-title" title={timeline.pivotPath}>
|
||||
<span className="slicer-title" data-tip={timeline.pivotPath}>
|
||||
{timeline.fieldName}
|
||||
</span>
|
||||
<button
|
||||
className="slicer-clear"
|
||||
title={t('dlgTimelineClear')}
|
||||
data-tip={t('dlgTimelineClear')}
|
||||
aria-label={t('dlgTimelineClear')}
|
||||
disabled={range === null}
|
||||
onClick={() => onClear(timeline.id)}
|
||||
>
|
||||
@@ -119,7 +120,8 @@ export function TimelinePanels({
|
||||
</button>
|
||||
<button
|
||||
className="slicer-close"
|
||||
title={t('dlgTimelineRemove')}
|
||||
data-tip={t('dlgTimelineRemove')}
|
||||
aria-label={t('dlgTimelineRemove')}
|
||||
onClick={() => onRemove(timeline.id)}
|
||||
>
|
||||
×
|
||||
@@ -134,7 +136,7 @@ export function TimelinePanels({
|
||||
<button
|
||||
key={key}
|
||||
className={selected ? 'timeline-month selected' : 'timeline-month'}
|
||||
title={monthLabel(key)}
|
||||
data-tip={monthLabel(key)}
|
||||
onClick={(event) => {
|
||||
if (event.shiftKey && range !== null) {
|
||||
onRange(timeline.id, Math.min(range.start, key), Math.max(range.end, key))
|
||||
|
||||
@@ -856,7 +856,7 @@ function EditableShapeVisual({
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
title={
|
||||
data-tip={
|
||||
textEditing
|
||||
? undefined
|
||||
: allowText
|
||||
@@ -886,7 +886,8 @@ function EditableShapeVisual({
|
||||
{!textEditing && (
|
||||
<button
|
||||
className="shape-delete-button"
|
||||
title={t('appDeleteVisualTitle')}
|
||||
data-tip={t('appDeleteVisualTitle')}
|
||||
aria-label={t('appDeleteVisualTitle')}
|
||||
onPointerDown={(event) => event.stopPropagation()}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
@@ -1242,7 +1243,8 @@ function ChartVisual({
|
||||
{canEdit && !isEditing && (
|
||||
<button
|
||||
className="chart-edit-button"
|
||||
title={t('appEditChartTitle')}
|
||||
data-tip={t('appEditChartTitle')}
|
||||
aria-label={t('appEditChartTitle')}
|
||||
onClick={() => setIsEditing(true)}
|
||||
>
|
||||
✎
|
||||
@@ -1658,7 +1660,7 @@ function ChartEditor({
|
||||
<input
|
||||
className="chart-editor-range"
|
||||
placeholder={series.valuesRef ?? t('appValuesPlaceholder')}
|
||||
title={t('appValuesRangeTitle', {
|
||||
data-tip={t('appValuesRangeTitle', {
|
||||
name: series.name || t('appSeriesN', { n: index + 1 }),
|
||||
})}
|
||||
value={ranges[String(index)]?.values ?? ''}
|
||||
@@ -1676,7 +1678,7 @@ function ChartEditor({
|
||||
<input
|
||||
className="chart-editor-range"
|
||||
placeholder={series.categoriesRef ?? t('appLabelsPlaceholder')}
|
||||
title={t('appCategoriesRangeTitle', {
|
||||
data-tip={t('appCategoriesRangeTitle', {
|
||||
name: series.name || t('appSeriesN', { n: index + 1 }),
|
||||
})}
|
||||
value={ranges[String(index)]?.categories ?? ''}
|
||||
|
||||
@@ -108,6 +108,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,
|
||||
}: {
|
||||
readonly atts: readonly AttachmentMeta[]
|
||||
readonly previews: Record<string, string>
|
||||
}): React.JSX.Element {
|
||||
return (
|
||||
<div className="ai-msg-attachments">
|
||||
{atts.map((a) =>
|
||||
ATTACHMENT_IMAGE_EXTS.has(a.ext) ? (
|
||||
<span key={a.path} className="ai-attachment-thumb" title={a.name}>
|
||||
{previews[a.path] ? (
|
||||
<img src={previews[a.path]} alt={a.name} />
|
||||
) : (
|
||||
<span className="ai-attachment-thumb-pending" aria-hidden>
|
||||
<img src={fileImageIcon} alt="" />
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
) : (
|
||||
<span key={a.path} className="ai-attachment-card" title={a.name}>
|
||||
<span className="ai-attachment-card-icon">
|
||||
<AttachmentCardIcon ext={a.ext} />
|
||||
</span>
|
||||
<span className="ai-attachment-card-meta">
|
||||
<span className="ai-attachment-card-name">{truncateCardName(a.name)}</span>
|
||||
<span className="ai-attachment-card-size">{formatAttachmentSize(a.sizeBytes)}</span>
|
||||
</span>
|
||||
</span>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Resizable panel width: persisted, clamped to min/max, drives the .sheet-body grid column via --copilot-width */
|
||||
const PANEL_WIDTH_KEY = 'sheets-ai-panel-width'
|
||||
const PANEL_WIDTH_MIN = 280
|
||||
@@ -144,6 +182,8 @@ export interface AiChatMessage {
|
||||
readonly loginRequired?: boolean | undefined
|
||||
/** Set when this message reflects an auto-applied plan; renders an inline [Undo] button. */
|
||||
readonly autoApplied?: { readonly opCount: number } | undefined
|
||||
/** attachments consumed from the composer by this user message (read-only echo chips) */
|
||||
readonly attachments?: readonly AttachmentMeta[] | undefined
|
||||
}
|
||||
|
||||
export function AiChatPanel({
|
||||
@@ -187,8 +227,9 @@ export function AiChatPanel({
|
||||
readonly preview: ChangePlan | null
|
||||
readonly aiBusy: boolean
|
||||
readonly onPromptChange: (prompt: string) => void
|
||||
/** Send the composer text, or the given instruction when provided (used by the failed-run Retry) */
|
||||
readonly onSend: (instruction?: string) => void
|
||||
/** Send the composer text, or the given instruction when provided (used by the
|
||||
* failed-run Retry, which also resends the message's original attachments) */
|
||||
readonly onSend: (instruction?: string, attachments?: readonly AttachmentMeta[]) => void
|
||||
readonly onStop: () => void
|
||||
readonly onNewChat: () => void
|
||||
readonly onUndo: () => void
|
||||
@@ -207,7 +248,14 @@ export function AiChatPanel({
|
||||
/** image paths with a read already issued — one readAttachmentImage per attach, even while pending */
|
||||
const previewRequestedRef = useRef(new Set<string>())
|
||||
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((m) => m.attachments ?? []),
|
||||
...historicChat.flatMap((m) => m.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))
|
||||
@@ -219,7 +267,7 @@ export function AiChatPanel({
|
||||
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.desktopApi.readAttachmentImage(a.path).then((r) => {
|
||||
@@ -232,7 +280,7 @@ export function AiChatPanel({
|
||||
}
|
||||
})
|
||||
}
|
||||
}, [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<HTMLDivElement>): void => {
|
||||
@@ -327,7 +375,12 @@ export function AiChatPanel({
|
||||
if (!isOpen) {
|
||||
return (
|
||||
<aside className="copilot collapsed">
|
||||
<button className="expand-copilot" onClick={onExpand} title={t('aiOpenAssistant')}>
|
||||
<button
|
||||
className="expand-copilot"
|
||||
onClick={onExpand}
|
||||
data-tip={t('aiOpenAssistant')}
|
||||
aria-label={t('aiOpenAssistant')}
|
||||
>
|
||||
<GensparkMark size={22} />
|
||||
</button>
|
||||
</aside>
|
||||
@@ -398,11 +451,21 @@ export function AiChatPanel({
|
||||
</span>
|
||||
<div className="ai-panel-header-actions">
|
||||
{(chat.length > 0 || historicChat.length > 0) && (
|
||||
<button className="ai-header-btn" onClick={onNewChat} title={t('aiNewChat')}>
|
||||
<button
|
||||
className="ai-header-btn"
|
||||
onClick={onNewChat}
|
||||
data-tip={t('aiNewChat')}
|
||||
aria-label={t('aiNewChat')}
|
||||
>
|
||||
<IconNewChat size={15} />
|
||||
</button>
|
||||
)}
|
||||
<button className="ai-header-btn" onClick={onCollapse} title={t('aiCollapsePanel')}>
|
||||
<button
|
||||
className="ai-header-btn"
|
||||
onClick={onCollapse}
|
||||
data-tip={t('aiCollapsePanel')}
|
||||
aria-label={t('aiCollapsePanel')}
|
||||
>
|
||||
<IconCollapse size={15} />
|
||||
</button>
|
||||
</div>
|
||||
@@ -414,6 +477,9 @@ export function AiChatPanel({
|
||||
<>
|
||||
{historicChat.map((entry, i) => (
|
||||
<div key={`h${i}`} className={`ai-msg ai-msg-${entry.role} ai-msg-historic`}>
|
||||
{entry.role === 'user' && entry.attachments && entry.attachments.length > 0 && (
|
||||
<SentAttachments atts={entry.attachments} previews={attachmentPreviews} />
|
||||
)}
|
||||
{entry.tools.length > 0 && <ToolChipList tools={entry.tools} />}
|
||||
{entry.text && <Markdown text={entry.text} />}
|
||||
</div>
|
||||
@@ -438,12 +504,18 @@ export function AiChatPanel({
|
||||
>
|
||||
{entry.role === 'user' ? (
|
||||
<>
|
||||
{entry.attachments && entry.attachments.length > 0 && (
|
||||
<SentAttachments atts={entry.attachments} previews={attachmentPreviews} />
|
||||
)}
|
||||
{entry.text}
|
||||
{entry.undelivered && (
|
||||
<div className="ai-msg-undelivered">
|
||||
{t('aiUndelivered')}
|
||||
{!aiBusy && (
|
||||
<button className="ai-retry-btn" onClick={() => onSend(entry.text)}>
|
||||
<button
|
||||
className="ai-retry-btn"
|
||||
onClick={() => onSend(entry.text, entry.attachments ?? [])}
|
||||
>
|
||||
{t('aiRetry')}
|
||||
</button>
|
||||
)}
|
||||
@@ -469,7 +541,7 @@ export function AiChatPanel({
|
||||
<span className="ai-auto-applied-text">
|
||||
{t('aiAutoApplied', { count: entry.autoApplied.opCount })}
|
||||
</span>
|
||||
<button className="ai-undo-btn" onClick={onUndo} title={t('aiUndoTitle')}>
|
||||
<button className="ai-undo-btn" onClick={onUndo} data-tip={t('aiUndoTitle')}>
|
||||
{t('aiUndo')}
|
||||
</button>
|
||||
</div>
|
||||
@@ -547,7 +619,7 @@ export function AiChatPanel({
|
||||
<span
|
||||
key={attachment.path}
|
||||
className="ai-attachment-thumb"
|
||||
title={attachment.path}
|
||||
data-tip={attachment.path}
|
||||
>
|
||||
{attachmentPreviews[attachment.path] ? (
|
||||
<img src={attachmentPreviews[attachment.path]} alt={attachment.name} />
|
||||
@@ -559,7 +631,7 @@ export function AiChatPanel({
|
||||
<button
|
||||
className="ai-attachment-thumb-remove"
|
||||
onClick={() => onRemoveAttachment(attachment.path)}
|
||||
title={t('aiRemoveAttachment')}
|
||||
data-tip={t('aiRemoveAttachment')}
|
||||
aria-label={t('aiRemoveAttachment')}
|
||||
>
|
||||
<svg width="16" height="16" viewBox="0 0 32 32" aria-hidden>
|
||||
@@ -576,7 +648,7 @@ export function AiChatPanel({
|
||||
<span
|
||||
key={attachment.path}
|
||||
className="ai-attachment-card"
|
||||
title={attachment.path}
|
||||
data-tip={attachment.path}
|
||||
>
|
||||
<span className="ai-attachment-card-icon">
|
||||
<AttachmentCardIcon ext={attachment.ext} />
|
||||
@@ -592,7 +664,7 @@ export function AiChatPanel({
|
||||
<button
|
||||
className="ai-attachment-thumb-remove"
|
||||
onClick={() => onRemoveAttachment(attachment.path)}
|
||||
title={t('aiRemoveAttachment')}
|
||||
data-tip={t('aiRemoveAttachment')}
|
||||
aria-label={t('aiRemoveAttachment')}
|
||||
>
|
||||
<svg width="16" height="16" viewBox="0 0 32 32" aria-hidden>
|
||||
@@ -627,7 +699,8 @@ export function AiChatPanel({
|
||||
<button
|
||||
className="ai-attach-btn"
|
||||
onClick={onPickAttachments}
|
||||
title={t('aiAttachTitle')}
|
||||
data-tip={t('aiAttachTitle')}
|
||||
aria-label={t('aiAttachTitle')}
|
||||
>
|
||||
<img src={attachIcon} alt="" aria-hidden />
|
||||
</button>
|
||||
@@ -802,14 +875,14 @@ function ToolChipList({ tools }: { tools: readonly AiToolChip[] }): React.JSX.El
|
||||
<button
|
||||
type="button"
|
||||
className="ai-step-title clickable"
|
||||
title={tool.name}
|
||||
data-tip={tool.name}
|
||||
aria-expanded={isOpen}
|
||||
onClick={() => toggle(j)}
|
||||
>
|
||||
{tool.summary}
|
||||
</button>
|
||||
) : (
|
||||
<span className="ai-step-title" title={tool.name}>
|
||||
<span className="ai-step-title" data-tip={tool.name}>
|
||||
{tool.summary}
|
||||
</span>
|
||||
)}
|
||||
|
||||
@@ -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
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -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: '縮放至選取範圍',
|
||||
|
||||
@@ -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: '斜體',
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 =
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<readonly string[]> | null = null
|
||||
|
||||
async function queryFamilies(): Promise<readonly string[]> {
|
||||
const query = (window as { queryLocalFonts?: () => Promise<{ readonly family: string }[]> })
|
||||
.queryLocalFonts
|
||||
if (!query) return []
|
||||
try {
|
||||
const fonts = await query.call(window)
|
||||
const families = new Set<string>()
|
||||
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<readonly string[]> {
|
||||
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<readonly string[]>(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,
|
||||
}
|
||||
}
|
||||
@@ -1913,6 +1913,12 @@ export interface DesktopApi {
|
||||
getTheme(): Promise<UiTheme>
|
||||
/** 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<WorkbookFile | null>
|
||||
readWorkbookRange(request: WorkbookRangeRequest): Promise<WorkbookRangeResult>
|
||||
readWorkbookFormulas(request: WorkbookFormulaCellsRequest): Promise<WorkbookFormulaCellsResult>
|
||||
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -215,6 +215,159 @@ const sheetsMyWorksheet = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
|
||||
const sheetsChart = `<c:chartSpace xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart"><c:chart><c:plotArea><c:barChart><c:ser><c:val><c:numRef><c:f>Data!$A$1:$A$2</c:f></c:numRef></c:val></c:ser></c:barChart></c:plotArea></c:chart></c:chartSpace>`
|
||||
|
||||
/// 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<Buffer> {
|
||||
const zip = new JSZip()
|
||||
const keepFormula = options.tableRef ? '<c r="B1"><f>SUM(DecoTable[Amt])</f><v>3</v></c>' : ''
|
||||
const keepDrawing = options.sharedImage ? '<drawing r:id="rId1"/>' : ''
|
||||
// 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
|
||||
? '<definedNames><definedName name="DecoRef" localSheetId="1">SUM(DecoTable[Amt])</definedName></definedNames>'
|
||||
: ''
|
||||
zip.file(
|
||||
'[Content_Types].xml',
|
||||
`<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
|
||||
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
|
||||
<Default Extension="xml" ContentType="application/xml"/>
|
||||
<Default Extension="png" ContentType="image/png"/>
|
||||
<Default Extension="vml" ContentType="application/vnd.openxmlformats-officedocument.vmlDrawing"/>
|
||||
<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>
|
||||
<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>
|
||||
<Override PartName="/xl/worksheets/sheet2.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>
|
||||
<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>
|
||||
<Override PartName="/xl/drawings/drawing1.xml" ContentType="application/vnd.openxmlformats-officedocument.drawing+xml"/>
|
||||
${options.sharedImage ? '<Override PartName="/xl/drawings/drawing2.xml" ContentType="application/vnd.openxmlformats-officedocument.drawing+xml"/>' : ''}
|
||||
<Override PartName="/xl/charts/chart1.xml" ContentType="application/vnd.openxmlformats-officedocument.drawingml.chart+xml"/>
|
||||
<Override PartName="/xl/charts/colors1.xml" ContentType="application/vnd.ms-office.chartcolorstyle+xml"/>
|
||||
<Override PartName="/xl/comments1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml"/>
|
||||
<Override PartName="/xl/tables/table1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml"/>
|
||||
</Types>`,
|
||||
)
|
||||
zip.file('_rels/.rels', packageRelationships)
|
||||
zip.file(
|
||||
'xl/workbook.xml',
|
||||
`<?xml version="1.0" encoding="UTF-8"?>
|
||||
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
|
||||
<sheets><sheet name="Keep" sheetId="1" r:id="rId1"/><sheet name="Deco" sheetId="2" r:id="rId2"/></sheets>
|
||||
${definedNames}
|
||||
</workbook>`,
|
||||
)
|
||||
zip.file(
|
||||
'xl/_rels/workbook.xml.rels',
|
||||
`<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
|
||||
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>
|
||||
<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet2.xml"/>
|
||||
<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>
|
||||
</Relationships>`,
|
||||
)
|
||||
zip.file(
|
||||
'xl/worksheets/sheet1.xml',
|
||||
`<?xml version="1.0" encoding="UTF-8"?>
|
||||
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
|
||||
<sheetData><row r="1"><c r="A1"><v>1</v></c>${keepFormula}</row></sheetData>
|
||||
${keepDrawing}
|
||||
</worksheet>`,
|
||||
)
|
||||
if (options.sharedImage) {
|
||||
zip.file(
|
||||
'xl/worksheets/_rels/sheet1.xml.rels',
|
||||
`<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
|
||||
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing" Target="../drawings/drawing2.xml"/>
|
||||
</Relationships>`,
|
||||
)
|
||||
zip.file(
|
||||
'xl/drawings/drawing2.xml',
|
||||
'<xdr:wsDr xmlns:xdr="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing"/>',
|
||||
)
|
||||
zip.file(
|
||||
'xl/drawings/_rels/drawing2.xml.rels',
|
||||
`<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
|
||||
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="../media/image1.png"/>
|
||||
</Relationships>`,
|
||||
)
|
||||
}
|
||||
zip.file(
|
||||
'xl/worksheets/sheet2.xml',
|
||||
`<?xml version="1.0" encoding="UTF-8"?>
|
||||
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
|
||||
<sheetData><row r="1"><c r="A1"><v>5</v></c></row><row r="2"><c r="A2"><v>7</v></c></row></sheetData>
|
||||
<drawing r:id="rId1"/>
|
||||
<legacyDrawing r:id="rId3"/>
|
||||
<tableParts count="1"><tablePart r:id="rId4"/></tableParts>
|
||||
</worksheet>`,
|
||||
)
|
||||
zip.file(
|
||||
'xl/worksheets/_rels/sheet2.xml.rels',
|
||||
`<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
|
||||
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing" Target="../drawings/drawing1.xml"/>
|
||||
<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments" Target="../comments1.xml"/>
|
||||
<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing" Target="../drawings/vmlDrawing1.vml"/>
|
||||
<Relationship Id="rId4" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/table" Target="../tables/table1.xml"/>
|
||||
${options.pivot ? '<Relationship Id="rId5" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/pivotTable" Target="../pivotTables/pivotTable1.xml"/>' : ''}
|
||||
</Relationships>`,
|
||||
)
|
||||
zip.file(
|
||||
'xl/drawings/drawing1.xml',
|
||||
'<xdr:wsDr xmlns:xdr="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing"/>',
|
||||
)
|
||||
zip.file(
|
||||
'xl/drawings/_rels/drawing1.xml.rels',
|
||||
`<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
|
||||
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="../media/image1.png"/>
|
||||
<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart" Target="../charts/chart1.xml"/>
|
||||
</Relationships>`,
|
||||
)
|
||||
zip.file(
|
||||
'xl/charts/chart1.xml',
|
||||
'<c:chartSpace xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart"><c:chart><c:plotArea><c:barChart><c:ser><c:val><c:numRef><c:f>Deco!$A$1:$A$2</c:f></c:numRef></c:val></c:ser></c:barChart></c:plotArea></c:chart></c:chartSpace>',
|
||||
)
|
||||
zip.file(
|
||||
'xl/charts/_rels/chart1.xml.rels',
|
||||
`<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
|
||||
<Relationship Id="rId1" Type="http://schemas.microsoft.com/office/2011/relationships/chartColorStyle" Target="colors1.xml"/>
|
||||
</Relationships>`,
|
||||
)
|
||||
zip.file(
|
||||
'xl/charts/colors1.xml',
|
||||
'<cs:colorStyle xmlns:cs="http://schemas.microsoft.com/office/drawing/2012/chartStyle"/>',
|
||||
)
|
||||
zip.file('xl/comments1.xml', kitchenSinkComments)
|
||||
zip.file('xl/drawings/vmlDrawing1.vml', kitchenSinkVml)
|
||||
zip.file(
|
||||
'xl/tables/table1.xml',
|
||||
`<?xml version="1.0" encoding="UTF-8"?>
|
||||
<table xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" id="1" name="DecoTable" displayName="DecoTable" ref="A1:A2"><tableColumns count="1"><tableColumn id="1" name="Amt"/></tableColumns></table>`,
|
||||
)
|
||||
if (options.pivot) {
|
||||
zip.file(
|
||||
'xl/pivotTables/pivotTable1.xml',
|
||||
'<pivotTableDefinition xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"/>',
|
||||
)
|
||||
}
|
||||
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.
|
||||
|
||||
@@ -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<string> {
|
||||
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('<f>Data!A1+SUM(Plain!A1:A2)</f>')
|
||||
const workbook = await entryText(mutation.buffer, 'xl/workbook.xml')
|
||||
expect(workbook).toContain('<definedName name="LocalMy" localSheetId="2">Plain!$A$1</definedName>')
|
||||
expect(workbook).toContain(
|
||||
'<definedName name="LocalMy" localSheetId="2">Plain!$A$1</definedName>',
|
||||
)
|
||||
|
||||
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 = '<Relationships><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing" Target="../drawings/drawing1.xml"/></Relationships>'
|
||||
expect(() => assertSheetRelsRemovable(drawingRels, 'Data')).toThrow(SheetEditError)
|
||||
const hyperlinkRels = '<Relationships><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://example.com" TargetMode="External"/></Relationships>'
|
||||
expect(() => assertSheetRelsRemovable(hyperlinkRels, 'Data')).not.toThrow()
|
||||
it('classifies removed-sheet relationships into owned, ignorable, and blocking', () => {
|
||||
const rels =
|
||||
'<Relationships>' +
|
||||
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing" Target="../drawings/drawing1.xml"/>' +
|
||||
'<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments" Target="../comments1.xml"/>' +
|
||||
'<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://example.com" TargetMode="External"/>' +
|
||||
'<Relationship Id="rId4" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/printerSettings" Target="../printerSettings/printerSettings1.bin"/>' +
|
||||
'</Relationships>'
|
||||
expect(classifyRemovedSheetRels(rels, 'Data')).toEqual([
|
||||
'../drawings/drawing1.xml',
|
||||
'../comments1.xml',
|
||||
])
|
||||
const pivotRels =
|
||||
'<Relationships><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/pivotTable" Target="../pivotTables/pivotTable1.xml"/></Relationships>'
|
||||
expect(() => classifyRemovedSheetRels(pivotRels, 'Data')).toThrow(/pivot table/)
|
||||
const slicerRels =
|
||||
'<Relationships><Relationship Id="rId1" Type="http://schemas.microsoft.com/office/2007/relationships/slicer" Target="../slicers/slicer1.xml"/></Relationships>'
|
||||
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('<table id="1" name="T1" displayName="DecoTable" ref="A1:A2"/>')).toBe(
|
||||
'DecoTable',
|
||||
)
|
||||
})
|
||||
|
||||
it('definedNamesUseToken sees surviving names and skips names scoped to removed sheets', () => {
|
||||
const scoped =
|
||||
'<workbook><definedNames>' +
|
||||
'<definedName name="Scoped" localSheetId="1">SUM(DecoTable[Amt])</definedName>' +
|
||||
'</definedNames></workbook>'
|
||||
expect(definedNamesUseToken(scoped, 'DecoTable[', new Set([1]))).toBe(false)
|
||||
expect(definedNamesUseToken(scoped, 'DecoTable[', new Set())).toBe(true)
|
||||
const global =
|
||||
'<workbook><definedNames>' +
|
||||
'<definedName name="Global">SUM(DecoTable[Amt])</definedName>' +
|
||||
'</definedNames></workbook>'
|
||||
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("<f>'My Sheet'!A1*2</f>")
|
||||
expect(copy).toContain('<c r="B1" t="inlineStr"><is><t xml:space="preserve">copied</t></is></c>')
|
||||
expect(copy).toContain(
|
||||
'<c r="B1" t="inlineStr"><is><t xml:space="preserve">copied</t></is></c>',
|
||||
)
|
||||
// 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',
|
||||
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
|
||||
+ '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://example.com" TargetMode="External"/>'
|
||||
+ '<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/printerSettings" Target="../printerSettings/printerSettings1.bin"/>'
|
||||
+ '</Relationships>',
|
||||
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
|
||||
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://example.com" TargetMode="External"/>' +
|
||||
'<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/printerSettings" Target="../printerSettings/printerSettings1.bin"/>' +
|
||||
'</Relationships>',
|
||||
)
|
||||
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',
|
||||
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
|
||||
+ '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing" Target="../drawings/drawing1.xml"/>'
|
||||
+ '</Relationships>',
|
||||
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
|
||||
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing" Target="../drawings/drawing1.xml"/>' +
|
||||
'</Relationships>',
|
||||
)
|
||||
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(
|
||||
'<sheetViews><sheetView tabSelected="1" workbookViewId="0"/></sheetViews>',
|
||||
)).toBe('<sheetViews><sheetView workbookViewId="0"/></sheetViews>')
|
||||
expect(stripPageSetupRelIds('<pageSetup paperSize="9" r:id="rId3" orientation="portrait"/>'))
|
||||
.toBe('<pageSetup paperSize="9" orientation="portrait"/>')
|
||||
const hyperlinkOnly = '<Relationships><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://example.com" TargetMode="External"/></Relationships>'
|
||||
expect(prepareClonedSheetRels(hyperlinkOnly, 'Data'))
|
||||
.toEqual({ relsXml: hyperlinkOnly, droppedPrinterSettings: false })
|
||||
const printerOnly = '<Relationships><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/printerSettings" Target="../printerSettings/printerSettings1.bin"/></Relationships>'
|
||||
expect(prepareClonedSheetRels(printerOnly, 'Data'))
|
||||
.toEqual({ relsXml: null, droppedPrinterSettings: true })
|
||||
const commentRels = '<Relationships><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments" Target="../comments1.xml"/></Relationships>'
|
||||
expect(
|
||||
sanitizeClonedWorksheetXml(
|
||||
'<sheetViews><sheetView tabSelected="1" workbookViewId="0"/></sheetViews>',
|
||||
),
|
||||
).toBe('<sheetViews><sheetView workbookViewId="0"/></sheetViews>')
|
||||
expect(
|
||||
stripPageSetupRelIds('<pageSetup paperSize="9" r:id="rId3" orientation="portrait"/>'),
|
||||
).toBe('<pageSetup paperSize="9" orientation="portrait"/>')
|
||||
const hyperlinkOnly =
|
||||
'<Relationships><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://example.com" TargetMode="External"/></Relationships>'
|
||||
expect(prepareClonedSheetRels(hyperlinkOnly, 'Data')).toEqual({
|
||||
relsXml: hyperlinkOnly,
|
||||
droppedPrinterSettings: false,
|
||||
})
|
||||
const printerOnly =
|
||||
'<Relationships><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/printerSettings" Target="../printerSettings/printerSettings1.bin"/></Relationships>'
|
||||
expect(prepareClonedSheetRels(printerOnly, 'Data')).toEqual({
|
||||
relsXml: null,
|
||||
droppedPrinterSettings: true,
|
||||
})
|
||||
const commentRels =
|
||||
'<Relationships><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments" Target="../comments1.xml"/></Relationships>'
|
||||
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 = /<sheets>([\s\S]*?)<\/sheets>/.exec(workbook)?.[1] ?? ''
|
||||
expect(sheetsBlock).toBe(
|
||||
'<sheet name="Summary" sheetId="4" r:id="rId6"/>'
|
||||
+ '<sheet name="Numbers" sheetId="1" r:id="rId1"/>'
|
||||
+ '<sheet name="My Sheet" sheetId="3" r:id="rId3"/>',
|
||||
'<sheet name="Summary" sheetId="4" r:id="rId6"/>' +
|
||||
'<sheet name="Numbers" sheetId="1" r:id="rId1"/>' +
|
||||
'<sheet name="My Sheet" sheetId="3" r:id="rId3"/>',
|
||||
)
|
||||
const chart = await entryText(mutation.buffer, 'xl/charts/chart1.xml')
|
||||
expect(chart).toContain('<c:f>Numbers!$A$1:$A$2</c:f>')
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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-<v>.dmg /
|
||||
// GenOffice-<v>-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-<v>.AppImage / genoffice_<v>_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 ./<new>.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,
|
||||
|
||||
@@ -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<string | null> => {
|
||||
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<TabKind, keyof MenuIconSet> = {
|
||||
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)
|
||||
|
||||
@@ -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<UpdateUiState>): void {
|
||||
if (!currentState) return
|
||||
currentState = { ...currentState, ...patch }
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user