diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 3b5c43c..00bf387 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -82,6 +82,17 @@ jobs:
fi
npm run check:theme-colors
+ # skills/*/SKILL.md ship to users' agent directories; a body change
+ # without a metadata.version bump would never be offered as an update.
+ - name: Check skill versions
+ env:
+ FORMAT_BASE_REF: ${{ github.event.pull_request.base.sha || github.event.before }}
+ run: |
+ if [ "${{ github.event_name }}" = "pull_request" ]; then
+ FORMAT_BASE_REF=$(git rev-parse HEAD^1)
+ fi
+ npm run check:skill-version
+
# Added lines only: Han text outside locale tables, review-tool tags,
# feedback-ledger ids, sample-corpus ids, internal PR numbers, personal
# paths/e-mails, credentials, NUL bytes (tools/check-public-hygiene.mjs).
@@ -118,6 +129,11 @@ jobs:
- name: Check committed fixtures match the generator
run: git diff --exit-code -- fixtures/generated
+ # pptx-engine's OOXML schema gate validates saved decks with xmllint
+ # (tools/ooxml-validate); the runner image is not guaranteed to have it.
+ - name: Install xmllint
+ run: sudo apt-get install -y --no-install-recommends libxml2-utils
+
- name: Test
run: npm test
diff --git a/.prettierignore b/.prettierignore
index 07fcd29..69c9216 100644
--- a/.prettierignore
+++ b/.prettierignore
@@ -22,3 +22,6 @@ apps/slides/src/renderer/ai/prompts/*.md
# In-page extractor fragments: concatenated into one function body, kept verbatim.
packages/html2docx/src/browser/
+
+# ISO/IEC 29500 schemas: keep byte-identical to the published files (one marked amendment).
+tools/ooxml-validate/schemas/
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 9e56390..fac3231 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -22,7 +22,7 @@ directly on this repository as usual.
## Repository layout
-- `apps/*` — the six Electron apps (docs, sheets, slides, pdf, markdown, shell).
+- `apps/*` — the seven Electron apps (docs, sheets, slides, pdf, markdown, html, shell).
Each app is an npm workspace with its own `src/main` (Electron main
process), `src/renderer` (React UI), and `tests/`.
- `packages/*` — pure TypeScript engine and shared packages (no Electron
@@ -30,6 +30,48 @@ directly on this repository as usual.
i18n, UI kit.
- `apps/sheets/native/xlsx-engine` — Rust xlsx engine (runs as a sidecar process) for xlsx import/export.
+## Engine packages
+
+All pure TypeScript, no Electron dependency, unit-tested (except the UI kit):
+
+- `packages/docx-engine` — docx parsing → block tree (with `docxIndex`
+ anchors and passthrough), OOXML fragment generation, byte-level paragraph
+ patching.
+- `packages/pptx-engine` / `packages/pptx-render` — pptx model and rendering.
+- `packages/pdf2docx` — local PDF → DOCX conversion: PDFium character-level
+ extraction, pure-geometry layout analysis, rebuild through `docx-engine`;
+ the same analysis drives the PDF app's PowerPoint and Excel exports.
+- `packages/html2docx` — local HTML → DOCX conversion: the page is rendered in
+ the app's own Chromium, reduced in-browser to a document intent tree, and
+ written as native OOXML with the `docx` library; only visuals with no Word
+ counterpart are screenshotted. Drives the HTML app's Export as Word.
+- `packages/file-parse` — text extraction for AI attachments (office formats,
+ text formats).
+- `packages/agent-core` — the AI agent loop and skill composition shared by
+ every app.
+- `packages/ai-provider` — provider abstraction and streaming for the model
+ backends.
+- `packages/ai-search` — Genspark auth + web/image search tools.
+- `packages/i18n`, `packages/ui`, `packages/project-store`,
+ `packages/electron-utils` — shared i18n core, React UI kit, recent-files
+ store, and Electron main-process helpers.
+
+### Architecture notes (docx round trip)
+
+```
+open docx ─► archive original by hash (never touched)
+ ─► docx-engine parses word/document.xml top-level elements (w:p / w:tbl / …)
+ ─► Block tree, each block anchored by docxIndex + original XML slice
+ ─► Tiptap streaming editor (manual + AI editing, dirty tracking)
+save ─► dirty blocks → OOXML fragments (referencing existing styles only)
+ ─► splice into original document.xml (untouched blocks keep original bytes)
+ ─► repack zip; all other entries copied byte-for-byte
+```
+
+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.
+
## Getting started
Prerequisites: Node 22+, npm 10+, and a Rust toolchain (`cargo` on PATH,
@@ -70,7 +112,7 @@ formatting diff.
## Building installers
Run these from the repository root — they regenerate the third-party
-notices and build all six apps before packaging:
+notices and build all seven apps before packaging:
```bash
npm run dist:mac # dmg + zip
diff --git a/NOTICE b/NOTICE
index 5e3319f..9f140d9 100644
--- a/NOTICE
+++ b/NOTICE
@@ -23,3 +23,11 @@ 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.
+
+Office Open XML schemas
+
+tools/ooxml-validate/schemas contains the ISO/IEC 29500-4:2016 (ECMA-376
+Part 4, Transitional) XML Schema files for PresentationML and DrawingML, as
+distributed in the python-docx repository (ref/xsd), with one marked local
+amendment (see tools/ooxml-validate/README.md). They are used only by tests
+and development tooling and are not shipped in the application.
diff --git a/README.md b/README.md
index 615db30..09b728b 100644
--- a/README.md
+++ b/README.md
@@ -23,6 +23,7 @@ Word, Excel, PowerPoint and PDF files, edited by you and your AI, saved back in
Download ·
+ CLI ·
Website ·
Community ·
Privacy
@@ -47,6 +48,10 @@ file, makes the change, and shows you exactly what it touched.
key for Claude, OpenAI, Gemini, DeepSeek, Kimi, GLM, Qwen, Doubao, MiniMax,
Grok, Mistral, OpenRouter, Requesty, or any OpenAI-compatible endpoint, local
servers included.
+- **Scriptable and agent-ready.** The app ships a `genoffice` command line and
+ a skill for Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode
+ and Windsurf, so a coding agent can create, convert, read and edit real
+ Office files on your machine without opening a window.
**Get it:** [macOS](https://github.com/genspark-ai/genoffice/releases/latest) (Apple Silicon and Intel) ·
[Windows](https://github.com/genspark-ai/genoffice/releases/latest) (x64 and Arm) ·
@@ -55,8 +60,9 @@ details and requirements in [Download](#download).
## Demo
-Six apps, one AI panel. Every screenshot is the real app on macOS, with the
-AI driven from the prompt you can read in the panel.
+Six apps, one AI panel, and a command line for your coding agent. Every
+screenshot is the real app on macOS, with the AI driven from the prompt you
+can read in the panel.
### 1 · Docs — open and edit `.docx` with an AI you can review
@@ -154,6 +160,26 @@ self-contained `.html` file against those tokens.
+### 7 · CLI — your coding agent drives GenOffice, on your machine
+
+GenOffice ships a `genoffice` command line and an agent skill. Install the
+skill and Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode or
+Windsurf can create, convert, read and edit real Office files through the
+same engines as the apps, without opening a window.
+
+
+
+
+
+
+
+
+
+One prompt to your agent — "Build an eight-slide deck about the Solar System." The agent reads the skill, writes a style sheet, an outline and one page spec per slide, generates the two photos with genoffice image, and lets genoffice slides check reject anything that overflows or overlaps before genoffice create assembles the .pptx and slides render hands back a PNG per slide to look at.
+Install once, from Settings → Integrations — GenOffice lists the coding agents it finds on this computer and writes the skill into each one you pick. Or download the skill as a zip, or run npx skills add genspark-ai/genoffice. Commands and the full workflow are in Command line and agent skill .
+
+
+
## Why GenOffice
- **Open source**, Apache-2.0, built in the open on GitHub.
@@ -170,6 +196,9 @@ self-contained `.html` file against those tokens.
- **PDF done properly.** Edit text inside the page, and convert PDF to Word,
Excel or PowerPoint on-device, with system OCR for scans.
- **Markdown and HTML too**, with the same AI panel and local export to Word.
+- **Scriptable.** A `genoffice` command line and an agent skill put every
+ engine at the service of Claude Code, Codex, Cursor and other coding agents,
+ still on-device.
- **Free**, for individuals and teams alike.
## AI backends
@@ -191,6 +220,73 @@ The whole suite ships light, dark and system themes. Themes only change what
is on screen: exports, prints and saved files always keep the document's own
colors.
+## Command line and agent skill
+
+Everything the apps can do to a file, the `genoffice` command line can do from
+a terminal: inspect, convert, create, read and edit Word, Excel, PowerPoint,
+PDF, Markdown and HTML on the same engines, headless. It installs with
+GenOffice, needs no runtime of its own, and never sends a document anywhere.
+Paired with the bundled **agent skill**, it turns a coding agent into a
+document worker that produces real Office files instead of Markdown
+approximations.
+
+**Works with:** Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot,
+OpenCode and Windsurf out of the box, and any other agent that reads skills.
+
+### Install the skill
+
+| How | What happens |
+| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| **Settings → Integrations** in the app | Lists the agents found on this computer; one click writes the skill into each one you choose. An **Update** button appears when a GenOffice release ships a newer skill. |
+| **Download as zip** on the same page | The layout claude.ai, the Claude desktop apps and other assistants accept as an uploaded skill. |
+| `npx skills add genspark-ai/genoffice` | Installs from this repository into any skills-compatible agent. |
+
+Then start a new chat and ask for a document. The skill teaches the agent when
+to reach for `genoffice`, how to read a file before editing it, and how to
+check its own work.
+
+### Quickstart from the terminal
+
+```bash
+genoffice --version
+genoffice info report.docx --json # headings and blocks; or sheets, slides, pages
+genoffice convert report.md --to pdf # md/html/docx/xlsx/pptx → pdf, pdf → docx/xlsx/pptx, …
+genoffice create --type docx --from notes.md --out notes.docx
+genoffice create --type xlsx --from table.json --out sales.xlsx # "=SUM(B2:B9)" cells stay live formulas
+genoffice docs read report.docx --range 0-9 --json # then `docs apply --ops edits.json` edits in place
+genoffice render report.docx --out shots/ # one PNG per page, to look at what you made
+genoffice open sales.xlsx # hand the result to the editor
+```
+
+Every command prints a one-line summary, or a single JSON object with
+`--json`. Edits are atomic: a rejected op leaves the file untouched and comes
+back with a guided error. `genoffice help` lists the current command surface;
+the full reference is [packages/cli/README.md](packages/cli/README.md).
+
+### What the agent actually runs
+
+The Solar System deck in the [demo](#demo) took one prompt in Claude Code.
+Behind it, the agent followed the skill's staged workflow and the CLI checked
+every stage before the next one started:
+
+```bash
+genoffice capabilities --json # which cloud tools GenOffice has configured
+genoffice guide slides design # the deck workflow and layout library
+genoffice image "the eight planets in a row …" --aspect 16:9 --out deck/assets/cover.jpg
+genoffice slides check deck/outline.json --json # 8 pages, no findings
+genoffice slides check deck/pages/01.json --json # builds one slide, audits overflow and overlap
+… # one page file per slide, fixed until each check is clean
+genoffice create --type pptx --spec deck/pages --outline deck/outline.json --out deck/solar-system.pptx --json
+genoffice slides render deck/solar-system.pptx --out deck/shots --json
+genoffice slides audit deck/solar-system.pptx --json # 8 slides, no layout issues
+genoffice slides replace deck/solar-system.pptx --slide 4 --spec deck/pages/05.json --json
+genoffice open deck/solar-system.pptx
+```
+
+No model call happens inside `genoffice`: the agent does the thinking, the CLI
+does the building and the checking, and the result opens in GenOffice or
+PowerPoint as an ordinary `.pptx`.
+
## Download
| Platform | Requirements | Download |
@@ -353,6 +449,18 @@ form fields and page backgrounds; only visuals with no Word counterpart
+
+Can I drive GenOffice from Claude Code, Codex, Cursor or a script?
+
+Yes. GenOffice installs a `genoffice` command line that runs the same engines
+headless: inspect, convert, create, read and edit documents from a terminal or
+a script, with `--json` output for programs. The bundled agent skill teaches
+Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode and Windsurf
+to use it; install it from **Settings → Integrations**. See
+[Command line and agent skill](#command-line-and-agent-skill).
+
+
+
Does GenOffice collect any data?
diff --git a/apps/docs/src/main/docs-main.ts b/apps/docs/src/main/docs-main.ts
index 6e96752..94617a0 100644
--- a/apps/docs/src/main/docs-main.ts
+++ b/apps/docs/src/main/docs-main.ts
@@ -8,8 +8,20 @@ import {
unlinkSync,
writeFileSync,
} from 'node:fs'
-import { copyFile, mkdir, readFile, readdir, stat, unlink, writeFile } from 'node:fs/promises'
+import {
+ copyFile,
+ mkdir,
+ mkdtemp,
+ readFile,
+ readdir,
+ rm,
+ stat,
+ unlink,
+ writeFile,
+} from 'node:fs/promises'
+import { tmpdir } from 'node:os'
import { basename, join } from 'node:path'
+import { pathToFileURL } from 'node:url'
import {
BrowserWindow,
Menu,
@@ -30,6 +42,7 @@ import {
fetchRemoteImage,
installContextMenu,
installNavigationGuard,
+ isHeadlessMode,
printHtmlToPdf,
safeExternalUrl,
saveAsSuggestion,
@@ -37,6 +50,11 @@ import {
showSaveDialogWithMemory,
toggleDevToolsItem,
windowMenuTemplate,
+ type HeadlessExportFormat,
+ type HeadlessExportTarget,
+ installRendererProtocol,
+ registerRendererScheme,
+ rendererUrl,
} from '@genoffice/electron-utils'
import { configureMetricsCache, familyVerticalMetrics } from '@genoffice/font-metrics'
import { createI18n, getUiLang, normalizeLang, setUiLang } from '@genoffice/i18n'
@@ -49,6 +67,8 @@ import type {
WebContents,
} from 'electron'
import { parseFileToText } from '@genoffice/file-parse'
+import { convertHtmlToDocx } from '../../../../packages/html2docx/src'
+import { ElectronBrowserDriver } from '../../../../packages/html2docx/src/drivers/electron'
import {
AiCreditsError,
AiTimeoutError,
@@ -3195,6 +3215,10 @@ export function registerProjectIpc(): void {
})
}
+/** A4 at 96dpi, as the HTML app exports */
+const ALT_CHUNK_VIEWPORT = { width: 794, height: 1123, deviceScaleFactor: 2 }
+const ALT_CHUNK_HTML_MAX_CHARS = 64 * 1024 * 1024
+
/** document/attachment/window IPC (everything except the AI proxy above) */
export function registerDocsIpc(): void {
registerZoteroIpc()
@@ -3223,6 +3247,32 @@ export function registerDocsIpc(): void {
ipcMain.handle('docs:open-path', (event, filePath: string) => loadDocx(filePath, event.sender.id))
+ // w:altChunk HTML: the same html2docx chain as the HTML app's export, in a
+ // hidden window; the renderer parses the result and shows its blocks
+ ipcMain.handle('docs:altchunk-html-to-docx', async (_event, html: unknown) => {
+ if (typeof html !== 'string' || !html.trim() || html.length > ALT_CHUNK_HTML_MAX_CHARS) {
+ return null
+ }
+ const workDir = await mkdtemp(join(tmpdir(), 'genoffice-altchunk-'))
+ let driver: ElectronBrowserDriver | null = null
+ try {
+ const htmlPath = join(workDir, 'chunk.html')
+ // the BOM outranks a stale left in the decoded markup
+ await writeFile(htmlPath, `\ufeff${html}`, 'utf8')
+ driver = await ElectronBrowserDriver.create(ALT_CHUNK_VIEWPORT)
+ const { docx } = await convertHtmlToDocx({ url: pathToFileURL(htmlPath).href }, driver, {
+ naturalTableWidth: true,
+ })
+ return docx
+ } catch (err) {
+ console.warn('[docs] altChunk conversion failed:', err)
+ return null
+ } finally {
+ await driver?.close()
+ await rm(workDir, { recursive: true, force: true }).catch(() => {})
+ }
+ })
+
// Review > Protect > Encrypt with Password: set/clear the open password.
// Takes effect on the next save (docs:save / save-as / save-new all consult the store).
ipcMain.handle(
@@ -3313,6 +3363,25 @@ export function registerDocsIpc(): void {
return content
})
+ // ---- headless export mode (--headless-export) ----
+
+ ipcMain.handle('docs:consume-headless-export', (event): HeadlessExportTarget | null => {
+ const target = headlessExportTargets.get(event.sender.id) ?? null
+ headlessExportTargets.delete(event.sender.id)
+ return target
+ })
+
+ ipcMain.on('docs:headless-export-done', (event, result: unknown) => {
+ const settle = headlessExportWaiters.get(event.sender.id)
+ if (!settle) return
+ headlessExportWaiters.delete(event.sender.id)
+ const state = result as { ok?: unknown; error?: unknown } | null
+ settle({
+ ok: state?.ok === true,
+ ...(typeof state?.error === 'string' ? { error: state.error } : {}),
+ })
+ })
+
ipcMain.handle(
'docs:save',
async (event, filePath: string, data: ArrayBuffer, auto?: boolean) => {
@@ -3854,6 +3923,9 @@ export function setDocsShellHooks(hooks: DocsShellHooks | null): void {
* (shell) or reveal it in the folder (standalone). Tab-opening failure must
* not report the write itself as failed — the file is already persisted. */
function openGeneratedFile(path: string): void {
+ // Headless export has no tab strip and no user: revealing the file in Finder
+ // would be the only visible effect of a run that must stay silent.
+ if (isHeadlessMode()) return
try {
if (shellHooks?.openGeneratedPath?.(path)) return
} catch (err) {
@@ -4191,6 +4263,73 @@ export function buildDocsMenu(): void {
Menu.setApplicationMenu(Menu.buildFromTemplate(template))
}
+// ---- headless export ----
+
+/** hidden export windows: webContents id -> what the renderer must write */
+const headlessExportTargets = new Map()
+/** settled by 'docs:headless-export-done' (or by the renderer dying) */
+const headlessExportWaiters = new Map void>()
+
+interface HeadlessExportReport {
+ ok: boolean
+ error?: string
+}
+
+/**
+ * Render `input` to `outPath` (as PDF or standalone HTML) with no visible window.
+ *
+ * The window is wired exactly like createDocsWindow's (same preload, sandbox
+ * and `backgroundThrottling: false`) and the document rides the normal
+ * pending-open queue, so the renderer runs its usual load -> paginate ->
+ * export pipeline; only the save dialog is skipped, by pre-authorizing
+ * `outPath` the way a dialog would. Rejects with the renderer's reason when
+ * the export fails or the deadline passes.
+ */
+export async function exportDocsHeadless(
+ input: string,
+ outPath: string,
+ format: HeadlessExportFormat = 'pdf',
+ timeoutMs = 300_000,
+): Promise {
+ const win = new BrowserWindow({
+ show: false,
+ width: 1360,
+ height: 900,
+ webPreferences: {
+ preload: runtime.preloadPath,
+ contextIsolation: true,
+ nodeIntegration: false,
+ sandbox: true,
+ backgroundThrottling: false,
+ },
+ })
+ const wcId = win.webContents.id
+ pendingWindowOpens.set(wcId, input)
+ headlessExportTargets.set(wcId, { outPath, format })
+ allowPdfWrite(wcId, outPath)
+ let timer: ReturnType | undefined
+ try {
+ const report = await new Promise((resolve) => {
+ headlessExportWaiters.set(wcId, resolve)
+ win.webContents.on('render-process-gone', (_event, details) =>
+ resolve({ ok: false, error: `docs renderer stopped (${details.reason})` }),
+ )
+ timer = setTimeout(
+ () => resolve({ ok: false, error: `docs export timed out after ${timeoutMs}ms` }),
+ timeoutMs,
+ )
+ void win.webContents.loadURL(rendererUrl(runtime.rendererUrl, 'docs'))
+ })
+ if (!report.ok) throw new Error(report.error ?? 'docs export failed')
+ } finally {
+ if (timer) clearTimeout(timer)
+ headlessExportWaiters.delete(wcId)
+ headlessExportTargets.delete(wcId)
+ pendingWindowOpens.delete(wcId)
+ if (!win.isDestroyed()) win.destroy()
+ }
+}
+
// ---- window ----
export function createDocsWindow(openPath?: string): BrowserWindow {
@@ -4234,11 +4373,7 @@ export function createDocsWindow(openPath?: string): BrowserWindow {
return { action: 'deny' }
})
- if (runtime.rendererUrl) {
- void win.loadURL(runtime.rendererUrl)
- } else {
- void win.loadFile(runtime.rendererFile)
- }
+ void win.loadURL(rendererUrl(runtime.rendererUrl, 'docs'))
// close guard for standalone-window mode (tab mode goes through the same flow via the shell's tab-manager/window-close path)
let closeConfirmed = false
win.on('close', (event) => {
@@ -4457,14 +4592,7 @@ export function createDocsView(openPath?: string): WebContentsView {
// mode=tab: the shell's tab strip owns the traffic lights / caption buttons,
// so the ribbon must not reserve space for them
- if (runtime.rendererUrl) {
- // append via URL so a dev URL that already carries query params stays valid
- const devUrl = new URL(runtime.rendererUrl)
- devUrl.searchParams.set('mode', 'tab')
- void view.webContents.loadURL(devUrl.toString())
- } else {
- void view.webContents.loadFile(runtime.rendererFile, { query: { mode: 'tab' } })
- }
+ void view.webContents.loadURL(rendererUrl(runtime.rendererUrl, 'docs', { mode: 'tab' }))
// view.webContents becomes undefined after destroy, so grab the id beforehand
const wcId = view.webContents.id
view.webContents.once('destroyed', () => {
@@ -4486,6 +4614,7 @@ export function hasDocsWindow(): boolean {
// ---- standalone lifecycle (apps/docs running on its own) ----
export function startDocsStandalone(): void {
+ registerRendererScheme()
installNavigationGuard(app)
installContextMenu(app, () => contextMenuLabels(getUiLang()))
// dev runs must not share the packaged app's userData (recent files, AI settings)
@@ -4518,6 +4647,7 @@ export function startDocsStandalone(): void {
registerDocsIpc()
app.whenReady().then(() => {
+ installRendererProtocol({ docs: join(__dirname, '../renderer') })
setUiLang(normalizeLang(process.env.GENOFFICE_LANG ?? app.getLocale()))
// packaged builds get the Dock icon from icon.icns; dev shows Electron's default
if (isDev && process.platform === 'darwin') {
diff --git a/apps/docs/src/main/zotero-ipc.ts b/apps/docs/src/main/zotero-ipc.ts
index 5b039e2..c77759d 100644
--- a/apps/docs/src/main/zotero-ipc.ts
+++ b/apps/docs/src/main/zotero-ipc.ts
@@ -13,10 +13,11 @@ let registered = false
function requestRenderer(contents: WebContents, request: ZoteroWireRequest): Promise {
return new Promise((resolve, reject) => {
const requestId = randomUUID()
+ // a displayAlert waits on a modal the user may leave open for a while
const timer = setTimeout(() => {
pending.delete(requestId)
reject(new Error(`Timed out handling ${request.command}`))
- }, 120_000)
+ }, 600_000)
pending.set(requestId, {
webContentsId: contents.id,
resolve: (value) => {
diff --git a/apps/docs/src/main/zotero-wire.ts b/apps/docs/src/main/zotero-wire.ts
index daf17b6..11db32f 100644
--- a/apps/docs/src/main/zotero-wire.ts
+++ b/apps/docs/src/main/zotero-wire.ts
@@ -60,10 +60,17 @@ export class ZoteroWireClient {
private socket: Socket | null = null
private active = false
+ constructor(
+ private readonly host = ZOTERO_INTEGRATION_HOST,
+ private readonly port = ZOTERO_INTEGRATION_PORT,
+ ) {}
+
get isActive(): boolean {
return this.active
}
+ /** Resolves when Zotero has finished the command (it closes the connection after
+ * Document_complete), so callers can keep the document busy for the whole run. */
async run(
command: string,
handleRequest: (request: ZoteroWireRequest) => Promise,
@@ -72,12 +79,10 @@ export class ZoteroWireClient {
this.active = true
const decoder = new ZoteroFrameDecoder()
+ let socket: Socket
try {
- const socket = await new Promise((resolve, reject) => {
- const candidate = createConnection({
- host: ZOTERO_INTEGRATION_HOST,
- port: ZOTERO_INTEGRATION_PORT,
- })
+ socket = await new Promise((resolve, reject) => {
+ const candidate = createConnection({ host: this.host, port: this.port })
const onError = (error: Error) => reject(error)
candidate.once('error', onError)
candidate.once('connect', () => {
@@ -85,7 +90,14 @@ export class ZoteroWireClient {
resolve(candidate)
})
})
- this.socket = socket
+ } catch (error) {
+ this.active = false
+ this.socket = null
+ throw error
+ }
+ this.socket = socket
+ return new Promise((resolve, reject) => {
+ let failure: Error | null = null
socket.on('data', (chunk) => {
let frames: ZoteroWireFrame[]
try {
@@ -96,19 +108,17 @@ export class ZoteroWireClient {
}
for (const frame of frames) void this.respondToFrame(socket, frame, handleRequest)
})
+ socket.once('error', (error) => {
+ failure = error
+ })
socket.once('close', () => {
if (this.socket === socket) this.socket = null
this.active = false
- })
- socket.once('error', () => {
- // Post-connect errors terminate the socket; request failures are returned as ERR frames.
+ if (failure) reject(failure)
+ else resolve()
})
socket.write(encodeZoteroFrame(0, JSON.stringify({ command, templateVersion: 1 })))
- } catch (error) {
- this.active = false
- this.socket = null
- throw error
- }
+ })
}
close(): void {
diff --git a/apps/docs/src/preload/index.ts b/apps/docs/src/preload/index.ts
index 6ccedfe..9a60ad6 100644
--- a/apps/docs/src/preload/index.ts
+++ b/apps/docs/src/preload/index.ts
@@ -57,6 +57,7 @@ const api: DesktopApi = {
respondToZotero: (response) => ipcRenderer.send('zotero:response', response),
openDocx: () => ipcRenderer.invoke('docs:open'),
openDocxPath: (path: string) => ipcRenderer.invoke('docs:open-path', path),
+ convertAltChunkHtml: (html: string) => ipcRenderer.invoke('docs:altchunk-html-to-docx', html),
openDocxDecrypt: (path: string, password: string) =>
ipcRenderer.invoke('docs:open-decrypt', path, password),
setDocPassword: (filePath: string | null, password: string | null) =>
@@ -72,6 +73,9 @@ const api: DesktopApi = {
consumePendingOpenDocx: () => ipcRenderer.invoke('docs:consume-pending-open'),
consumeNewBlankDoc: () => ipcRenderer.invoke('docs:consume-new-blank'),
consumeAiDocContent: () => ipcRenderer.invoke('docs:consume-ai-doc-content'),
+ consumeHeadlessExport: () => ipcRenderer.invoke('docs:consume-headless-export'),
+ headlessExportDone: (result: { ok: boolean; error?: string }) =>
+ ipcRenderer.send('docs:headless-export-done', result),
createDocument: (request) => ipcRenderer.invoke('docs:create-document', request),
onOpenDocx: (handler) => {
const listener = (_event: IpcRendererEvent, result: Parameters[0]) =>
diff --git a/apps/docs/src/renderer/App.tsx b/apps/docs/src/renderer/App.tsx
index 261aeef..77fd549 100644
--- a/apps/docs/src/renderer/App.tsx
+++ b/apps/docs/src/renderer/App.tsx
@@ -1,4 +1,5 @@
import { DOC_CSS_COMMITTED_EVENT } from './editor/cjk-punct-shrink'
+import { justifyShrinkPluginKey } from './editor/justify-shrink'
import {
useCallback,
useEffect,
@@ -11,12 +12,35 @@ import {
import type { CSSProperties, MouseEvent as ReactMouseEvent, SetStateAction } 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 { NodeSelection } from '@tiptap/pm/state'
+import { DOMParser as PmDOMParser, type Mark as PmMark, Slice as PmSlice } from '@tiptap/pm/model'
+import { NodeSelection, type Transaction } from '@tiptap/pm/state'
import { Dropdown, useAutoSavePref } from '@genoffice/ui'
import { wordRangeAtCaret } from './editor/comments'
import { markdownPasteHtml } from './editor/markdown-paste'
import { pasteTextSlice, singleCellPasteText } from './editor/paste-text'
+import {
+ imageFilesFromDataTransfer,
+ insertImageFilesAtCoords,
+ isImageFileDrag,
+} from './editor/image-drop'
+import {
+ caretFontSlots,
+ fillMissingRunFonts,
+ isForeignPasteHtml,
+ pushDownWebInlineStyles,
+} from './editor/paste-web-html'
+import {
+ beginForeignPaste,
+ caretParaFormat,
+ caretStyleMark,
+ consumeForeignPaste,
+ defaultPasteMode,
+ lastForeignPasteMode,
+ mergeFormattingFragment,
+ stashPastePayload,
+ takeTextReroute,
+} from './editor/paste-options'
+import { PasteOptionsChip } from './components/PasteOptionsChip'
import {
BLANK_BULLET_NUM_ID,
BLANK_ORDERED_NUM_ID,
@@ -45,6 +69,7 @@ import { AiPanel, AI_REVISION_AUTHOR } from './ai/AiPanel'
import type { AiCommentsAccess, AiHeaderFooterAccess } from './ai/tools'
import { applyHfText, hfEditText } from './editor/hf-text'
import { textColorValue } from './editor/text-color'
+import { textOutlineCssValue } from './editor/text-outline'
import { AiAskPopover } from './components/AiAskPopover'
import { EDIT_QUEUE_MAX, selectionForAnchor, type DocsEditQueueItem } from './ai/edit-queue'
import { addQueueAnchor, clearQueueAnchors, removeQueueAnchors } from './editor/ai-queue-anchors'
@@ -53,6 +78,7 @@ import { CommentsPanel } from './components/CommentsPanel'
import { EquationModal } from './components/EquationModal'
import { HeaderFooterArea } from './components/HeaderFooterArea'
import { PageFootnotes, PageEndnotes } from './components/PageNoteAreas'
+import { noteMarkText, type NoteKind } from './note-format'
import { PaginationPreview } from './components/PaginationPreview'
import { PrintDialog } from './components/PrintDialog'
import {
@@ -70,6 +96,7 @@ import {
measureBlocks,
docGridPitchPt,
type LineAnchor,
+ hfVariantOf,
pageNumbers,
sliceWithLineSplit,
type SliceOutputs,
@@ -80,8 +107,17 @@ import {
pageAt,
singleCutCell,
columnLayoutSpecs,
+ widthPassGate,
+ newWidthPassState,
+ resetWidthPassHistory,
vAlignShiftSpecs,
+ verticalTextSpecs,
+ blockInlineExtraPx,
+ sectionVertical,
+ sectionTopMarginSpecs,
sectionWidthSpecs,
+ paperWidthPx,
+ pageLeftPx,
sectionGridPitchPt,
sectionGridPitchSpecs,
docCharSpacePt,
@@ -107,6 +143,8 @@ import {
alignGapHfStrips,
alignTableGapFills,
clearFloatShifts,
+ floatFlowChangedMeta,
+ insideFloatTable,
setFloatVShifts,
setOversizeClips,
setPageGaps,
@@ -115,11 +153,13 @@ import {
syncCutOverlays,
syncFloatShifts,
syncPageBorders,
+ syncPageSheets,
clampCellBoxTops,
pageBorderStyleOf,
type PageGapSpec,
} from './editor/pagination-gaps'
import { setColumnLayout } from './editor/column-layout'
+import { syncLineNumbers } from './editor/line-numbers'
import {
MARKUP_AREA_W,
clearMarginAnnotations,
@@ -230,6 +270,7 @@ import {
type FileActionContext,
type PendingPdfExport,
} from './file-actions'
+import { runHeadlessDocumentExport } from './headless-export'
import {
allocateListNumId as allocateListNumIdImpl,
continueNumbering as continueNumberingImpl,
@@ -300,16 +341,43 @@ function posFromAnchor(view: Editor['view'], anchor: LineAnchor): number | undef
}
}
-/** Clean pasted Word/web HTML: mso conditional comments, , and unwrapping x
*/
+/** Clean pasted Word/web HTML: mso conditional comments, , and unwrapping x
;
+ * foreign fragments also get block-level font/size/color pushed down onto
+ * spans so whole-paragraph web copies keep their formatting (r181) */
function cleanPastedHtml(html: string): string {
- return unwrapSingleCellTable(
+ const cleaned = unwrapSingleCellTable(
html
.replace(//g, '')
.replace(/[\s\S]*?<\/o:p>/g, '')
.replace(/]*)>\s*]*>([\s\S]*?)<\/p>\s*<\/li>/g, '
$2 '),
)
+ return isForeignPasteHtml(html) ? pushDownWebInlineStyles(cleaned) : cleaned
}
+/** Plain text for a text-mode paste whose clipboard carries no text/plain
+ * flavor (some apps write HTML only) — the fragment's text content with
+ * block boundaries as line breaks. */
+function htmlFallbackText(html: string): string {
+ if (!html) return ''
+ try {
+ const body = new window.DOMParser().parseFromString(html, 'text/html').body
+ for (const block of body.querySelectorAll('p,div,li,tr,h1,h2,h3,h4,h5,h6,br')) {
+ block.after(body.ownerDocument.createTextNode('\n'))
+ }
+ return (body.textContent ?? '').replace(/\n{2,}/g, '\n').trim()
+ } catch {
+ return ''
+ }
+}
+
+// The per-paste foreign-HTML handshake (mode selection, chip payload) lives
+// in editor/paste-options.ts: the paste DOM handler and the ribbon Paste
+// button arm it (the clipboard is parsed BEFORE handlePaste runs, so the
+// mode must be decided when the paste event arrives), transformPasted and
+// the handlePaste lanes consume it. Our own clipboard HTML keeps its exact
+// run marks, plain-text pastes go through pasteTextSlice, and drops never
+// arm anything.
+
/**
* Word parity: pasting a copy of a SINGLE spreadsheet cell inserts its
* content as text, not a 1x1 table (alpha ledger r146 — a lone cell copied
@@ -365,10 +433,14 @@ function blockNoteScanRuns(b: Block): NonNullable {
}
/** Note entry content: superscript number + styled runs (shared by the canvas gap area and the hidden height measurer) */
-function appendNoteRuns(row: HTMLElement, it: Omit): void {
+function appendNoteRuns(
+ row: HTMLElement,
+ it: Omit,
+ kind: NoteKind,
+): void {
if (!it.noRefMark) {
const sup = document.createElement('sup')
- sup.textContent = String(it.no)
+ sup.textContent = noteMarkText(kind, it.no)
row.append(sup)
}
if (it.richParas) {
@@ -388,6 +460,7 @@ function appendNoteRuns(row: HTMLElement, it: Omit,
+ kind: NoteKind,
widthPx: number,
lineHeightPx: number,
fontSizePt: number,
@@ -426,7 +500,7 @@ function measureNoteHeightDom(
noteMeasureHost.style.fontSize = `${fontSizePt}pt`
noteMeasureHost.style.lineHeight = `${lineHeightPx}px`
const row = document.createElement('div')
- appendNoteRuns(row, entry)
+ appendNoteRuns(row, entry, kind)
// the renderers' sup style (CSS classes don't reach the detached host)
const sup = row.querySelector('sup')
if (sup) {
@@ -451,6 +525,9 @@ function makeGapNotesEl(
const wrap = document.createElement('div')
wrap.className = 'page-gap-notes'
wrap.style.left = `${leftPx}px`
+ // paper x: block gaps start at the paper edge, mid-paragraph gaps at their page's
+ // edge — alignGapHfStrips re-anchors from the actual gap origin
+ wrap.dataset.paperX = leftPx.toFixed(1)
wrap.style.width = `${widthPx}px`
wrap.style.height = `${heightPx}px`
// same line height as the reservation model; min-height keeps rows at the
@@ -465,7 +542,7 @@ function makeGapNotesEl(
if (it.lineHeightPx) row.style.lineHeight = `${it.lineHeightPx}px`
if (it.fontSizePt) row.style.fontSize = `${it.fontSizePt}pt`
if (it.fontFamily) row.style.fontFamily = it.fontFamily
- appendNoteRuns(row, it)
+ appendNoteRuns(row, it, 'footnote')
row.addEventListener('dblclick', () => onEdit(it.id))
wrap.appendChild(row)
}
@@ -707,6 +784,7 @@ export function App() {
const [showPagePreview, setShowPagePreview] = useState(false)
const [splitHtml, setSplitHtml] = useState('')
const [showFind, setShowFind] = useState(false)
+ const [imageDragOver, setImageDragOver] = useState(false)
const [findFocusReplace, setFindFocusReplace] = useState(0)
const [showShortcuts, setShowShortcuts] = useState(false)
const ribbonActionsRef = useRef<{
@@ -859,12 +937,79 @@ export function App() {
// plain-text paste takes the insertion point's formatting like typing
// (Word Keep Text Only) — the default parser misses storedMarks (r172)
clipboardTextParser: (text, $context, _plain, view) => pasteTextSlice(text, $context, view),
+ handleDOMEvents: {
+ paste: (_view, event) => {
+ const html = event.clipboardData?.getData('text/html') ?? ''
+ const armed = beginForeignPaste(html)
+ stashPastePayload(
+ armed
+ ? {
+ html,
+ text: event.clipboardData?.getData('text/plain') ?? '',
+ mode: defaultPasteMode(),
+ }
+ : null,
+ )
+ return false
+ },
+ },
+ // foreign-HTML paste, by the armed mode: 'source' fills runs that still
+ // have no concrete font after the parse (generic-only family chains
+ // like `sans-serif`) with the insertion point's font slots (r181);
+ // 'merge' formats the whole fragment like typing at the insertion
+ // point, keeping emphasis and structure; 'text' passes through — the
+ // handlePaste reroute below sends it down the plain-text lane
+ transformPasted: (slice, view) => {
+ const mode = consumeForeignPaste()
+ if (!mode || mode === 'text') return slice
+ const schema = view.state.schema
+ const markType = schema.marks.docTextStyle
+ if (!markType) return slice
+ const marks = view.state.storedMarks ?? view.state.selection.$from.marks()
+ if (mode === 'merge') {
+ return new PmSlice(
+ mergeFormattingFragment(
+ slice.content,
+ schema,
+ caretStyleMark(marks, schema),
+ caretParaFormat(view.state.selection.$from, schema),
+ ),
+ slice.openStart,
+ slice.openEnd,
+ )
+ }
+ const slots = caretFontSlots(marks, markType)
+ if (!slots) return slice
+ return new PmSlice(
+ fillMissingRunFonts(slice.content, slots, schema),
+ slice.openStart,
+ slice.openEnd,
+ )
+ },
+ // image files dragged from the OS (or a browser) land as inline pictures
+ // at the drop point, like Word; other drops keep the default handling
+ handleDrop: (_view, event) => {
+ const ed = editorRef.current
+ const files = imageFilesFromDataTransfer(event.dataTransfer)
+ if (!ed || files.length === 0) return false
+ return insertImageFilesAtCoords(ed, files, { left: event.clientX, top: event.clientY })
+ },
// clipboard images (screenshots/copied images): become inline images; mixed content
// with HTML still uses default parsing (text in the HTML takes priority)
handlePaste: (view, event) => {
const data = event.clipboardData
if (!data) return false
const html = data.getData('text/html')
+ // text-mode foreign paste (default setting or chip choice): the whole
+ // payload goes down the plain-text lane, formatting like typing
+ if (takeTextReroute()) {
+ const plain = data.getData('text/plain') || htmlFallbackText(html)
+ if (plain) {
+ const slice = pasteTextSlice(plain, view.state.selection.$from, view)
+ view.dispatch(view.state.tr.replaceSelection(slice).scrollIntoView())
+ return true
+ }
+ }
// a lone unformatted spreadsheet cell is a text paste (the r146 unwrap
// turns it into text) and takes the insertion point's formatting like
// typing (r172) — the HTML lanes below keep no marks for it and would
@@ -917,9 +1062,28 @@ export function App() {
const dom = new window.DOMParser().parseFromString(cleanPastedHtml(html), 'text/html')
const parsed = PmDOMParser.fromSchema(view.state.schema).parse(dom.body)
if (parsed.content.childCount > 0) {
- view.dispatch(
- view.state.tr.replaceWith($from.before(1), $from.after(1), parsed.content),
- )
+ // this lane re-parses and dispatches itself, bypassing
+ // transformPasted — apply the armed paste mode to foreign
+ // fragments here too (r181; the empty paragraph's pilcrow
+ // memory lives in storedMarks, caret-marks.ts)
+ let content = parsed.content
+ if (isForeignPasteHtml(html)) {
+ const schema = view.state.schema
+ const markType = schema.marks.docTextStyle
+ const marks = view.state.storedMarks ?? $from.marks()
+ if (lastForeignPasteMode() === 'merge') {
+ content = mergeFormattingFragment(
+ content,
+ schema,
+ caretStyleMark(marks, schema),
+ caretParaFormat($from, schema),
+ )
+ } else {
+ const slots = markType ? caretFontSlots(marks, markType) : null
+ if (slots) content = fillMissingRunFonts(content, slots, schema)
+ }
+ }
+ view.dispatch(view.state.tr.replaceWith($from.before(1), $from.after(1), content))
return true
}
} catch {
@@ -1049,7 +1213,7 @@ export function App() {
},
})
// Blink only respells an editable as a consequence of real (trusted)
- // typing of a word-committing character inside it. The r168 retest ruled
+ // typing of a word-committing character inside it. A retest ruled
// everything else out pixel by pixel: attribute flips, focus cycles (the
// first attempt at this fix), script or execCommand edits, fresh DOM
// nodes, session spellchecker kicks, synthetic clicks and arrow keys —
@@ -1069,6 +1233,20 @@ export function App() {
respellKickBusy.current = true
const sub = getActiveSubEditor()
const prev = document.activeElement as HTMLElement | null
+ // the caret can sit pages away from the viewport (last edit position);
+ // focusing and typing there scrolls it into view and the toggle
+ // "jumps to another page". Pin the scroller
+ // for the whole round trip: the reset runs inside the scroll event,
+ // before paint, so no jump ever shows.
+ const scroller = scrollContainerRef.current
+ const pinTop = scroller?.scrollTop ?? 0
+ const pinLeft = scroller?.scrollLeft ?? 0
+ const pinScroll = () => {
+ if (!scroller) return
+ if (scroller.scrollTop !== pinTop) scroller.scrollTop = pinTop
+ if (scroller.scrollLeft !== pinLeft) scroller.scrollLeft = pinLeft
+ }
+ scroller?.addEventListener('scroll', pinScroll, true)
view.focus() // puts the DOM caret where the state says it is
const sel = window.getSelection()
// typing over a range would replace it — kick from a caret instead;
@@ -1080,8 +1258,21 @@ export function App() {
const caretText = caretNode instanceof Text ? caretNode : null
const caretData = caretText?.data ?? null
let sawKick = false
+ let kickDown = false
+ let kickPress = false
+ // shield: PM's keymap must not see the kick, and the user's own keys
+ // must not mutate the DOM while the observer is paused (the dwell
+ // below makes that window user-noticeable on Windows) — swallow them.
+ // Exactly one space keydown and the keypress it produces pass (the
+ // kick); a later user space would land behind PM's back too
const shield = (e: KeyboardEvent) => {
- if (e.key === ' ') sawKick = true
+ let pass = false
+ if (e.key === ' ') {
+ if (e.type === 'keydown' && !kickDown) pass = kickDown = true
+ else if (e.type === 'keypress' && !kickPress) pass = kickPress = true
+ }
+ if (pass) sawKick = true
+ else e.preventDefault()
e.stopPropagation()
}
document.addEventListener('keydown', shield, true)
@@ -1126,6 +1317,15 @@ export function App() {
while (!sawKick && Date.now() < deadline) {
await new Promise((r) => setTimeout(r, 30))
}
+ // Linux/mac Hunspell respells in the keystroke's wake; the Windows
+ // OS spellchecker samples the text asynchronously with throttling,
+ // and a scrub 0.12s after the keystroke erased the mutation before
+ // the service ever saw it (squiggles only
+ // returned when repeated toggles happened to straddle a sampling
+ // window). Let the typed state live long enough to be sampled.
+ if (sawKick && /win/i.test(navigator.platform)) {
+ await new Promise((r) => setTimeout(r, 900))
+ }
scrub()
observer.start()
document.removeEventListener('keydown', shield, true)
@@ -1134,9 +1334,13 @@ export function App() {
view.focus() // resync the DOM selection from PM state
// ribbon toggle during textbox editing: keep the routing and hand
// the keyboard back where it was — typing must not replace the box
- if (!sub) return
- setActiveSubEditor(sub)
- if (prev && prev !== dom) prev.focus({ preventScroll: true })
+ if (sub) {
+ setActiveSubEditor(sub)
+ if (prev && prev !== dom) prev.focus({ preventScroll: true })
+ }
+ // unpin after the focus resync so its selection scroll is caught too
+ pinScroll()
+ scroller?.removeEventListener('scroll', pinScroll, true)
})
})
}
@@ -1245,6 +1449,14 @@ export function App() {
storage.enabled = trackChanges
}, [editor, trackChanges])
+ // forms protection locks the body but the form's own checkboxes stay
+ // clickable; Read Mode and a still-loading document keep them read-only
+ useEffect(() => {
+ if (!editor) return
+ editor.storage.checkboxToggle.formsFill =
+ !writeLocked && editRestriction === 'forms' && !readMode && !docLoading
+ }, [editor, writeLocked, editRestriction, readMode, docLoading])
+
// window title follows the document, so the OS window list and Switch Window show file names
useEffect(() => {
document.title = doc ? doc.fileName : 'GenOffice Docs'
@@ -1904,6 +2116,31 @@ export function App() {
setShowPagePreview(true)
}, [exportPdf])
+ // Headless export mode (--headless-export): this renderer lives in a hidden
+ // window whose only job is to run the File menu's PDF or HTML export against
+ // a path the CLI chose, then report back so the main process can quit.
+ const headlessExportStartedRef = useRef(false)
+ useEffect(() => {
+ if (headlessExportStartedRef.current) return
+ headlessExportStartedRef.current = true
+ void (async () => {
+ const target = await window.desktop.consumeHeadlessExport()
+ if (!target) return
+ const report = await runHeadlessDocumentExport(
+ target.outPath,
+ // A failed open falls back to an untitled blank document (filePath
+ // null); exporting that would hand the CLI a blank PDF and call it
+ // success, so only a document that came from disk counts as ready.
+ () => {
+ const doc = fileCtxRef.current.doc
+ return { opened: typeof doc?.filePath === 'string', failed: doc?.filePath === null }
+ },
+ target.format === 'html' ? exportHtml : exportPdf,
+ )
+ window.desktop.headlessExportDone(report)
+ })()
+ }, [exportPdf, exportHtml])
+
useEffect(() => {
const pending = pendingMixedExportRef.current
if (pending === false) return
@@ -2177,9 +2414,10 @@ export function App() {
fn: NoteInfo | undefined,
no: number,
sec: SectionSettings,
+ kind: NoteKind,
): { height: number; lineHeightPx: number; fontSizePt: number; fontFamily?: string } => {
const contentW = twipsToPx(sec.pageWidth - sec.marginLeft - sec.marginRight)
- const key = `${fn?.id ?? ''}|${no}|${Math.round(contentW)}|${fn?.styleId ?? ''}|${fn?.text ?? ''}`
+ const key = `${kind}|${fn?.id ?? ''}|${no}|${Math.round(contentW)}|${fn?.styleId ?? ''}|${fn?.text ?? ''}`
let v = cache.get(key)
if (!v) {
const style = noteStyleOf(fn)
@@ -2194,6 +2432,7 @@ export function App() {
...(fn?.richParas ? { richParas: fn.richParas } : {}),
...(fn?.noRefMark ? { noRefMark: true as const } : {}),
},
+ kind,
contentW,
lineHeightPx,
fontSizePt,
@@ -2217,12 +2456,21 @@ export function App() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [footnotes, endnotes, noteStyleOf])
- // page-bottom heights (px) reserved for footnote references inside a block, one per reference in run order
+ // display number of a note: the engine's body-order numbering (numStart / eachSect
+ // applied); notes added in this session are not in the map and count by list position
+ const noteNo = useCallback(
+ (kind: 'footnote' | 'endnote', id: string, index: number): number =>
+ doc?.parsed.noteNumbers?.[`${kind}:${id}`] ?? index + 1,
+ [doc],
+ )
+
+ // page-bottom heights (px) reserved for footnote references inside a block, one per
+ // reference in run order, measured with the marker the page will draw
const footnoteBandsOf = useCallback(
(b: Block): Array<{ heightPx: number }> => {
const runs = blockNoteScanRuns(b)
if (runs.length === 0 || footnotes.length === 0) return []
- const noOf = new Map(footnotes.map((f, i) => [f.id, i + 1]))
+ const noOf = new Map(footnotes.map((f, i) => [f.id, noteNo('footnote', f.id, i)]))
const bands: Array<{ heightPx: number }> = []
for (const run of runs) {
if (run.noteRef?.kind !== 'footnote') continue
@@ -2231,13 +2479,13 @@ export function App() {
if (!sec) continue
const fn = footnotes.find((f) => f.id === run.noteRef!.id)
bands.push({
- heightPx: noteRenderInfoOf(fn, noOf.get(run.noteRef!.id) ?? 0, sec).height,
+ heightPx: noteRenderInfoOf(fn, noOf.get(run.noteRef!.id) ?? 0, sec, 'footnote').height,
})
}
// the once-per-page separator is charged by the pagination engine, not per block
return bands
},
- [footnotes, sections, section, noteRenderInfoOf],
+ [footnotes, sections, section, noteRenderInfoOf, noteNo],
)
// typed w:docGrid line pitch (pt) when every section shares one; null = no snapping
@@ -2393,6 +2641,14 @@ export function App() {
[doc, header, footer, sectionHfEdits, titlePg, hfVariants, hfMeasureEpoch],
)
+ // paragraphs without w:pStyle take the default paragraph style's constraints (widowControl off in Normal)
+ const defaultParaStyle = useMemo(
+ () =>
+ doc
+ ? [...doc.parsed.styles.values()].find((s) => s.type === 'paragraph' && s.isDefault)
+ : undefined,
+ [doc],
+ )
// pagination-constraint injection: docxIndex → parse-layer semantics (keepNext/keepLines/widow/table-row flags).
// DOM measurement only has geometry; these constraints decide page cut points (no orphan headings / unbreakable lines / repeated table headers).
const blockMetaOf = useCallback(
@@ -2416,23 +2672,27 @@ export function App() {
...(fnExtra > 0 ? { footnoteExtraPx: fnExtra, footnoteBands: fnBands } : {}),
}
}
- const styleDisplay = b.styleId ? doc?.parsed.styles.get(b.styleId)?.display : undefined
+ const styleDisplay = (b.styleId ? doc?.parsed.styles.get(b.styleId) : defaultParaStyle)
+ ?.display
const keepNext = b.format?.keepNext ?? styleDisplay?.keepNext
const keepLines = b.format?.keepLines ?? styleDisplay?.keepLines
const breakBefore = b.format?.pageBreakBefore ?? styleDisplay?.pageBreakBefore
- const widowOff = b.format?.widowControl === false
+ const widowOff = (b.format?.widowControl ?? styleDisplay?.widowControl) === false
+ const noLineNo = b.format?.suppressLineNumbers ?? styleDisplay?.suppressLineNumbers
const fnBands = footnoteBandsOf(b)
const fnExtra = fnBands.reduce((s, band) => s + band.heightPx, 0)
- if (!keepNext && !keepLines && !breakBefore && !widowOff && fnExtra === 0) return undefined
+ if (!keepNext && !keepLines && !breakBefore && !widowOff && !noLineNo && fnExtra === 0)
+ return undefined
return {
...(keepNext ? { keepNext: true } : {}),
...(keepLines ? { keepLines: true } : {}),
+ ...(noLineNo ? { suppressLineNumbers: true } : {}),
...(breakBefore ? { breakBefore: true } : {}),
...(widowOff ? { widowControl: false as const } : {}),
...(fnExtra > 0 ? { footnoteExtraPx: fnExtra, footnoteBands: fnBands } : {}),
}
},
- [doc, footnoteBandsOf],
+ [doc, defaultParaStyle, footnoteBandsOf],
)
// per-page footnote collection: the page of the referencing block → that page's footnote entries (number/text/estimated height)
@@ -2440,7 +2700,7 @@ export function App() {
(blocks: BlockBox[], slices: PageSlice[]): PageNoteItem[][] => {
const out: PageNoteItem[][] = slices.map(() => [])
if (!doc || footnotes.length === 0 || !section) return out
- const noOf = new Map(footnotes.map((f, i) => [f.id, i + 1]))
+ const noOf = new Map(footnotes.map((f, i) => [f.id, noteNo('footnote', f.id, i)]))
for (const b of blocks) {
if (b.docxIndex === undefined) continue
const pb = doc.parsed.blocks.find((bl) => bl.docxIndex === b.docxIndex)
@@ -2462,7 +2722,7 @@ export function App() {
const page = band
? pageAt(slices, b.top + (b.spaceBeforePx ?? 0) + band.offset + 0.5) - 1
: blockPage
- const info = noteRenderInfoOf(fn, noOf.get(id) ?? 0, sec)
+ const info = noteRenderInfoOf(fn, noOf.get(id) ?? 0, sec, 'footnote')
out[page]?.push({
no: noOf.get(id) ?? 0,
id,
@@ -2478,7 +2738,7 @@ export function App() {
}
return out
},
- [doc, footnotes, sections, section, noteRenderInfoOf],
+ [doc, footnotes, sections, section, noteRenderInfoOf, noteNo],
)
// endnote-area entries (placed together at the document end, shared by pagination preview and page slicing): height measured with the final section's content width
@@ -2486,9 +2746,10 @@ export function App() {
if (!section || endnotes.length === 0) return []
const sec = sections[sections.length - 1]?.settings ?? section
return endnotes.map((n, i) => {
- const info = noteRenderInfoOf(n, i + 1, sec)
+ const no = noteNo('endnote', n.id, i)
+ const info = noteRenderInfoOf(n, no, sec, 'endnote')
return {
- no: i + 1,
+ no,
id: n.id,
text: n.text,
...(n.richParas ? { richParas: n.richParas } : {}),
@@ -2499,7 +2760,7 @@ export function App() {
...(info.fontFamily ? { fontFamily: info.fontFamily } : {}),
}
})
- }, [endnotes, sections, section, noteRenderInfoOf])
+ }, [endnotes, sections, section, noteRenderInfoOf, noteNo])
// canvas column mode:
// - 'uniform': every section shares one equal-width multi-column spec (and is LTR) —
@@ -2514,9 +2775,12 @@ export function App() {
const g0 = sectionColGeom(sections[0])
const uniform =
!sections.some(sectionBidi) &&
- // a same-count nextColumn boundary advances a column — whole-page CSS
- // multicol can't paint that, so such documents go through mixed mode
- !sections.some((s, i) => i > 0 && s.startType === 'nextColumn') &&
+ // a same-count nextColumn boundary advances a column and a continuous one
+ // balances the closed columns mid-page — whole-page CSS multicol can't
+ // paint either, so such documents go through mixed mode
+ !sections.some(
+ (s, i) => i > 0 && (s.startType === 'nextColumn' || s.startType === 'continuous'),
+ ) &&
sections.every((s) => {
const g = sectionColGeom(s)
return (
@@ -2542,6 +2806,8 @@ export function App() {
() => sections.some((s) => s.settings.vAlign === 'center' || s.settings.vAlign === 'bottom'),
[sections],
)
+ // vertical-text sections (verticalTextSpecs) ride the same translate channel
+ const hasVertical = useMemo(() => sections.some((s) => sectionVertical(s.settings)), [sections])
// single-flow measuring state for the columned canvas: uniform mode temporarily drops
// the CSS columns and sets the width to the column width; mixed mode neutralizes the
@@ -2550,7 +2816,7 @@ export function App() {
// column flow (synchronous layout round-trip, no visible flicker)
const measureSingleFlow = useCallback(
function run(pm: HTMLElement, fn: () => T): T {
- if ((colMode === 'none' && !hasVAlign) || viewMode !== 'print') return fn()
+ if ((colMode === 'none' && !hasVAlign && !hasVertical) || viewMode !== 'print') return fn()
pm.classList.add('measuring-columns')
try {
return fn()
@@ -2558,7 +2824,7 @@ export function App() {
pm.classList.remove('measuring-columns')
}
},
- [colMode, hasVAlign, viewMode],
+ [colMode, hasVAlign, hasVertical, viewMode],
)
// column-flow geometry gate: when the canvas column layout is inactive, measure as full-width single flow; the geometry must drop cols to match
@@ -2583,6 +2849,8 @@ export function App() {
const { blocks, totalHeight, sectBreaks } = measureBlocks(pm, origin, factor)
const live = liveSections(sections, blocks, sectBreaks, delSectBreaks)
let s: PageSlice[]
+ // same row-split mode as the canvas pass, or TOC page numbers drift
+ const splitOut: SliceOutputs = { rowSplits: [] }
if (live.length > 0) {
assignSections(blocks, live)
s = sliceWithLineSplit(
@@ -2591,6 +2859,7 @@ export function App() {
totalHeight,
factor,
blockMetaOf,
+ splitOut,
)
} else {
const contentH = twipsToPx(section.pageHeight) - effTopSingle - effBottomSingle
@@ -2608,6 +2877,7 @@ export function App() {
totalHeight,
factor,
blockMetaOf,
+ splitOut,
)
}
return { mBlocks: blocks, slices: s, secs: live }
@@ -2650,12 +2920,17 @@ export function App() {
if (!scroller) return
const factor = zoom / 100
const mTopPx = canvasTop
+ // shared paper = the widest section's page; narrower pages are centered on it
+ const paperWPx = paperWidthPx(sections, sections[0]?.settings ?? section)
+ const pageLeftOf = (set: SectionSettings) => pageLeftPx(set, paperWPx)
+ const mixedPaper = sections.some((s) => pageLeftOf(s.settings) > 0.5)
const contentH = twipsToPx(section.pageHeight) - effTopSingle - effBottomSingle
let slices: PageSlice[] = []
let timer: number | null = null
let suppressSig = ''
let secWidthSig = ''
let charSpaceSig = ''
+ const colWidthPass = newWidthPassState()
const pmEl = () => document.querySelector('.editor-scroll .ProseMirror') as HTMLElement | null
const locate = () => {
const pm = pmEl()
@@ -2667,8 +2942,17 @@ export function App() {
// slices use gapless virtual coordinates; subtract the page-gap height above the midpoint
// (including mid-paragraph inline gaps and repeated-header clone rows, which carry
// page-repeat-header but not page-gap)
+ // page-turn gaps only, like the page frames: a split floating table's
+ // in-table gaps count (they are page turns) while its carry spacer does
+ // not — the two sums agree past the spacer, and inside the float's pages
+ // only the former maps the midpoint onto the page shown there. Its
+ // repeated-header clones are float content (the carry covers only the
+ // gap bands; the continuation's page starts at the gap's bottom)
let gapAbove = 0
- for (const gap of pm.querySelectorAll('.page-gap, .page-repeat-header')) {
+ for (const gap of pm.querySelectorAll(
+ '.page-gap:not(.page-gap-carry), .page-repeat-header',
+ )) {
+ if (gap.classList.contains('page-repeat-header') && insideFloatTable(gap)) continue
const r = gap.getBoundingClientRect()
if (r.top < midScreen) gapAbove += Math.min(r.height, midScreen - r.top)
}
@@ -2681,6 +2965,15 @@ export function App() {
)
}
const remeasure = () => {
+ try {
+ remeasurePass()
+ } finally {
+ // a pass that threw between the add and the pre-setPageGaps remove
+ // must not leave the gap widgets hidden
+ pmEl()?.classList.remove('measuring-natural')
+ }
+ }
+ const remeasurePass = () => {
const pm = pmEl()
if (!pm) return
const tStart = performance.now()
@@ -2689,6 +2982,15 @@ export function App() {
// consecutive anchor-paragraph runs collapse onto their band union before
// measurement (layout-affecting, idempotent)
syncAnchorBands(pm, factor)
+ // natural-flow measuring state: in-paragraph gap widgets force a line break
+ // at the PREVIOUS pass's cut, so measuring with them in layout re-confirms
+ // that cut even after decoration-only reflows (justify space-shrink) moved
+ // the natural wrap points — a justified page-last line then stayed
+ // stretched sparse until an at-boundary edit (r177). Hidden, sampling AND
+ // cut-anchor resolution below see the natural wrap; removed before
+ // setPageGaps so widget building and later display-state reads (strip
+ // alignment, cut overlays, locate) run against the real layout.
+ pm.classList.add('measuring-natural')
// a columned canvas measures + slices in the single-flow measuring state (fillLineBoxes
// also reads the DOM for line sampling, so it must share the state); display-state DOM
// reads like gap positioning happen outside the measuring state
@@ -2696,6 +2998,8 @@ export function App() {
const t0 = performance.now()
const origin = pm.getBoundingClientRect().top + mTopPx * factor
const { blocks, totalHeight, floats, sectBreaks } = measureBlocks(pm, origin, factor)
+ if (hasVertical)
+ for (const b of blocks) if (b.el && !b.floated) b.inlineExtraPx = blockInlineExtraPx(b.el)
tMeasure = performance.now() - t0
// multi-section: assign blocks to sections by docxIndex; each section has its own content height / forced breaks.
// liveSections: when a section-break block is deleted, that section merges into the next in real time (effective before saving)
@@ -2722,7 +3026,16 @@ export function App() {
const flowH = flowWithFloats ?? withEndnotes?.totalHeight ?? totalHeight
const hfHs = secList ? hfHeightsOf(secList) : null
const t1 = performance.now()
- const sliceOut: SliceOutputs = { rowFills: [], floatVShifts: [], oversizeClips: [] }
+ // rowSplits enables the per-cell row split; the canvas only needs the
+ // matching row heights (the preview applies the cell shifts)
+ const sliceOut: SliceOutputs = {
+ rowFills: [],
+ rowSplits: [],
+ floatVShifts: [],
+ floatFlows: [],
+ floatSplits: [],
+ oversizeClips: [],
+ }
const s = secList
? sliceWithLineSplit(
blocks,
@@ -2757,10 +3070,22 @@ export function App() {
floats,
rowFills: sliceOut.rowFills ?? [],
floatVShifts: sliceOut.floatVShifts ?? [],
+ floatFlows: sliceOut.floatFlows ?? [],
+ floatSplits: sliceOut.floatSplits ?? [],
oversizeClips: sliceOut.oversizeClips ?? [],
}
})
- const { blocks, secList, hfHs, floats, rowFills, floatVShifts, oversizeClips } = measured
+ const {
+ blocks,
+ secList,
+ hfHs,
+ floats,
+ rowFills,
+ floatVShifts,
+ floatFlows,
+ floatSplits,
+ oversizeClips,
+ } = measured
slices = measured.s
// document-end footer shows the last page's displayed number, not the physical count
if (slices.length > 0) {
@@ -2808,6 +3133,9 @@ export function App() {
const tGaps0 = performance.now()
if (editor) {
const gaps: PageGapSpec[] = []
+ // in-table gap height per split floating table (its anchor paragraph
+ // skips the same distance to start beside the last portion)
+ const carryGaps = new Map()
const overlayCutAnchors: LineAnchor[] = []
const lineRectsOf = createLineRectsCache()
const gapIds = new Set()
@@ -2831,7 +3159,7 @@ export function App() {
const pageNo = nums[pageIdx]
const split = (imgs?: HfImage[] | null) => ({
images: imgs?.filter((img) => !img.floating),
- floats: imgs?.filter((img) => img.floating) ?? [],
+ floats: imgs?.filter((img) => img.floating && !(watermarkDirty && img.wordArt)) ?? [],
})
if (!secList || secList.length <= 1) {
if (titlePg && pageIdx === 0) {
@@ -2851,12 +3179,7 @@ export function App() {
const pageSlice = slices[pageIdx]
const sec = secList[Math.min(pageSlice.section, secList.length - 1)]
const refs = effRefs![Math.min(pageSlice.section, effRefs!.length - 1)]
- const variant =
- sec.titlePg && firsts[pageIdx]
- ? 'first'
- : evenOddHf && pageNo % 2 === 0
- ? 'even'
- : 'default'
+ const variant = hfVariantOf(sec.titlePg, firsts[pageIdx], evenOddHf, pageNo)
const ov = variant === 'default' ? sectionHfOverride(pageSlice.section, kind) : null
const rId = refs[kind][variant]
return {
@@ -2877,6 +3200,7 @@ export function App() {
marginBottom: effectiveBottomPx(s, hfH.footerPx),
headerDist: twipsToPx(s.headerDist ?? 720),
sectMarginTop: twipsToPx(s.marginTop),
+ paperX: pageLeftOf(s),
}
}
const pageNoTextOf = (pageIdx: number) =>
@@ -2894,7 +3218,7 @@ export function App() {
imgs
.map(
(f) =>
- `${f.dataUrl.length}:${hashStr(f.dataUrl.slice(0, 1024) + f.dataUrl.slice(-1024))}:${f.posXPx ?? f.posH ?? ''}:${f.posYPx ?? f.posV ?? ''}:${f.posHRel ?? ''}${f.posVRel ?? ''}:${f.widthPx ?? ''}x${f.heightPx ?? ''}${f.washout ? ':w' : ''}`,
+ `${f.dataUrl.length}:${hashStr(f.dataUrl.slice(0, 1024) + f.dataUrl.slice(-1024))}:${f.posXPx ?? f.posH ?? ''}:${f.posYPx ?? f.posV ?? ''}:${f.posHRel ?? ''}${f.posVRel ?? ''}:${f.widthPx ?? ''}x${f.heightPx ?? ''}${f.washout ? ':w' : ''}${f.rotationDeg ? `:r${f.rotationDeg}` : ''}${f.wordArt ? `:t${f.wordArt.text}` : ''}`,
)
.join('|')
const visiblePages = visiblePageCount(slices)
@@ -2904,14 +3228,16 @@ export function App() {
? twipsToPx(canvasSet.pageWidth - canvasSet.marginLeft - canvasSet.marginRight)
: 0
const mixedWidths =
- canvasSet != null &&
- (secList ?? []).some(
- (s) =>
- Math.abs(
- twipsToPx(s.settings.pageWidth - s.settings.marginLeft - s.settings.marginRight) -
- canvasContentWPx,
- ) > 0.5,
- )
+ mixedPaper ||
+ (canvasSet != null &&
+ (secList ?? []).some(
+ (s) =>
+ Math.abs(
+ twipsToPx(
+ s.settings.pageWidth - s.settings.marginLeft - s.settings.marginRight,
+ ) - canvasContentWPx,
+ ) > 0.5,
+ ))
// equal-width docs: strip centered, clamped to the canvas paper. Differing-width
// docs: strip gets its section's width and is aligned to the body blocks' left
// edge afterwards by measurement (alignGapHfStrips) — gap-box origins vary per
@@ -2937,7 +3263,12 @@ export function App() {
const stripGeomSig = (set: typeof canvasSet) => {
if (!set) return ''
const b = sectionPageBox(set)
- return [twipsToPx(set.marginLeft), b.contentWidth, b.headerDist, b.footerDist]
+ return [
+ pageLeftOf(set) + twipsToPx(set.marginLeft),
+ b.contentWidth,
+ b.headerDist,
+ b.footerDist,
+ ]
.map((v) => v.toFixed(1))
.join(',')
}
@@ -2969,12 +3300,15 @@ export function App() {
marginBottom: effectiveBottomPx(prevSec, prevHf.footerPx),
marginLeft: twipsToPx(nextSec.marginLeft),
marginRight: twipsToPx(nextSec.marginRight),
- // header/footer strip inset (alignGapHfStrips): survives the inline/
- // in-cell gaps below overriding marginLeft/Right with the host block's
- // paper offset (which folds in paragraph indents and cell positions)
- sectionMarginLeft: twipsToPx(nextSec.marginLeft),
+ // header/footer strip inset on the paper (alignGapHfStrips): survives
+ // the inline/in-cell gaps below overriding marginLeft/Right with the host
+ // block's paper offset (which folds in paragraph indents and cell positions)
+ sectionMarginLeft: pageLeftOf(nextSec) + twipsToPx(nextSec.marginLeft),
sectionMarginRight: twipsToPx(nextSec.marginRight),
sectionMarginTop: twipsToPx(nextSec.marginTop),
+ ...(mixedPaper
+ ? { pageLeft: pageLeftOf(nextSec), pageWidth: twipsToPx(nextSec.pageWidth) }
+ : {}),
}
// a page ended early (explicit break / section break / keepNext) leaves unused
// content height; pad the gap so the canvas paints the full paper height and the
@@ -3020,7 +3354,10 @@ export function App() {
sizeGapHf(el, box)
// the footer belongs to the page ABOVE the gap: its own section's
// left margin, not the next section's (alignGapHfStrips)
- el.style.setProperty('--hf-ml', `${twipsToPx(prevSec.marginLeft)}px`)
+ el.style.setProperty(
+ '--hf-ml',
+ `${pageLeftOf(prevSec) + twipsToPx(prevSec.marginLeft)}px`,
+ )
hfEls.push(el)
}
if (hfHasVisibleContent(gapHeader.value, gapHeader.images)) {
@@ -3042,7 +3379,10 @@ export function App() {
el.style.bottom = 'auto'
el.style.top = `calc(100% - ${metrics.marginTop - headerStripTop}px)`
sizeGapHf(el, box)
- el.style.setProperty('--hf-ml', `${twipsToPx(nextSec.marginLeft)}px`)
+ el.style.setProperty(
+ '--hf-ml',
+ `${pageLeftOf(nextSec) + twipsToPx(nextSec.marginLeft)}px`,
+ )
hfEls.push(el)
}
// next page's floating header images (picture watermarks): behind-text,
@@ -3072,7 +3412,7 @@ export function App() {
)
notes = makeGapNotesEl(
items,
- twipsToPx(prevSec.marginLeft),
+ pageLeftOf(prevSec) + twipsToPx(prevSec.marginLeft),
contentW,
fnH,
footnoteLineHeightPx(prevSec.docGrid),
@@ -3082,7 +3422,18 @@ export function App() {
notesMetrics = { ...metrics, marginBottom: metrics.marginBottom + fnH }
}
const markShown = () => items.forEach((n) => gapIds.add(n.id))
- const i = blocks.findIndex((b) => Math.abs(b.top - slice.start) < 0.5)
+ // split floating table: the boundary is one of its row cuts, so the
+ // page turn is an in-table gap of the float; the anchor paragraph
+ // below it shares that top and must not take a block gap
+ const fsplit = floatSplits.find((f) =>
+ f.cutYs.some((y) => Math.abs(y - slice.start) < 0.5),
+ )
+ const fsBlock = fsplit
+ ? blocks.find(
+ (bb) => bb.el && bb.floatTable && Math.abs(bb.top - fsplit.blockTop) < 0.5,
+ )
+ : undefined
+ const i = fsBlock ? -1 : blocks.findIndex((b) => Math.abs(b.top - slice.start) < 0.5)
if (i >= 0 && blocks[i].el) {
// footnotes sit at the paper bottom (Word): shift past the padding
if (notes && pad > 0) notes.style.top = `${5 + pad}px`
@@ -3104,9 +3455,11 @@ export function App() {
return
}
// mid-paragraph page break (line-level cut point): insert an inline gap at the broken line. In-table cut points are not decorated yet
- const b = blocks.find(
- (bb) => bb.el && bb.top < slice.start && slice.start < bb.top + bb.height - 0.5,
- )
+ const b =
+ fsBlock ??
+ blocks.find(
+ (bb) => bb.el && bb.top < slice.start && slice.start < bb.top + bb.height - 0.5,
+ )
if (!b?.el) {
// deliberate trailing blank page (document ends with a page break): no
// anchor block exists — hang the gap at the document end so the blank
@@ -3127,6 +3480,9 @@ export function App() {
}
return
}
+ // block-relative Y of the cut (a shifted float's rows start at its --tblp-dy)
+ const cutOff =
+ slice.start - b.top - (b.spaceBeforePx ?? 0) - (fsBlock ? fsplit!.dyPx : 0)
if (b.el.querySelector('tr')) {
// in-table cut point: insert an in-table gap row (display:table-row widget)
// before the broken row (next page's first row). Positioning must subtract the
@@ -3146,12 +3502,8 @@ export function App() {
const gapsAbove = gapRects.reduce((s, g) => (g.top <= trTop ? s + g.height : s), 0)
const off = (trTop - elTop - gapsAbove) / factor
// last real row starting at/above the cut = the row the cut falls inside
- if (
- !tr.classList.contains('page-gap') &&
- off <= slice.start - b.top - (b.spaceBeforePx ?? 0) + 0.5
- )
- cutRow = tr
- if (Math.abs(off - (slice.start - b.top - (b.spaceBeforePx ?? 0))) < 1.5) {
+ if (!tr.classList.contains('page-gap') && off <= cutOff + 0.5) cutRow = tr
+ if (Math.abs(off - cutOff) < 1.5) {
matched = true
try {
const $pos = editor.view.state.doc.resolve(editor.view.posAtDOM(tr, 0))
@@ -3221,6 +3573,14 @@ export function App() {
}
: {}),
})
+ if (fsplit) {
+ const gapH =
+ metrics.marginBottom + tablePad + GAP_BAND + metrics.marginTop
+ carryGaps.set(
+ fsplit.blockTop,
+ (carryGaps.get(fsplit.blockTop) ?? 0) + gapH,
+ )
+ }
break
}
}
@@ -3232,12 +3592,7 @@ export function App() {
}
if (!matched) {
// in-row cut point (page break between a cell's lines): anchor at the first line after it
- const anchor = nextLineAnchor(
- b.el,
- slice.start - b.top - (b.spaceBeforePx ?? 0),
- factor,
- lineRectsOf,
- )
+ const anchor = nextLineAnchor(b.el, cutOff, factor, lineRectsOf)
if (anchor == null) return
// anchors inside the read-only nested-table NodeView have no distinct PM
// position (posAtDOM collapses them all to the node start): overlay markers
@@ -3261,8 +3616,8 @@ export function App() {
metrics: {
...metrics,
// rect offsets from the paper edge already include the page margins
- marginLeft: (r.left - pmRect.left) / factor,
- marginRight: (pmRect.right - r.right) / factor,
+ marginLeft: (r.left - pmRect.left) / factor - pageLeftOf(nextSec),
+ marginRight: (pmRect.right - r.right) / factor - pageLeftOf(nextSec),
},
...(pullUp > 0.5 ? { pullUp } : {}),
...hfProps,
@@ -3277,18 +3632,8 @@ export function App() {
// fallback: font-load reflow can leave lineStartAnchor's exact-offset match
// just outside tolerance; the first line after the cut still gets the gap
const anchor =
- lineStartAnchor(
- b.el,
- slice.start - b.top - (b.spaceBeforePx ?? 0),
- factor,
- lineRectsOf,
- ) ??
- nextLineAnchor(
- b.el,
- slice.start - b.top - (b.spaceBeforePx ?? 0),
- factor,
- lineRectsOf,
- )
+ lineStartAnchor(b.el, cutOff, factor, lineRectsOf) ??
+ nextLineAnchor(b.el, cutOff, factor, lineRectsOf)
const pos = anchor ? posFromAnchor(editor.view, anchor) : undefined
if (pos == null) {
console.warn('[pagination] no line anchor at page boundary', slice.start)
@@ -3301,8 +3646,8 @@ export function App() {
boundaryY: slice.start,
metrics: {
...notesMetrics,
- marginLeft: (elRect.left - pmRect.left) / factor,
- marginRight: (pmRect.right - elRect.right) / factor,
+ marginLeft: (elRect.left - pmRect.left) / factor - pageLeftOf(nextSec),
+ marginRight: (pmRect.right - elRect.right) / factor - pageLeftOf(nextSec),
},
...(pullUp > 0.5 ? { pullUp } : {}),
...(notes ? { notes, notesKey } : {}),
@@ -3318,7 +3663,7 @@ export function App() {
const box = floatBoxOf(0)
firstPageFloats = {
els: floats.map((img) => makeHfFloatImgEl(img, box, 'lead')),
- key: `${floatSig(floats)}·${Math.round(box.pageW)}x${Math.round(box.pageH)}·${Math.round(box.marginTop)}·${Math.round(box.sectMarginTop)}`,
+ key: `${floatSig(floats)}·${Math.round(box.pageW)}x${Math.round(box.pageH)}·${Math.round(box.marginTop)}·${Math.round(box.sectMarginTop)}·${Math.round(box.paperX ?? 0)}`,
}
}
}
@@ -3357,7 +3702,7 @@ export function App() {
tGapsBuild = performance.now() - tGaps0
const tSet0 = performance.now()
// split declared-height rows: resolve the engine's target heights to tr elements
- const rowFillEls: Array<{ el: Element; targetPx: number }> = []
+ const rowFillEls: Array<{ el: Element; targetPx: number; extraPx?: number }> = []
for (const f of rowFills) {
const b = blocks.find((bb) => bb.tableRows && Math.abs(bb.top - f.blockTop) < 0.5)
if (!b?.el) continue
@@ -3368,7 +3713,12 @@ export function App() {
!tr.classList.contains('page-repeat-header'),
)
const tr = trs[f.row]
- if (tr) rowFillEls.push({ el: tr, targetPx: f.targetPx })
+ if (tr)
+ rowFillEls.push({
+ el: tr,
+ targetPx: f.targetPx,
+ ...(f.extraPx ? { extraPx: f.extraPx } : {}),
+ })
}
setRowFills(editor.view, rowFillEls)
// oversized single-line blocks: resolve the engine's page-bottom clips to their elements
@@ -3381,20 +3731,53 @@ export function App() {
}
setOversizeClips(editor.view, oversizeEls)
// page/margin-anchored floated tables: resolve the engine's Y shifts to table elements
- const floatVEls: Array<{ el: Element; dyPx: number }> = []
+ const floatVEls: Array<{
+ el: Element
+ dyPx: number
+ flow?: boolean
+ carryPx?: number
+ }> = []
for (const f of floatVShifts) {
const b = blocks.find(
(bb) => bb.pageRelVyPx !== undefined && Math.abs(bb.top - f.blockTop) < 0.5,
)
if (b?.el) floatVEls.push({ el: b.el, dyPx: f.dyPx })
}
+ for (const f of floatFlows) {
+ const b = blocks.find((bb) => bb.floatTable && Math.abs(bb.top - f.blockTop) < 0.5)
+ if (b?.el) floatVEls.push({ el: b.el, dyPx: 0, flow: true })
+ }
+ // split floating table: its anchor paragraph (the next block) starts
+ // beside the last portion — a flow spacer carries it past the earlier
+ // portions, a gap-sized spacer past the table's in-table gaps
+ for (const f of floatSplits) {
+ const bi = blocks.findIndex(
+ (bb) => bb.el && bb.floatTable && Math.abs(bb.top - f.blockTop) < 0.5,
+ )
+ const anchor = bi >= 0 ? blocks[bi + 1] : undefined
+ if (!anchor?.el || anchor.floated) continue
+ const carry = f.blockTop + f.carryPx - (anchor.top - (anchor.carryAppliedPx ?? 0))
+ if (carry > 0.5) floatVEls.push({ el: anchor.el, dyPx: 0, carryPx: carry })
+ const gapPx = carryGaps.get(f.blockTop) ?? 0
+ if (gapPx > 0.5)
+ gaps.push({
+ el: anchor.el,
+ carryPx: gapPx,
+ metrics: { marginTop: 0, marginBottom: 0, marginLeft: 0, marginRight: 0 },
+ })
+ }
setFloatVShifts(editor.view, floatVEls)
+ pm.classList.remove('measuring-natural')
setPageGaps(editor.view, gaps, firstPageFloats)
// mixed-column canvas: paint the engine's regions via per-block width/translate decorations
const colSpecs =
viewMode === 'print' && !readMode && colMode === 'mixed' && secList
? columnLayoutSpecs(blocks, slices, secList)
: []
+ // unequal columns: a block's width follows the column it lands in,
+ // which follows its measured height — one more pass per change, and a
+ // block ping-ponging between columns is pinned to its narrower width
+ const colGranted = widthPassGate(colWidthPass, colSpecs)
// sectPr w:vAlign pages ride the same visual-translate channel
const vaSpecs =
viewMode === 'print' && !readMode && secList && hfHs
@@ -3403,7 +3786,7 @@ export function App() {
// sections whose content width differs from the canvas section: per-block wrap widths
const secWSpecs =
viewMode === 'print' && !readMode && secList && hfHs
- ? sectionWidthSpecs(blocks, secList, sectionGeoms(secList, hfHs))
+ ? sectionWidthSpecs(blocks, secList, sectionGeoms(secList, hfHs), paperWPx)
: []
// sections disagreeing on the typed docGrid pitch: per-block pitch vars
const gridSpecs =
@@ -3411,10 +3794,24 @@ export function App() {
// sections disagreeing on the docGrid charSpace delta: per-block letter-spacing vars
const charSpecs =
viewMode === 'print' && !readMode && secList ? sectionCharSpaceSpecs(blocks, secList) : []
+ // sections disagreeing on the top margin: per-block --doc-margin-top for page-relative anchors
+ const topSpecs =
+ viewMode === 'print' && !readMode && secList ? sectionTopMarginSpecs(blocks, secList) : []
+ // sectPr w:textDirection sections: writing-mode boxes placed sideways (width wins)
+ const vertSpecs =
+ viewMode === 'print' && !readMode && secList && hfHs
+ ? verticalTextSpecs(blocks, slices, secList, sectionGeoms(secList, hfHs))
+ : []
// one spec per block: mixed-column placement wins the width, translates add up
- const specLists = [gridSpecs, charSpecs, secWSpecs, colSpecs, vaSpecs].filter(
- (l) => l.length > 0,
- )
+ const specLists = [
+ gridSpecs,
+ charSpecs,
+ topSpecs,
+ secWSpecs,
+ colSpecs,
+ vaSpecs,
+ vertSpecs,
+ ].filter((l) => l.length > 0)
let layoutSpecs = specLists.flat()
if (specLists.length > 1) {
const mergedSpecs = new Map()
@@ -3433,7 +3830,7 @@ export function App() {
alignTableGapFills(pm, factor)
if (secWSpecs.length > 0 && section) {
const cSet = secList?.[0]?.settings ?? section
- alignGapHfStrips(pm, twipsToPx(cSet.marginLeft), factor)
+ alignGapHfStrips(pm, pageLeftOf(cSet) + twipsToPx(cSet.marginLeft), factor)
}
// after setPageGaps: widget insertion is synchronous, so anchor rects are final
syncFloatShifts(
@@ -3452,7 +3849,18 @@ export function App() {
// exclude pages; the border must not run through the page gaps)
const pbSec = secList?.[0]?.settings ?? section
const borderStyle = pbSec ? pageBorderStyleOf(pbSec) : null
- syncPageBorders((pm.closest('.page-wrap') as HTMLElement) ?? pm, borderStyle, factor)
+ const wrapEl = (pm.closest('.page-wrap') as HTMLElement) ?? pm
+ const firstFrame = pbSec
+ ? { left: pageLeftOf(pbSec), width: twipsToPx(pbSec.pageWidth) }
+ : undefined
+ syncPageBorders(wrapEl, borderStyle, factor, firstFrame)
+ syncLineNumbers(wrapEl, pm, blocks, secList ?? [], factor, blockMetaOf, firstFrame)
+ // differing-width documents paint one sheet per page (the shared paper is transparent)
+ syncPageSheets(
+ wrapEl,
+ factor,
+ mixedPaper && viewMode === 'print' && !readMode ? (firstFrame ?? null) : null,
+ )
}
syncMarginAnnotations(
(pm.closest('.page-wrap') as HTMLElement) ?? pm,
@@ -3469,14 +3877,16 @@ export function App() {
suppressSig = sig
onUpdate()
}
- // freshly applied wrap widths change line breaks: one follow-up remeasure with them in the DOM
- const wSig = secWSpecs
+ // freshly applied wrap widths (section widths, unequal column widths,
+ // vertical-text line lengths) change line breaks: one follow-up remeasure with them in the DOM
+ const wSig = [...secWSpecs, ...colSpecs, ...vertSpecs]
.map((s) => `${Math.round(s.widthPx ?? -1)}:${Math.round(s.contentWPx ?? -1)}`)
.join(',')
if (wSig !== secWidthSig) {
secWidthSig = wSig
onUpdate()
}
+ if (colGranted) onUpdate()
// freshly applied per-block letter-spacing changes line breaks the same way
const cSig =
charSpecs.length === 0
@@ -3488,7 +3898,7 @@ export function App() {
}
// the last page paints as a full sheet like the ones above it:
// extend the canvas to that page's paper bottom, measured from the last gap
- const gapEls = pm.querySelectorAll('.page-gap')
+ const gapEls = pm.querySelectorAll('.page-gap:not(.page-gap-carry)')
const lastGapEl = gapEls[gapEls.length - 1]
if (lastGapEl && slices.length > 1) {
const last = slices[slices.length - 1]
@@ -3595,13 +4005,31 @@ export function App() {
const onLoadingDone = () => onFontsChanged(true)
document.fonts.addEventListener('loadingdone', onLoadingDone)
scroller.addEventListener('scroll', locate, { passive: true })
- editor?.on('update', onUpdate)
+ const onDocUpdate = () => {
+ resetWidthPassHistory(colWidthPass)
+ onUpdate()
+ }
+ editor?.on('update', onDocUpdate)
+ // justify-shrink re-decides via decoration-only transactions that move the
+ // wrap points of justified paragraphs; tiptap 'update' fires only on doc
+ // changes, so without this the inline gap widgets keep their pre-shrink cut
+ // positions and force a stretched-sparse page-last line (r177). The stale
+ // block re-samples via the shrink fingerprint in lineSampleSig.
+ const onShrinkTr = (props: { transaction: Transaction }) => {
+ if (
+ props.transaction.getMeta(justifyShrinkPluginKey) ||
+ props.transaction.getMeta(floatFlowChangedMeta)
+ )
+ onUpdate()
+ }
+ editor?.on('transaction', onShrinkTr)
return () => {
if (timer) window.clearTimeout(timer)
if (hfTimer) window.clearTimeout(hfTimer)
document.fonts.removeEventListener('loadingdone', onLoadingDone)
scroller.removeEventListener('scroll', locate)
- editor?.off('update', onUpdate)
+ editor?.off('update', onDocUpdate)
+ editor?.off('transaction', onShrinkTr)
}
}, [
doc,
@@ -4584,10 +5012,12 @@ export function App() {
// canvas geometry is anchored to the first section (stable across cursor moves);
// sections with a different content width carry per-block width decorations
// the shared paper must cover the widest section or its content lays out past
- // the paper edge onto the editor background (a white band down the right side)
- const paperW = canvasBox
- ? Math.max(canvasBox.width, ...sections.map((s) => twipsToPx(s.settings.pageWidth)))
- : 0
+ // the paper edge onto the editor background (a white band down the right side);
+ // narrower pages are centered on it (pageLeftPx) and paint their own sheets
+ const paperW = canvasBox ? paperWidthPx(sections, canvasSection) : 0
+ const pageLeftOf = (set: SectionSettings) => pageLeftPx(set, paperW)
+ const mixedPaper =
+ viewMode === 'print' && !readMode && sections.some((s) => pageLeftOf(s.settings) > 0.5)
// the trailing footer strip belongs to the LAST page, which is always in the
// last section; on differing-width docs the stylesheet centering (50% of the
// first-section paper) puts it at the wrong x, so pin it to its own section
@@ -4602,7 +5032,7 @@ export function App() {
(paperW - lastBox.width > 0.5 || Math.abs(lastBox.contentWidth - canvasBox.contentWidth) > 0.5)
? {
width: `${lastBox.contentWidth}px`,
- left: `${twipsToPx(lastSection!.marginLeft)}px`,
+ left: `${pageLeftOf(lastSection!) + twipsToPx(lastSection!.marginLeft)}px`,
transform: 'none',
bottom: `${lastBox.footerDist}px`,
}
@@ -4613,7 +5043,7 @@ export function App() {
canvasBox && canvasSection && paperW - canvasBox.width > 0.5
? {
width: `${canvasBox.contentWidth}px`,
- left: `${twipsToPx(canvasSection.marginLeft)}px`,
+ left: `${pageLeftOf(canvasSection) + twipsToPx(canvasSection.marginLeft)}px`,
transform: 'none',
}
: undefined
@@ -4629,6 +5059,9 @@ export function App() {
'--footer-dist': canvasBox ? `${canvasBox.footerDist}px` : undefined,
'--page-bg': pageColor ? `#${pageColor}` : undefined,
'--page-cols': colFlow && viewMode === 'print' ? colFlow.cols : undefined,
+ // end-of-document footnote area sits on the last page's sheet
+ '--last-page-w': mixedPaper && lastBox ? `${lastBox.width}px` : undefined,
+ '--last-page-x': mixedPaper && lastSection ? `${pageLeftOf(lastSection)}px` : undefined,
} as CSSProperties
// page-dark: dark paper + remapped colors (styles.css @media screen block); a
@@ -4668,7 +5101,7 @@ export function App() {
)}
{doc && section && (
// over-wide tables may spill into the margins (Word/LO), capped at the paper edge
-
+
)}
{/* Theme CSS comes from live state, so a Design ▸ Themes/Fonts/Colors pick shows
on the page immediately instead of only in the saved file */}
@@ -4706,6 +5139,9 @@ export function App() {
inkHighlighter={inkHighlighter}
inkCount={inkAnnotations.length}
sources={sources}
+ zoteroNoteFields={
+ footnotes.some((note) => note.zoteroField) || endnotes.some((note) => note.zoteroField)
+ }
zoom={Math.round(zoom)}
darkPage={darkPage}
tabRequest={ribbonTabRequest}
@@ -4792,9 +5228,10 @@ export function App() {
onQueueRemove={queueRemove}
/>
)}
+ {doc && }
{
scrollPosRef.current = {
@@ -4802,6 +5239,28 @@ export function App() {
top: e.currentTarget.scrollTop,
}
}}
+ onDragOver={(e) => {
+ if (!editor?.isEditable || !isImageFileDrag(e.dataTransfer)) return
+ e.preventDefault()
+ if (!imageDragOver) setImageDragOver(true)
+ }}
+ onDragLeave={(e) => {
+ const next = e.relatedTarget as Node | null
+ if (!next || !e.currentTarget.contains(next)) setImageDragOver(false)
+ }}
+ onDrop={(e) => {
+ setImageDragOver(false)
+ const files = imageFilesFromDataTransfer(e.dataTransfer)
+ if (files.length === 0) return
+ // a drop the editor's own handler did not take (read-only
+ // islands, the page margin) still must not navigate the window
+ const handledByEditor = e.isDefaultPrevented()
+ e.preventDefault()
+ if (handledByEditor || !editor) return
+ if (editor.view.dom.contains(e.target as Node)) {
+ insertImageFilesAtCoords(editor, files, { left: e.clientX, top: e.clientY })
+ }
+ }}
>
{doc ? (
)}
-
- {watermark && (
+
+ {watermark && watermarkDirty && (
{watermark}
@@ -4898,12 +5357,14 @@ export function App() {
noteNo('footnote', n.id, i)}
onEdit={(id) => editNote('footnote', id)}
onDelete={(id) => deleteNote('footnote', id)}
/>
noteNo('endnote', n.id, i)}
onEdit={(id) => editNote('endnote', id)}
onDelete={(id) => deleteNote('endnote', id)}
/>
@@ -5146,8 +5607,10 @@ export function App() {
},
}}
watermark={watermark}
+ watermarkDirty={watermarkDirty}
blockMetaOf={blockMetaOf}
pageFootnotesOf={pageFootnotesOf}
+ footnotesBeneathText={doc.parsed.footnoteProps?.pos === 'beneathText'}
endnoteItems={endnoteItems}
sectionHfOverride={sectionHfOverride}
comments={comments}
@@ -5163,6 +5626,8 @@ export function App() {
if (wrap) {
syncCutOverlays(wrap as HTMLElement, [], 1)
syncPageBorders(wrap as HTMLElement, null, 1)
+ syncLineNumbers(wrap as HTMLElement, wrap as HTMLElement, [], [], 1)
+ syncPageSheets(wrap as HTMLElement, 1, null)
clearMarginAnnotations(wrap as HTMLElement)
clearFloatShifts(wrap as HTMLElement)
}
diff --git a/apps/docs/src/renderer/ai/AiPanel.tsx b/apps/docs/src/renderer/ai/AiPanel.tsx
index 75482b1..6a04e6e 100644
--- a/apps/docs/src/renderer/ai/AiPanel.tsx
+++ b/apps/docs/src/renderer/ai/AiPanel.tsx
@@ -1,7 +1,7 @@
import { useEffect, useRef, useState } from 'react'
import type { Editor } from '@tiptap/core'
import type { Block } from '@genoffice/docx-engine'
-import { AgentLoop, composeSkills, type AgentImage } from '@genoffice/agent-core'
+import { AgentLoop, composeSkills, streamText, type AgentImage } from '@genoffice/agent-core'
import { imageGenerationAvailable } from '@genoffice/ai-provider/browser'
import type { AiSettings, AttachmentAddResult, AttachmentMeta } from '../../shared/ipc'
import { ATTACHMENT_IMAGE_EXTS } from '../../shared/ipc'
@@ -11,6 +11,14 @@ import { countWords, findNumId, type NumIds } from './protocol'
import { DOC_NAV_SCHEME, navigateToBlock, parseDocNavHref } from './doc-nav'
import { markDocSeen, type AiCommentsAccess, type AiHeaderFooterAccess } from './tools'
import { createDocsSkill } from './docs-skill'
+import {
+ buildDocWriterRequest,
+ countFragmentBlocks,
+ DOC_MAX_CHARS,
+ extractFragment,
+ type DocWriteResult,
+ type DocWriteSpec,
+} from './doc-writer'
import { EditQueueCard } from './EditQueueCard'
import {
buildQueueInstruction,
@@ -58,6 +66,9 @@ interface ToolActivity {
/** Max characters of tool output in the UI expansion panel */
const TOOL_OUTPUT_MAX_CHARS = 2000
+/** progress chip refresh while a write streams */
+const CHIP_UPDATE_MS = 400
+
/** Cap on tool args/output persisted in the transcript (the store layer has another 16k truncation fallback) */
const PERSIST_TOOL_FIELD_MAX = 16_000
@@ -325,6 +336,11 @@ export function AiPanel({
/** a send waiting on a phased open's tail; Stop / New chat abort it before it runs */
const pendingSendRef = useRef<{ aborted: boolean } | null>(null)
const [chat, setChat] = useState([])
+ /** a streamed write stopped early: the draft stays in the document until the user keeps or discards it */
+ const [activePartial, setActivePartial] = useState<{ blocks: number } | null>(null)
+ const partialResolverRef = useRef<((keep: boolean) => void) | null>(null)
+ /** bumped by New chat / unmount: a writer resuming after its abort must not open the keep card */
+ const writerEpochRef = useRef(0)
/** Past conversation restored from JSONL (read-only transcript, not fed to the model) */
const [historicChat, setHistoricChat] = useState([])
const [trackChanges, setTrackChanges] = useState(
@@ -415,6 +431,15 @@ export function AiPanel({
window.addEventListener('resize', onResize)
return () => window.removeEventListener('resize', onResize)
}, [])
+ // a pending keep/discard must not outlive the panel: settle it as discard
+ useEffect(
+ () => () => {
+ writerEpochRef.current++
+ partialResolverRef.current?.(false)
+ partialResolverRef.current = null
+ },
+ [],
+ )
// bumped on selection/doc changes so the scope hint & quick actions stay fresh
const [, setScopeTick] = useState(0)
/** the scope chip's expandable preview of the selected text */
@@ -617,6 +642,83 @@ export function AiPanel({
})
}
+ const transportRef = useRef | null>(null)
+ if (!transportRef.current)
+ transportRef.current = createElectronTransport(() => settingsRef.current)
+
+ /**
+ * Long-form writing: one tool-less request whose reply is the fragment, streamed
+ * into the document as a draft by the tool. A stream that stops early leaves the
+ * user a keep-or-discard choice; a stream that produced nothing is retried once.
+ */
+ const runDocWriter = async (
+ spec: DocWriteSpec,
+ onProgress: (html: string) => void,
+ signal?: AbortSignal,
+ ): Promise => {
+ const { system, user } = buildDocWriterRequest(spec, aiLangDirective())
+ const epoch = writerEpochRef.current
+ let closed = false
+ let chipTimer: ReturnType | null = null
+ let latest = ''
+ const updateChip = () => {
+ chipTimer = null
+ if (closed) return
+ const blocks = countFragmentBlocks(latest)
+ patchLastAssistant((last) => ({
+ tools: last.tools?.map((tl) =>
+ tl.running ? { ...tl, summary: tModule('aiWritingDocument', { blocks }) } : tl,
+ ),
+ }))
+ }
+ const attempt = () =>
+ streamText({
+ transport: transportRef.current!,
+ system,
+ user,
+ signal,
+ maxChars: DOC_MAX_CHARS,
+ extract: (raw) => ({ text: extractFragment(raw) }),
+ onProgress: (html) => {
+ if (closed) return
+ latest = html
+ onProgress(html)
+ if (chipTimer === null) chipTimer = setTimeout(updateChip, CHIP_UPDATE_MS)
+ },
+ })
+ let outcome = await attempt()
+ if (outcome.status === 'empty' && !signal?.aborted) outcome = await attempt()
+ closed = true
+ if (chipTimer !== null) clearTimeout(chipTimer)
+ if (outcome.status === 'complete') return { ok: true, html: outcome.text }
+ if (outcome.status === 'empty') return { ok: false, error: outcome.error }
+ if (epoch !== writerEpochRef.current) return { ok: false, error: 'the chat was reset' }
+ // the draft stays in the document while the user decides
+ const keep = await new Promise((resolve) => {
+ partialResolverRef.current = resolve
+ setActivePartial({ blocks: countFragmentBlocks(outcome.text) })
+ })
+ return keep
+ ? { ok: true, html: outcome.text, truncated: true }
+ : {
+ ok: false,
+ error: `${outcome.reason}${outcome.error ? `: ${outcome.error}` : ''}; the user discarded the partial content`,
+ }
+ }
+ const runDocWriterRef = useRef(runDocWriter)
+ runDocWriterRef.current = runDocWriter
+
+ const decidePartial = (keep: boolean): void => {
+ partialResolverRef.current?.(keep)
+ partialResolverRef.current = null
+ setActivePartial(null)
+ }
+ /** New chat / unmount: discard an open keep card and keep a still-settling writer from opening one */
+ const abandonWriter = (): void => {
+ writerEpochRef.current++
+ decidePartial(false)
+ }
+
const loopRef = useRef | null>(null)
if (!loopRef.current) {
const numIds = (): NumIds => ({
@@ -624,7 +726,7 @@ export function AiPanel({
ordered: findNumId(blocksRef.current, 'ordered') ?? numIdFallbackRef.current?.ordered ?? null,
})
loopRef.current = new AgentLoop({
- transport: createElectronTransport(() => settingsRef.current),
+ transport: transportRef.current,
systemSuffix: aiLangDirective,
skill: composeSkills('docs+files', '', [
createDocsSkill(
@@ -634,6 +736,9 @@ export function AiPanel({
() => commentsAccessRef.current,
() => hfAccessRef.current,
() => imageGenerationAvailable(settingsRef.current, gskLoggedInRef.current),
+ () => ({
+ write: (spec, onProgress, signal) => runDocWriterRef.current(spec, onProgress, signal),
+ }),
),
createFilesSkill(availableAttachments),
]),
@@ -979,6 +1084,7 @@ export function AiPanel({
pendingSendRef.current.aborted = true
pendingSendRef.current = null
}
+ abandonWriter()
loopRef.current?.reset()
setBusy(false)
setChat([])
@@ -1358,6 +1464,28 @@ export function AiPanel({
{attachNotice &&
{attachNotice}
}
+ {activePartial && (
+
+
+ {t('aiPartialTitle')}
+
+
+ {t('aiPartialBody', { blocks: activePartial.blocks })}
+
+
+ decidePartial(false)}
+ >
+ {t('aiPartialDiscard')}
+
+ decidePartial(true)}>
+ {t('aiPartialAdopt')}
+
+
+
+ )}
void,
+ signal?: AbortSignal,
+ ): Promise
+}
+
+const WRITER_SYSTEM = [
+ 'You are the document writer of GenOffice Docs, a Word-style editor. You receive a plan (title, sections, key points, tone, length) and reference material, and you write the complete content.',
+ '',
+ '## Writing rules',
+ '- Write the requested content in full: every section in the plan, real prose, no placeholders, no "[to be added]" notes.',
+ '- Real data only: use the facts, figures, names and quotes from the reference material and the plan; never invent facts or numbers beyond them.',
+ '- Follow the length the plan asks for; when it gives none, write what the content genuinely needs.',
+ '',
+ '## Output',
+ 'Reply with the restricted HTML fragment only: it starts with the first block tag and ends with the last closing tag. No markdown code fences, no commentary before or after, no / wrapper.',
+ HTML_RULES,
+].join('\n')
+
+export function buildDocWriterRequest(
+ spec: DocWriteSpec,
+ langDirective: string,
+): { system: string; user: string } {
+ const context = spec.context?.trim()
+ ? `\n\n## Reference material (all names, figures and facts come from here)\n${spec.context.slice(0, CONTEXT_CAP)}`
+ : ''
+ const instruction = spec.instruction.trim()
+ ? `\n\n## The user's request\n${spec.instruction.slice(0, 2000)}`
+ : ''
+ return {
+ system: WRITER_SYSTEM + langDirective,
+ user: `## Plan\n${spec.title ? `Title: ${spec.title}\n` : ''}${spec.plan.slice(0, 6000)}${context}${instruction}\n\nWrite the content now.`,
+ }
+}
+
+/** Strip a fence or chatter before the first block tag and a closing fence at the end. */
+export function extractFragment(raw: string): string {
+ let text = raw.replace(/\r\n/g, '\n')
+ const start = text.search(/<(?:h[1-6]|p|ul|ol|table|pre|blockquote|formula)[\s>]/i)
+ if (start > 0) text = text.slice(start)
+ else if (start < 0) text = text.replace(/^\s*```[a-z]*\n?/i, '')
+ return text.replace(/\n?```\s*$/, '').trimEnd()
+}
+
+/** rough top-level block count of a fragment, for the progress chip */
+export function countFragmentBlocks(html: string): number {
+ return (html.match(/<(?:h[1-6]|p|ul|ol|table|pre|blockquote|formula)[\s>]/gi) ?? []).length
+}
+
+export type WritePosition = { kind: 'whole' } | { kind: 'after'; index: number }
+
+/** meta on every draft transaction: not an edit, not history, not a tracked change */
+export const DRAFT_META = 'aiDraft'
+
+/**
+ * Live draft of a streaming fragment inside the document. Each tick re-parses
+ * the fragment received so far (the HTML parser closes open tags, so a
+ * half-received block still renders) and swaps only the blocks that changed.
+ * The draft is outside undo history and Track Changes; `finish()` removes it
+ * so the caller can land the final fragment through the regular insert path,
+ * giving one undo step and normal revision marks.
+ */
+export class DraftLanding {
+ private from: number
+ private to: number
+ /** the text of the last tick that parsed and rendered */
+ private rendered: string | null = null
+ private pending: string | null = null
+ private timer: ReturnType | null = null
+ private closed = false
+ private follow = true
+ private readonly onTransaction = ({ transaction }: { transaction: Transaction }) => {
+ if (!transaction.docChanged || transaction.getMeta(DRAFT_META)) return
+ this.from = transaction.mapping.map(this.from, 1)
+ this.to = Math.max(this.from, transaction.mapping.map(this.to, -1))
+ }
+
+ constructor(
+ private readonly editor: Editor,
+ private readonly numIds: NumIds,
+ position: WritePosition,
+ ) {
+ this.from =
+ position.kind === 'after' && position.index >= 0
+ ? blockRangePositions(editor, position.index, position.index).to
+ : 0
+ this.to = this.from
+ editor.on('transaction', this.onTransaction)
+ }
+
+ /** latest cumulative fragment; rendered on the next tick */
+ update(html: string): void {
+ if (this.closed) return
+ this.pending = html
+ if (this.timer === null) this.timer = setTimeout(() => this.flush(), DRAFT_TICK_MS)
+ }
+
+ /** the top-level block index the draft sits after (-1 = document start), after any user edits */
+ indexBefore(): number {
+ const doc = this.editor.state.doc
+ let index = -1
+ let i = 0
+ doc.forEach((node, offset) => {
+ if (offset + node.nodeSize <= this.from) index = i
+ i++
+ })
+ return index
+ }
+
+ /**
+ * Remove the draft; the document is back to what it was around it. Returns the
+ * text of the last tick that rendered, so a kept stream whose tail no longer
+ * parses (a half-received formula or table) can still land what the user saw.
+ */
+ finish(): string | null {
+ if (this.closed) return this.rendered
+ if (this.timer !== null) clearTimeout(this.timer)
+ this.timer = null
+ this.flush()
+ this.closed = true
+ this.editor.off('transaction', this.onTransaction)
+ if (this.to > this.from && !this.editor.isDestroyed) {
+ this.editor.view.dispatch(this.draftTr().delete(this.from, this.to))
+ }
+ this.to = this.from
+ return this.rendered
+ }
+
+ /** live top-level blocks inside the draft range, after any user edits */
+ private liveNodes(): Array<{ node: ProseMirrorNode; end: number }> {
+ const out: Array<{ node: ProseMirrorNode; end: number }> = []
+ this.editor.state.doc.forEach((node, offset) => {
+ if (offset >= this.from && offset + node.nodeSize <= this.to)
+ out.push({ node, end: offset + node.nodeSize })
+ })
+ return out
+ }
+
+ private draftTr(): Transaction {
+ return this.editor.state.tr
+ .setMeta(DRAFT_META, true)
+ .setMeta('addToHistory', false)
+ .setMeta(TRACK_IGNORE, true)
+ .setMeta(TABLE_TRAILING_SKIP, true)
+ }
+
+ private flush(): void {
+ this.timer = null
+ if (this.closed || this.pending === null || this.editor.isDestroyed) return
+ const html = this.pending
+ this.pending = null
+ let next: ProseMirrorNode[]
+ try {
+ next = parseHtmlFragment(html, this.numIds).map((n) =>
+ this.editor.schema.nodeFromJSON({ ...n, attrs: { ...n.attrs, aiChanged: false } }),
+ )
+ } catch {
+ return // a half-received formula or table is retried on the next tick
+ }
+ this.rendered = html
+ // compare against the live document: a user edit inside the draft changes sizes and drops that block from the kept prefix
+ const live = this.liveNodes()
+ let keep = 0
+ while (keep < live.length && keep < next.length && live[keep]!.node.eq(next[keep]!)) keep++
+ if (keep === live.length && keep === next.length) return
+ const at = keep > 0 ? live[keep - 1]!.end : this.from
+ const wasVisible = this.follow && this.endVisible()
+ this.editor.view.dispatch(this.draftTr().replaceWith(at, this.to, next.slice(keep)))
+ this.to = at + next.slice(keep).reduce((size, n) => size + n.nodeSize, 0)
+ if (wasVisible) this.scrollToEnd()
+ else this.follow = false
+ }
+
+ private endVisible(): boolean {
+ if (this.to === this.from) return true
+ try {
+ const { top } = this.editor.view.coordsAtPos(this.to - 1)
+ return top >= 0 && top <= window.innerHeight
+ } catch {
+ return true
+ }
+ }
+
+ private scrollToEnd(): void {
+ if (this.to === this.from) return
+ try {
+ const { node } = this.editor.view.domAtPos(this.to - 1)
+ const el = node instanceof Element ? node : node.parentElement
+ el?.scrollIntoView?.({ block: 'nearest' })
+ } catch {
+ /* layout not ready */
+ }
+ }
+}
diff --git a/apps/docs/src/renderer/ai/docs-skill.ts b/apps/docs/src/renderer/ai/docs-skill.ts
index 3df0877..bae7f50 100644
--- a/apps/docs/src/renderer/ai/docs-skill.ts
+++ b/apps/docs/src/renderer/ai/docs-skill.ts
@@ -7,6 +7,7 @@ import {
type AiTrack,
type NumIds,
} from './protocol'
+import type { AiDocWriter } from './doc-writer'
import {
AGENT_TOOLS,
executeTool,
@@ -32,6 +33,8 @@ export function createDocsSkill(
getHf?: () => AiHeaderFooterAccess | undefined,
/** live predicate (gsk login && cloud-tools toggle, or a BYOK media key); false hides generate_image */
imageGenAvailable?: () => boolean,
+ /** streaming long-form writer behind write_document (panel-owned: progress chip, partial keep/discard) */
+ getWriter?: () => AiDocWriter | undefined,
): AgentSkill {
// Selection frozen per run: tools act on the range the prompt described,
// not on wherever the user's live selection has wandered mid-run. The doc
@@ -66,6 +69,7 @@ export function createDocsSkill(
frozen,
getComments?.(),
getHf?.(),
+ getWriter?.(),
),
}
}
diff --git a/apps/docs/src/renderer/ai/protocol.ts b/apps/docs/src/renderer/ai/protocol.ts
index fbae82a..3d95519 100644
--- a/apps/docs/src/renderer/ai/protocol.ts
+++ b/apps/docs/src/renderer/ai/protocol.ts
@@ -83,7 +83,7 @@ export const OPS_GUIDE = [
'BC-4 Using findReplace sentence by sentence for rewrites such as translation/abbreviation; use replace_blocks (or replace_selection for a selected span) instead;',
].join('\n')
-const HTML_RULES = [
+export const HTML_RULES = [
'The html tool input is a restricted HTML fragment. Rules:',
'- Only these tags are allowed: h1 h2 h3 h4 h5 h6 p ul ol li strong em u s a br table thead tbody tr th td pre code blockquote',
'- Tables: use for the first (header) row; cells contain plain text only ( may split lines); nested tables / merged cells are not supported; once inserted the table is protected as a whole, only cell text remains editable',
@@ -112,6 +112,7 @@ export const AGENT_SYSTEM_PROMPT = [
'- Every user message carries the latest "document block list" (index|type|content preview; previews may be truncated); after modifications, call get_document_context if you need the latest state;',
'- When a list preview is truncated, read the full content with read_blocks before rewriting; never rewrite based on a truncated preview;',
'- Content changes: use insert_content for new content, and replace_blocks to rewrite/replace existing blocks (pass a block index range and the new HTML); replaced blocks pass their paragraph and text formatting (font, size, color, indent, spacing, alignment) on to the new blocks automatically, and a rewritten table keeps its widths, borders, shading and cell formatting, so a rewrite never needs follow-up formatting commands;',
+ '- Long new content (drafting a whole document, a chapter, a full report/article/translation — anything beyond a few paragraphs) goes through write_document: you pass the plan and the reference material, and the system writer streams the text into the document while the user watches; never paste long content into insert_content. When the document is blank and the user asks for content, use write_document;',
'- Formatting, structure, and batch operations (color/font size/line spacing/alignment/indent/heading level/find & replace/delete/move/list conversion) go through apply_ops — do not rewrite whole blocks with replace_blocks;',
'- Small in-place text fixes (changing a few words inside a sentence) go through apply_ops findReplace with a target — do not rewrite the whole block; styling every occurrence of a phrase (e.g. bold each "TODO") uses setMatchedFont;',
'- When the user has text selected, the message includes the selection block indexes and content; rewrite-style requests apply to the selection by default;',
diff --git a/apps/docs/src/renderer/ai/tools.ts b/apps/docs/src/renderer/ai/tools.ts
index 171b84a..87eaa9b 100644
--- a/apps/docs/src/renderer/ai/tools.ts
+++ b/apps/docs/src/renderer/ai/tools.ts
@@ -4,6 +4,12 @@ import type { ChartDisplay, CommentInfo, NewChart } from '@genoffice/docx-engine
import type { AgentToolCall, AgentToolDef, CreateDocumentType } from '../../shared/ipc'
import { t } from '../i18n/locale'
import { executeOps, opNames } from './ops'
+import {
+ DraftLanding,
+ type AiDocWriter,
+ type DocWriteResult,
+ type WritePosition,
+} from './doc-writer'
import {
blockRangePositions,
buildCommentsContext,
@@ -74,6 +80,37 @@ export const AGENT_TOOLS: AgentToolDef[] = [
required: ['html'],
},
},
+ {
+ name: 'write_document',
+ description:
+ '[For long new content: a whole document, a chapter, a full report, article or translation] Hands the writing to the system writer, which streams restricted HTML straight into the document while the user watches; you never write the text yourself. Give a concrete plan (title, section outline with the key points of each, tone, target length) and put every fact, figure, name and quote the text must use into context — the writer sees only the plan and context, not the conversation. Omit afterBlockIndex on a blank document; on a document with content, pass afterBlockIndex to insert after that block, or replaceDocument=true when the user asked to rewrite everything. Short additions (a paragraph or two) use insert_content instead.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ plan: {
+ type: 'string',
+ description: 'title, section outline with key points per section, tone, target length',
+ },
+ title: { type: 'string', description: 'document/chapter title, when there is one' },
+ context: {
+ type: 'string',
+ description:
+ 'reference material: facts, figures, quotes, sources gathered from the conversation, attachments and web_search',
+ },
+ afterBlockIndex: {
+ type: 'integer',
+ description:
+ 'insert after this block index (-1 = document start); omitted = whole document',
+ },
+ replaceDocument: {
+ type: 'boolean',
+ description:
+ 'true replaces all existing content (only when the user asked for a rewrite)',
+ },
+ },
+ required: ['plan'],
+ },
+ },
{
name: 'replace_blocks',
description:
@@ -472,6 +509,7 @@ function editedExternally(editor: Editor): boolean {
/** tools addressing the document by block index: refused after an external edit until the model re-reads */
const INDEX_WRITE_SUMMARIES: Record string> = {
insert_content: () => t('aiSumInsertContent'),
+ write_document: () => t('aiSumWriteDocument'),
replace_blocks: () => t('aiSumReplaceContent'),
replace_selection: () => t('aiSumReplaceSelection'),
apply_ops: () => t('aiSumApplyCommands'),
@@ -717,6 +755,7 @@ export function executeTool(
frozen?: FrozenSelection | null,
comments?: AiCommentsAccess,
hf?: AiHeaderFooterAccess,
+ writer?: AiDocWriter,
): ToolExecution | Promise {
const scope = frozen && frozen.doc === editor.state.doc ? frozen.scope : null
const staleSummary = INDEX_WRITE_SUMMARIES[call.name]
@@ -739,9 +778,98 @@ export function executeTool(
) {
return executeAsyncTool(editor, call, signal)
}
+ if (call.name === 'write_document')
+ return writeDocument(editor, call, numIds, track, signal, writer)
return settle(executeSyncTool(editor, call, numIds, track, scope, comments, hf))
}
+async function writeDocument(
+ editor: Editor,
+ call: AgentToolCall,
+ numIds: NumIds,
+ track: AiTrack | undefined,
+ signal: AbortSignal | undefined,
+ writer: AiDocWriter | undefined,
+): Promise {
+ const summary = t('aiSumWriteDocument')
+ const plan = String(call.input.plan ?? '').trim()
+ if (!plan) return fail(summary, 'plan must not be empty')
+ if (!writer) return fail(summary, 'document writing is not available here')
+ const count = editor.state.doc.childCount
+ const afterRaw = call.input.afterBlockIndex
+ let position: WritePosition
+ if (afterRaw !== undefined && afterRaw !== null) {
+ if (!Number.isInteger(afterRaw) || Number(afterRaw) < -1 || Number(afterRaw) >= count)
+ return fail(summary, rangeError(editor))
+ position = { kind: 'after', index: Number(afterRaw) }
+ } else if (isBlankDocument(editor) || call.input.replaceDocument === true) {
+ position = { kind: 'whole' }
+ } else {
+ return fail(
+ summary,
+ 'the document is not blank: pass afterBlockIndex to insert the new content after a block, or replaceDocument=true when the user asked to rewrite the whole document',
+ )
+ }
+ const str = (v: unknown) => (v === undefined || v === null ? undefined : String(v))
+ const draft = new DraftLanding(editor, numIds, position)
+ let result: DocWriteResult
+ let rendered: string | null
+ try {
+ result = await writer.write(
+ {
+ plan,
+ title: str(call.input.title),
+ context: str(call.input.context),
+ instruction: '',
+ },
+ (html) => draft.update(html),
+ signal,
+ )
+ } finally {
+ rendered = draft.finish()
+ }
+ if (editor.isDestroyed) return fail(summary, 'the document was closed')
+ if (!result.ok || !result.html) {
+ return fail(
+ t('aiSumWriteDocumentFailed'),
+ `The writer produced nothing (${result.error ?? 'no output'}); the document is unchanged. Tell the user briefly and offer to try again.`,
+ )
+ }
+ let nodes: ReturnType
+ try {
+ nodes = parseHtmlFragment(result.html, numIds)
+ } catch (e) {
+ // a kept partial can end mid-formula: land what the user saw rendered instead
+ if (!result.truncated || !rendered)
+ return fail(t('aiSumWriteDocumentFailed'), e instanceof Error ? e.message : String(e))
+ nodes = parseHtmlFragment(rendered, numIds)
+ }
+ if (nodes.length === 0)
+ return fail(
+ t('aiSumWriteDocumentFailed'),
+ 'the writer output did not parse into any content blocks',
+ )
+ // a blank document or an explicit rewrite replaces everything; text the user typed
+ // into a formerly blank document while the draft streamed is kept, the content goes into the draft's slot
+ if (
+ position.kind === 'whole' &&
+ (isBlankDocument(editor) || call.input.replaceDocument === true)
+ ) {
+ replaceBlockRange(editor, 0, editor.state.doc.childCount - 1, nodes, track)
+ } else {
+ insertBlocksAfter(editor, draft.indexBefore(), nodes, track)
+ }
+ markDocSeen(editor)
+ const note = result.truncated
+ ? ' The stream ended early, so the content is INCOMPLETE (the user chose to keep it): the tail is missing. Say so and offer to finish the missing sections with write_document (afterBlockIndex at the end) or insert_content.'
+ : ''
+ return {
+ output: `Content written by the system (${nodes.length} block(s), ${result.html.length} chars). Block indexes have changed; use get_document_context if needed.${note}\nReply with one or two sentences describing what was written; do not paste the content.`,
+ mutated: true,
+ summary: result.truncated ? t('aiSumWriteDocumentPartial') : summary,
+ }
+}
+
function executeSyncTool(
editor: Editor,
call: AgentToolCall,
diff --git a/apps/docs/src/renderer/components/HeaderFooterArea.tsx b/apps/docs/src/renderer/components/HeaderFooterArea.tsx
index fc1d07b..298c74d 100644
--- a/apps/docs/src/renderer/components/HeaderFooterArea.tsx
+++ b/apps/docs/src/renderer/components/HeaderFooterArea.tsx
@@ -17,13 +17,17 @@ import {
hfLeadIndentCss,
hfRowStyle,
hfSegLeftCss,
- hfTabSegments,
+ hfTabLeadNeedsStrut,
+ hfTabLines,
+ hfTabOverflowPx,
hfBoxAnchorEl,
hfTextBoxClass,
hfTextBoxStyle,
hfUsesLegacyHash,
paraBorderCss,
+ paraBorderPadding,
type HfStripGeom,
+ type HfTabLayout,
hfParaLineHeightCss,
hfStackedSpacingPx,
} from '../editor/hf-dom'
@@ -31,6 +35,7 @@ import { applyHfText, hfEditText, hfParasOf, PAGE_TOKEN } from '../editor/hf-tex
import { dkStyleProps } from '../editor/dark-page'
import { INLINE_RULE_CLASS, inlineRuleStyle } from '../editor/inline-rule'
import { textColorValue } from '../editor/text-color'
+import { textOutlineCssValue } from '../editor/text-outline'
import { cssRunFontFamily, fontKerningCss, runLetterSpacingCss } from '../line-metrics'
export interface HfValue {
@@ -58,6 +63,7 @@ function runStyle(run: Run): React.CSSProperties {
const kerning = fontKerningCss(run)
if (kerning) style.fontKerning = kerning
if (run.font || run.fontAscii) style.fontFamily = cssRunFontFamily(run.fontAscii, run.font)
+ if (run.textOutline) style.WebkitTextStroke = textOutlineCssValue(run.textOutline)
if (run.caps === 'all') style.textTransform = 'uppercase'
else if (run.caps === 'small') style.fontVariantCaps = 'small-caps'
else if (run.caps === 'none') {
@@ -81,10 +87,11 @@ function paraStyle(para: HfParagraph): React.CSSProperties {
}
// frame placement wins over the paragraph's own jc (mirrors makeGapHfEl)
if (para.frameXAlign) style.textAlign = para.frameXAlign
- if (para.shadingFill) {
- style.backgroundColor = `#${para.shadingFill}`
- Object.assign(style, dkStyleProps({ background: `#${para.shadingFill}` }))
- }
+ const shdBg = para.shadingDisplay ?? para.shadingFill
+ if (shdBg) {
+ style.backgroundColor = `#${shdBg}`
+ Object.assign(style, dkStyleProps({ background: `#${shdBg}` }))
+ } else if (para.shadingClear) style.backgroundColor = 'transparent'
if (para.borders) {
const line = (side: 't' | 'b' | 'l' | 'r') => paraBorderCss(para.borderLines?.[side])
const borders: Partial> = {}
@@ -93,7 +100,7 @@ function paraStyle(para: HfParagraph): React.CSSProperties {
if (para.borders.includes('l')) style.borderLeft = borders.l = line('l')
if (para.borders.includes('r')) style.borderRight = borders.r = line('r')
Object.assign(style, dkStyleProps({ borders }))
- style.padding = '1px 4px'
+ Object.assign(style, paraBorderPadding(para.borders, para.borderLines))
}
return style
}
@@ -180,14 +187,18 @@ export function HeaderFooterArea({
// preview/export strips lay out like the canvas gaps and the push-down probe
const strutPt = hfDeclaredStrutPt(paras)
const hasBoxes = boxGeom != null && paras.some((p) => p.box)
+ const tabOver = Math.max(
+ 0,
+ ...paras.map((p) => (p.cells ? 0 : hfTabOverflowPx(hfTabLines(p, display) ?? [], boxGeom))),
+ )
return (
0 ? { ['--hf-tab-over' as string]: `${tabOver.toFixed(1)}px` } : {}),
+ ...style,
+ }}
data-tip={
readOnly
? undefined
@@ -365,8 +376,8 @@ function HfContent({
) : (
(() => {
- const tabbed = hfTabSegments(para, display)
- if (!tabbed) {
+ const tabLines = hfTabLines(para, display)
+ if (!tabLines) {
return (
)
}
- const leadIndent = hfLeadIndentCss(tabbed)
- return (
-
+ // tab layout happens in left-aligned space; w:jc becomes an explicit shift
+ const lineStyle = (tabbed: HfTabLayout): React.CSSProperties => {
+ const leadIndent = hfLeadIndentCss(tabbed)
+ return {
+ ...(tabbed.minHeightPt ? { minHeight: `${tabbed.minHeightPt}pt` } : {}),
+ textAlign: 'left',
+ ...(leadIndent ? { textIndent: leadIndent } : {}),
+ }
+ }
+ const lineContent = (tabbed: HfTabLayout) => (
+ <>
+ {hfTabLeadNeedsStrut(tabbed) ? '\u200b' : null}
{tabbed.lead.map((run, j) => (
{display(run.text)}
@@ -414,6 +423,33 @@ function HfContent({
))}
))}
+ >
+ )
+ const frame = para.frameXAlign ? ' page-hf-frame' : ''
+ if (tabLines.length === 1) {
+ return (
+
+ {lineContent(tabLines[0])}
+
+ )
+ }
+ // a w:br paragraph stacks one positioned line per break inside the
+ // paragraph block (which keeps the spacing and borders)
+ return (
+
+ {tabLines.map((tabbed, m) => (
+
+ {lineContent(tabbed)}
+
+ ))}
)
})()
diff --git a/apps/docs/src/renderer/components/PageNoteAreas.tsx b/apps/docs/src/renderer/components/PageNoteAreas.tsx
index c7c61c6..2d5af03 100644
--- a/apps/docs/src/renderer/components/PageNoteAreas.tsx
+++ b/apps/docs/src/renderer/components/PageNoteAreas.tsx
@@ -1,5 +1,5 @@
import type { NoteInfo } from '@genoffice/docx-engine'
-import { toRoman } from '../note-format'
+import { noteMarkText } from '../note-format'
import { useI18n } from '../i18n/locale'
function NoteRow({
@@ -45,11 +45,14 @@ function NoteRow({
export function PageFootnotes({
notes,
skipIds,
+ numberOf,
onEdit,
onDelete,
}: {
notes: NoteInfo[]
skipIds: ReadonlySet
+ /** display number of a note (document reference order); default = list position */
+ numberOf?: (note: NoteInfo, index: number) => number
onEdit: (id: string) => void
onDelete: (id: string) => void
}) {
@@ -61,7 +64,7 @@ export function PageFootnotes({
{shown.map((n) => (
number
onEdit: (id: string) => void
onDelete: (id: string) => void
}) {
@@ -101,7 +106,7 @@ export function PageEndnotes({
{notes.map((n, i) => (
{
+ const si = Math.max(0, Math.min(slice.section, sections.length - 1))
+ const mode = sectionVertical(sections[si]?.settings)
+ const g = geoms[Math.min(si, geoms.length - 1)]
+ if (!mode || !g || slice.regions) return
+ const page = `.pv-page[data-pv-page="${i}"]`
+ // the clip is the full body height (lines span it), so the window pad's
+ // ride-along neighbours must not show: hide the addressable blocks and
+ // reveal those intersecting this page (floated frames and other
+ // horizontal blocks included; blocks without an index stay visible).
+ // Canvas gap chrome (page / hf / notes gaps, cut marks, float hosts) has
+ // no index and would paint inside the sheet: hide it too.
+ rules.push(
+ `${page} .pv-content > [data-idx],` +
+ `${page} .pv-content > :is([class*="page-gap"],.page-float-host){visibility:hidden;}`,
+ )
+ for (const b of blocks) {
+ if (!b.el || b.top >= slice.end - 0.5 || b.top + b.height <= slice.start + 0.5) continue
+ const idx = b.el.dataset.idx
+ if (idx === undefined) continue
+ const sel = `${page} .pv-content > [data-idx="${idx}"]`
+ if (!b.el.classList.contains('doc-vert-block')) {
+ rules.push(`${sel}{visibility:visible;}`)
+ continue
+ }
+ const { dx, dy } = verticalBlockShift(mode, g.contentHeight, b.top - slice.start, b.height)
+ rules.push(
+ `${sel}{visibility:visible;--pv-vdx:${dx.toFixed(2)}px;--pv-vdy:${dy.toFixed(2)}px;}`,
+ )
+ }
+ })
+ return rules.join('\n')
+}
+
export function pinnedCloneCss(pageCount: number): string {
const rules: string[] = []
for (let i = 0; i < pageCount; i++) {
@@ -603,6 +673,61 @@ export interface HfSet {
* sections is real). Headers/footers render per page by Word variant rules (first page /
* odd-even), with real page numbers.
*/
+/** anchored header/footer picture on a preview page; an a:srcRect crop becomes
+ * an overflow-hidden window over the scaled image (mirrors hfImgNode) */
+function FloatHfImg({
+ img,
+ pos,
+}: {
+ img: HfImage
+ pos: ReturnType
+}): React.JSX.Element {
+ const base: React.CSSProperties = {
+ left: pos.x,
+ top: pos.y,
+ transform: hfFloatTransform(img, pos),
+ ...(img.widthPx ? { width: img.widthPx } : {}),
+ ...(img.heightPx ? { height: img.heightPx } : {}),
+ ...(img.washout ? { filter: hfWashoutFilter(img.washout) } : {}),
+ ...(img.behind ? {} : { zIndex: 1 }),
+ }
+ if (img.wordArt) {
+ return (
+
+ )
+ }
+ const c = img.crop
+ if (c && img.widthPx && img.heightPx) {
+ const span = (a: number, b: number) => Math.max(0.01, 1 - a - b)
+ const sw = img.widthPx / span(c.l, c.r)
+ const sh = img.heightPx / span(c.t, c.b)
+ return (
+
+
+
+ )
+ }
+ return (
+
+ )
+}
+
export function PaginationPreview({
section,
canvasTop,
@@ -613,8 +738,10 @@ export function PaginationPreview({
colMode,
hf,
watermark,
+ watermarkDirty,
blockMetaOf,
pageFootnotesOf,
+ footnotesBeneathText,
endnoteItems,
sectionHfOverride,
clearPageGaps,
@@ -641,10 +768,14 @@ export function PaginationPreview({
colMode: 'none' | 'uniform' | 'mixed'
hf: HfSet
watermark: string | null
+ /** unsaved Design → Watermark edit: draw `watermark` as the ghost text and hide the parsed WordArt shape */
+ watermarkDirty?: boolean
/** docxIndex → parse-layer pagination constraints (keepNext/widow/table-row flags) */
blockMetaOf?: BlockMetaOf
/** Per-page footnote collection (referencing page → entry list), for page-bottom rendering */
pageFootnotesOf?: (blocks: BlockBox[], slices: PageSlice[]) => PageNoteItem[][]
+ /** w:footnotePr w:pos="beneathText": the note area follows the last body line instead of sitting at the page bottom */
+ footnotesBeneathText?: boolean
/** Endnote entries (placed together at the document end, take part in slicing, may continue across pages) */
endnoteItems?: PageNoteItem[]
/** Multi-section: unsaved per-section header/footer edit overrides (default variant) */
@@ -670,7 +801,11 @@ export function PaginationPreview({
}) {
const { t } = useI18n()
const [slices, setSlices] = useState([])
+ const [splitCss, setSplitCss] = useState('')
+ const [vertCss, setVertCss] = useState('')
const [pageNotes, setPageNotes] = useState([])
+ /** per-page flow-coordinate bottom of the body text (beneathText footnote anchor) */
+ const [textEnds, setTextEnds] = useState([])
/** Top Y of the endnote area (virtual coordinates); null = no endnotes */
const [endnotesTop, setEndnotesTop] = useState(null)
const [html, setHtml] = useState('')
@@ -715,7 +850,12 @@ export function PaginationPreview({
colMode !== 'none' ||
section.vAlign === 'center' ||
section.vAlign === 'bottom' ||
- sections.some((s) => s.settings.vAlign === 'center' || s.settings.vAlign === 'bottom')
+ sections.some(
+ (s) =>
+ s.settings.vAlign === 'center' ||
+ s.settings.vAlign === 'bottom' ||
+ sectionVertical(s.settings),
+ )
if (measureNeutralize) pm.classList.add('measuring-columns')
try {
const origin = pm.getBoundingClientRect().top + canvasTop * factor
@@ -741,8 +881,10 @@ export function PaginationPreview({
const flowH = flowWithFloats ?? withEndnotes?.totalHeight ?? totalHeight
setEndnotesTop(withEndnotes?.top ?? null)
let computed: PageSlice[]
+ const splitOut: SliceOutputs = { rowSplits: [] }
/** flow-coordinate bottom of page i's clip window (the last page opens to full capacity unless vertically aligned) */
let winEndOf: (s: PageSlice, i: number) => number
+ let liveGeoms: SectionGeom[] = []
if (live.length > 0) {
// each section's default-variant header/footer estimated heights → body push-down (matching the canvas)
const refs = effectiveHfRefs(live)
@@ -808,9 +950,10 @@ export function PaginationPreview({
}
})
const geoms = sectionGeoms(live, hfHs)
+ liveGeoms = geoms
// when the canvas column layout is inactive, measure as full-width single flow; the geometry drops column flow to match
if (colMode === 'none') for (const g of geoms) if (g.cols) g.cols = undefined
- computed = sliceWithLineSplit(blocks, geoms, flowH, factor, blockMetaOf)
+ computed = sliceWithLineSplit(blocks, geoms, flowH, factor, blockMetaOf, splitOut)
const firsts = sectionFirstPages(computed)
const last = computed.length - 1
winEndOf = (s, i) => {
@@ -869,6 +1012,7 @@ export function PaginationPreview({
flowH,
factor,
blockMetaOf,
+ splitOut,
)
const last = computed.length - 1
winEndOf = (s, i) => {
@@ -927,10 +1071,14 @@ export function PaginationPreview({
// and resolve against the page box at their page-relative offsets
for (const f of floats) {
if (!f.pageRelV) continue
- const wrap = f.el.closest('.doc-protected-floating, .doc-img-float')
+ const wrap = f.el.closest(
+ '.doc-protected-floating, .doc-img-float, .doc-anchor-origin',
+ )
if (!wrap) continue
const boxes = Array.from(
- wrap.querySelectorAll(':scope > .doc-textbox, :scope > .doc-img-wrap'),
+ wrap.querySelectorAll(
+ ':scope > .doc-textbox, :scope > .doc-img-wrap, :scope .doc-inline-img-anchor > img',
+ ),
)
// static siblings (an inline drawing sharing the paragraph) neither
// need the shared containing block nor ride the page-margin translate:
@@ -952,6 +1100,7 @@ export function PaginationPreview({
// owning page lets other clones hide the ride-along copies.
for (const el of pm.querySelectorAll('[data-pv-hoist]')) {
delete el.dataset.pvHoist
+ delete el.dataset.pvHoistSlot
delete el.dataset.pinPage
el.style.removeProperty('--pv-hoist-dy')
}
@@ -968,12 +1117,10 @@ export function PaginationPreview({
if (wrap.dataset.pvPagerel === '1' || wrap.classList.contains('doc-protected-pagepinned'))
continue
if (!wfs.every((f) => !f.pinned && !f.pageRelV)) continue
- // the hoist CSS re-pins by inline left/top: boxes on the right/center
- // slots (right:0 / left:50%) resolve against the column and must stay
- if (
- !wfs.every((f) => /(?:^|;)\s*left:\s*-?[\d.]+px/.test(f.el.getAttribute('style') ?? ''))
- )
- continue
+ // the hoist CSS re-pins against the page box, so each slot (left px,
+ // left:50%, right:0) gets its own column-to-page correction
+ const slot = hoistSlotOf(wfs[0])
+ if (!slot || !wfs.every((f) => hoistSlotOf(f) === slot)) continue
const pg = pinnedFloatPage(computed, wfs[0].anchorTop)
const slice = computed[pg]
if (!slice || slice.repeatHeader) continue
@@ -987,12 +1134,18 @@ export function PaginationPreview({
const spills = wfs.some((f) => f.top + f.height > win.end + 1 || f.top < win.start - 1)
if (!spills && !win.multiCol) continue
wrap.dataset.pvHoist = '1'
+ wrap.dataset.pvHoistSlot = slot
wrap.dataset.pinPage = String(pg)
wrap.style.setProperty('--pv-hoist-dy', `${win.dy}px`)
}
applyLiftTops(computed, blocks)
+ setSplitCss(rowSplitCss(splitOut.rowSplits ?? [], blocks, computed))
+ setVertCss(
+ liveGeoms.some((g) => g.vertical) ? verticalPageCss(blocks, computed, live, liveGeoms) : '',
+ )
setSlices(computed)
setPageNotes(pageFootnotesOf ? pageFootnotesOf(blocks, computed) : [])
+ setTextEnds(footnotesBeneathText ? pageTextEnds(blocks, computed) : [])
// comment anchors, measured in the same neutralized geometry as the blocks;
// content-relative X: the pm element is the padded .doc-page, but the
// preview clones strip that padding and sit inside the sheet's own
@@ -1021,13 +1174,19 @@ export function PaginationPreview({
gapAccum += rect.height
continue
}
+ if (el.classList.contains('page-float-carry')) continue
let innerGap = 0
for (const g of el.querySelectorAll('.page-gap-inline'))
innerGap += g.getBoundingClientRect().height
const cs = window.getComputedStyle(el)
const vTop = (rect.top - anchorShiftPx(el) * factor - origin - gapAccum) / factor
const h = (rect.height - innerGap) / factor
- gapAccum += innerGap
+ // a CSS float's in-table gaps grow only the float's own box (measureBlocks)
+ const cssFloat =
+ (el.classList.contains('doc-table-float-left') ||
+ el.classList.contains('doc-table-float-right')) &&
+ !el.classList.contains('doc-table-float-flow')
+ if (!cssFloat) gapAccum += innerGap
metas.push({
html: cloneBlockHtml(el),
vTop,
@@ -1066,6 +1225,13 @@ export function PaginationPreview({
return () => window.removeEventListener('keydown', onKey, true)
}, [onClose, suppressEscape])
+ // line numbers (w:lnNumType) ride the cloned pages: measured after the sheets mount;
+ // markup spots rescale the sheets, so they re-measure too
+ useEffect(() => {
+ const root = document.querySelector('.pv-scroll')
+ if (root) syncPreviewLineNumbers(root, secs, blockMetaOf)
+ }, [secs, blockMetaOf, slices, commentSpots, revSpots])
+
const multiSection = secs.length > 1
const commentById = useMemo(() => new Map((comments ?? []).map((c) => [c.id, c])), [comments])
const effRefs = useMemo(() => effectiveHfRefs(secs), [secs])
@@ -1135,8 +1301,7 @@ export function PaginationPreview({
const slice = slices[i]
const sec = secs[Math.min(slice.section, secs.length - 1)]
const refs = effRefs[Math.min(slice.section, effRefs.length - 1)]
- const variant =
- sec.titlePg && firsts[i] ? 'first' : hf.evenOddHf && pageNo % 2 === 0 ? 'even' : 'default'
+ const variant = hfVariantOf(sec.titlePg, firsts[i], hf.evenOddHf, pageNo)
// unsaved per-section header/footer edits take priority over document parts (default variant)
const ovHeader = variant === 'default' ? sectionHfOverride?.(slice.section, 'header') : null
const ovFooter = variant === 'default' ? sectionHfOverride?.(slice.section, 'footer') : null
@@ -1164,6 +1329,8 @@ export function PaginationPreview({
+ {splitCss && }
+ {vertCss && }
{/* aria-hidden: the cloned page stack is a visual print preview; exposing
its full-document DOM to the accessibility tree overflows Blink's AX
update queue on long documents and crashes the renderer */}
@@ -1186,15 +1353,37 @@ export function PaginationPreview({
hfHeaderGeom(s),
),
)
- const mBottom = effectiveBottomPx(
- s,
- hfReservedHeightPx('footer', parts.footer, secContentW, parts.footerImages),
+ const footerReservedPx = hfReservedHeightPx(
+ 'footer',
+ parts.footer,
+ secContentW,
+ parts.footerImages,
)
+ const mBottom = effectiveBottomPx(s, footerReservedPx)
const contentH = pageH - mTop - mBottom
+ const notes = pageNotes[i] ?? []
+ const notesH =
+ notes.length > 0
+ ? notes.reduce((sum, n) => sum + n.height, 0) + FOOTNOTE_SEPARATOR_H
+ : 0
// page vertical alignment (sectPr w:vAlign): content of non-full pages shifts down as a whole
const usedH = Math.min(slice.end - slice.start, contentH)
const vSpare = Math.max(0, contentH - usedH)
- const vOffset = s.vAlign === 'center' ? vSpare / 2 : s.vAlign === 'bottom' ? vSpare : 0
+ // (vertical-text pages: the slice span is the sideways fill, not leftover height)
+ const vOffset = sectionVertical(s)
+ ? 0
+ : s.vAlign === 'center'
+ ? vSpare / 2
+ : s.vAlign === 'bottom'
+ ? vSpare
+ : 0
+ const noteArea = noteAreaPlacement(notesH, textEnds[i], slice, {
+ pageH,
+ mTop,
+ mBottom,
+ headerH: slice.repeatHeader?.height ?? 0,
+ vOffset,
+ })
// the window opens up into the top margin: fully on the first page (nothing
// precedes the flow there, so a side-wrapped picture anchored above its
// paragraph paints into the margin like Word), else by a lifted table's hang
@@ -1229,6 +1418,7 @@ export function PaginationPreview({
key={i}
className="pv-page"
data-pv-page={i}
+ data-pv-section={slice.section}
// inert: cloned pages carry natively focusable nodes (links,
// contenteditable cells); keyboard focus must not enter the
// aria-hidden subtree. Kept off .pv-scroll so it stays scrollable.
@@ -1257,14 +1447,14 @@ export function PaginationPreview({
...(markupOn ? markupTransform : {}),
}}
>
- {watermark && (
+ {watermark && watermarkDirty && (
{watermark}
)}
{drawPageBorder && (
+ >
+ {(['top', 'right', 'bottom', 'left'] as const).map((name) => {
+ const art = pageBorder.sides[name]?.art
+ return art ? (
+
+ ) : null
+ })}
+
)}
{(parts.headerImages ?? [])
- .filter((img) => img.floating)
+ .filter((img) => img.floating && !(watermarkDirty && img.wordArt))
.map((img, k) => {
// picture watermark (anchored image in the header): drawn once
// per page behind the body (negative z-index; .pv-page isolates)
@@ -1293,23 +1494,25 @@ export function PaginationPreview({
headerDist: pageBox.headerDist,
sectMarginTop: twipsToPx(s.marginTop),
})
- return (
-
- )
+ return
+ })}
+ {(parts.footerImages ?? [])
+ .filter((img) => img.floating)
+ .map((img, k) => {
+ // anchored footer picture (seal beside the address block):
+ // paragraph-relative offsets measure from the footer strip top
+ const pos = hfFloatPagePos(img, {
+ pageW,
+ pageH,
+ marginLeft: twipsToPx(s.marginLeft),
+ marginRight: twipsToPx(s.marginRight),
+ marginTop: mTop,
+ marginBottom: mBottom,
+ headerDist: pageBox.headerDist,
+ sectMarginTop: twipsToPx(s.marginTop),
+ paraOriginY: pageH - pageBox.footerDist - footerReservedPx,
+ })
+ return
})}
{/* image-only parts (logo headers) have a null text value but must still render */}
{(parts.header || parts.headerImages?.some((img) => !img.floating)) && (
@@ -1477,7 +1680,7 @@ export function PaginationPreview({
height:
openTop +
bodyLift +
- (i === slices.length - 1 && vOffset <= 0.5
+ ((i === slices.length - 1 && vOffset <= 0.5) || sectionVertical(s)
? contentH - (slice.repeatHeader?.height ?? 0)
: Math.max(
0,
@@ -1519,19 +1722,19 @@ export function PaginationPreview({
)}
- {(pageNotes[i]?.length ?? 0) > 0 && (
- // page-bottom footnotes (Word behavior: placed at the bottom of the page's content area, separator on top)
+ {notes.length > 0 && (
sum + n.height, 0) + FOOTNOTE_SEPARATOR_H,
+ height: notesH,
+ ...(noteArea.top === null
+ ? { bottom: twipsToPx(s.marginBottom) }
+ : { top: noteArea.top }),
}}
>
- {pageNotes[i]!.map((n) => (
+ {notes.map((n) => (
// entries get reserved heights (DOM-measured at these exact styles);
// min-height lets a residual long entry spill into the bottom margin
// instead of overprinting the next entry
@@ -1545,7 +1748,7 @@ export function PaginationPreview({
...(n.fontFamily ? { fontFamily: n.fontFamily } : {}),
}}
>
- {!n.noRefMark &&
{n.no} }
+ {!n.noRefMark &&
{noteMarkText('footnote', n.no)} }
{n.richParas
? n.richParas.map((para, pi) => (
@@ -1567,6 +1770,9 @@ export function PaginationPreview({
fontFamily: run.fontAscii
? cssFontFamily(run.fontAscii)
: undefined,
+ WebkitTextStroke: run.textOutline
+ ? textOutlineCssValue(run.textOutline)
+ : undefined,
textTransform: run.caps === 'all' ? 'uppercase' : undefined,
fontVariantCaps:
run.caps === 'small' ? 'small-caps' : undefined,
@@ -1594,7 +1800,12 @@ export function PaginationPreview({
style={{
left: twipsToPx(s.marginLeft),
width: pageW - twipsToPx(s.marginLeft) - twipsToPx(s.marginRight),
- top: mTop + (slice.repeatHeader?.height ?? 0) + (rows[0].top - slice.start),
+ top:
+ mTop +
+ (slice.regions ? 0 : vOffset) +
+ (slice.repeatHeader?.height ?? 0) +
+ (rows[0].top - slice.start) +
+ noteArea.endnoteShift,
}}
>
{rows.map(({ item: n, height, withSeparator }) => (
@@ -1609,7 +1820,7 @@ export function PaginationPreview({
}}
>
{withSeparator &&
}
- {!n.noRefMark && {toRoman(n.no)} }
+ {!n.noRefMark && {noteMarkText('endnote', n.no)} }
{n.richParas
? n.richParas.map((para, pi) => (
@@ -1634,6 +1845,9 @@ export function PaginationPreview({
fontFamily: run.fontAscii
? cssFontFamily(run.fontAscii)
: undefined,
+ WebkitTextStroke: run.textOutline
+ ? textOutlineCssValue(run.textOutline)
+ : undefined,
textTransform: run.caps === 'all' ? 'uppercase' : undefined,
fontVariantCaps:
run.caps === 'small' ? 'small-caps' : undefined,
diff --git a/apps/docs/src/renderer/components/PasteOptionsChip.tsx b/apps/docs/src/renderer/components/PasteOptionsChip.tsx
new file mode 100644
index 0000000..7844cbe
--- /dev/null
+++ b/apps/docs/src/renderer/components/PasteOptionsChip.tsx
@@ -0,0 +1,266 @@
+/**
+ * Post-paste floating "Paste options" chip (Word parity): after pasting
+ * foreign HTML (web pages, Word, mail), a small button appears at the end of
+ * the pasted content offering the three paste modes — keep source formatting,
+ * merge formatting, keep text only. Choosing one undoes the paste, restores
+ * the insertion point and re-applies the SAME clipboard payload through the
+ * editor's full paste pipeline; "always use this choice" persists the mode
+ * as the default for pasting from other programs (editor/paste-options.ts).
+ *
+ * Mounted at the app root with fixed positioning (coordsAtPos speaks viewport
+ * coordinates, the AiAskPopover pattern); repositions while the document
+ * scrolls and hides on any other document change.
+ */
+import React, { useEffect, useRef, useState } from 'react'
+import type { Editor } from '@tiptap/core'
+import type { EditorState, Transaction } from '@tiptap/pm/state'
+import { useI18n, type StringKey } from '../i18n/locale'
+import {
+ beginForeignPaste,
+ capturePasteRestore,
+ defaultPasteMode,
+ forceNextPasteMode,
+ revertPaste,
+ setDefaultPasteMode,
+ takePastePayload,
+ type PasteMode,
+ type PastePayload,
+ type PasteRestore,
+} from '../editor/paste-options'
+import { IconPaste } from './icons'
+
+type ChipState = {
+ payload: PastePayload
+ from: number
+ to: number
+ mode: PasteMode
+ restore: PasteRestore
+}
+
+type PastedRange = Pick
+
+const MODE_KEYS: Array<[PasteMode, StringKey]> = [
+ ['source', 'appPasteKeepSource'],
+ ['merge', 'appPasteMergeFormat'],
+ ['text', 'appPasteTextOnly'],
+]
+
+const GAP = 6
+const EDGE = 8
+const REVERT_META = 'pasteOptionsRevert'
+
+/** The range a transaction's steps touched, in final-doc coordinates. */
+function changedRangeOf(tr: Transaction): { from: number; to: number } | null {
+ let from = Infinity
+ let to = -Infinity
+ const maps = tr.mapping.maps
+ maps.forEach((stepMap, index) => {
+ stepMap.forEach((_oldFrom, _oldTo, newFrom, newTo) => {
+ let start = newFrom
+ let end = newTo
+ for (let later = index + 1; later < maps.length; later++) {
+ start = maps[later]!.map(start, 1)
+ end = maps[later]!.map(end, -1)
+ }
+ from = Math.min(from, start)
+ to = Math.max(to, end)
+ })
+ })
+ return from <= to ? { from, to } : null
+}
+
+export function PasteOptionsChip({ editor }: { editor: Editor }) {
+ const { t } = useI18n()
+ const [chip, setChip] = useState(null)
+ const [open, setOpen] = useState(false)
+ const [pos, setPos] = useState<{ left: number; top: number } | null>(null)
+ // setDefaultPasteMode writes localStorage — bump to re-read it in render
+ const [, setPrefTick] = useState(0)
+ const reapplying = useRef(false)
+ // the state a document-changing transaction started from (editor.state is
+ // already the new one when 'transaction' fires) and the paste a re-apply
+ // produced (null when it produced none), read back once pasteHTML returns
+ const beforeState = useRef(null)
+ const reapplied = useRef(null)
+ const rootRef = useRef(null)
+
+ // show on a paste transaction (payload stashed by the paste entry points),
+ // track re-applies, hide on any other document change
+ useEffect(() => {
+ const onBeforeTransaction = ({ transaction }: { transaction: Transaction }) => {
+ if (transaction.docChanged) beforeState.current = editor.state
+ }
+ const onTransaction = ({
+ transaction: tr,
+ appendedTransactions,
+ }: {
+ transaction: Transaction
+ appendedTransactions: Transaction[]
+ }) => {
+ if (!tr.docChanged) return
+ if (tr.getMeta(REVERT_META)) {
+ reapplied.current = null
+ return
+ }
+ const payload = reapplying.current ? null : takePastePayload()
+ if (!payload && !reapplying.current) {
+ setChip(null)
+ setOpen(false)
+ return
+ }
+ const range = changedRangeOf(tr)
+ const restore =
+ range && beforeState.current
+ ? capturePasteRestore(beforeState.current, [tr, ...appendedTransactions])
+ : null
+ const pasted = range && restore ? { from: range.from, to: range.to, restore } : null
+ if (reapplying.current) {
+ reapplied.current = pasted
+ return
+ }
+ setChip(payload && pasted ? { payload, mode: payload.mode, ...pasted } : null)
+ setOpen(false)
+ }
+ editor.on('beforeTransaction', onBeforeTransaction)
+ editor.on('transaction', onTransaction)
+ return () => {
+ editor.off('beforeTransaction', onBeforeTransaction)
+ editor.off('transaction', onTransaction)
+ }
+ }, [editor])
+
+ // anchor at the end of the pasted content; follow scrolling
+ useEffect(() => {
+ if (!chip) {
+ setPos(null)
+ return
+ }
+ const place = () => {
+ try {
+ const max = editor.state.doc.content.size
+ const coords = editor.view.coordsAtPos(Math.min(chip.to, max))
+ const left = Math.min(coords.right + GAP, window.innerWidth - EDGE - 32)
+ const top = Math.min(coords.bottom + GAP, window.innerHeight - EDGE - 32)
+ setPos({ left: Math.max(EDGE, left), top: Math.max(EDGE, top) })
+ } catch {
+ setChip(null)
+ }
+ }
+ place()
+ window.addEventListener('scroll', place, true)
+ window.addEventListener('resize', place)
+ return () => {
+ window.removeEventListener('scroll', place, true)
+ window.removeEventListener('resize', place)
+ }
+ }, [editor, chip])
+
+ // Esc closes the menu, then the chip; outside clicks close the menu
+ useEffect(() => {
+ if (!chip) return
+ const onKey = (event: KeyboardEvent) => {
+ if (event.key !== 'Escape') return
+ if (open) setOpen(false)
+ else {
+ setChip(null)
+ // focus may sit inside the chip (menu buttons, the checkbox) —
+ // dismissing returns it to the document like Word does
+ editor.commands.focus()
+ }
+ }
+ const onPointerDown = (event: MouseEvent) => {
+ if (rootRef.current && !rootRef.current.contains(event.target as Node)) setOpen(false)
+ }
+ window.addEventListener('keydown', onKey)
+ window.addEventListener('mousedown', onPointerDown)
+ return () => {
+ window.removeEventListener('keydown', onKey)
+ window.removeEventListener('mousedown', onPointerDown)
+ }
+ }, [editor, chip, open])
+
+ if (!chip || !pos) return null
+
+ const applyMode = (mode: PasteMode) => {
+ if (mode === chip.mode) {
+ setOpen(false)
+ return
+ }
+ const view = editor.view
+ const revert = revertPaste(view.state, chip.restore)
+ if (!revert) {
+ setChip(null)
+ setOpen(false)
+ return
+ }
+ reapplying.current = true
+ try {
+ view.dispatch(revert.setMeta(REVERT_META, true))
+ forceNextPasteMode(mode)
+ beginForeignPaste(chip.payload.html)
+ const data = new DataTransfer()
+ data.setData('text/html', chip.payload.html)
+ if (chip.payload.text) data.setData('text/plain', chip.payload.text)
+ view.pasteHTML(
+ chip.payload.html,
+ new ClipboardEvent('paste', { clipboardData: data }) as ClipboardEvent,
+ )
+ } finally {
+ reapplying.current = false
+ }
+ const pasted = reapplied.current
+ setChip((prev) => (prev && pasted ? { ...prev, ...pasted, mode } : null))
+ setOpen(false)
+ editor.commands.focus()
+ }
+
+ const remembered = defaultPasteMode() === chip.mode
+
+ return (
+
+
setOpen((v) => !v)}
+ >
+
+ ▾
+
+ {open && (
+
+ {MODE_KEYS.map(([mode, key]) => (
+
applyMode(mode)}
+ >
+ {chip.mode === mode ? '✓' : ''}
+ {t(key)}
+
+ ))}
+
+
+ {
+ setDefaultPasteMode(event.target.checked ? chip.mode : 'source')
+ setPrefTick((tick) => tick + 1)
+ }}
+ />
+ {t('appPasteRememberDefault')}
+
+
+ )}
+
+ )
+}
diff --git a/apps/docs/src/renderer/components/Ribbon.tsx b/apps/docs/src/renderer/components/Ribbon.tsx
index b742e59..d4119ac 100644
--- a/apps/docs/src/renderer/components/Ribbon.tsx
+++ b/apps/docs/src/renderer/components/Ribbon.tsx
@@ -46,6 +46,7 @@ import { applyCase, type CaseMode } from '../editor/case-transform'
import { setParagraphDirection, setSelectionAlign } from '../editor/direction'
import { setInactiveSelectionShown } from '../editor/inactive-selection'
import { stepParagraphIndent } from '../editor/indent'
+import { beginForeignPaste, defaultPasteMode, stashPastePayload } from '../editor/paste-options'
import { formatNumber } from '../editor/numbering'
import type { InkTool } from '../editor/ink'
import type { RibbonFormatState } from './ribbon-format-state'
@@ -199,6 +200,8 @@ interface RibbonProps {
/** References → footnotes / endnotes / citations */
onInsertNote: (kind: 'footnote' | 'endnote') => void
sources: SourceInfo[]
+ /** footnotes/endnotes hold Zotero citation fields the bridge cannot see yet */
+ zoteroNoteFields?: boolean
onAddSource: (source: SourceInfo) => void
/** TOC page-number backfill: docHeadings in document order → real page numbers (null when not computable) */
headingPages?: () => number[] | null
@@ -654,6 +657,7 @@ function RibbonInner({
onInkClearAll,
onInsertNote,
sources,
+ zoteroNoteFields,
onAddSource,
headingPages,
zoom,
@@ -1835,6 +1839,12 @@ function RibbonInner({
if (item.types.includes('text/html')) {
const html = await (await item.getType('text/html')).text()
if (html) {
+ // arm the foreign-paste handshake exactly like a Ctrl+V — the
+ // synthetic pasteHTML never fires the DOM paste handler, so
+ // ribbon pastes skipped the paste mode and the r181 fill
+ if (beginForeignPaste(html)) {
+ stashPastePayload({ html, text, mode: defaultPasteMode() })
+ }
ed.view.pasteHTML(html, pasteEvent(html, text))
ed.commands.focus()
return
@@ -2483,7 +2493,7 @@ function RibbonInner({
{t('ribbonGroupShading')}
-
+
applyCellBorders('all')}>
@@ -3814,6 +3824,7 @@ function RibbonInner({
setDropdown={setDropdown}
onInsertNote={onInsertNote}
sources={sources}
+ zoteroNoteFields={zoteroNoteFields}
onAddSource={onAddSource}
headingPages={headingPages}
/>
diff --git a/apps/docs/src/renderer/components/Ruler.tsx b/apps/docs/src/renderer/components/Ruler.tsx
index a2262fa..29d7658 100644
--- a/apps/docs/src/renderer/components/Ruler.tsx
+++ b/apps/docs/src/renderer/components/Ruler.tsx
@@ -12,6 +12,18 @@ export function isRenderableTabStop(stop: TabStop): boolean {
return stop.val !== 'clear'
}
+/** A ruler edit makes the whole set direct (Word writes style-inherited stops
+ out too). An inherited stop the user removed or moved needs a `clear` at its
+ old position, or the style chain puts it back on reopen. Exported for tests. */
+export function directTabStops(original: TabStop[], edited: TabStop[]): TabStop[] {
+ const clears = original
+ .filter((s) => s.inherited && !edited.some((e) => e.pos === s.pos))
+ .map((s): TabStop => ({ pos: s.pos, val: 'clear' }))
+ return [...edited.map(({ inherited: _inherited, ...s }) => s), ...clears].sort(
+ (a, b) => a.pos - b.pos,
+ )
+}
+
/** Horizontal ruler above the page: inch numbers, gray margin zones, tab stops. */
export function Ruler({
section,
@@ -73,8 +85,10 @@ export function Ruler({
}
const { stops, relStops } = currentTabStops()
- const withRel = (edited: TabStop[]): TabStop[] | null =>
- edited.length > 0 || relStops.length > 0 ? [...edited, ...relStops] : null
+ const withRel = (edited: TabStop[]): TabStop[] | null => {
+ const direct = directTabStops(stops, edited)
+ return direct.length > 0 || relStops.length > 0 ? [...direct, ...relStops] : null
+ }
// Drag state
const dragRef = useRef<{ stopIndex: number; startX: number; origPos: number } | null>(null)
@@ -136,9 +150,9 @@ export function Ruler({
document.addEventListener('mouseup', onMouseUp)
}
- // Default tab stop markers (light gray) when no custom stops defined
+ // Default tab stop markers (light gray) when no custom stops mark a position
const defaultStops: number[] = []
- if (stops.length === 0) {
+ if (!stops.some(isRenderableTabStop)) {
const contentWidth = section.pageWidth - section.marginLeft - section.marginRight
for (let pos = DEFAULT_TAB_TWIPS; pos < contentWidth; pos += DEFAULT_TAB_TWIPS) {
defaultStops.push(section.marginLeft + pos)
diff --git a/apps/docs/src/renderer/components/ribbon-layout-tab.tsx b/apps/docs/src/renderer/components/ribbon-layout-tab.tsx
index cc814cc..dc08379 100644
--- a/apps/docs/src/renderer/components/ribbon-layout-tab.tsx
+++ b/apps/docs/src/renderer/components/ribbon-layout-tab.tsx
@@ -112,12 +112,15 @@ export function LayoutTab({
const applyMargins = (m: PageMargins) => {
if (!section || !marginsFitPage(m, section.pageWidth, section.pageHeight)) return
+ // a user-set value is an ordinary margin, not the file's header-proof fixed one
onSection({
...section,
marginTop: m.top,
marginRight: m.right,
marginBottom: m.bottom,
marginLeft: m.left,
+ marginTopFixed: undefined,
+ marginBottomFixed: undefined,
})
}
diff --git a/apps/docs/src/renderer/components/ribbon-references-tab.tsx b/apps/docs/src/renderer/components/ribbon-references-tab.tsx
index eb81949..f672e8d 100644
--- a/apps/docs/src/renderer/components/ribbon-references-tab.tsx
+++ b/apps/docs/src/renderer/components/ribbon-references-tab.tsx
@@ -340,6 +340,8 @@ interface ReferencesTabProps extends TabProps {
blocks: Block[]
onInsertNote: (kind: 'footnote' | 'endnote') => void
sources: SourceInfo[]
+ /** footnotes/endnotes hold Zotero citation fields the bridge cannot see yet */
+ zoteroNoteFields?: boolean
onAddSource: (source: SourceInfo) => void
/** TOC page-number backfill: docHeadings in document order → real page numbers */
headingPages?: () => number[] | null
@@ -353,6 +355,7 @@ export function ReferencesTab({
setDropdown,
onInsertNote,
sources,
+ zoteroNoteFields,
onAddSource,
headingPages,
}: ReferencesTabProps) {
@@ -363,8 +366,14 @@ export function ReferencesTab({
const runZotero = async (command: ZoteroCommand) => {
if (zoteroBusy) return
- setZoteroBusy(command)
setDropdown(() => null)
+ // every command lets Zotero rebuild the bibliography from the fields it can see;
+ // note citations are not among them yet, so their works would silently drop out
+ if (zoteroNoteFields) {
+ window.alert(t('zoteroNoteFieldsUnsupported'))
+ return
+ }
+ setZoteroBusy(command)
try {
const result = await window.desktop.zoteroCommand(command)
if (!result.ok) {
diff --git a/apps/docs/src/renderer/components/ribbon-tabs.tsx b/apps/docs/src/renderer/components/ribbon-tabs.tsx
index 4de267f..89372f9 100644
--- a/apps/docs/src/renderer/components/ribbon-tabs.tsx
+++ b/apps/docs/src/renderer/components/ribbon-tabs.tsx
@@ -297,15 +297,18 @@ export async function insertImageFromDataUrl(
// next keystroke REPLACES the picture (alpha ledger r152). Ensure a
// paragraph follows the image and put a text caret there — also what
// Word does after inserting a picture.
+ // A mid-paragraph insert already leaves the caret in the split-off rest
+ // of the paragraph; only a doc-level landing needs the paragraph check.
{
const { doc, selection, schema } = editor.state
- const after = Math.min(selection.to, doc.content.size)
- const nextIsTextblock = doc.resolve(after).nodeAfter?.isTextblock === true
- const chain = editor.chain()
- if (!nextIsTextblock && schema.nodes.docParagraph) {
- chain.insertContentAt(after, { type: 'docParagraph' })
+ const $after = doc.resolve(Math.min(selection.to, doc.content.size))
+ if (!$after.parent.isTextblock) {
+ const chain = editor.chain()
+ if ($after.nodeAfter?.isTextblock !== true && schema.nodes.docParagraph) {
+ chain.insertContentAt($after.pos, { type: 'docParagraph' })
+ }
+ chain.setTextSelection($after.pos + 1).run()
}
- chain.setTextSelection(after + 1).run()
}
return true
} catch {
diff --git a/apps/docs/src/renderer/doc-style-css.ts b/apps/docs/src/renderer/doc-style-css.ts
index 2f30b47..20e0d84 100644
--- a/apps/docs/src/renderer/doc-style-css.ts
+++ b/apps/docs/src/renderer/doc-style-css.ts
@@ -1,7 +1,9 @@
import {
readSections,
+ tocLevelOf,
type ParsedDocFull,
type StyleDisplay,
+ type StyleInfo,
type ThemeColors,
type ThemeFonts,
} from '@genoffice/docx-engine'
@@ -31,7 +33,9 @@ import {
import { sectionGridPitchPt } from './pagination'
import { DARK_PAPER_HEX, DK_SIDE, darkPageBorderCss, darkPageColor } from './editor/dark-page'
import { fillInk } from './editor/shading-ink'
-import { paraBorderCss } from './editor/hf-dom'
+import { textOutlineDecl } from './editor/text-outline'
+import { textAlignDecl } from './editor/text-effects'
+import { paraBorderCss, paraBorderPadding, paraBorderPaddingDecls } from './editor/hf-dom'
/** lines laid out on list geometry: list items and the numbered stray line of a textbox anchor */
const LIST_LINES = '.doc-li, .doc-li-stray'
@@ -187,6 +191,10 @@ export function docCjkFactor(parsed: ParsedDocFull): number {
*/
const NOTO_HAN_SUPERFAMILY_RE = /^(?:noto (?:sans|serif) cjk|source han (?:sans|serif))\b/
export function docAutospaceOff(parsed: ParsedDocFull): boolean {
+ // docDefaults w:lang w:val naming an East Asian language classifies the
+ // Latin text itself as East Asian: no gaps anywhere (Word probe 2026-09-11,
+ // ja-JP both ways; zh/ko assumed by the same mechanism)
+ if (/^(?:ja|zh|ko)(?:[-_]|$)/i.test(parsed.docDefaults?.lang ?? '')) return true
const normal = defaultParaDisplay(parsed)
const normalEa =
normal?.font &&
@@ -264,6 +272,11 @@ export function docBodyFont(parsed: ParsedDocFull): string | undefined {
return normal?.fontAscii ?? normal?.font ?? parsed.docDefaults?.asciiFont
}
+/** the Hyperlink character style: Word's id, or a localized id under the English name */
+function isHyperlinkStyle(info: StyleInfo): boolean {
+ return info.styleId === 'Hyperlink' || /^hyperlink$/i.test(info.name)
+}
+
export function docStyleCss(parsed: ParsedDocFull): string {
const rules: string[] = []
// Dark-page twins of every color rule below (editor/dark-page.ts): same
@@ -608,12 +621,23 @@ export function docStyleCss(parsed: ParsedDocFull): string {
darkDecls.push(`background:${darkPageColor(t.firstRow.fill)}`)
}
if (t.firstRow.bold) decls.push('font-weight:600')
+ if (t.firstRow.italic) decls.push('font-style:italic')
if (t.firstRow.color) {
decls.push(`color:#${t.firstRow.color}`)
darkDecls.push(`color:${darkPageColor(t.firstRow.color)}`)
}
if (t.firstRow.sizeHalfPoints) decls.push(`font-size:${t.firstRow.sizeHalfPoints / 2}pt`)
- const firstRowSel = `${sel} tr:first-child td, ${sel} tr:first-child th`
+ if (t.firstRow.fontAscii) decls.push(`font-family:${cssFontFamily(t.firstRow.fontAscii)}`)
+ if (t.firstRow.charSpacingTwips !== undefined)
+ decls.push(`letter-spacing:${t.firstRow.charSpacingTwips / 20}pt`)
+ if (t.firstRow.caps === 'all') decls.push('text-transform:uppercase')
+ else if (t.firstRow.caps === 'small') decls.push('font-variant-caps:small-caps')
+ // Word extends header-row formatting over the leading w:tblHeader rows;
+ // kept as a comma list because the ink helpers split on ','
+ const headerTr = 'tr[data-repeat-header="1"]:not(tr:not([data-repeat-header="1"]) ~ tr)'
+ const firstRowSel = [`${sel} tr:first-child`, `${sel} ${headerTr}`]
+ .flatMap((tr) => [`${tr} td`, `${tr} th`])
+ .join(', ')
if (decls.length > 0) rules.push(`${firstRowSel} { ${decls.join(';')} }`)
darkTwin(firstRowSel, darkDecls)
if (t.firstRow.fill && !t.firstRow.color) autoInk(firstRowSel, t.firstRow.fill, tableDark)
@@ -704,6 +728,11 @@ export function docStyleCss(parsed: ParsedDocFull): string {
if (gridStrut) decls.push(`--doc-grid-strut-tail:${cssFontFamily(d.fontAscii)}`)
decls.push(`--doc-latin-chain:${docLatinChainCss(d.fontAscii)}`)
}
+ // Latin lines of a paragraph style follow the style's own face, not the
+ // body font (Cambria headings under a Calibri body: 1.172 vs 1.22)
+ if (d.fontAscii && info.type === 'paragraph') {
+ decls.push(`--doc-line-factor-latin:${lineHeightFactor(d.fontAscii)}`)
+ }
if (d.charSpacingTwips !== undefined) decls.push(`letter-spacing:${d.charSpacingTwips / 20}pt`)
// the inherited threshold is re-tested against the style's own size
const kernHalf = d.kernHalfPoints ?? docKernHalf
@@ -714,6 +743,17 @@ export function docStyleCss(parsed: ParsedDocFull): string {
if (d.caps === 'all') decls.push('text-transform:uppercase')
else if (d.caps === 'small') decls.push('font-variant-caps:small-caps')
else if (d.caps === 'none') decls.push('text-transform:none', 'font-variant-caps:normal')
+ if (d.textOutline) decls.push(textOutlineDecl(d.textOutline))
+ // a paragraph style's rPr shading colours its runs, not the block; only
+ // character styles map onto one span
+ if (info.type === 'character' && d.shading) {
+ decls.push(`background-color:#${d.shading}`)
+ darkDecls.push(`background:${darkPageColor(d.shading)}`)
+ if (!d.color && fillInk(d.shading) === 'light') {
+ decls.push(AUTO_INK.light.paper)
+ darkDecls.push(AUTO_INK.light.dark)
+ }
+ }
const styleLh = cssLineHeight(d.lineRule, d.lineRawTwips, d.lineSpacing)
if (styleLh) decls.push(`line-height:${styleLh}`)
// grid span snapping scales by the style's multiple (an explicit single
@@ -732,7 +772,8 @@ export function docStyleCss(parsed: ParsedDocFull): string {
// (:not() bumps specificity above the grid span rule); --doc-line-fixed
// marks them for measureBlocks, which must not divide an inherited document
// auto multiple out of their full-height line box (breakOnlyLineH)
- if ((d.lineRule === 'exact' || d.lineRule === 'atLeast') && d.lineRawTwips) {
+ // (atLeast includes the line="0" natural-height form, like extensions.ts)
+ if ((d.lineRule === 'exact' && d.lineRawTwips) || d.lineRule === 'atLeast') {
decls.push('--doc-line-fixed:1')
rules.push(
`.doc-page [data-style="${CSS.escape(info.styleId)}"]:not(.doc-lh-fixed) span { line-height:inherit }`,
@@ -786,7 +827,7 @@ export function docStyleCss(parsed: ParsedDocFull): string {
)
}
}
- if (d.align) decls.push(`text-align:${d.align}`)
+ if (d.align) decls.push(textAlignDecl(d.align))
if (
parsed.autoHyphenation &&
info.type === 'paragraph' &&
@@ -796,22 +837,22 @@ export function docStyleCss(parsed: ParsedDocFull): string {
decls.push(`hyphens:${h}`, `-webkit-hyphens:${h}`)
}
// style-level paragraph shading (explicit pPr w:shd is inline style and wins)
- if (d.shadingFill) {
+ if (d.shadingFill && d.shadingFill !== 'auto') {
decls.push(`background-color:#${d.shadingFill}`)
darkDecls.push(`background-color:${darkPageColor(d.shadingFill)}`)
}
// style-level w:pBdr, same look as blockAttrs' direct borders (which win as inline style)
if (d.borderSides) {
- let drawn = false
+ let drawn = ''
for (const side of ['top', 'bottom', 'left', 'right'] as const) {
const line = d.borderSides[DK_SIDE[side]]
if (!line) continue
- drawn = true
+ drawn += DK_SIDE[side]
const css = paraBorderCss(line)
decls.push(`border-${side}:${css}`)
darkDecls.push(`border-${side}:${darkPageBorderCss(css)}`)
}
- if (drawn) decls.push('padding:1px 4px')
+ decls.push(...paraBorderPaddingDecls(paraBorderPadding(drawn, d.borderSides)))
}
// the static sheet guesses italic for h4-h6 (Word's built-in defaults);
// a real style definition without w:i means upright
@@ -850,6 +891,24 @@ export function docStyleCss(parsed: ParsedDocFull): string {
rules.push(`.doc-page ${s}.ctx-sp:has(+ ${s}) { margin-bottom:0 !important }`)
rules.push(`.doc-page ${s} + ${s}.ctx-sp { margin-top:0 !important }`)
}
+ // a defined Hyperlink character style paints its links (colour, underline or
+ // none); the .doc-link default only stands in when the document has none.
+ // Word's print layout hides that style's colour and underline on TOC field
+ // entries (TOC \h wraps them in w:hyperlink with the style): the entry keeps
+ // the TOC paragraph's ink while the style's face/size still apply.
+ const tocScopes = [
+ '.doc-toc-line',
+ ...[...parsed.styles.values()]
+ .filter((s) => s.type === 'paragraph' && tocLevelOf(s.styleId, parsed.styles) !== null)
+ .map((s) => `[data-style="${CSS.escape(s.styleId)}"]`),
+ ].join(',')
+ for (const info of parsed.styles.values()) {
+ if (info.type !== 'character' || !isHyperlinkStyle(info)) continue
+ const h = `[data-style="${CSS.escape(info.styleId)}"]`
+ rules.push(`.doc-page .doc-link:has(${h}) { color:inherit;text-decoration:none }`)
+ rules.push(`.doc-page :is(${tocScopes}) ${h} { color:inherit;text-decoration:none }`)
+ darkRules.push(`.page-dark .doc-page :is(${tocScopes}) ${h} { color:inherit }`)
+ }
if (gridStrut) {
// after every [data-style] family rule so the strut face wins the cascade;
// the tail keeps each context's own inherited chain rendering the glyphs
diff --git a/apps/docs/src/renderer/editor/border-metrics.ts b/apps/docs/src/renderer/editor/border-metrics.ts
new file mode 100644
index 0000000..862d23f
--- /dev/null
+++ b/apps/docs/src/renderer/editor/border-metrics.ts
@@ -0,0 +1,53 @@
+/**
+ * Word's drawn thickness of an OOXML border line. w:sz (eighths of a point)
+ * is the width of ONE line; compound styles add fixed 0.75pt "thin" strokes
+ * and gaps around it (probed against Word 2026-09-12: single/double/triple
+ * and the thin/thick families at sz 4, 12, 24, 48). Rows advance by this total,
+ * so every layout consumer must measure the compound thickness, not w:sz.
+ */
+export type BorderLine = { style: string; szEighths?: number } | undefined | null
+
+const THIN_PT = 0.75
+
+const COMPOUND_PT: Record number> = {
+ double: (w) => 3 * w,
+ triple: (w) => 5 * w,
+ thinThickSmallGap: (w) => w + 2 * THIN_PT,
+ thickThinSmallGap: (w) => w + 2 * THIN_PT,
+ thinThickThinSmallGap: (w) => w + 4 * THIN_PT,
+ thinThickMediumGap: (w) => 2 * w,
+ thickThinMediumGap: (w) => 2 * w,
+ thinThickThinMediumGap: (w) => 3 * w,
+ thinThickLargeGap: (w) => w + 3 * THIN_PT,
+ thickThinLargeGap: (w) => w + 3 * THIN_PT,
+ thinThickThinLargeGap: (w) => 2 * w + 4 * THIN_PT,
+}
+
+const DASHED = new Set(['dashed', 'dashSmallGap', 'dotDash', 'dotDotDash', 'dashDotStroked'])
+
+export function isDrawnBorder(b: BorderLine): b is { style: string; szEighths?: number } {
+ return !!b && b.style !== 'none' && b.style !== 'nil'
+}
+
+export function borderTotalPt(b: BorderLine): number {
+ if (!isDrawnBorder(b)) return 0
+ const w = (b.szEighths ?? 4) / 8
+ return COMPOUND_PT[b.style]?.(w) ?? w
+}
+
+/** unrounded CSS px of the drawn thickness */
+export function borderTruePx(b: BorderLine): number {
+ return (borderTotalPt(b) / 72) * 96
+}
+
+/** whole px we draw (Chromium snaps sub-px borders anyway), at least 1 for a drawn line */
+export function borderDrawnPx(b: BorderLine): number {
+ return isDrawnBorder(b) ? Math.max(1, Math.round(borderTruePx(b))) : 0
+}
+
+/** closest CSS border-style; multi-line families become `double` at their total thickness */
+export function borderCssStyle(style: string): string {
+ if (style === 'dotted') return 'dotted'
+ if (DASHED.has(style)) return 'dashed'
+ return style in COMPOUND_PT ? 'double' : 'solid'
+}
diff --git a/apps/docs/src/renderer/editor/caret-marks.ts b/apps/docs/src/renderer/editor/caret-marks.ts
index 3aeead0..42ba2bf 100644
--- a/apps/docs/src/renderer/editor/caret-marks.ts
+++ b/apps/docs/src/renderer/editor/caret-marks.ts
@@ -45,6 +45,74 @@ export const firstTextMarksIn = (doc: PmNode, from: number, to: number): readonl
return marks
}
+/** Paragraph FORMATTING that must survive replacing whole paragraphs — the
+ * paragraph counterpart of FORMAT_MARKS. A selection that consumes whole
+ * blocks makes ProseMirror fill the hole with a DEFAULT paragraph, so
+ * style-derived fonts, alignment, indents and the paragraph-mark font all
+ * silently reset to the theme (r176 follow-up). Identity and annotation
+ * attrs (docxIndex, bookmarks, comments, revisions, sdtShell...) must never
+ * be cloned onto the fresh paragraph; pageBreakBefore stays off for the
+ * r157 reason (a newline must not clone a page break). */
+export const PARA_FORMAT_ATTRS = [
+ 'styleId',
+ 'align',
+ 'lineSpacing',
+ 'lineRule',
+ 'lineRawTwips',
+ 'snapToGrid',
+ 'indentLeft',
+ 'indentRight',
+ 'indentFirstLine',
+ 'spaceBefore',
+ 'spaceAfter',
+ 'spaceBeforeAuto',
+ 'spaceAfterAuto',
+ 'contextualSpacing',
+ 'bidi',
+ 'autoSpace',
+ 'wordWrap',
+ 'overflowPunct',
+ 'eaLang',
+ 'shadingFill',
+ 'shadingDisplay',
+ 'borders',
+ 'borderLines',
+ 'borderReset',
+ 'tabStops',
+ 'emptyRunSize',
+ 'emptyRunFont',
+] as const
+
+/** format attrs of the first textblock in [from, to] — the paragraph
+ * counterpart of firstTextMarksIn (Word's start-of-range rule) */
+export const firstParaFormatIn = (
+ doc: PmNode,
+ from: number,
+ to: number,
+): Record | null => {
+ let found: Record | null = null
+ doc.nodesBetween(from, to, (node) => {
+ if (found) return false
+ if (node.isTextblock) {
+ const picked: Record = {}
+ for (const key of PARA_FORMAT_ATTRS) if (key in node.attrs) picked[key] = node.attrs[key]
+ found = picked
+ return false
+ }
+ return true
+ })
+ return found
+}
+
+/** true when every format attr still sits at its type default — i.e. the
+ * block is the fresh filler paragraph a whole-block replace leaves behind,
+ * not a survivor that kept real formatting (which must not be stomped) */
+export const paraFormatIsDefault = (node: PmNode): boolean =>
+ PARA_FORMAT_ATTRS.every((key) => {
+ const spec = node.type.spec.attrs?.[key]
+ return !spec || node.attrs[key] === spec.default
+ })
+
export const CaretMarksMemory = Extension.create({
name: 'caretMarksMemory',
addProseMirrorPlugins() {
@@ -78,21 +146,37 @@ export const CaretMarksMemory = Extension.create({
// A deletion just emptied this block (Delete/Backspace/Cut over a
// selection): Word keeps the formatting of the START of the
// removed text on the pilcrow, so typing or pasting here must not
- // fall back to the theme font (alpha ledger r172; the typing-over
- // and Enter-over paths carry marks already — plain deletion did not)
+ // fall back to the theme font (r172; the typing-over and
+ // Enter-over paths carry marks already — plain deletion did not)
if (!transactions.some((tr) => tr.docChanged) || oldState.selection.empty) return null
const { from, to } = oldState.selection
const kept = (firstTextMarksIn(oldState.doc, from, to) ?? []).filter((mark) =>
FORMAT_MARKS.has(mark.type.name),
)
- if (kept.length === 0) return null
- return newState.tr
+ // A selection that consumed whole paragraphs left a DEFAULT filler
+ // block: its paragraph formatting (style, paragraph-mark font,
+ // alignment...) must come back from the removed range's first
+ // paragraph, or style-derived fonts reset to the theme (r176)
+ const paraFormat = paraFormatIsDefault(block)
+ ? firstParaFormatIn(oldState.doc, from, to)
+ : null
+ const restoresPara =
+ paraFormat !== null &&
+ PARA_FORMAT_ATTRS.some(
+ (key) => key in block.attrs && paraFormat[key] !== block.attrs[key],
+ )
+ if (kept.length === 0 && !restoresPara) return null
+ const tr = newState.tr
.setNodeMarkup(blockPos, undefined, {
...block.attrs,
+ ...(restoresPara ? paraFormat : null),
caretMarks: serializeMarks(kept),
})
- .setStoredMarks(kept)
.setMeta('addToHistory', false)
+ // an explicit empty stored-marks list means "user cleared" — only
+ // set marks that actually carry something
+ if (kept.length > 0) tr.setStoredMarks(kept)
+ return tr
}
try {
const parsed = JSON.parse(stamped) as { type: string; attrs: Record }[]
diff --git a/apps/docs/src/renderer/editor/checkbox-toggle.ts b/apps/docs/src/renderer/editor/checkbox-toggle.ts
new file mode 100644
index 0000000..b296d85
--- /dev/null
+++ b/apps/docs/src/renderer/editor/checkbox-toggle.ts
@@ -0,0 +1,97 @@
+import { Extension } from '@tiptap/core'
+import type { Mark as PmMark } from '@tiptap/pm/model'
+import { Plugin, TextSelection, type EditorState, type Transaction } from '@tiptap/pm/state'
+import { sdtCheckboxGlyphs } from '@genoffice/docx-engine'
+import { TRACK_IGNORE } from './revisions'
+
+/**
+ * Click-to-toggle for the two kinds of checkbox a docx can hold: legacy
+ * FORMCHECKBOX form fields and w14:checkbox content controls. Both are one
+ * glyph run in the editor whose write-back reads the state off the glyph, so
+ * toggling is swapping the character; the marks stay so the field or control
+ * survives. Plain box characters typed as text are not controls and stay text.
+ */
+
+export interface CheckboxToggleStorage {
+ /** forms protection: the body is read-only, filling the form fields is not */
+ formsFill: boolean
+}
+
+declare module '@tiptap/core' {
+ interface Storage {
+ checkboxToggle: CheckboxToggleStorage
+ }
+}
+
+const FORM_FIELD_GLYPHS = { checked: '\u2612', unchecked: '\u2610' }
+
+function toggledGlyph(glyph: string, marks: readonly PmMark[]): string | null {
+ const field = marks.find((m) => m.type.name === 'instrField')
+ const control = marks.find((m) => m.type.name === 'ctrlCheckbox')
+ const glyphs = control
+ ? sdtCheckboxGlyphs(String(control.attrs.sdtPr ?? ''))
+ : field?.attrs.instr === 'FORMCHECKBOX'
+ ? FORM_FIELD_GLYPHS
+ : null
+ if (!glyphs) return null
+ if (glyph === glyphs.checked) return glyphs.unchecked
+ if (glyph === glyphs.unchecked) return glyphs.checked
+ return null
+}
+
+/**
+ * The transaction toggling the checkbox whose glyph sits right after (`side`
+ * 'after') or right before `pos`, or null when that character is not one. The
+ * toggle is not a tracked change: Word records neither kind of checkbox flip.
+ */
+export function toggleCheckboxAt(
+ state: EditorState,
+ pos: number,
+ side: 'before' | 'after',
+): Transaction | null {
+ const from = side === 'after' ? pos : pos - 1
+ if (from < 0 || from >= state.doc.content.size) return null
+ const node = state.doc.resolve(from).nodeAfter
+ if (!node?.isText || !node.text) return null
+ const glyph = node.text[0]
+ const next = toggledGlyph(glyph, node.marks)
+ if (next === null) return null
+ const tr = state.tr.replaceWith(from, from + glyph.length, state.schema.text(next, node.marks))
+ tr.setSelection(TextSelection.create(tr.doc, from + next.length))
+ return tr.setMeta(TRACK_IGNORE, true).setMeta('addToHistory', true)
+}
+
+export const CheckboxToggleExtension = Extension.create({
+ name: 'checkboxToggle',
+
+ addStorage() {
+ return { formsFill: false }
+ },
+
+ addProseMirrorPlugins() {
+ const storage = this.storage
+ return [
+ new Plugin({
+ props: {
+ handleClick(view, pos, event) {
+ if (event.button !== 0 || event.detail > 1) return false
+ if (event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) return false
+ if (!view.editable && !storage.formsFill) return false
+ // pos is the caret slot nearest the click; the glyph under the
+ // pointer is the character on the side the pointer is on
+ let side: 'before' | 'after' = 'after'
+ try {
+ side = event.clientX >= view.coordsAtPos(pos).left ? 'after' : 'before'
+ } catch {
+ // a position without layout (mid-rerender): fall through
+ }
+ const tr = toggleCheckboxAt(view.state, pos, side)
+ if (!tr) return false
+ view.dispatch(tr)
+ return true
+ },
+ },
+ }),
+ ]
+ },
+})
diff --git a/apps/docs/src/renderer/editor/cjk-punct-shrink.ts b/apps/docs/src/renderer/editor/cjk-punct-shrink.ts
index ea9691d..4560cbb 100644
--- a/apps/docs/src/renderer/editor/cjk-punct-shrink.ts
+++ b/apps/docs/src/renderer/editor/cjk-punct-shrink.ts
@@ -3,6 +3,7 @@ import { Plugin, PluginKey, type EditorState } from '@tiptap/pm/state'
import { Decoration, DecorationSet, type EditorView } from '@tiptap/pm/view'
import type { Node as ProseMirrorNode } from '@tiptap/pm/model'
import { SettledParagraphCache } from './settled-measure'
+import { sameLine } from './justify-shrink'
/**
* Word's CJK line breaking (settings characterSpacingControl =
@@ -265,10 +266,6 @@ function charAdvancePx(cs: CSSStyleDeclaration, ch: string): number {
return w
}
-function sameLine(a: { top: number; bottom: number }, b: { top: number; bottom: number }): boolean {
- return a.top < b.bottom - 1 && a.bottom > b.top + 1
-}
-
class CjkPunctShrinkView {
private lastSig = ''
private results = new SettledParagraphCache()
diff --git a/apps/docs/src/renderer/editor/column-layout.ts b/apps/docs/src/renderer/editor/column-layout.ts
index 7f5db70..64fbbcb 100644
--- a/apps/docs/src/renderer/editor/column-layout.ts
+++ b/apps/docs/src/renderer/editor/column-layout.ts
@@ -2,6 +2,8 @@ import { Extension } from '@tiptap/core'
import { Plugin, PluginKey } from '@tiptap/pm/state'
import { Decoration, DecorationSet } from '@tiptap/pm/view'
import type { EditorView } from '@tiptap/pm/view'
+import { splitFloatStyle } from '../pagination-lines'
+import type { ColumnSplitShape, VerticalBlockSpec } from '../pagination-types'
const key = new PluginKey('columnLayout')
@@ -56,6 +58,8 @@ export interface ColumnBlockSpec {
/** owning section's side margins (--doc-margin-left/right overrides) */
marginLeftPx?: number
marginRightPx?: number
+ /** owning section's top margin (--doc-margin-top override) in docs whose sections disagree on it */
+ marginTopPx?: number
/** owning section's typed docGrid pitch (pt) in mixed-grid docs; 0 = untyped
* section (opts out like snapToGrid=0 via doc-grid-nosnap) */
gridPitchPt?: number
@@ -65,20 +69,51 @@ export interface ColumnBlockSpec {
/** translate; dy < 0 pulls content up over vacated column space */
dx: number
dy: number
+ /** left edge of the block's page on the shared paper (--page-cx); not undone by page-relative anchors */
+ pageDx?: number
+ /** vertical-text section block (doc-vert-block): writing-mode box, see verticalTextSpecs */
+ vertical?: VerticalBlockSpec
+ /** paragraph straddling two columns of different widths: a leading float
+ * (doc-col-split-float) rewraps the head or the tail at the narrower width */
+ split?: ColumnSplitShape
+}
+
+const SPLIT_CLASS = 'doc-col-split-float'
+
+function splitFloatEl(style: string): HTMLElement {
+ const span = document.createElement('span')
+ span.className = SPLIT_CLASS
+ span.contentEditable = 'false'
+ span.setAttribute('aria-hidden', 'true')
+ span.style.cssText = style
+ return span
}
const PATCH_PROPS = [
'--col-w',
'--col-dx',
'--col-dy',
+ '--page-cx',
'--doc-content-w',
'--doc-margin-left',
'--doc-margin-right',
+ '--doc-margin-top',
'--doc-grid-pitch',
'--doc-char-space',
+ '--vert-mb',
]
-const PATCH_CLASSES = ['doc-col-block', 'doc-grid-block', 'doc-grid-nosnap', 'doc-charspace-block']
+const PATCH_CLASSES = [
+ 'doc-col-block',
+ 'doc-grid-block',
+ 'doc-grid-nosnap',
+ 'doc-charspace-block',
+ 'doc-vert-block',
+ 'doc-vert-first',
+ 'doc-vert-tbRl',
+ 'doc-vert-tbRlV',
+ 'doc-vert-btLr',
+]
/** pitch/charSpace-only specs get an inert marker class: .doc-col-block's
* width/transform rules must not touch blocks that only carry their section's
@@ -88,14 +123,21 @@ const PATCH_CLASSES = ['doc-col-block', 'doc-grid-block', 'doc-grid-nosnap', 'do
* snapToGrid=0 class. */
function specClass(spec: ColumnBlockSpec): string {
const varsOnly =
- (spec.gridPitchPt !== undefined || spec.charSpacePt !== undefined) &&
+ (spec.gridPitchPt !== undefined ||
+ spec.charSpacePt !== undefined ||
+ spec.marginTopPx !== undefined) &&
spec.widthPx === undefined &&
spec.contentWPx === undefined &&
spec.dx === 0 &&
- spec.dy === 0
+ spec.dy === 0 &&
+ !spec.pageDx
let cls = varsOnly ? 'doc-grid-block' : 'doc-col-block'
if (spec.gridPitchPt === 0) cls += ' doc-grid-nosnap'
if (spec.charSpacePt !== undefined) cls += ' doc-charspace-block'
+ if (spec.vertical) {
+ cls += ` doc-vert-block doc-vert-${spec.vertical.mode}`
+ if (spec.vertical.firstOnPage) cls += ' doc-vert-first'
+ }
return cls
}
@@ -103,16 +145,30 @@ function specClass(spec: ColumnBlockSpec): string {
export function setColumnLayout(view: EditorView, specs: ColumnBlockSpec[]): void {
const decos: Decoration[] = []
const styleOf = new Map()
+ const splitOf = new Map()
for (const spec of specs) {
+ if (spec.split)
+ splitOf.set(
+ spec.el,
+ splitFloatStyle(
+ spec.split.floatPx,
+ spec.split.heightPx,
+ spec.split.insetPx,
+ spec.split.rtl,
+ ),
+ )
const style =
(spec.widthPx !== undefined ? `--col-w:${round2(spec.widthPx)}px;` : '') +
(spec.contentWPx !== undefined
? `--doc-content-w:${round2(spec.contentWPx)}px;--doc-margin-left:${round2(spec.marginLeftPx ?? 0)}px;--doc-margin-right:${round2(spec.marginRightPx ?? 0)}px;`
: '') +
+ (spec.marginTopPx !== undefined ? `--doc-margin-top:${round2(spec.marginTopPx)}px;` : '') +
(spec.gridPitchPt !== undefined
? `--doc-grid-pitch:${spec.gridPitchPt > 0 ? `${round2(spec.gridPitchPt)}pt` : '0.0001px'};`
: '') +
(spec.charSpacePt !== undefined ? `--doc-char-space:${round4(spec.charSpacePt)}pt;` : '') +
+ (spec.pageDx ? `--page-cx:${round2(spec.pageDx)}px;` : '') +
+ (spec.vertical ? `--vert-mb:${round2(spec.vertical.marginBottomPx)}px;` : '') +
`--col-dx:${round2(spec.dx)}px;--col-dy:${round2(spec.dy)}px`
const cls = specClass(spec)
styleOf.set(spec.el, { style, cls })
@@ -126,6 +182,15 @@ export function setColumnLayout(view: EditorView, specs: ColumnBlockSpec[]): voi
continue
}
decos.push(Decoration.node(from, to, { class: cls, style }, { key: `col-${cls}-${style}` }))
+ const split = splitOf.get(spec.el)
+ if (split)
+ decos.push(
+ Decoration.widget(from + 1, () => splitFloatEl(split), {
+ side: -1,
+ key: `col-split-${split}`,
+ ignoreSelection: true,
+ }),
+ )
}
const next = DecorationSet.create(view.state.doc, decos)
const prev = key.getState(view.state)
@@ -145,6 +210,20 @@ export function setColumnLayout(view: EditorView, specs: ColumnBlockSpec[]): voi
el.classList.remove(...PATCH_CLASSES)
for (const p of PATCH_PROPS) el.style.removeProperty(p)
}
+ // split floats the widget decoration could not place (atomic node views)
+ for (const el of Array.from(
+ view.dom.querySelectorAll(`[data-col-split-patch] > .${SPLIT_CLASS}`),
+ ) as HTMLElement[]) {
+ const host = el.parentElement as HTMLElement
+ if (splitOf.get(host) === el.style.cssText) continue
+ el.remove()
+ host.removeAttribute('data-col-split-patch')
+ }
+ for (const [el, style] of splitOf) {
+ if (el.querySelector(`:scope > .${SPLIT_CLASS}`)) continue
+ el.setAttribute('data-col-split-patch', '1')
+ el.insertBefore(splitFloatEl(style), el.firstChild)
+ }
for (const [el, { style, cls }] of styleOf) {
const classes = cls.split(' ')
if (classes.every((c) => el.classList.contains(c)) && !el.hasAttribute('data-col-patch'))
diff --git a/apps/docs/src/renderer/editor/convert.ts b/apps/docs/src/renderer/editor/convert.ts
index 8b99470..03aee3b 100644
--- a/apps/docs/src/renderer/editor/convert.ts
+++ b/apps/docs/src/renderer/editor/convert.ts
@@ -18,8 +18,9 @@ import {
type TextboxSizePatch,
patchTextboxParas,
generateTableModelXml,
+ symbolGlyph,
+ symbolPuaChar,
type Block,
- type CellBorder,
type ChartDisplay,
type ChartPatch,
type ChartSeriesPatch,
@@ -43,6 +44,7 @@ import {
type TextboxParasPatchSet,
} from '@genoffice/docx-engine'
import { t } from '../i18n/locale'
+import { symbolFontCovers } from '../font-check'
import {
canvasMetrics,
charScaleEm,
@@ -54,6 +56,10 @@ import {
import { firstStrongDir } from './direction'
import { inlineMathML } from './equation'
import { isStraightLineKind } from './shape-svg'
+import { borderDrawnPx, borderTotalPt } from './border-metrics'
+import { parseRunBorderAttr } from './run-border'
+import { parseTextOutlineAttr } from './text-outline'
+import { charScaleXAttr, parseGlowAttr, parseTextEffectAttr } from './text-effects'
/** minimal ProseMirror JSON shapes */
export interface PmMark {
@@ -70,7 +76,23 @@ export interface PmNode {
// ---- Block[] -> ProseMirror doc ----
-export function blocksToPmDoc(blocks: Block[], sections?: SectionInfo[]): PmNode {
+/** document-level layout switches for the display models built here */
+export interface PmDocOptions {
+ /** settings.xml compatibilityMode < 15: w:tblInd measures to the cell text, so
+ * the table border sits one left cell margin further out (Word 2013+ measures
+ * to the border) */
+ legacyTableIndent?: boolean
+}
+
+export function pmDocOptions(parsed: { compatibilityMode?: number }): PmDocOptions {
+ return { legacyTableIndent: (parsed.compatibilityMode ?? 0) < 15 }
+}
+
+export function blocksToPmDoc(
+ blocks: Block[],
+ sections?: SectionInfo[],
+ options: PmDocOptions = {},
+): PmNode {
const content: PmNode[] = []
for (const block of blocks) {
if (block.hidden) continue
@@ -79,6 +101,7 @@ export function blocksToPmDoc(blocks: Block[], sections?: SectionInfo[]): PmNode
block,
sectionRowCapTwips(sections, block.docxIndex),
sectionWidthBudget(sections, block.docxIndex),
+ options,
),
)
}
@@ -119,11 +142,15 @@ function formatAttrs(format: ParaFormat | undefined, runs?: Run[]): Record= colCount) continue
// merged-away and vertical-text cells don't demand word width
if (cell.vMerge === 'continue' || cell.textDirection) continue
+ const mar = cell.cellMarTwips ?? model.cellMarTwips
+ const pad = (mar?.left ?? DEFAULT_CELL_MAR) + (mar?.right ?? DEFAULT_CELL_MAR)
+ for (const nt of cell.nestedTables ?? []) {
+ const ntMin = nestedTableMinTwips(nt, metrics)
+ if (ntMin > 0) mins[start] = Math.max(mins[start], ntMin + pad)
+ }
let wordPx = cellMaxWordPx(cell, metrics)
if (wordPx <= 0) continue
if (metrics) wordPx += MEASURED_EDGE_PX
- const mar = cell.cellMarTwips ?? model.cellMarTwips
- const pad = (mar?.left ?? DEFAULT_CELL_MAR) + (mar?.right ?? DEFAULT_CELL_MAR)
mins[start] = Math.max(mins[start], Math.ceil(wordPx * slack * 15) + pad)
}
}
return mins
}
+/** the autofit reclaim pass never compresses a column below its min-content
+ * or MIN_COL_TWIPS; sliver slots already under that keep their width */
+function reclaimFloorTwips(width: number, minContent: number): number {
+ return Math.max(minContent, Math.min(width, MIN_COL_TWIPS))
+}
+
+/** side cell margins of a table's own cells (twips) */
+function sideMarginTwips(model: TableModel): number {
+ const mar = model.cellMarTwips
+ return (mar?.left ?? DEFAULT_CELL_MAR) + (mar?.right ?? DEFAULT_CELL_MAR)
+}
+
+/** narrowest width a nested table can take inside its cell: fixed grids keep
+ * their declared width, pct tables follow the cell, autofit ones shrink to
+ * every column's min-content (an empty cell keeps its side margins). Word
+ * straddles the outer vertical borders, so the box is half a border wider on
+ * each side (a regression sample: eight nesting levels, each parent column
+ * = nested grid + 216 + 10 twips for sz 4 borders). */
+function nestedTableMinTwips(nt: TableModel, metrics: FontMetricsProvider | null): number {
+ const widths = nt.colWidthsTwips
+ if (!widths?.length || nt.widthPct) return 0
+ const indent = tableIndentTwips(nt)
+ const border = ((borderTotalPt(nt.borders?.left) + borderTotalPt(nt.borders?.right)) / 2) * 20
+ if (nt.fixedLayout) return widths.reduce((a, b) => a + b, 0) + indent + border
+ const mins = minContentColTwips(nt, widths.length, metrics)
+ return (
+ mins.reduce((sum, m, i) => sum + nestedFloorTwips(widths[i], m, sideMarginTwips(nt)), 0) +
+ indent +
+ border
+ )
+}
+
+/** a nested table over its cell width shrinks each column to its min-content;
+ * an empty column keeps its side margins (Word: tcW 360/360 holding a nested
+ * table and "8" in a 544-twip cell -> 222/328), sliver grid slots keep their width */
+function nestedFloorTwips(width: number, minContent: number, sideMar: number): number {
+ return Math.max(minContent, Math.min(width, sideMar))
+}
+
/** paragraph indent inside a cell eats line width like the word itself does;
* list fallbacks mirror the .doc-li per-level CSS defaults (0.55in + 0.3in/level) */
function paraIndentPx(para: TableParagraph): number {
@@ -388,43 +458,58 @@ function cellMaxWordPx(cell: TableCell, metrics: FontMetricsProvider | null): nu
* Word autofit (tblW auto/absent, no fixed tblLayout): a column grows to its
* min-content — the widest unbreakable word — so narrow declared widths don't
* shatter words char by char (heuristic estimate, see maxWordWidthPx). Growth
- * past the fit width (or the declared total, if that was already wider) is
- * reclaimed proportionally from columns with surplus over their own
- * min-content; any remainder spills and is bounded by clampTableColWidths.
- * Display-only, like the clamp.
+ * past the fit width, like a declared total already past it, is reclaimed
+ * proportionally from columns with surplus over their own min-content; any
+ * remainder spills and is bounded by clampTableColWidths. Display-only, like
+ * the clamp.
*/
export function expandAutofitColWidths(
model: TableModel,
availTwips: number,
fitTwips: number = availTwips,
metrics: FontMetricsProvider | null = canvasMetrics(),
+ nested = false,
): TableModel {
const indent = tableIndentTwips(model)
const budget = availTwips - indent
let widths = model.colWidthsTwips
let widthsChanged = false
+ // a dxa tblW is only a preferred width: without w:tblLayout fixed Word still
+ // grows a column to its widest unbreakable word and reclaims the growth from
+ // the other columns' surplus, keeping the declared total (measured: a long
+ // merge-field token grew its tcW 2835 -> 3000, neighbours shrank)
+ const autofit = model.autoLayout || (!model.fixedLayout && !model.widthPct)
// pct-width autofit tables: the min-content floor applies to the resolved
// widths (Word never wraps below the widest word even when w:tblW is a tiny
// percentage); growth converts the table to absolute widths for display.
// pct resolves against the full text column — the render path draws
// width:N% of the content box and applies the indent as a margin
let resolvedPct = false
- if (model.autoLayout && model.widthPct && model.colWidthsPct?.length && budget > 0) {
+ if (autofit && model.widthPct && model.colWidthsPct?.length && budget > 0) {
const tableW = (Math.min(fitTwips, availTwips) * model.widthPct) / 100
if (tableW > 0) {
widths = model.colWidthsPct.map((p) => Math.round((p / 100) * tableW))
resolvedPct = true
}
}
- if (model.autoLayout && (resolvedPct || !model.widthPct) && widths?.length && budget > 0) {
+ if (autofit && (resolvedPct || !model.widthPct) && widths?.length && budget > 0) {
const mins = minContentColTwips(model, widths.length, metrics).map((m) => Math.min(m, budget))
- if (mins.some((m, i) => m > widths![i])) {
- const declared = widths.reduce((a, b) => a + b, 0)
+ const declared = widths.reduce((a, b) => a + b, 0)
+ const target = Math.min(fitTwips, availTwips) - indent
+ // Word aligns cell text, not the border, with the text column: a tblW auto
+ // grid may hang into both margins by its side cell margins, and over-wide
+ // tcW (preferred widths) compress to that box, not to the column itself.
+ // A nested table sits inside the cell padding, so it never hangs.
+ const sideMar = sideMarginTwips(model)
+ const kept =
+ resolvedPct || nested ? target : Math.max(target, Math.min(declared, target + sideMar))
+ if (mins.some((m, i) => m > widths![i]) || (!resolvedPct && declared > kept)) {
const grown = widths.map((w, i) => Math.max(w, mins[i]))
- const target = Math.max(Math.min(fitTwips, availTwips) - indent, declared)
- const overflow = grown.reduce((a, b) => a + b, 0) - target
+ const overflow = grown.reduce((a, b) => a + b, 0) - kept
if (overflow > 0) {
- const floors = grown.map((w, i) => Math.max(mins[i], Math.min(w, MIN_COL_TWIPS)))
+ const floors = grown.map((w, i) =>
+ nested ? nestedFloorTwips(w, mins[i], sideMar) : reclaimFloorTwips(w, mins[i]),
+ )
const surplus = grown.map((w, i) => Math.max(0, w - floors[i]))
const totalSurplus = surplus.reduce((a, b) => a + b, 0)
if (totalSurplus > 0) {
@@ -436,8 +521,8 @@ export function expandAutofitColWidths(
// token): compress proportionally like Word instead of handing the
// excess to clampTableColWidths, which zeroes trailing columns
const sum = grown.reduce((a, b) => a + b, 0)
- if (sum > target) {
- const scale = target / sum
+ if (sum > kept) {
+ const scale = kept / sum
for (let i = 0; i < grown.length; i++)
grown[i] = Math.max(1, Math.round(grown[i] * scale))
}
@@ -447,7 +532,7 @@ export function expandAutofitColWidths(
}
}
const { rows, changed: rowsChanged } = mapNestedTables(model, widths, budget, (nt, avail) =>
- expandAutofitColWidths(nt, avail, avail, metrics),
+ expandAutofitColWidths(nt, avail, avail, metrics, true),
)
if (!widthsChanged && !rowsChanged) return model
const result = withColWidths(model, rows, widthsChanged ? widths : undefined)
@@ -455,13 +540,22 @@ export function expandAutofitColWidths(
return result
}
+/** legacy tblInd (measured to the cell text) as a border-edge indent; display-only */
+export function legacyIndentTable(model: TableModel): TableModel {
+ if (model.align === 'center' || model.align === 'right' || model.floatSide) return model
+ const shift = model.cellMarTwips?.left ?? DEFAULT_CELL_MAR
+ return shift > 0 ? { ...model, indentTwips: (model.indentTwips ?? 0) - shift } : model
+}
+
function displayTable(
table: TableModel | null,
rowCapTwips: number | null,
budget: TableWidthBudget | null,
+ options: PmDocOptions = {},
): TableModel | null {
if (!table) return null
let t = table
+ if (options.legacyTableIndent) t = legacyIndentTable(t)
if (rowCapTwips != null) t = capTableRowHeights(t, rowCapTwips)
if (budget != null) {
t = expandAutofitColWidths(t, budgetAvail(t, budget), budget.fit)
@@ -474,7 +568,10 @@ function blockToPmNode(
block: Block,
rowCapTwips: number | null = null,
budget: TableWidthBudget | null = null,
+ options: PmDocOptions = {},
): PmNode {
+ if (block.altChunk && options.legacyTableIndent)
+ options = { ...options, legacyTableIndent: false }
switch (block.type) {
case 'heading':
return {
@@ -547,6 +644,7 @@ function blockToPmNode(
budget ? budgetAvail(table, budget) : null,
budget?.fit ?? null,
budget?.paper ?? null,
+ options.legacyTableIndent ?? false,
)
// content-control member tables need the shell for chrome hit-testing
if (block.sdtShell) node.attrs = { ...node.attrs, sdtShell: JSON.stringify(block.sdtShell) }
@@ -568,6 +666,7 @@ function blockToPmNode(
imageWidthPx: block.imageWidthPx ?? null,
imageHeightPx: block.imageHeightPx ?? null,
imageCrop: block.imageCrop ?? null,
+ imageEffects: block.imageEffects ?? null,
imageFillRect: block.imageFillRect ?? null,
imageLeadingText: block.imageLeadingText ?? null,
imageLeadingFont: block.imageLeadingFont ?? null,
@@ -586,6 +685,7 @@ function blockToPmNode(
imageZOrder: block.imageZOrder ?? null,
imageOffsetXEmu: block.imageOffsetXEmu ?? null,
imageOffsetYEmu: block.imageOffsetYEmu ?? null,
+ imageRelV: block.imageRelV ?? null,
imageAnchorLocked: block.imageAnchorLocked ?? false,
imagePosH: block.imagePosH ?? null,
imagePosV: block.imagePosV ?? null,
@@ -593,7 +693,7 @@ function blockToPmNode(
imageFlipH: block.imageFlipH ?? false,
imageFlipV: block.imageFlipV ?? false,
imageBorder: block.imageBorder ?? null,
- table: displayTable(block.table ?? null, rowCapTwips, budget),
+ table: displayTable(block.table ?? null, rowCapTwips, budget, options),
fieldDisplay: block.fieldDisplay ?? null,
diagramDisplay: block.diagramDisplay ?? null,
decorative: block.decorative ?? false,
@@ -632,10 +732,7 @@ function cellRowSpan(model: TableModel, row: number, cell: number, positions: nu
return span
}
-function cellBorderPx(b: CellBorder | undefined): number {
- if (!b || b.style === 'none' || b.style === 'nil') return 0
- return Math.max(1, Math.round(((b.szEighths ?? 4) / 8 / 72) * 96))
-}
+const cellBorderPx = borderDrawnPx
/** Inner clip-box height (twips) for cells of hRule="exact" rows — Word clips overflow
* instead of growing the row. null = not exact, or the cell spans rows (its clip height
@@ -671,7 +768,9 @@ export function tableModelToPmNode(
availTwips: number | null = null,
fitTwips: number | null = null,
paperTwips: number | null = null,
+ legacyIndent = false,
): PmNode {
+ if (legacyIndent) model = legacyIndentTable(model)
if (rowCapTwips != null) model = capTableRowHeights(model, rowCapTwips)
if (availTwips != null) {
model = expandAutofitColWidths(model, availTwips, fitTwips ?? availTwips)
@@ -685,9 +784,10 @@ export function tableModelToPmNode(
return at
})
})
- // 1 px = 15 twips (96dpi); use real values when absolute grid widths exist, fall back to percentage approximation otherwise
+ // 1 px = 15 twips (96dpi); use real values when absolute grid widths exist, fall back to percentage approximation otherwise.
+ // No px floor on real grids: form grids hold dozens of sliver columns that only sit inside spanned cells
const widthPx = model.colWidthsTwips
- ? model.colWidthsTwips.map((width) => Math.max(24, Math.round(width / 15)))
+ ? model.colWidthsTwips.map((width) => Math.max(1, Math.round(width / 15)))
: model.colWidthsPct?.map((width) => Math.max(24, Math.round(width * 6.24)))
const hasHeaderRow =
model.rows.length > 1 && model.rows[0].every((cell) => cell.bold || cell.fill !== undefined)
@@ -748,6 +848,8 @@ export function tableModelToPmNode(
tblFloatYTwips: model.floatPos?.yTwips ?? null,
tblFloatHorzAnchor: model.floatPos?.horzAnchor ?? null,
tblFloatVertAnchor: model.floatPos?.vertAnchor ?? null,
+ tblFloatXSpec: model.floatPos?.xSpec ?? null,
+ tblFloatYSpec: model.floatPos?.ySpec ?? null,
tblFloatDistance: model.floatPos?.distanceTwips ?? null,
tblFloatWidthPx:
tblFloatSource && widthPx ? widthPx.reduce((sum, width) => sum + width, 0) : null,
@@ -1206,7 +1308,7 @@ export function runsToInline(runs: Run[]): PmNode[] {
const marks = runMarks(run)
// \n = soft line break, \f = in-paragraph page break, \v = column break
const breakMarks = marks.length > 0 ? { marks } : {}
- for (const segment of run.text.split(/([\n\f\v])/)) {
+ for (const segment of symDisplayText(run).split(/([\n\f\v])/)) {
if (segment === '\n') nodes.push({ type: 'hardBreak', ...breakMarks })
else if (segment === '\f')
nodes.push({ type: 'hardBreak', attrs: { pageBreak: true }, ...breakMarks })
@@ -1229,6 +1331,7 @@ export function runsToInline(runs: Run[]): PmNode[] {
wrap: run.image.wrap ?? null,
offsetXEmu: run.image.offsetXEmu ?? null,
offsetYEmu: run.image.offsetYEmu ?? null,
+ relV: run.image.relV ?? null,
wrapDistTopEmu: run.image.wrapDistTopEmu ?? null,
wrapDistBottomEmu: run.image.wrapDistBottomEmu ?? null,
wrapDistLeftEmu: run.image.wrapDistLeftEmu ?? null,
@@ -1280,6 +1383,7 @@ function runMarks(run: Run): PmMark[] {
attrs: { href: run.link.href, rId: run.link.rId ?? null, tooltip: run.link.tooltip ?? null },
})
if (run.refField !== undefined) marks.push({ type: 'refField', attrs: { name: run.refField } })
+ if (run.sym) marks.push({ type: 'docSym', attrs: { font: run.sym.font, char: run.sym.char } })
if (run.instrField !== undefined) {
const isZotero = /^\s*(?:ADDIN\s+)?(?:ZOTERO_|CSL_)/i.test(run.instrField)
let fieldId: number | null = null
@@ -1301,6 +1405,8 @@ function runMarks(run: Run): PmMark[] {
},
})
}
+ if (run.sdtCheckboxXml !== undefined)
+ marks.push({ type: 'ctrlCheckbox', attrs: { sdtPr: run.sdtCheckboxXml } })
if (run.commentIds?.length)
marks.push({ type: 'comment', attrs: { ids: run.commentIds.join(' ') } })
if (run.ins) {
@@ -1336,6 +1442,13 @@ function runMarks(run: Run): PmMark[] {
run.kernHalfPoints !== undefined ||
run.highlight ||
run.shading ||
+ run.shadingDisplay ||
+ run.textOutline ||
+ run.textEffect ||
+ run.dstrike ||
+ run.glow ||
+ run.positionHalfPoints ||
+ run.bdr ||
run.vertAlign ||
run.em ||
run.bold === false ||
@@ -1348,6 +1461,12 @@ function runMarks(run: Run): PmMark[] {
run.styleId ||
run.rawRPr
) {
+ // an inline-block cannot wrap and drops inherited underlines: only
+ // whitespace-free, undecorated runs get the real glyph compression
+ const scaleX =
+ run.charScalePct && !/\s/.test(run.text) && !run.underline && !run.strike && !run.link
+ ? charScaleXAttr(run.text, run.charScalePct, charScaleEm(run.text, run.charScalePct))
+ : null
marks.push({
type: 'docTextStyle',
attrs: {
@@ -1359,10 +1478,18 @@ function runMarks(run: Run): PmMark[] {
// cs chain only kicks in for complex-script text (Word's w:cs semantics)
csFont: run.csFont && textHasComplexScript(run.text) ? run.csFont : null,
charSpacingTwips: run.charSpacingTwips ?? null,
- charScaleEm: run.charScalePct ? charScaleEm(run.text, run.charScalePct) : null,
+ charScaleEm: run.charScalePct && !scaleX ? charScaleEm(run.text, run.charScalePct) : null,
+ charScaleX: scaleX,
kern: wordKerns(run.kernHalfPoints, run.sizeHalfPoints) ?? null,
highlight: run.highlight ?? null,
shading: run.shading ?? null,
+ shadingDisplay: run.shadingDisplay ?? null,
+ textOutline: run.textOutline ? JSON.stringify(run.textOutline) : null,
+ textEffect: run.textEffect ?? null,
+ dstrike: run.dstrike ?? null,
+ glow: run.glow ? JSON.stringify(run.glow) : null,
+ positionHalfPoints: run.positionHalfPoints ?? null,
+ bdr: run.bdr ? JSON.stringify(run.bdr) : null,
vertAlign: run.vertAlign ?? null,
em: run.em ?? null,
boldOff: run.bold === false || null,
@@ -1404,7 +1531,151 @@ export interface SavePlan {
totalOriginal: number
}
-export function pmDocToSavePlan(doc: PmNode, originalBlocks: Block[]): SavePlan {
+const ZOTERO_FIELD_INSTR_RE = /^\s*(?:ADDIN\s+)?(?:ZOTERO_|CSL_)/i
+type ZoteroFieldPart = 'single' | 'begin' | 'inside' | 'end'
+interface ZoteroTextRef {
+ blockIndex: number
+ /** ordinal of the leaf among the block's leaves, for adjacency checks */
+ leafIndex: number
+ node: PmNode
+ markIndex: number
+ instr: string
+ fieldId: number | null
+ part: string | null
+}
+
+/**
+ * Zotero fields whose result spans paragraphs share a fieldId, and each run's
+ * part decides where the field begin/end runs are written. Editing can leave a
+ * group without those runs (paragraph deleted, begin run split by Enter, last
+ * run's text removed, pasted copy without ids), so the parts are recomputed
+ * from document order before saving: the first run begins, the last one ends,
+ * and a group interrupted by another field or a non-paragraph block becomes
+ * separate fields instead of swallowing what lies between.
+ */
+export function normalizeZoteroFieldParts(doc: PmNode): PmNode {
+ const blocks = doc.content ?? []
+ const refs: ZoteroTextRef[] = []
+ const leafCounts: number[] = []
+ const collect = (node: PmNode, blockIndex: number) => {
+ if (node.content) {
+ for (const child of node.content) collect(child, blockIndex)
+ return
+ }
+ const leafIndex = leafCounts[blockIndex]++
+ if (node.text === undefined) return
+ const markIndex = (node.marks ?? []).findIndex(
+ (m) => m.type === 'instrField' && ZOTERO_FIELD_INSTR_RE.test(String(m.attrs?.instr ?? '')),
+ )
+ if (markIndex < 0) return
+ const attrs = node.marks![markIndex].attrs ?? {}
+ const id = Number(attrs.fieldId)
+ refs.push({
+ blockIndex,
+ leafIndex,
+ node,
+ markIndex,
+ instr: String(attrs.instr ?? ''),
+ fieldId: Number.isSafeInteger(id) && id > 0 ? id : null,
+ part: typeof attrs.fieldPart === 'string' ? attrs.fieldPart : null,
+ })
+ }
+ blocks.forEach((block, index) => {
+ leafCounts[index] = 0
+ collect(block, index)
+ })
+ if (refs.length === 0) return doc
+
+ let nextId = Math.max(0, ...refs.map((ref) => ref.fieldId ?? 0)) + 1
+ // runs that lost their id (clipboard round trip) rejoin as one field while they
+ // touch each other with the same instruction (or end one paragraph and open the
+ // next); two copies of a citation with text between them stay two fields, and
+ // they never join a field that kept its id
+ const touches = (prev: ZoteroTextRef, next: ZoteroTextRef) =>
+ prev.blockIndex === next.blockIndex
+ ? next.leafIndex === prev.leafIndex + 1
+ : next.blockIndex === prev.blockIndex + 1 &&
+ prev.leafIndex === leafCounts[prev.blockIndex] - 1 &&
+ next.leafIndex === 0
+ const lostId = new Set()
+ for (let i = 0; i < refs.length; i++) {
+ const ref = refs[i]
+ if (ref.fieldId !== null) continue
+ const prev = refs[i - 1]
+ const joins =
+ prev !== undefined && lostId.has(prev) && prev.instr === ref.instr && touches(prev, ref)
+ ref.fieldId = joins ? prev.fieldId : nextId++
+ ref.part = null
+ lostId.add(ref)
+ }
+ const groups = new Map()
+ const idsInBlock = new Map>()
+ for (const ref of refs) {
+ const id = ref.fieldId!
+ groups.set(id, [...(groups.get(id) ?? []), ref])
+ idsInBlock.set(ref.blockIndex, new Set([...(idsInBlock.get(ref.blockIndex) ?? []), id]))
+ }
+ const isParagraphBlock = (index: number) => {
+ const type = blocks[index]?.type
+ return type === 'docParagraph' || type === 'docHeading' || type === 'docListItem'
+ }
+ const desired = new Map()
+ for (const [id, members] of groups) {
+ const segments: ZoteroTextRef[][] = [[members[0]]]
+ for (let i = 1; i < members.length; i++) {
+ const prev = members[i - 1]
+ const cur = members[i]
+ let split = false
+ for (let b = prev.blockIndex + 1; b < cur.blockIndex && !split; b++) {
+ const others = idsInBlock.get(b)
+ split = !isParagraphBlock(b) || (others !== undefined && [...others].some((o) => o !== id))
+ }
+ if (split) segments.push([cur])
+ else segments[segments.length - 1].push(cur)
+ }
+ segments.forEach((segment, si) => {
+ const fieldId = si === 0 ? id : nextId++
+ segment.forEach((ref, ri) => {
+ const part: ZoteroFieldPart =
+ segment.length === 1
+ ? 'single'
+ : ri === 0
+ ? 'begin'
+ : ri === segment.length - 1
+ ? 'end'
+ : 'inside'
+ const idAttr = Number(ref.node.marks![ref.markIndex].attrs?.fieldId)
+ if (idAttr !== fieldId || ref.part !== part)
+ desired.set(ref.node, { markIndex: ref.markIndex, fieldId, part })
+ })
+ })
+ }
+ if (desired.size === 0) return doc
+
+ const rebuild = (node: PmNode): PmNode => {
+ const want = desired.get(node)
+ if (want) {
+ const marks = node.marks!.map((mark, i) =>
+ i === want.markIndex
+ ? { ...mark, attrs: { ...mark.attrs, fieldId: want.fieldId, fieldPart: want.part } }
+ : mark,
+ )
+ return { ...node, marks }
+ }
+ if (!node.content) return node
+ let changed = false
+ const content = node.content.map((child) => {
+ const next = rebuild(child)
+ if (next !== child) changed = true
+ return next
+ })
+ return changed ? { ...node, content } : node
+ }
+ return rebuild(doc)
+}
+
+export function pmDocToSavePlan(inputDoc: PmNode, originalBlocks: Block[]): SavePlan {
+ const doc = normalizeZoteroFieldParts(inputDoc)
const originalByIndex = new Map()
for (const block of originalBlocks) {
if (!block.hidden && block.docxIndex !== null) originalByIndex.set(block.docxIndex, block)
@@ -2135,7 +2406,7 @@ function tableTextsPatch(node: PmNode, original: Block): (string[] | null)[][] |
const origRow = patchableCells(orig.rows[r])
return patchableCells(row).map((cell, c) => {
const originalCell = origRow[c]
- if (!originalCell) return null
+ if (!originalCell || cell.vMerge === 'continue') return null
if (cell.paras.join('\n') === originalCell.paras.join('\n')) return null
changed = true
return cell.paras
@@ -2154,7 +2425,8 @@ function tableTextsPatchFromModel(
const origRow = patchableCells(original.table!.rows[r])
return patchableCells(row).map((cell, c): CellTextsPatch | null => {
const originalCell = origRow[c]
- if (!originalCell) return null
+ // the PM model never carries continuation-cell content: their original bytes stay
+ if (!originalCell || cell.vMerge === 'continue') return null
// nested tables: diff cell texts per table; changes go through the recursive surgical patch
if (cell.nestedTables?.length && originalCell.nestedTables?.length) {
const nested = cell.nestedTables.map((nt, i) => {
@@ -2213,7 +2485,7 @@ function nestedTextsDiff(
const origRow = patchableCells(original.rows[r])
return patchableCells(row).map((cell, c): CellParaPatch[] | null => {
const originalCell = origRow[c]
- if (!originalCell) return null
+ if (!originalCell || cell.vMerge === 'continue') return null
const text = cell.paras.join('\n')
const richTexts = parsedCellParaTexts(originalCell)
if (text === originalCell.paras.join('\n') || text === richTexts.join('\n')) return null
@@ -2435,6 +2707,18 @@ function nodeFormat(node: PmNode): ParaFormat | undefined {
/* ignore malformed */
}
}
+ if (node.attrs?.frame) {
+ try {
+ const parsed = JSON.parse(String(node.attrs.frame))
+ if (parsed && typeof parsed === 'object' && parsed.wTwips > 0) format.frame = parsed
+ } catch {
+ /* ignore malformed */
+ }
+ }
+ if (node.attrs?.textDirection) {
+ const dir = String(node.attrs.textDirection)
+ if (dir === 'tbRl' || dir === 'tbRlV' || dir === 'btLr') format.textDirection = dir
+ }
if (node.attrs?.emptyRunSize) format.emptyRunSizeHalfPoints = Number(node.attrs.emptyRunSize)
if (node.attrs?.emptyRunFont) format.emptyRunFontFamily = String(node.attrs.emptyRunFont)
return Object.keys(format).length > 0 ? format : undefined
@@ -2544,7 +2828,13 @@ export function inlineToRuns(content: PmNode[]): Run[] {
const ch = node.attrs?.pageBreak ? '\f' : node.attrs?.colBreak ? '\v' : '\n'
const prev = runs[runs.length - 1]
const prevAtomic =
- prev && (prev.noteRef || prev.xeTerm !== undefined || prev.math || prev.ruby || prev.image)
+ prev &&
+ (prev.noteRef ||
+ prev.xeTerm !== undefined ||
+ prev.math ||
+ prev.sym ||
+ prev.ruby ||
+ prev.image)
if (node.marks?.length) runs.push(runFromMarks(ch, node.marks))
else if (prev && !prevAtomic) prev.text += ch
else runs.push({ text: ch })
@@ -2602,11 +2892,29 @@ export function inlineToRuns(content: PmNode[]): Run[] {
continue
}
if (node.type !== 'text' || !node.text) continue
- runs.push(runFromMarks(node.text, node.marks ?? []))
+ runs.push(...symRuns(runFromMarks(node.text, node.marks ?? [])))
}
return mergeRuns(runs)
}
+/** an installed symbol font draws the w:sym glyph itself (the exact Word shape), so the
+ * editor text is the private-use code the font's cmap indexes; the Unicode stand-in is
+ * for machines without the font. Display only: runFromMarks turns it back. */
+function symDisplayText(run: Run): string {
+ if (!run.sym) return run.text
+ const pua = symbolPuaChar(run.sym.char)
+ return pua && run.text !== pua && symbolFontCovers(run.sym.font, pua) ? pua : run.text
+}
+
+/** a w:sym run is one glyph; text edited or merged under its mark goes back as plain runs */
+function symRuns(run: Run): Run[] {
+ if (!run.sym) return [run]
+ const glyph = symbolGlyph(run.sym.font, run.sym.char)
+ if (run.text === glyph) return [run]
+ const { sym, ...plain } = run
+ return [...run.text].map((ch) => ({ ...plain, text: ch, ...(ch === glyph ? { sym } : {}) }))
+}
+
function runFromMarks(text: string, marks: PmMark[]): Run {
const run: Run = { text }
for (const mark of marks) {
@@ -2622,6 +2930,10 @@ function runFromMarks(text: string, marks: PmMark[]): Run {
}
} else if (mark.type === 'refField') {
run.refField = String(mark.attrs?.name ?? '')
+ } else if (mark.type === 'docSym') {
+ run.sym = { font: String(mark.attrs?.font ?? ''), char: String(mark.attrs?.char ?? '') }
+ if (run.text === symbolPuaChar(run.sym.char))
+ run.text = symbolGlyph(run.sym.font, run.sym.char) ?? run.text
} else if (mark.type === 'instrField') {
run.instrField = String(mark.attrs?.instr ?? '')
if (mark.attrs?.beginXml) run.fldBeginXml = String(mark.attrs.beginXml)
@@ -2638,6 +2950,8 @@ function runFromMarks(text: string, marks: PmMark[]): Run {
run.zoteroFieldPart = fieldPart
}
}
+ } else if (mark.type === 'ctrlCheckbox') {
+ run.sdtCheckboxXml = String(mark.attrs?.sdtPr ?? '')
} else if (mark.type === 'comment') {
const ids = String(mark.attrs?.ids ?? '')
.split(' ')
@@ -2659,6 +2973,23 @@ function runFromMarks(text: string, marks: PmMark[]): Run {
run.charSpacingTwips = Number(mark.attrs.charSpacingTwips)
if (mark.attrs?.highlight) run.highlight = String(mark.attrs.highlight)
if (mark.attrs?.shading) run.shading = String(mark.attrs.shading)
+ if (mark.attrs?.textOutline) {
+ const outline = parseTextOutlineAttr(String(mark.attrs.textOutline))
+ if (outline) run.textOutline = outline
+ }
+ const effect = parseTextEffectAttr(mark.attrs?.textEffect)
+ if (effect) run.textEffect = effect
+ if (mark.attrs?.dstrike) run.dstrike = true
+ if (mark.attrs?.glow) {
+ const glow = parseGlowAttr(String(mark.attrs.glow))
+ if (glow) run.glow = glow
+ }
+ if (mark.attrs?.positionHalfPoints)
+ run.positionHalfPoints = Number(mark.attrs.positionHalfPoints)
+ if (mark.attrs?.bdr) {
+ const bdr = parseRunBorderAttr(String(mark.attrs.bdr))
+ if (bdr) run.bdr = bdr
+ }
if (mark.attrs?.vertAlign === 'superscript' || mark.attrs?.vertAlign === 'subscript') {
run.vertAlign = mark.attrs.vertAlign
}
@@ -2695,13 +3026,17 @@ function mergeRuns(runs: Run[]): Run[] {
run.noteRef ||
run.xeTerm !== undefined ||
run.instrField !== undefined ||
+ run.sdtCheckboxXml !== undefined ||
run.math ||
+ run.sym ||
run.ruby ||
run.image ||
prev?.noteRef ||
prev?.xeTerm !== undefined ||
prev?.instrField !== undefined ||
+ prev?.sdtCheckboxXml !== undefined ||
prev?.math ||
+ prev?.sym ||
prev?.ruby ||
prev?.image
if (prev && !atomic && runStyleKey(prev) === runStyleKey(run)) prev.text += run.text
@@ -2724,6 +3059,7 @@ function runStyleKey(run: Run): string {
run.fontAscii ?? null,
run.highlight ?? null,
run.shading ?? null,
+ run.textOutline ? JSON.stringify(run.textOutline) : null,
run.vertAlign ?? null,
run.link?.href ?? null,
run.link?.rId ?? null,
@@ -2734,7 +3070,9 @@ function runStyleKey(run: Run): string {
run.refField ?? null,
run.instrField ?? null,
run.fldBeginXml ?? null,
+ run.sdtCheckboxXml ?? null,
run.math?.omml ?? null,
+ run.sym ? [run.sym.font, run.sym.char] : null,
run.ruby?.xml ?? null,
])
}
@@ -2780,8 +3118,11 @@ function normalizedRuns(runs: Run[]): unknown[] {
r.xeTerm ?? null,
r.refField ?? null,
r.instrField ?? null,
+ r.zoteroFieldPart ?? null,
r.fldBeginXml ?? null,
+ r.sdtCheckboxXml ?? null,
r.math?.omml ?? null,
+ r.sym ? [r.sym.font, r.sym.char] : null,
r.ruby?.xml ?? null,
r.image?.xml ?? null,
],
diff --git a/apps/docs/src/renderer/editor/decoration-extensions.ts b/apps/docs/src/renderer/editor/decoration-extensions.ts
index 6bfe30a..f05c2b3 100644
--- a/apps/docs/src/renderer/editor/decoration-extensions.ts
+++ b/apps/docs/src/renderer/editor/decoration-extensions.ts
@@ -163,9 +163,113 @@ interface MeasuredTab {
/** run carries the underline mark: browsers do not draw text-decoration
* across a tab advance, so the gap gets a border-bottom line instead */
underlined?: boolean
- /** no room left on the line: render at a hair's width (font-size 0 lifts
- * Chromium's one-space minimum tab advance) */
+ /** no room left on the line: render at half a space (the smallest advance
+ * Chromium honours without skipping to the next stop) */
collapsed?: boolean
+ /** right/center/decimal tab whose short segment fits at the stop:
+ * white-space:pre glues the tab to the word after it so a rounding
+ * overflow cannot strand the segment on the next line */
+ glue?: boolean
+ /** first-line tab inside the hanging area: rendered as a box of this width
+ * (layout px) because no tab-size can express its advance (see measureParagraph) */
+ fixed?: number
+}
+
+export interface TabTargetInput {
+ /** tab position in tab-origin space (layout px) */
+ x: number
+ minAdv: number
+ segWidth: number
+ /** this tab's segment plus everything after it up to a hard break */
+ restWidth: number
+ paraW: number
+ stops: Array<{ x: number; val: TabStop['val']; leader?: string }>
+ /** default tab grid (layout px); 0 = zero-width default tabs */
+ gridPx: number
+ /** left indent (tab-origin px) of a paragraph whose first line starts before
+ * it (w:hanging); only passed for tabs on that first line */
+ hangingX?: number
+}
+
+export interface TabTarget {
+ target: number
+ val: TabStop['val']
+ leader?: string
+ collapsed: boolean
+ glue: boolean
+}
+
+/**
+ * Where a tab at `x` lands: the next custom stop, else the default grid.
+ * On the first line of a hanging indent Word treats the left indent as an
+ * implicit stop: a tab before it lands there unless a custom stop sits in
+ * between, and custom stops beyond it are not considered for that tab.
+ * Right/decimal/center stops place the segment's end/middle at the stop.
+ * A stop that would push the segment past the paragraph width pins it flush
+ * to the right edge (Word never wraps such TOC-style lines; Chromium would).
+ * In-column left stops advance to the stop and let a segment too wide for
+ * the trailing space wrap naturally — but a left stop past the right edge
+ * pins too (TOC page numbers), and so does a short segment that still fits
+ * flush right of the tab: wrapping it makes non-last lines justify-stretch,
+ * whose inflated measurements feed back into ever-larger targets
+ * (three-column signature rows). Pinning reserves room for everything after
+ * this tab (restWidth), so a run of trailing tabs packs against the edge
+ * instead of spilling over. The 1px slack keeps the 0.5px cssSize round-up
+ * from re-triggering wrap.
+ *
+ * Chromium breaks a line after a tab like after a space, so a right-ish tab
+ * whose short segment fits at the stop is glued to it (white-space:pre on the
+ * tab span: the boundary from a pre tab to the following text is not a break
+ * opportunity) and the segment cannot be stranded on the next line by a
+ * rounding overflow. A segment that no longer fits before its stop is not
+ * glued: Word collapses the tab to zero width and lets the text flow on from
+ * the tab's position, wrapping only at the margin — it never pulls the word
+ * before the tab down to keep the segment at the stop. Tabs whose remaining
+ * line content exceeds half the column keep Chromium's own wrapping.
+ */
+export function resolveTabTarget(input: TabTargetInput): TabTarget {
+ const { x, minAdv, segWidth, restWidth, paraW, gridPx, hangingX } = input
+ // Word takes any custom stop strictly ahead, however close: a stop nearer
+ // than the minimum advance collapses below instead of being skipped
+ let next = input.stops.find((s) => s.x > x + 0.5)
+ const inHang = hangingX !== undefined && x < hangingX
+ if (inHang && !(next && next.x <= hangingX)) next = { x: hangingX, val: 'left' }
+ let target: number
+ let val: TabStop['val'] = 'left'
+ let leader: string | undefined
+ if (next) {
+ target = next.x
+ val = next.val
+ leader = next.leader
+ } else if (gridPx > 0) {
+ target = (Math.floor((x + minAdv) / gridPx) + 1) * gridPx
+ } else {
+ // defaultTabStop 0: Word advances the caret imperceptibly (tdf#168607)
+ target = x + minAdv
+ }
+ // decimal is approximated as right (no '.'-splitting)
+ if (val === 'right' || val === 'decimal') target -= segWidth
+ else if (val === 'center') target -= segWidth / 2
+ // no flush-right pin inside the hanging area: Word wraps the first-line
+ // text on to the left indent rather than stranding the label
+ if (
+ target + segWidth > paraW - 1 &&
+ (val !== 'left' || target > paraW - 1 || (!inHang && paraW - segWidth - 1 > x))
+ )
+ target = paraW - 1 - restWidth
+ let collapsed = false
+ if (target < x + minAdv) {
+ // no room before the edge: Word collapses the tab to zero width. Chromium
+ // skips a tab whose distance to its stop is under half the paragraph
+ // font's space width to the *next* stop (a whole tab-size, pushing the
+ // segment onto the next line), so the smallest safe advance is half a
+ // space plus slack (minAdv = space + 1); font-size 0 does not lift it
+ collapsed = true
+ target = x + minAdv / 2 + 0.5
+ }
+ const glue =
+ !collapsed && val !== 'left' && val !== 'bar' && segWidth > 0 && restWidth <= paraW / 2
+ return { target, val, leader, collapsed, glue }
}
/**
@@ -221,6 +325,16 @@ function spaceWidthPx(cs: CSSStyleDeclaration): number {
return Math.max(1, w * 1.2)
}
+function tabGlyphLeft(view: EditorView, pos: number): number | null {
+ const { node, offset } = view.domAtPos(pos, 1)
+ if (node.nodeType !== Node.TEXT_NODE || node.nodeValue?.[offset] !== '\t') return null
+ const range = document.createRange()
+ range.setStart(node, offset)
+ range.setEnd(node, offset + 1)
+ const rect = range.getClientRects()[0]
+ return rect ? rect.left : null
+}
+
const MEASURE_RETRY_MAX = 10
/**
* Distinct decoration signatures tolerated between external invalidations
@@ -373,11 +487,14 @@ class TabLayoutView {
for (const t of tabs) {
const leader = t.leader && t.leader !== 'none' ? ` doc-tab-leader-${t.leader}` : ''
const underline = t.underlined ? ' doc-tab-underline' : ''
- const collapse = t.collapsed ? ' doc-tab-collapse' : ''
+ const fixed = t.fixed !== undefined
+ const collapse = t.collapsed && !fixed ? ' doc-tab-collapse' : ''
+ const glue = t.glue && !fixed ? ' doc-tab-glue' : ''
+ const box = fixed ? ' doc-tab-fixed' : ''
decos.push(
Decoration.inline(t.pos, t.pos + 1, {
- class: `doc-tab${leader}${underline}${collapse}`,
- style: `tab-size:${t.cssSize}px`,
+ class: `doc-tab${leader}${underline}${collapse}${glue}${box}`,
+ style: fixed ? `width:${t.fixed}px` : `tab-size:${t.cssSize}px`,
}),
)
}
@@ -536,6 +653,10 @@ class TabLayoutView {
let coords: { left: number; top: number; bottom: number }
try {
coords = view.coordsAtPos(tabPos, 1)
+ // coordsAtPos measures whitespace with an empty-range caret rect, which
+ // drifts inside line-height:0 runs (doc-ws-run); the glyph's own rect is exact
+ const glyphLeft = tabGlyphLeft(view, tabPos)
+ if (glyphLeft !== null) coords = { ...coords, left: glyphLeft }
} catch {
continue
}
@@ -545,59 +666,28 @@ class TabLayoutView {
const x = sameLine ? prevEnd : measuredX
prevLine = { top: coords.top, bottom: coords.bottom }
- const next = stopsPx.find((s) => s.x > x + minAdv)
- let target: number
- let val: TabStop['val'] = 'left'
- let leader: string | undefined
- if (next) {
- target = next.x
- val = next.val
- leader = next.leader
- } else {
- const gridTwips = this.storage.defaultTabStopTwips ?? DEFAULT_TAB_TWIPS
- if (gridTwips > 0) {
- const grid = gridTwips / TWIPS_PER_PX
- target = (Math.floor((x + minAdv) / grid) + 1) * grid
- } else {
- // defaultTabStop 0: Word advances the caret imperceptibly (tdf#168607)
- target = x + minAdv
- }
- }
-
const segWidth = segWidths[i]
- // right/decimal/center align the segment at the stop; decimal is
- // approximated as right (no '.'-splitting)
- if (val === 'right' || val === 'decimal') target -= segWidth
- else if (val === 'center') target -= segWidth / 2
- // A right/center/decimal stop that would push the segment past the
- // paragraph width pins it flush to the right edge (Word never wraps such
- // TOC-style lines; Chromium would). In-column left stops advance to the
- // stop and let a segment too wide for the trailing space wrap naturally —
- // but a left stop past the right edge pins too (TOC page numbers), and so
- // does a short segment that still fits flush right of the tab: wrapping
- // it makes non-last lines justify-stretch, whose inflated measurements
- // feed back into ever-larger targets (three-column signature rows).
- // Pinning reserves room for everything after this tab (restWidths), so a
- // run of trailing tabs packs against the edge instead of spilling over.
- // The 1px slack keeps the 0.5px cssSize round-up from re-triggering wrap.
- if (
- target + segWidth > paraW - 1 &&
- (val !== 'left' || target > paraW - 1 || paraW - segWidth - 1 > x)
- )
- target = paraW - 1 - restWidths[i]
- let collapsed = false
- if (target < x + minAdv) {
- // no room before the edge: a normal tab would still advance a space
- // width (Chromium's minimum), overflowing the line — collapse it to a
- // hair's width instead (font-size 0 lifts the minimum)
- collapsed = true
- target = x + 0.6
- }
+ const gridTwips = this.storage.defaultTabStopTwips ?? DEFAULT_TAB_TWIPS
+ // first-line tab inside the hanging area (negative text-indent)
+ const inHang = textIndent < 0 && x < contentEdge
+ const { target, leader, collapsed, glue } = resolveTabTarget({
+ x,
+ minAdv,
+ segWidth,
+ restWidth: restWidths[i],
+ paraW,
+ stops: stopsPx,
+ gridPx: gridTwips > 0 ? gridTwips / TWIPS_PER_PX : 0,
+ hangingX: inHang ? contentEdge : undefined,
+ })
// convert the Word-space target to a CSS tab-size: the next multiple of
// it past the tab's position must be the target itself, so it needs to
// stay greater than the tab's content-edge-relative x (by the minimum
- // rendered advance, or Chromium skips to the following multiple)
- const cssSize = Math.max(target - contentEdge, x - contentEdge + 0.6, 0.5)
+ // rendered advance, or Chromium skips to the following multiple).
+ // Chromium counts 0 (the content edge) as a multiple too, so a tab left
+ // of the edge can neither cross it nor reach an arbitrary point before
+ // it; such tabs become a box of the exact advance instead
+ const cssSize = inHang ? 0 : Math.max(target - contentEdge, x - contentEdge + 0.6, 0.5)
prevEnd = target + segWidth
// 0.5px rounding damps measure→decorate→re-measure oscillation
out.push({
@@ -606,6 +696,8 @@ class TabLayoutView {
leader,
underlined: tabUnderlined.get(tabPos),
collapsed,
+ glue,
+ fixed: inHang ? Math.round((target - x) * 2) / 2 : undefined,
})
}
return out
diff --git a/apps/docs/src/renderer/editor/extensions.ts b/apps/docs/src/renderer/editor/extensions.ts
index e8d9631..25fdaec 100644
--- a/apps/docs/src/renderer/editor/extensions.ts
+++ b/apps/docs/src/renderer/editor/extensions.ts
@@ -40,6 +40,7 @@ import {
paraLineFactorCss,
SIMSUN_GAP_CHAR_RE,
simsunGapLineFactor,
+ SPACE_ONLY_RE,
strutFontCss,
textHasCjk,
justifySymbolRanges,
@@ -48,6 +49,7 @@ import {
cssSimsunGapLineExpr,
WORD_AUTO_SPACING_PT,
} from '../line-metrics'
+import { textAlignDecl } from './text-effects'
import { noteMarkText } from '../note-format'
import { t } from '../i18n/locale'
import {
@@ -58,17 +60,22 @@ import {
type DocDefaults,
type FieldDisplay,
type FormulaDisplay,
+ type ImageEffects,
type NewChart,
type NumberingDef,
type NumberingLevel,
+ type ParaFrameBox,
type Run,
type StrayIndent,
type StyleDisplay,
type StyleInfo,
+ type TabStop,
type TableCell,
type TableModel,
type TextboxDisplay,
type TextboxListMarker,
+ type ParaFrame,
+ type TextFlowDirection,
} from '@genoffice/docx-engine'
import {
bulletMarkerScale,
@@ -78,7 +85,9 @@ import {
} from './numbering'
import { symbolFontCovers } from '../font-check'
import { dropActiveSubEditor, notifySubEditorState, setActiveSubEditor } from './active-editor'
-import { borderLineCss, paraBorderCss } from './hf-dom'
+import { type BorderLine, borderDrawnPx, borderTruePx } from './border-metrics'
+import { borderLineCss, paraBorderCss, paraBorderPadding, paraBorderPaddingDecls } from './hf-dom'
+import { paraFrameCss } from './para-frame'
export { borderLineCss }
import {
@@ -87,19 +96,34 @@ import {
parseInlineRuleEl,
type InlineRule,
} from './inline-rule'
-import { DK_SIDE, dkBackground, dkBorder, dkColor, dkTableBorders } from './dark-page'
+import {
+ DK_SIDE,
+ darkPageColor,
+ dkBackground,
+ dkBorder,
+ dkColor,
+ dkTableBorders,
+} from './dark-page'
import { fillInk } from './shading-ink'
import {
FloatVShiftsExtension,
PaginationGapsExtension,
RowFillsExtension,
} from './pagination-gaps'
-import { CaretMarksMemory, FORMAT_MARKS, firstTextMarksIn, serializeMarks } from './caret-marks'
+import {
+ CaretMarksMemory,
+ FORMAT_MARKS,
+ firstParaFormatIn,
+ firstTextMarksIn,
+ paraFormatIsDefault,
+ serializeMarks,
+} from './caret-marks'
import { insertPageBreak } from './page-break'
import { ColumnLayoutExtension } from './column-layout'
import { TableHandle } from './table-handle'
import { TRACK_IGNORE, TrackChangesExtension } from './revisions'
import { inlineToRuns, runsToInline, textboxParaSignature, type PmNode as PmJson } from './convert'
+import { inlineMathML } from './equation'
import { constrainTableWidthAtCell } from './table-sizing'
/**
@@ -111,6 +135,7 @@ import { constrainTableWidthAtCell } from './table-sizing'
import {
CHART_MAX_WIDTH_PX,
CHART_TITLE_ROW_PX,
+ cellBoxesSpec,
drawChartSvg,
renderChartSpec,
renderFieldSpec,
@@ -128,7 +153,9 @@ import {
CommentMark,
DelMark,
InsMark,
+ CtrlCheckboxMark,
InstrFieldMark,
+ SymMark,
ItalicMark,
LinkMark,
RefFieldMark,
@@ -157,6 +184,7 @@ import { CjkPunctShrinkExtension } from './cjk-punct-shrink'
import { AutoDirectionExtension } from './direction'
import { InactiveSelectionExtension } from './inactive-selection'
import { AiQueueAnchorsExtension } from './ai-queue-anchors'
+import { CheckboxToggleExtension } from './checkbox-toggle'
import { PageGapNavExtension } from './page-gap-nav'
import { TrailingTableExitExtension } from './trailing-table-exit'
import { moveBlocks } from './move-block'
@@ -219,8 +247,12 @@ const anchorAttrs = {
shadingFill: { default: null as string | null },
/** display-only pattern-shading blend (w:shd pctNN); never saved back */
shadingDisplay: { default: null as string | null },
+ /** explicit w:shd fill=auto: cancels the style's shading (display-only) */
+ shadingClear: { default: null as boolean | null },
/** sides a direct w:pBdr resets to none: cancels the style-level border (display-only) */
borderReset: { default: null as string | null },
+ /** JSON ParaFrameBox: w:framePr width/height/wrap the paragraph lays out in (display-only) */
+ frameBox: { default: null as string | null },
/** w:sz (half-points) of the paragraph mark / dropped empty runs; sizes the line of run-less paragraphs */
emptyRunSize: { default: null as number | null },
/** w:rFonts of the paragraph mark / dropped empty runs; faces the line of run-less paragraphs */
@@ -233,6 +265,10 @@ const anchorAttrs = {
tabStops: { default: null as string | null },
/** drop cap: JSON {type:'drop'|'margin',lines:number} */
dropCap: { default: null as string | null },
+ /** positioned frame: JSON ParaFrame (w:framePr with a width) */
+ frame: { default: null as string | null },
+ /** w:pPr w:textDirection: tbRl | tbRlV | btLr (rendered inside frames) */
+ textDirection: { default: null as string | null },
/** SDT shell: JSON SdtShell (alias, tag, controlType, openXml, closeXml) */
sdtShell: { default: null as string | null },
/** move revision type: 'from' (content moved away) or 'to' (content moved here) */
@@ -250,6 +286,22 @@ const anchorAttrs = {
caretMarks: { default: null as string | null },
}
+/** Word lays a space-only paragraph out like an empty one: the mark sizes the line */
+function isSpaceOnlyParagraph(node: {
+ textContent?: string
+ childCount?: number
+ descendants?: PmNode['descendants']
+}): boolean {
+ if (!node.childCount || !node.descendants || !SPACE_ONLY_RE.test(node.textContent ?? ''))
+ return false
+ let textOnly = true
+ node.descendants((child) => {
+ if (!child.isText) textOnly = false
+ return false
+ })
+ return textOnly
+}
+
/** Max explicit run size (half-points, plus size uniformity) when *every* text child declares one, else null.
* Any run inheriting the body size keeps the inherited strut (conservative: never shrinks a line Word would keep tall). */
function explicitStrutHalfPoints(node: {
@@ -262,6 +314,8 @@ function explicitStrutHalfPoints(node: {
node.descendants((child) => {
if (inherited) return false
if (!child.isText) return true
+ // space-only runs never size a line (Word probe 2026-09-11)
+ if (SPACE_ONLY_RE.test(child.text ?? '')) return false
const sz = child.marks.find((m) => m.type.name === 'docTextStyle')?.attrs.sizeHalfPoints as
number | null | undefined
if (sz == null) inherited = true
@@ -461,7 +515,9 @@ const CLIPBOARD_PARA_ATTR_TYPES: Record
eaLang: 'string',
shadingFill: 'string',
shadingDisplay: 'string',
+ shadingClear: 'boolean',
borderReset: 'string',
+ frameBox: 'string',
emptyRunSize: 'number',
emptyRunFont: 'string',
borders: 'string',
@@ -469,6 +525,8 @@ const CLIPBOARD_PARA_ATTR_TYPES: Record
outlineOnly: 'boolean',
tabStops: 'string',
dropCap: 'string',
+ frame: 'string',
+ textDirection: 'string',
// docListItem identity (paragraphs never set them; ProseMirror drops attrs
// unknown to the parsing node type). numId stays out: a pasted copy pointing
// at another document's numbering table would dangle.
@@ -558,9 +616,7 @@ function blockAttrs(
}
// explicit autoSpaceDE/DN off also disables the browser's native 1/8em gap
if (node.attrs.autoSpace === false) styles.push('text-autospace:no-autospace')
- if (node.attrs.align) {
- styles.push(`text-align:${node.attrs.align === 'distribute' ? 'justify' : node.attrs.align}`)
- }
+ if (node.attrs.align) styles.push(textAlignDecl(String(node.attrs.align)))
// 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).
@@ -568,7 +624,8 @@ function blockAttrs(
// (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) {
+ const spaceOnly = isSpaceOnlyParagraph(node)
+ if (node.textContent && !spaceOnly) {
// Word breaks Korean at spaces (UAX#14 default would break between syllables);
// scoped to Hangul-bearing paragraphs so CJ text keeps per-char breaking.
// overflow-wrap keeps the sim's overlong-word hard-break fallback.
@@ -594,7 +651,7 @@ function blockAttrs(
const fam = node.attrs.emptyRunFont ? String(node.attrs.emptyRunFont) : null
if (fam) {
styles.push(`--doc-line-factor:${lineHeightFactor(fam)}`, `font-family:${cssFontFamily(fam)}`)
- } else if (!node.childCount) {
+ } else if (!node.childCount || spaceOnly) {
// a mark without its own w:rFonts lays the line with the inherited ascii
// face (Word probe 2026-09-05), not the document's CJK root factor
styles.push('--doc-line-factor:var(--doc-line-factor-latin,1.2)')
@@ -669,11 +726,13 @@ function blockAttrs(
const shdBg = node.attrs.shadingDisplay ?? node.attrs.shadingFill
// authored colors stay the declaration; the --dk-* twins feed the dark page (dark-page.ts)
if (shdBg) styles.push(`background-color:#${shdBg}`, dkBackground(`#${shdBg}`))
+ else if (node.attrs.shadingClear) styles.push('background-color:transparent')
const ink = fillInk(shdBg ? String(shdBg) : null)
if (ink) attrs['data-ink'] = ink
if (node.attrs.borders) {
const borders = String(node.attrs.borders)
- let borderLines: Partial> = {}
+ let borderLines: Partial> =
+ {}
if (node.attrs.borderLines) {
try {
borderLines = JSON.parse(String(node.attrs.borderLines))
@@ -687,13 +746,19 @@ function blockAttrs(
const line = paraBorderCss(borderLines[key])
styles.push(`border-${side}:${line}`, dkBorder(key, line))
}
- styles.push('padding:1px 4px')
+ styles.push(...paraBorderPaddingDecls(paraBorderPadding(borders, borderLines)))
}
if (node.attrs.borderReset) {
for (const side of ['top', 'bottom', 'left', 'right'] as const) {
- if (String(node.attrs.borderReset).includes(DK_SIDE[side])) styles.push(`border-${side}:none`)
+ if (!String(node.attrs.borderReset).includes(DK_SIDE[side])) continue
+ styles.push(`border-${side}:none`)
+ // list items indent through padding-inline-start, so their reset l/r sides keep it
+ if (!listGeometry || side === 'top' || side === 'bottom') styles.push(`padding-${side}:0`)
}
}
+ // a positioned frame (below) models the same w:framePr; frameBox only covers frames without a width
+ if (node.attrs.frameBox && !node.attrs.frame)
+ styles.push(...frameBoxCss(String(node.attrs.frameBox)))
if (node.attrs.tabStops) {
// debugging aid only; actual tab layout is measured by TabStopExtension
attrs['data-tab-stops'] = String(node.attrs.tabStops)
@@ -701,6 +766,18 @@ function blockAttrs(
if (node.attrs.dropCap) {
attrs['data-drop-cap'] = String(node.attrs.dropCap)
}
+ if (node.attrs.frame) {
+ try {
+ const frame = JSON.parse(String(node.attrs.frame)) as ParaFrame
+ if (frame && frame.wTwips > 0) {
+ const fc = paraFrameCss(frame, node.attrs.textDirection as TextFlowDirection | null)
+ attrs['class'] = [attrs['class'], ...fc.classes].filter(Boolean).join(' ')
+ styles.push(...fc.styles)
+ }
+ } catch {
+ /* ignore malformed */
+ }
+ }
if (node.attrs.sdtShell) {
attrs['data-sdt'] = 'true'
}
@@ -835,6 +912,7 @@ export const DocInlineImage = Node.create({
wrap: { default: null as string | null },
offsetXEmu: { default: null as number | null },
offsetYEmu: { default: null as number | null },
+ relV: { default: null as string | null },
wrapDistTopEmu: { default: null as number | null },
wrapDistBottomEmu: { default: null as number | null },
wrapDistLeftEmu: { default: null as number | null },
@@ -893,11 +971,13 @@ export const DocInlineImage = Node.create({
const xf = pictureTransformFns(node.attrs.rotDeg, node.attrs.flipH, node.attrs.flipV)
const px = (v: number) => `${v.toFixed(1)}px`
const wrap = node.attrs.wrap as string | null
+ const relV = node.attrs.relV as string | null
+ const pageRelV = relV === 'page' || relV === 'margin'
if (wrap === 'front' || wrap === 'behind') {
// no-wrap / behind-text anchor: absolute overlay at the anchor offset from
// the hosting paragraph's origin (styles.css positions that paragraph;
- // zero flow footprint, like Word); behind approximated by reduced
- // opacity — the flowing canvas has no z layer under the text
+ // zero flow footprint, like Word); behind-text drops under the flow via
+ // z-index (Word paints it at full opacity)
const left = Number(node.attrs.offsetXEmu ?? 0) / EMU_PER_PX
const top = Number(node.attrs.offsetYEmu ?? 0) / EMU_PER_PX
// positive offsets ride on transform, not left/top: an off-page anchor
@@ -908,13 +988,20 @@ export const DocInlineImage = Node.create({
// page-wide picture's static box right would create that same overflow.
const lx = Math.min(left, 0)
const ty = Math.min(top, 0)
+ // page-relative Y in content-area coordinates; pagination re-pins it on the anchor's page
+ const dy =
+ relV === 'page' ? `calc(${px(top - ty)} - var(--doc-margin-top,0px))` : px(top - ty)
styles.push(
`position:absolute;left:${px(lx)};top:${px(ty)}`,
- `transform:translate(${px(left - lx)}, ${px(top - ty)})${xf.length ? ` ${xf.join(' ')}` : ''}`,
+ `transform:translate(${px(left - lx)}, ${dy})${xf.length ? ` ${xf.join(' ')}` : ''}`,
'max-width:none',
)
attrs.style = styles.join(';')
if (wrap === 'behind') attrs.class += ' doc-inline-img--behind'
+ if (pageRelV) {
+ attrs['data-page-rel-v'] = '1'
+ if (relV === 'page') attrs['data-page-rel-from'] = 'page'
+ }
return [
'span',
{ class: 'doc-inline-img-anchor', 'data-inline-image-anchor': '1' },
@@ -926,6 +1013,8 @@ export const DocInlineImage = Node.create({
// flow reserves the quarter-turned bounding box; floats keep their own
// side pinned and grow toward the text
const qt = quarterTurnInsetPx(w, h, node.attrs.rotDeg)
+ // the column clamp must meet the turned bounding box, not the unturned extent
+ if (qt) styles.push('max-width:none')
// topBottom is a centred block: its visual centre is the box centre, so
// only the stylesheet's 2px band gap needs carrying
const bandGap = wrap === 'topBottom' ? 2 : 0
@@ -968,8 +1057,11 @@ export const DocInlineImage = Node.create({
sliverGuard = wrapSliverGuardCss(wrap, tx + qt, qt ? h : w, right, qt)
}
// paragraph-relative posOffset Y: the float (and its text exclusion)
- // starts that far below the anchor line; position wins over distT
- const ty = node.attrs.offsetYEmu != null ? Number(node.attrs.offsetYEmu) / EMU_PER_PX : 0
+ // starts that far below the anchor line; position wins over distT. A
+ // page/margin-relative Y is a page position a CSS float cannot rise to,
+ // so it starts at the anchor line (Word anchors to the nearest paragraph)
+ const ty =
+ node.attrs.offsetYEmu != null && !pageRelV ? Number(node.attrs.offsetYEmu) / EMU_PER_PX : 0
if ((ty !== 0 || qt) && wrap !== 'topBottom') {
// the offset places the extent box, whose unturned top is the img box
// top; the turned visual (Word's exclusion) starts an inset above it
@@ -1105,6 +1197,24 @@ export const DocHardBreak = Node.create({
},
})
+/**
+ * TipTap core's clearDocument plugin runs clearNodes() after a select-all
+ * deletion, replacing the surviving paragraph with an attribute-less default
+ * one — a generic-editor convenience (reset a heading to a paragraph) that is
+ * the opposite of Word: Word keeps the paragraph formatting on the surviving
+ * paragraph mark, so a select-all + Delete (or Enter) must not reset the
+ * paragraph style, the paragraph-mark font, alignment or indents to the
+ * theme (r176 follow-up). The plugin is keyed, so it can be removed exactly.
+ */
+export const WordSelectAllDelete = Extension.create({
+ name: 'wordSelectAllDelete',
+ onBeforeCreate() {
+ // on 'mount', not onCreate: tiptap defers the create event to a timeout,
+ // which would leave the first user edit with the plugin still active
+ this.editor.on('mount', () => this.editor.unregisterPlugin('clearDocument'))
+ },
+})
+
/**
* Enter must replace ANY non-empty selection with a paragraph break (Word).
* Two selection shapes broke the default chain (alpha ledger r125/r129):
@@ -1131,6 +1241,12 @@ export const EnterReplacesSelection = Extension.create({
// EMPTIED paragraph with no neighbor to inherit from, so the first
// deleted character's marks must ride along explicitly (alpha
// ledger r133: keyboard whole-line selections type in theme font)
+ // paragraph formatting of the START of the replaced range: when the
+ // selection consumes whole paragraphs the delete leaves a DEFAULT
+ // filler block, so style-derived fonts, alignment and the
+ // paragraph-mark font all reset to the theme (r176 follow-up) —
+ // captured before the delete, applied to both emptied halves below
+ const paraFormat = firstParaFormatIn(sel.$from.doc, sel.from, sel.to)
const carryMarks = () => {
// first TEXT node in the replaced range (an AllSelection's $from
// sits at doc depth 0, where nodeAt returns the block, not a run)
@@ -1140,27 +1256,41 @@ export const EnterReplacesSelection = Extension.create({
const found = (marks ?? sel.$from.marks()).filter((mark) =>
FORMAT_MARKS.has(mark.type.name),
)
- if (found.length > 0) {
- const tr = this.editor.state.tr.setMeta('addToHistory', false)
- // Word keeps the pending format on BOTH empty paragraphs the
- // replace leaves behind. The caret-marks memory stamps only the
- // block the caret sits in (the second), so arrowing up to the
- // FIRST emptied line reverted typing to the theme font and the
- // font box to "(Body)" (alpha ledger r133 residual). The stamp
- // step must precede setStoredMarks: a doc-changing step resets
- // the transaction's stored marks.
- const $head = this.editor.state.selection.$from
- const boundary = $head.before($head.depth)
- const prev = this.editor.state.doc.resolve(boundary).nodeBefore
- if (prev && prev.isTextblock && prev.content.size === 0 && 'caretMarks' in prev.attrs) {
- tr.setNodeMarkup(boundary - prev.nodeSize, undefined, {
- ...prev.attrs,
- caretMarks: serializeMarks(found),
- })
- }
- tr.setStoredMarks([...found])
- this.editor.view.dispatch(tr)
+ const tr = this.editor.state.tr.setMeta('addToHistory', false)
+ let changed = false
+ // Word keeps the pending format on BOTH empty paragraphs the
+ // replace leaves behind. The caret-marks memory stamps only the
+ // block the caret sits in (the second), so arrowing up to the
+ // FIRST emptied line reverted typing to the theme font and the
+ // font box to "(Body)" (r133 residual). The stamp step must
+ // precede setStoredMarks: a doc-changing step resets the
+ // transaction's stored marks.
+ const $head = this.editor.state.selection.$from
+ const boundary = $head.before($head.depth)
+ const caretBlock = $head.parent
+ const prev = this.editor.state.doc.resolve(boundary).nodeBefore
+ const restoreOn = (pos: number, node: PmNode, extras: Record) => {
+ const restore =
+ paraFormat && node.content.size === 0 && paraFormatIsDefault(node) ? paraFormat : null
+ if (!restore && Object.keys(extras).length === 0) return
+ tr.setNodeMarkup(pos, undefined, { ...node.attrs, ...restore, ...extras })
+ changed = true
}
+ if (prev && prev.isTextblock && prev.content.size === 0 && 'caretMarks' in prev.attrs) {
+ restoreOn(
+ boundary - prev.nodeSize,
+ prev,
+ found.length > 0 ? { caretMarks: serializeMarks(found) } : {},
+ )
+ }
+ if (caretBlock.isTextblock && 'caretMarks' in caretBlock.attrs) {
+ restoreOn(boundary, caretBlock, {})
+ }
+ if (found.length > 0) {
+ tr.setStoredMarks([...found])
+ changed = true
+ }
+ if (changed) this.editor.view.dispatch(tr)
}
if (sel instanceof AllSelection) {
// an AllSelection maps to itself through the delete (it always
@@ -1545,7 +1675,7 @@ function lineFactorDecos(doc: PmNode): DecorationSet {
if (hostsAnchoredPicture(node)) {
decos.push(Decoration.node(pos, pos + node.nodeSize, { class: 'doc-anchor-origin' }))
}
- if (node.textContent) {
+ if (node.textContent && !isSpaceOnlyParagraph(node)) {
let cached = lineFactorCache.get(node)
if (cached === undefined) {
const perLine = perLineFactors(node)
@@ -1737,6 +1867,9 @@ function measureMarkerTwips(
return Number.isFinite(w) && w > 0 ? Math.round(w * 15) : null
}
+const MARKER_NATURAL_LINE_HEIGHT =
+ '--li-marker-lh:calc(var(--doc-line-factor,1.2) * 1em * var(--doc-line-mult,1))'
+
/** substitute glyph for a symbol-font bullet: pin a Latin font (CJK fallback draws ・) and
* compensate its smaller bullet; --li-marker-lh:0 keeps the scaled em box from stretching the line */
function substituteMarkerStyles(text: string): string[] {
@@ -1782,13 +1915,38 @@ function markerClippedByCell(
function specialIndentTw(attrs: Record, level: NumberingLevel): number | null {
if (attrs.indentFirstLine != null) return Number(attrs.indentFirstLine)
if (level.hanging) return -level.hanging
- return level.firstLine ?? (level.indentLeft ? 0 : null)
+ return level.firstLine ?? (level.indentLeft !== undefined ? 0 : null)
}
function cssString(text: string): string {
return `"${text.replace(/["\\]/g, '\\$&')}"`
}
+/** custom tab stop positions (twips) the marker tab can land on: style chain + direct,
+ * direct w:val="clear" removing the style's stop at that position */
+function paragraphTabStops(
+ attrs: Record,
+ storage: ListNumberingStorage,
+): number[] {
+ const styleStops =
+ typeof attrs.styleId === 'string'
+ ? (storage.styles?.get(attrs.styleId)?.display?.tabStops ?? [])
+ : []
+ let direct: TabStop[] = []
+ if (typeof attrs.tabStops === 'string') {
+ try {
+ const parsed: unknown = JSON.parse(attrs.tabStops)
+ if (Array.isArray(parsed)) direct = parsed as TabStop[]
+ } catch {
+ /* malformed attr: no direct stops */
+ }
+ }
+ const cleared = new Set(direct.filter((t) => t.val === 'clear').map((t) => t.pos))
+ return [...styleStops.filter((t) => !cleared.has(t.pos)), ...direct]
+ .filter((t) => t.val !== 'clear' && t.val !== 'bar' && !t.rel)
+ .map((t) => t.pos)
+}
+
/** the stray line's list geometry in docListItem attr shape (its w:ind is the anchor paragraph's) */
function strayGeometryAttrs(node: PmNode): Record {
const ind = node.attrs.strayIndent as StrayIndent | null
@@ -1871,9 +2029,13 @@ export const ListNumberingExtension = Extension.create = []
doc.descendants((node, pos) => {
if (node.type.name === 'docListItem') {
+ const deleted =
+ !!node.attrs.paraMarkDel ||
+ (node.attrs.blockRevision as { kind?: string } | null)?.kind === 'del'
refs.push({
numId: (node.attrs.numId as string | null) ?? null,
ilvl: Number(node.attrs.ilvl) || 0,
+ ...(deleted ? { deleted: true } : {}),
})
nodes.push({ pos, node })
return false
@@ -1909,6 +2071,10 @@ export const ListNumberingExtension = Extension.create= 0) {
- styles.push('--li-hang:0pt')
- if (ownFirst == null && firstTw > 0) styles.push(`text-indent:${firstTw / 20}pt`)
- }
- const szHalf =
- level.szHalfPoints ??
+ const runSizeHalf =
(stray
? (nodes[i].node.attrs.strayRuns as Run[] | null)?.[0]?.sizeHalfPoints
- : firstRunSizeHalfPoints(nodes[i].node)) ??
- undefined
+ : firstRunSizeHalfPoints(nodes[i].node)) ?? undefined
+ const szHalf = level.szHalfPoints ?? runSizeHalf
if (szHalf) styles.push(`--li-marker-size:${szHalf / 2}pt`)
+ // a text-font glyph draws in its own face without letting that face's leading
+ // stretch the line (an oversized w:sz below overrides the 0)
+ if (marker.font) {
+ styles.push(`--li-marker-font:${cssString(marker.font)}`, '--li-marker-lh:0')
+ }
+ const para = markerParagraphFont(nodeAttrs.styleId, storage)
+ // a level w:sz above the text size grows the first line by the marker's own
+ // natural height (Word); equal sizes keep the inherited line untouched
+ if (level.szHalfPoints && level.szHalfPoints > (runSizeHalf ?? para.sizeHalf)) {
+ styles.push(MARKER_NATURAL_LINE_HEIGHT)
+ }
+ if (level.color) {
+ styles.push(
+ `--li-marker-color:#${level.color}`,
+ `--dk-li-mc:${darkPageColor(level.color)}`,
+ )
+ }
if (level.suff === 'space' || level.suff === 'nothing') attrs['data-suff'] = level.suff
if (markerClippedByCell(doc, nodes[i].pos, nodeAttrs, level, szHalf ?? 20))
attrs['data-marker-clip'] = ''
// Word's default tab after the marker: a marker that escapes the hanging
// area (or one with no hanging area at all) pushes first-line text to
- // the next default tab stop, not right up against the marker
+ // the next tab stop, not right up against the marker
+ const tabSuff = level.suff === undefined || level.suff === 'tab'
+ let widthTw: number | null = null
if (
- (level.suff === undefined || level.suff === 'tab') &&
text &&
firstTw != null &&
- (firstTw >= 0 || leftTw > 0)
+ (level.lvlJc !== undefined || (tabSuff && (firstTw >= 0 || leftTw > 0)))
) {
- // no level/run size -> the marker renders at the li's 1em; family always
- // inherits from the li (level.font only applies to symbol bullets)
- const para = markerParagraphFont(nodeAttrs.styleId, storage)
- const widthTw = measureMarkerTwips(
+ // no level/run size -> the marker renders at the li's 1em; family
+ // inherits from the li unless the level declares a text font
+ widthTw = measureMarkerTwips(
text,
- para.family,
+ marker.font ?? para.family,
(szHalf ?? para.sizeHalf) / 2,
para.bold,
)
- const adv =
- widthTw !== null ? markerTabAdvance(leftTw + firstTw, widthTw, leftTw) : null
+ }
+ // lvlJc right/center: the marker's end/middle sits at the marker position,
+ // so its box starts earlier by the glyph width (or half of it)
+ const shift =
+ widthTw === null || !level.lvlJc
+ ? 0
+ : level.lvlJc === 'right'
+ ? widthTw
+ : Math.round(widthTw / 2)
+ if (firstTw != null && firstTw < 0 && (ownFirst == null || shift > 0)) {
+ styles.push(`--li-hang:${(-firstTw + shift) / 20}pt`)
+ }
+ // no hanging area: the marker sits at the first-line position instead of
+ // hanging the CSS default before it; its tab then runs to the next stop
+ if (firstTw != null && firstTw >= 0) {
+ styles.push(`--li-hang:${shift / 20}pt`)
+ if (ownFirst == null && firstTw > 0) styles.push(`text-indent:${firstTw / 20}pt`)
+ }
+ if (tabSuff && widthTw !== null && firstTw != null) {
+ const boxStart = leftTw + firstTw - shift
+ // without a hanging area nothing can "fit": the tab always runs to a stop
+ const adv = markerTabAdvance(
+ boxStart,
+ widthTw,
+ firstTw < 0 ? leftTw : boxStart,
+ 720,
+ paragraphTabStops(nodeAttrs, storage),
+ )
if (adv !== null) styles.push(`--li-tab:${adv / 20}pt`)
}
}
@@ -2021,29 +2220,19 @@ const tableCellAttrs = {
align: { default: null as string | null },
}
-export function borderWidthPx(b: { style: string; szEighths?: number } | undefined | null): number {
- if (!b || b.style === 'none' || b.style === 'nil') return 0
- return Math.max(1, Math.round(((b.szEighths ?? 4) / 8 / 72) * 96))
+export function borderWidthPx(b: BorderLine): number {
+ return borderDrawnPx(b)
}
-/** true border width (sz/8 pt) minus the whole px we draw. Word lays rows out
+/** true drawn thickness (border-metrics.ts) minus the whole px we draw. Word lays rows out
* with the true width (probe 2026-09-04: 0.5pt adds 0.667px per row, 1pt 1.333px);
* the td::before spacer in styles.css gives this back to the row height */
-export function borderSnapDeltaPx(
- b: { style: string; szEighths?: number } | undefined | null,
-): number {
- if (!b || b.style === 'none' || b.style === 'nil') return 0
- return ((b.szEighths ?? 4) / 8 / 72) * 96 - borderWidthPx(b)
+export function borderSnapDeltaPx(b: BorderLine): number {
+ return borderTruePx(b) - borderDrawnPx(b)
}
-export const bdDeltaCss = (
- side: 'top' | 'bottom',
- b: { style: string; szEighths?: number } | undefined | null,
-): string => `--cell-bd-${side === 'top' ? 't' : 'b'}:${borderSnapDeltaPx(b).toFixed(3)}px`
-
-type BorderLine = { style: string; szEighths?: number } | undefined | null
-const trueBorderPx = (b: BorderLine): number =>
- !b || b.style === 'none' || b.style === 'nil' ? 0 : ((b.szEighths ?? 4) / 8 / 72) * 96
+export const bdDeltaCss = (side: 'top' | 'bottom', b: BorderLine): string =>
+ `--cell-bd-${side === 'top' ? 't' : 'b'}:${borderSnapDeltaPx(b).toFixed(3)}px`
/** Word advances a declared-height row by trHeight PLUS the true gridline width
* (CSS collapsed borders fit inside the tr height): the table emits --doc-row-eat
@@ -2053,7 +2242,7 @@ export function tableRowEatCss(borders: TableBordersAttr | null, cellSpacing: bo
if (cellSpacing) return ['--doc-row-grid:0']
const insideH = borders?.insideH
if (!insideH || insideH.style === 'none' || insideH.style === 'nil') return []
- return [`--doc-row-eat:${trueBorderPx(insideH).toFixed(2)}px`]
+ return [`--doc-row-eat:${borderTruePx(insideH).toFixed(2)}px`]
}
/** cells: gridBefore/gridAfter placeholders must be filtered out by the caller */
@@ -2065,7 +2254,7 @@ export function rowHeightCss(
let inherits = false
for (const b of cellBorders) {
if (!b?.top || !b?.bottom) inherits = true
- explicit = Math.max(explicit, trueBorderPx(b?.top), trueBorderPx(b?.bottom))
+ explicit = Math.max(explicit, borderTruePx(b?.top), borderTruePx(b?.bottom))
}
const fixed = ((heightTwips / 1440) * 96).toFixed(1)
if (explicit > 0) {
@@ -2302,6 +2491,8 @@ export const DocTable = Node.create({
tblFloatYTwips: { default: null as number | null },
tblFloatHorzAnchor: { default: null as string | null },
tblFloatVertAnchor: { default: null as string | null },
+ tblFloatXSpec: { default: null as string | null },
+ tblFloatYSpec: { default: null as string | null },
tblFloatDistance: { default: null as Record | null },
/** display-only measured width used to place right AutoFit floats */
tblFloatWidthPx: { default: null as number | null },
@@ -2441,11 +2632,22 @@ export const DocTable = Node.create({
// is text-relative). The pagination engine resolves the page-relative
// target and applies the shift via --tblp-dy; flow CSS gets no margin.
const vAnchor = node.attrs.tblFloatVertAnchor
+ const ySpec = node.attrs.tblFloatYSpec as string | null
+ const vSpec =
+ ySpec === 'top' || ySpec === 'inside'
+ ? 'top'
+ : ySpec === 'bottom' || ySpec === 'outside'
+ ? 'bottom'
+ : ySpec === 'center'
+ ? 'center'
+ : null
const pageRelV =
- (vAnchor === 'page' || vAnchor === 'margin') && node.attrs.tblFloatYTwips != null
+ (vAnchor === 'page' || vAnchor === 'margin') &&
+ (node.attrs.tblFloatYTwips != null || vSpec !== null)
if (pageRelV) {
- attrs['data-tblp-vy'] = y.toFixed(1)
+ attrs['data-tblp-vy'] = (vSpec ? 0 : y).toFixed(1)
attrs['data-tblp-vanchor'] = String(vAnchor)
+ if (vSpec) attrs['data-tblp-vspec'] = vSpec
styles.push('margin-top:var(--tblp-dy,0px)')
}
const top = pageRelV ? 0 : y + Math.max(0, px(distance.top))
@@ -2461,16 +2663,25 @@ export const DocTable = Node.create({
// ledger, #genoffice-feedback task #6). Word keeps floats on the page.
const fromPageEdge = node.attrs.tblFloatHorzAnchor === 'page'
const tblWidth = Number(node.attrs.widthPx) || Number(node.attrs.tblFloatWidthPx) || 0
+ const xSpec = node.attrs.tblFloatXSpec as string | null
const xExpr = fromPageEdge
? `calc(${x.toFixed(1)}px - var(--doc-margin-left,0px))`
: `${x.toFixed(1)}px`
if (node.attrs.tblFloat === 'left') {
- if (x) {
+ if (xSpec === 'center' && tblWidth > 0 && !node.attrs.widthPct) {
+ styles.push(
+ `margin-left:max(0px,calc((var(--doc-content-w,100%) - ${tblWidth.toFixed(1)}px) / 2))`,
+ )
+ } else if (xSpec === null && (x || fromPageEdge)) {
+ // the right-edge cap never pulls a too-wide table left of the content box
const capped =
tblWidth > 0
- ? `min(${xExpr},calc(var(--doc-content-w,100%) - ${tblWidth.toFixed(1)}px))`
+ ? `min(${xExpr},max(0px,calc(var(--doc-content-w,100%) - ${tblWidth.toFixed(1)}px)))`
: xExpr
- styles.push(`margin-left:max(0px,${capped})`)
+ // a page-anchored X may reach into the left margin (Word draws cover
+ // blocks flush with the paper edge); margin anchors stop at the content edge
+ const floor = fromPageEdge ? 'calc(0px - var(--doc-margin-left,0px))' : '0px'
+ styles.push(`margin-left:max(${floor},${capped})`)
}
if (right) styles.push(`margin-right:${right.toFixed(1)}px`)
} else {
@@ -2623,38 +2834,7 @@ export const DocCellBoxes = Node.create({
return []
},
renderHTML({ node }) {
- const boxes = (node.attrs.boxes as TextboxDisplay[] | null) ?? []
- if (boxes.length === 0) return ['div', { class: 'doc-cell-boxes' }]
- let bottom = 0
- for (const b of boxes) {
- bottom = Math.max(
- bottom,
- (b.offsetYEmu ?? 0) / EMU_PER_PX + (b.heightPx ?? b.minHeightPx ?? 0),
- )
- }
- return [
- 'div',
- {
- class: 'doc-cell-boxes',
- contenteditable: 'false',
- // zero-width leading float: the cell (a BFC) grows to max(text, boxes)
- // like Word, without displacing the cell's own text
- style: bottom > 0 ? `height:${bottom.toFixed(1)}px` : '',
- },
- // floating boxes self-position from their anchor offsets; in-flow boxes get
- // the same offsets via a positioned wrapper (Word places both in the cell)
- ...boxes.map((b): DomSpec => {
- const spec = renderTextboxSpec(b)
- if (b.floating) return spec
- const left = (b.offsetXEmu ?? 0) / EMU_PER_PX
- const top = (b.offsetYEmu ?? 0) / EMU_PER_PX
- return [
- 'div',
- { style: `position:absolute;left:${left.toFixed(1)}px;top:${top.toFixed(1)}px` },
- spec,
- ]
- }),
- ]
+ return cellBoxesSpec((node.attrs.boxes as TextboxDisplay[] | null) ?? [])
},
})
@@ -2797,32 +2977,12 @@ export const DocNestedTable = Node.create({
},
})
-function emptyTopLevelTableAtCursor(state: EditorState): { from: number; to: number } | null {
- const { selection } = state
- if (!(selection instanceof TextSelection) || !selection.empty) return null
- const table = selection.$from.node(1)
- if (table.type.name !== 'docTable') return null
- let hasLeaf = false
- table.descendants((node) => {
- if (node.isLeaf) hasLeaf = true
- return !hasLeaf
- })
- if (hasLeaf) return null
- const from = selection.$from.before(1)
- return { from, to: from + table.nodeSize }
-}
-
-/** Delete a selected table, or a completely empty table under a text cursor. */
+/** Delete only an explicitly selected whole table; leave cursors and partial cell selections alone. */
export function deleteSelectedWholeTable(
state: EditorState,
dispatch?: (transaction: Transaction) => void,
): boolean {
const { selection } = state
- const emptyTable = emptyTopLevelTableAtCursor(state)
- if (emptyTable) {
- dispatch?.(state.tr.delete(emptyTable.from, emptyTable.to).scrollIntoView())
- return true
- }
if (selection instanceof NodeSelection) {
if (selection.node.type.spec.tableRole !== 'table') return false
dispatch?.(state.tr.delete(selection.from, selection.to).scrollIntoView())
@@ -2928,6 +3088,62 @@ export const NativeTableSupport = Extension.create({
const PERSISTABLE_IMAGE_URL = /^data:image\/(?:png|jpeg|gif);base64,/
/** display attrs a copied picture needs to round-trip through clipboard HTML */
+/**
+ * CSS filter pair for the affine map y = slope * (x + offset - 0.5) + 0.5.
+ * contrast() pivots at 0.5 and brightness() at 0, so the two compose to any
+ * such line; the order is chosen so the intermediate value never clips.
+ */
+function affineFilterCss(slope: number, offset: number): string[] {
+ if (offset >= 0) {
+ const m = 1 + 2 * slope * offset
+ return [`contrast(${(slope / m).toFixed(4)})`, `brightness(${m.toFixed(4)})`]
+ }
+ const k = slope * (1 - 2 * offset)
+ return [`brightness(${(1 / (1 - 2 * offset)).toFixed(4)})`, `contrast(${k.toFixed(4)})`]
+}
+
+/** a:lum / a:grayscl / a:biLevel → `filter:` declaration ('' when none) */
+export function pictureFilterCss(fx: ImageEffects | null | undefined): string {
+ if (!fx) return ''
+ const fns: string[] = []
+ if (fx.grayscale || fx.biLevelThresh !== undefined) fns.push('grayscale(1)')
+ if (fx.bright || fx.contrast) {
+ // Word: contrast scales about mid-grey by (1 + c), brightness then adds b
+ // (measured against Word's rendering of bright/contrast +40%)
+ const slope = Math.max(0.01, 1 + Math.max(-1, Math.min(1, fx.contrast ?? 0)))
+ const bright = Math.max(-1, Math.min(1, fx.bright ?? 0))
+ fns.push(...affineFilterCss(slope, bright / slope))
+ }
+ if (fx.biLevelThresh !== undefined) {
+ fns.push(...affineFilterCss(1000, 0.5 - Math.max(0, Math.min(1, fx.biLevelThresh))))
+ }
+ return fns.length ? `filter:${fns.join(' ')}` : ''
+}
+
+/** w:framePr box: the paragraph lays out at the frame size, floating beside the text when it wraps */
+function frameBoxCss(json: string): string[] {
+ let box: ParaFrameBox
+ try {
+ box = JSON.parse(json) as ParaFrameBox
+ } catch {
+ return []
+ }
+ const px = (twips: number): string => `${(twips / 15).toFixed(1)}px`
+ const out: string[] = []
+ if (box.wTwips) out.push(`width:${px(box.wTwips)}`, 'box-sizing:border-box')
+ if (box.hTwips) {
+ if (box.hRule === 'exact') out.push(`height:${px(box.hTwips)}`, 'overflow:hidden')
+ else out.push(`min-height:${px(box.hTwips)}`)
+ }
+ if (box.floatSide) {
+ out.push(`float:${box.floatSide}`)
+ if (box.hSpaceTwips)
+ out.push(`margin-${box.floatSide === 'left' ? 'right' : 'left'}:${px(box.hSpaceTwips)}`)
+ if (box.vSpaceTwips) out.push(`margin-bottom:${px(box.vSpaceTwips)}`)
+ }
+ return out
+}
+
const imageMetaJson = (attrs: Record): string =>
JSON.stringify({
imageWidthPx: attrs.imageWidthPx ?? null,
@@ -3019,6 +3235,8 @@ export const DocProtected = Node.create({
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 },
+ /** a:lum / a:grayscl / a:biLevel recolor, display-only */
+ imageEffects: { default: null as ImageEffects | null },
/** fill placement (a:fillRect) fractions (negative = bleed), display-only */
imageFillRect: { default: null as { l: number; t: number; r: number; b: number } | null },
imageLeadingText: { default: null as string | null },
@@ -3055,6 +3273,7 @@ export const DocProtected = Node.create({
imagePosH: { default: null as string | null },
imagePosV: { default: null as string | null },
imageOffsetYEmu: { default: null as number | null },
+ imageRelV: { default: null as string | null },
/** display-only table structure (blockType === 'table') */
table: { default: null as TableModel | null },
/** display-only rendering for field passthrough paragraphs */
@@ -3584,8 +3803,16 @@ function protectedDomSpec(node: PmNode): DomSpec {
(fieldDisplay as FieldDisplay | null)?.kind !== 'pageBreak'
) {
// the anchor paragraph's empty line (the break-chip branch below renders
- // its own stray line instead; a static inline drawing is its own line)
- children.unshift(['div', { class: 'doc-anchor-strut' }, ['br']])
+ // its own stray line instead; a static inline drawing is its own line).
+ // With the paragraph's own format at hand the line carries its style,
+ // spacing and line rule like Word's empty anchor paragraph
+ const line = node.attrs.anchorLine as Record | null
+ if (line) {
+ const spec = anchorLineSpec(line)
+ const lineAttrs = spec[1] as Record
+ lineAttrs.class += ' doc-anchor-strut'
+ children.unshift(spec)
+ } else children.unshift(['div', { class: 'doc-anchor-strut' }, ['br']])
}
if (diagram?.shapes?.length) children.push(diagramSpecOf(diagram))
// corner resize handle; multi-box nodes keep per-box autogrow semantics only
@@ -3701,6 +3928,9 @@ function protectedDomSpec(node: PmNode): DomSpec {
? `margin-left:calc(${Number(node.attrs.imageParagraphIndentFirstLine ?? 0) / 15 + explicitSpaceWidthPx}px + ${implicitSpaceCount * 0.5}em)`
: ''
let imgFloatPos = ''
+ const imgWrapData: Record = {}
+ const relV = node.attrs.imageRelV as string | null
+ const pageRelV = relV === 'page' || relV === 'margin'
// a quarter-turned picture keeps its extent box (turned about its centre)
// while the flow reserves the swapped bounding box, so in-flow offsets
// shift by half the side difference
@@ -3727,13 +3957,21 @@ function protectedDomSpec(node: PmNode): DomSpec {
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
+ const topCss =
+ relV === 'page'
+ ? `calc(${ty.toFixed(1)}px - var(--doc-margin-top,0px))`
+ : `${ty.toFixed(1)}px`
+ if (pageRelV) {
+ imgWrapData['data-page-rel-v'] = '1'
+ if (relV === 'page') imgWrapData['data-page-rel-from'] = 'page'
+ }
if (posH === 'center') {
- imgFloatPos = `left:50%;top:${ty.toFixed(1)}px${imgZIndexCss}`
+ imgFloatPos = `left:50%;top:${topCss}${imgZIndexCss}`
imgWrapTransform = 'transform:translateX(-50%)'
} else if (posH === 'right') {
- imgFloatPos = `right:0;top:${ty.toFixed(1)}px${imgZIndexCss}`
+ imgFloatPos = `right:0;top:${topCss}${imgZIndexCss}`
} else {
- imgFloatPos = `left:${tx.toFixed(1)}px;top:${ty.toFixed(1)}px${imgZIndexCss}`
+ imgFloatPos = `left:${tx.toFixed(1)}px;top:${topCss}${imgZIndexCss}`
}
} else if (banded) {
const tx = Number(node.attrs.imageOffsetXEmu) / EMU_PER_PX
@@ -3748,7 +3986,17 @@ function protectedDomSpec(node: PmNode): DomSpec {
// WYSIWYG): X measures from the column start, Y from the anchor
// paragraph top — matching the saved relativeFrom column/paragraph.
const wrapperCss: string[] = []
- if (node.attrs.imageOffsetYEmu != null || qt) {
+ if (pageRelV && node.attrs.imageOffsetYEmu != null) {
+ // page position on the landing page: the engine resolves the shift like w:tblpY
+ const ty = Number(node.attrs.imageOffsetYEmu) / EMU_PER_PX
+ attrs['data-tblp-vy'] = ty.toFixed(1)
+ attrs['data-tblp-vanchor'] = String(relV)
+ wrapperCss.push('margin-top:var(--tblp-dy,0px)')
+ if (imageWrap !== 'topBottom')
+ wrapperCss.push('shape-outside:inset(var(--tblp-dy,0px) 0 0 0)')
+ if (qt) imgWrapTransform = `margin-top:${(-qt).toFixed(1)}px`
+ hasOffsetTopMargin = true
+ } else if (node.attrs.imageOffsetYEmu != null || qt) {
// the offset places the extent box; the quarter turn about its centre
// lifts the visual (and the text exclusion) by the inset
const ty = Number(node.attrs.imageOffsetYEmu ?? 0) / EMU_PER_PX - qt
@@ -3827,10 +4075,12 @@ function protectedDomSpec(node: PmNode): DomSpec {
src: String(imageDataUrl),
class: 'doc-protected-img',
}
+ const filterCss = pictureFilterCss(node.attrs.imageEffects as ImageEffects | null)
if (imageWidthPx) {
imgAttrs['style'] =
`width:${Number(imageWidthPx)}px;` +
- (imageHeightPx ? `height:${Number(imageHeightPx)}px` : 'height:auto')
+ (imageHeightPx ? `height:${Number(imageHeightPx)}px` : 'height:auto') +
+ (qt ? ';max-width:none' : '')
}
// picture outline (document data, not chrome): border adds outside the
// extent, approximating Word's centered stroke
@@ -3870,7 +4120,7 @@ function protectedDomSpec(node: PmNode): DomSpec {
}
imgAttrs['style'] =
`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`
+ `width:${sw.toFixed(1)}px;height:${sh.toFixed(1)}px;max-width:none${filterCss ? `;${filterCss}` : ''}`
// the crop wrap carries the positioning margins itself, so the footprint
// inset folds into them instead of replacing them
const cropWrapMargins = foldQuarterTurnMargins(
@@ -3912,6 +4162,9 @@ function protectedDomSpec(node: PmNode): DomSpec {
imgAttrs['style'] =
`${imgAttrs['style'] ? `${imgAttrs['style']};` : ''}transform:${xf.join(' ')}`
}
+ if (filterCss) {
+ imgAttrs['style'] = `${imgAttrs['style'] ? `${imgAttrs['style']};` : ''}${filterCss}`
+ }
if (borderCss) {
imgAttrs['style'] = `${imgAttrs['style'] ? `${imgAttrs['style']};` : ''}${borderCss}`
}
@@ -3928,6 +4181,7 @@ function protectedDomSpec(node: PmNode): DomSpec {
'span',
{
class: 'doc-img-wrap',
+ ...imgWrapData,
...(imgFloatPos || imgWrapTransform
? {
style: `${imgFloatPos ? `position:absolute;${imgFloatPos};` : ''}display:inline-block${imgWrapTransform ? `;${imgWrapTransform}` : ''}`,
@@ -3947,6 +4201,19 @@ function protectedDomSpec(node: PmNode): DomSpec {
renderTableSpec(table as TableModel),
]
}
+ if ((chartDisplay as ChartDisplay | null)?.series?.length) {
+ attrs.class += ' doc-protected-chart'
+ // caption text sharing the chart's paragraph (SEQ figure numbers) sits under the plot
+ const caption = fieldDisplay ? renderFieldSpec(fieldDisplay as FieldDisplay) : null
+ return [
+ 'div',
+ attrs,
+ moveHandleSpec(t('editorMoveChart')),
+ renderChartSpec(chartDisplay as ChartDisplay),
+ ...(caption ? [['div', { class: 'doc-chart-caption' }, caption] as DomSpec] : []),
+ ['span', { class: 'box-resize-handle', contenteditable: 'false' }],
+ ]
+ }
if (fieldDisplay) {
const spec = renderFieldSpec(fieldDisplay as FieldDisplay)
if (spec) {
@@ -3967,16 +4234,6 @@ function protectedDomSpec(node: PmNode): DomSpec {
renderFormulaSpec(formulaDisplay as FormulaDisplay),
]
}
- if ((chartDisplay as ChartDisplay | null)?.series?.length) {
- attrs.class += ' doc-protected-chart'
- return [
- 'div',
- attrs,
- moveHandleSpec(t('editorMoveChart')),
- renderChartSpec(chartDisplay as ChartDisplay),
- ['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.
@@ -4112,6 +4369,9 @@ export function buildProtectedDom(node: PmNode): HTMLElement {
const mathml = (node.attrs.formulaDisplay as FormulaDisplay | null)?.mathml
const mathHost = el.querySelector?.('.doc-formula-math')
if (mathml && mathHost) mathHost.innerHTML = mathml
+ el.querySelectorAll?.('.doc-field-math').forEach((host) => {
+ host.innerHTML = inlineMathML(host.getAttribute('data-omml') ?? '')
+ })
return el
}
@@ -4307,7 +4567,8 @@ function wireFieldEditing(
view: EditorView,
): (ProtectedContentEditor & { cleanup(): void }) | null {
const field = getNode().attrs.fieldDisplay as FieldDisplay | null
- if (!field || field.kind === 'pageBreak') return null
+ // a chart caption is display-only: its field commit would rebuild the paragraph text
+ if (!field || field.kind === 'pageBreak' || getNode().attrs.chartDisplay) return null
const targets = Array.from(
dom.querySelectorAll('.doc-toc-title, .doc-toc-page, .doc-field-text'),
)
@@ -4488,6 +4749,8 @@ function textboxDocJson(box: TextboxDisplay): Record {
spaceBeforeAuto: para.spaceBeforeAuto ?? null,
spaceAfterAuto: para.spaceAfterAuto ?? null,
shadingFill: para.shadingFill ?? null,
+ shadingDisplay: para.shadingDisplay ?? null,
+ shadingClear: para.shadingClear ?? null,
borders: para.borders ?? null,
listMarker: para.listMarker ?? null,
},
@@ -4522,6 +4785,8 @@ function subEditorParas(sub: Editor): TextboxPara[] {
'spaceBeforeAuto',
'spaceAfterAuto',
'shadingFill',
+ 'shadingDisplay',
+ 'shadingClear',
'borders',
'listMarker',
] as const
@@ -5328,6 +5593,8 @@ const TextboxParagraph = Node.create({
spaceBeforeAuto: { default: null as boolean | null },
spaceAfterAuto: { default: null as boolean | null },
shadingFill: { default: null as string | null },
+ shadingDisplay: { default: null as string | null },
+ shadingClear: { default: null as boolean | null },
borders: { default: null as string | null },
listMarker: { default: null as TextboxListMarker | null },
}
@@ -5353,15 +5620,19 @@ const TextboxParagraph = Node.create({
const attrs: Record = { class: classes.join(' ') }
if (node.attrs.styleId) attrs['data-style'] = String(node.attrs.styleId)
const fontStyles: string[] = []
- if (node.textContent) {
+ if (node.textContent && !isSpaceOnlyParagraph(node)) {
fontStyles.push(`--doc-line-factor:${paraLineFactor(node)}`)
const fam = paraDeclaredFontFamily(node)
if (fam) fontStyles.push(`font-family:${fam}`)
const strut = explicitStrutHalfPoints(node)
if (strut) fontStyles.push(...strutFontCss(strut))
+ } else if (node.textContent) {
+ // space-only: the mark sizes the line with the Latin factor, never the space run
+ fontStyles.push('--doc-line-factor:var(--doc-line-factor-latin,1.2)')
}
const mult = cssAutoLineMult(lineRule, lineRawTwips, lineSpacing)
if (marker) attrs['data-marker'] = marker.text
+ if (marker?.picBulletSrc) attrs['data-marker-pic'] = ''
// Word precedence: the paragraph's own w:ind (an explicit 0 included), else the numbering
// level's, else the style's
const indentLeft = (node.attrs.indentLeft as number | null) ?? marker?.indentLeft ?? null
@@ -5370,10 +5641,9 @@ const TextboxParagraph = Node.create({
const hanging = marker && firstLine < 0 ? -firstLine : 0
// no hanging area at all: Word runs the marker to the next default tab stop (0.5in)
const markerTab = marker && !hanging && firstLine <= 0 ? ';--li-tab:36pt' : ''
+ const shdBg = (node.attrs.shadingDisplay ?? node.attrs.shadingFill) as string | null
const styles = [
- node.attrs.align
- ? `text-align:${node.attrs.align === 'distribute' ? 'justify' : node.attrs.align}`
- : '',
+ node.attrs.align ? textAlignDecl(String(node.attrs.align)) : '',
...fontStyles,
cssLineHeight(lineRule, lineRawTwips, lineSpacing)
? `line-height:${cssLineHeight(lineRule, lineRawTwips, lineSpacing)}`
@@ -5395,7 +5665,10 @@ const TextboxParagraph = Node.create({
? `text-indent:${Number(ownFirstLine) / 20}pt`
: '',
marker?.szHalfPoints ? `--li-marker-size:${marker.szHalfPoints / 2}pt` : '',
+ marker?.picBulletSrc ? `--li-marker-pic:url("${marker.picBulletSrc}")` : '',
...(marker?.symbol ? substituteMarkerStyles(marker.text) : []),
+ // after the substitute's --li-marker-lh:0 so the oversized height wins, as in the body list
+ marker?.oversized ? MARKER_NATURAL_LINE_HEIGHT : '',
node.attrs.spaceBeforeAuto
? `margin-top:${WORD_AUTO_SPACING_PT}pt`
: node.attrs.spaceBefore != null
@@ -5406,15 +5679,17 @@ const TextboxParagraph = Node.create({
: node.attrs.spaceAfter != null
? `margin-bottom:${Number(node.attrs.spaceAfter) / 20}pt`
: '',
- node.attrs.shadingFill
- ? `background-color:#${node.attrs.shadingFill};${dkBackground(`#${node.attrs.shadingFill}`)}`
- : '',
+ shdBg
+ ? `background-color:#${shdBg};${dkBackground(`#${shdBg}`)}`
+ : node.attrs.shadingClear
+ ? 'background-color:transparent'
+ : '',
]
.filter(Boolean)
.join(';')
if (styles) attrs.style = styles
{
- const ink = fillInk(node.attrs.shadingFill)
+ const ink = fillInk(shdBg)
if (ink) attrs['data-ink'] = ink
}
return ['div', attrs, 0]
@@ -5441,6 +5716,9 @@ const textboxSubExtensions = [
// without these marks the whole box fails to load into the sub-editor
RefFieldMark,
InstrFieldMark,
+ SymMark,
+ CtrlCheckboxMark,
+ CheckboxToggleExtension,
TextStyleMark,
CommentMark,
UndoRedo,
@@ -5527,6 +5805,8 @@ export const editorExtensions = [
LinkMark,
RefFieldMark,
InstrFieldMark,
+ SymMark,
+ CtrlCheckboxMark,
RprChangeMark,
TextStyleMark,
CommentMark,
@@ -5547,11 +5827,13 @@ export const editorExtensions = [
FloatVShiftsExtension,
InactiveSelectionExtension,
AiQueueAnchorsExtension,
+ CheckboxToggleExtension,
PageGapNavExtension,
TrailingTableExitExtension,
Gapcursor,
ImageCopyExtension,
EnterReplacesSelection,
+ WordSelectAllDelete,
AutoLinkOnDelimiter,
WordEditorShortcuts,
CaretMarksMemory,
diff --git a/apps/docs/src/renderer/editor/hf-dom.ts b/apps/docs/src/renderer/editor/hf-dom.ts
index c5a4b0c..ca78776 100644
--- a/apps/docs/src/renderer/editor/hf-dom.ts
+++ b/apps/docs/src/renderer/editor/hf-dom.ts
@@ -17,6 +17,7 @@ import {
estimateHfHeight,
runLetterSpacingCss,
} from '../line-metrics'
+import { borderCssStyle, borderDrawnPx, isDrawnBorder } from './border-metrics'
import { setDkBackground, setDkBorder, setDkColor } from './dark-page'
import { INLINE_RULE_CLASS, inlineRuleDecls } from './inline-rule'
@@ -33,23 +34,53 @@ export function paraBorderCss(line?: { color?: string; szPt?: number }): string
return `${widthPx}px solid #${line?.color ?? '444'}`
}
+export type ParaBorderPadding = Partial<
+ Record<'paddingTop' | 'paddingRight' | 'paddingBottom' | 'paddingLeft', string>
+>
+
+/**
+ * Padding for the drawn w:pBdr sides only, as longhands so a direct side and a
+ * style-level side on different edges layer per side (Word merges pBdr per
+ * side). Top/bottom: the line sits w:space pt from the text and the gap is
+ * part of the paragraph height; left/right keep the legacy 4px text inset.
+ */
+export function paraBorderPadding(
+ drawn: string,
+ lines?: Partial>,
+): ParaBorderPadding {
+ const out: ParaBorderPadding = {}
+ const v = (ch: 't' | 'b') => {
+ const space = lines?.[ch]?.spacePt
+ return space ? `${space}pt` : '0'
+ }
+ if (drawn.includes('t')) out.paddingTop = v('t')
+ if (drawn.includes('r')) out.paddingRight = '4px'
+ if (drawn.includes('b')) out.paddingBottom = v('b')
+ if (drawn.includes('l')) out.paddingLeft = '4px'
+ return out
+}
+
+const PADDING_PROP = {
+ paddingTop: 'padding-top',
+ paddingRight: 'padding-right',
+ paddingBottom: 'padding-bottom',
+ paddingLeft: 'padding-left',
+} as const
+
+export function paraBorderPaddingDecls(padding: ParaBorderPadding): string[] {
+ return (Object.keys(PADDING_PROP) as Array)
+ .filter((k) => padding[k] !== undefined)
+ .map((k) => `${PADDING_PROP[k]}:${padding[k]}`)
+}
+
/** One OOXML border → CSS border value; 'none' means explicitly borderless */
export function borderLineCss(
b: { style: string; szEighths?: number; color?: string } | undefined | null,
): string | null {
if (!b) return null
- if (b.style === 'none' || b.style === 'nil') return 'none'
- const px = Math.max(1, Math.round(((b.szEighths ?? 4) / 8 / 72) * 96))
- const dash =
- b.style === 'dashed'
- ? 'dashed'
- : b.style === 'dotted'
- ? 'dotted'
- : b.style === 'double'
- ? 'double'
- : 'solid'
+ if (!isDrawnBorder(b)) return 'none'
const color = b.color && b.color !== 'auto' ? `#${b.color}` : '#000'
- return `${px}px ${dash} ${color}`
+ return `${borderDrawnPx(b)}px ${borderCssStyle(b.style)} ${color}`
}
const px = (twips: number) => `${(twips / TWIPS_PER_PX).toFixed(1)}px`
@@ -141,6 +172,8 @@ export function hfCellParaStyle(
if (line.first && props.indentFirstLine) style.textIndent = px(props.indentFirstLine)
if (line.first && props.spaceBefore) style.marginTop = px(props.spaceBefore)
if (line.last && props.spaceAfter) style.marginBottom = px(props.spaceAfter)
+ const lh = hfParaLineHeightCss(props)
+ if (lh) style.lineHeight = lh
return style
}
@@ -173,6 +206,8 @@ export interface HfTabSegment {
/** offset from the text-column left edge; pct = margin-relative (w:ptab / implicit stops) */
left: { px: number } | { pct: number }
anchor: 'left' | 'center' | 'right'
+ /** laid-out right edge of a px-placed segment (column px) */
+ endPx?: number
}
export interface HfTabLayout {
@@ -326,7 +361,15 @@ export function hfTabSegments(
x,
val === 'center' ? target - segW / 2 : val === 'left' ? target : target - segW,
)
- if (runs.length > 0) segments.push({ runs, left: { px: placed }, anchor: 'left' })
+ // only an explicit stop may carry text past the column (a default-grid tab wraps in Word)
+ if (runs.length > 0) {
+ segments.push({
+ runs,
+ left: { px: placed },
+ anchor: 'left',
+ ...(stop ? { endPx: placed + segW } : {}),
+ })
+ }
x = placed + segW
}
// absolutely positioned segments add no flow height: an oversized run after a
@@ -344,6 +387,48 @@ export function hfTabSegments(
}
}
+/** Tab layouts of a strip paragraph, one per w:br line: every line lays its
+ * tabs out from the column edge again, w:ptab alignments keep their overall
+ * order across lines. Null when the paragraph has no tab. */
+export function hfTabLines(
+ para: Pick,
+ display: (text: string) => string = (t) => t,
+): HfTabLayout[] | null {
+ if (!para.runs.some((r) => r.text.includes('\t'))) return null
+ if (!para.runs.some((r) => r.text.includes('\n'))) return [hfTabSegments(para, display)!]
+ const lines: Run[][] = [[]]
+ for (const run of para.runs) {
+ const pieces = run.text.split('\n')
+ lines[lines.length - 1].push({ ...run, text: pieces[0] })
+ for (const piece of pieces.slice(1)) lines.push([{ ...run, text: piece }])
+ }
+ let tabsBefore = 0
+ return lines.map((runs) => {
+ const line = { ...para, runs, ptabAligns: para.ptabAligns?.slice(tabsBefore) }
+ tabsBefore += runs.reduce((n, r) => n + r.text.split('\t').length - 1, 0)
+ return hfTabSegments(line, display) ?? { lead: runs.filter((r) => r.text !== ''), segments: [] }
+ })
+}
+
+/** How far (px) tab segments run past the text column: Word keeps a stop set
+ * beyond the right margin and lets its text reach into the margin (a footer's
+ * right stop at 9360 twips on a 9070-twip column), so the strip's clip box
+ * widens by that much, never past the paper edge */
+export function hfTabOverflowPx(lines: HfTabLayout[], geom: HfStripGeom | undefined): number {
+ if (!geom) return 0
+ const column = geom.pageW - geom.marginLeft - geom.marginRight
+ let end = 0
+ for (const line of lines) for (const seg of line.segments) end = Math.max(end, seg.endPx ?? 0)
+ return Math.min(Math.max(0, end - column), Math.max(0, geom.marginRight))
+}
+
+/** a tab line whose lead shows nothing (footer starting with a tab) has no
+ * in-flow line box: without a strut the line collapses to zero height and
+ * the strip's overflow clips the positioned segments */
+export function hfTabLeadNeedsStrut(layout: HfTabLayout): boolean {
+ return !layout.lead.some((r) => r.text.trim() || r.image)
+}
+
/** Tab layout of one cell paragraph as display lines (null without tabs).
* Stops measure from the cell text edge; an overflowing tab wraps the rest
* onto further lines under Word 2013+ layout. */
@@ -652,8 +737,12 @@ export interface HfFloatBox {
marginBottom: number
/** header strip top (w:headerDist, px): origin of paragraph-relative vertical offsets */
headerDist: number
+ /** footer images: the footer strip top (page bottom - footerDist - strip height) replaces headerDist as that origin */
+ paraOriginY?: number
/** raw sectPr top margin (px, before push-down): origin wrapped margin-relative images reserve from */
sectMarginTop: number
+ /** left edge of this page on the shared canvas paper (differing-width documents center narrower pages) */
+ paperX?: number
}
/**
@@ -695,7 +784,7 @@ export function hfFloatPagePos(
img.posVRel === 'page'
? img.posYPx
: img.posVRel === 'paragraph'
- ? box.headerDist + img.posYPx
+ ? (box.paraOriginY ?? box.headerDist) + img.posYPx
: (wrapped ? box.sectMarginTop : box.marginTop) + img.posYPx
} else if (img.posV === 'center') {
y =
@@ -721,13 +810,66 @@ export function hfFloatPagePos(
*/
/**
- * Word's washout preset (gain 19661f, blacklevel 22938f) is the linear map
- * out = 0.3*in + 0.7 per channel (MS-ODRAW brightness/contrast), so white
- * stays white and the image fades toward white. invert-brightness-invert
- * reproduces it exactly: 1 - 0.3*(1 - in); brightness/contrast chains clamp
- * at white and repaint white pixels as grey.
+ * v:imagedata gain/blacklevel as a CSS filter chain. Measured against Word's
+ * rendering of its washout preset (gain 0.3, blacklevel 0.35): black maps to
+ * 0.805 and everything above 1 - blacklevel is white, i.e. brightness adds
+ * blacklevel first (clamped at white), then gain scales the distance from
+ * white: out = 1 - gain * (1 - min(1, in + blacklevel)).
+ * brightness(1/(1-b)) is that clamped add; invert-brightness-invert the scale.
*/
-export const HF_WASHOUT_FILTER = 'invert(1) brightness(0.3) invert(1)'
+export function hfWashoutFilter(w: NonNullable): string {
+ const b = Math.max(0, Math.min(0.99, w.blackLevel))
+ const g = Math.max(0, Math.min(1, w.gain))
+ const r = (v: number) => Math.round(v * 1000) / 1000
+ return `brightness(${r(1 / (1 - b))}) invert(1) brightness(${r(g * (1 - b))}) invert(1)`
+}
+
+/** CSS transform of a floating header/footer shape: anchor translate, then the VML rotation about the box center */
+export function hfFloatTransform(
+ img: Pick,
+ p: { translateX: number; translateY: number },
+): string | undefined {
+ const parts: string[] = []
+ if (p.translateX || p.translateY) parts.push(`translate(${p.translateX}%, ${p.translateY}%)`)
+ if (img.rotationDeg) parts.push(`rotate(${img.rotationDeg}deg)`)
+ return parts.length > 0 ? parts.join(' ') : undefined
+}
+
+let inkCtx: CanvasRenderingContext2D | null | undefined
+/**
+ * WordArt watermark as inline SVG: the string's glyph ink box (canvas
+ * measureText) is stretched onto the shape box, which is how Word's
+ * textpath fitshape draws it (tall narrow "DRAFT" across a wide box).
+ * Empty when the environment cannot measure text.
+ */
+export function wordArtSvgMarkup(img: HfImage): string {
+ const wa = img.wordArt
+ const w = img.widthPx ?? 0
+ const h = img.heightPx ?? 0
+ if (!wa || w <= 0 || h <= 0) return ''
+ if (inkCtx === undefined) inkCtx = document.createElement('canvas').getContext('2d')
+ if (!inkCtx || typeof inkCtx.measureText !== 'function') return ''
+ const family = wa.fontFamily ? `"${wa.fontFamily.replace(/"/g, '')}", sans-serif` : 'sans-serif'
+ const weight = wa.bold ? 'bold' : 'normal'
+ const styleKw = wa.italic ? 'italic' : 'normal'
+ inkCtx.font = `${styleKw} ${weight} 100px ${family}`
+ const m = inkCtx.measureText(wa.text)
+ const left = m.actualBoundingBoxLeft ?? 0
+ const inkW = left + (m.actualBoundingBoxRight ?? m.width)
+ const ascent = m.actualBoundingBoxAscent ?? 0
+ const inkH = ascent + (m.actualBoundingBoxDescent ?? 0)
+ if (!(inkW > 0) || !(inkH > 0)) return ''
+ const r = (v: number) => Math.round(v * 1000) / 1000
+ const esc = (t: string) =>
+ t.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"')
+ return (
+ `` +
+ `${esc(wa.text)} `
+ )
+}
+
/** for a header/footer picture; an a:srcRect crop becomes an
* overflow-hidden window over a scaled and offset image (body-path technique) */
function hfImgNode(img: {
@@ -765,25 +907,34 @@ function hfImgNode(img: {
}
export function makeHfFloatImgEl(img: HfImage, box: HfFloatBox, host: 'gap' | 'lead'): HTMLElement {
- const el = hfImgNode(img)
+ let el: HTMLElement
+ if (img.wordArt) {
+ el = document.createElement('span')
+ el.innerHTML = wordArtSvgMarkup(img)
+ } else {
+ el = hfImgNode(img)
+ }
el.className = 'page-hf-float-img'
+ if (!img.behind) el.style.zIndex = '1'
// a crop wrapper carries an inline position:relative for the strip hosts;
// the float path must stay absolute (inline style beats the class)
el.style.position = 'absolute'
const p = hfFloatPagePos(img, box)
+ const paperX = (box.paperX ?? 0) + p.x
if (host === 'gap') {
- el.style.left = `${p.x}px`
+ el.style.left = `${paperX}px`
+ // alignGapHfStrips re-anchors it to the paper: gap boxes don't start at the paper edge
+ el.dataset.paperX = paperX.toFixed(1)
el.style.top = `calc(100% + ${p.y - box.marginTop}px)`
} else {
- el.style.left = `${p.x - box.marginLeft}px`
+ el.style.left = `${paperX - box.marginLeft}px`
el.style.top = `${p.y - box.marginTop}px`
}
- if (p.translateX || p.translateY) {
- el.style.transform = `translate(${p.translateX}%, ${p.translateY}%)`
- }
+ const transform = hfFloatTransform(img, p)
+ if (transform) el.style.transform = transform
if (img.widthPx) el.style.width = `${img.widthPx}px`
if (img.heightPx) el.style.height = `${img.heightPx}px`
- if (img.washout) el.style.filter = HF_WASHOUT_FILTER
+ if (img.washout) el.style.filter = hfWashoutFilter(img.washout)
return el
}
@@ -947,6 +1098,7 @@ export function makeGapHfEl(opts: {
const paraEls: HTMLElement[] = []
const paras = parasOf(value)
const spacing = hfStackedSpacingPx(paras)
+ let tabOver = 0
for (const [index, para] of paras.entries()) {
if (para.box?.id !== boxId) {
boxId = para.box?.id
@@ -1089,33 +1241,42 @@ export function makeGapHfEl(opts: {
p.style.borderRight = line('r')
setDkBorder(p, 'r', line('r'))
}
- p.style.padding = '1px 4px'
+ Object.assign(p.style, paraBorderPadding(para.borders, para.borderLines))
}
- const tabbed = hfTabSegments(para, display)
- if (tabbed) {
- p.classList.add('page-hf-tabbed')
- if (tabbed.minHeightPt) p.style.minHeight = `${tabbed.minHeightPt}pt`
- // tab layout happens in left-aligned space; w:jc becomes an explicit shift
- p.style.textAlign = 'left'
- const leadIndent = hfLeadIndentCss(tabbed)
- if (leadIndent) p.style.textIndent = leadIndent
- for (const run of tabbed.lead) {
- const span = document.createElement('span')
- span.textContent = display(run.text)
- applyRunStyle(span, run)
- p.append(span)
- }
- for (const seg of tabbed.segments) {
- const segEl = document.createElement('span')
- segEl.className = `page-hf-tabseg page-hf-tabseg-${seg.anchor}`
- segEl.style.left = hfSegLeftCss(seg, tabbed)
- for (const run of seg.runs) {
+ const tabLines = hfTabLines(para, display)
+ if (tabLines) {
+ tabOver = Math.max(tabOver, hfTabOverflowPx(tabLines, geom))
+ // a w:br paragraph stacks one positioned line per break inside the
+ // paragraph block (which keeps the spacing and borders)
+ const single = tabLines.length === 1
+ for (const tabbed of tabLines) {
+ const line = single ? p : document.createElement('div')
+ line.classList.add('page-hf-tabbed')
+ if (tabbed.minHeightPt) line.style.minHeight = `${tabbed.minHeightPt}pt`
+ // tab layout happens in left-aligned space; w:jc becomes an explicit shift
+ line.style.textAlign = 'left'
+ const leadIndent = hfLeadIndentCss(tabbed)
+ if (leadIndent) line.style.textIndent = leadIndent
+ if (hfTabLeadNeedsStrut(tabbed)) line.append('\u200b')
+ for (const run of tabbed.lead) {
const span = document.createElement('span')
span.textContent = display(run.text)
applyRunStyle(span, run)
- segEl.append(span)
+ line.append(span)
}
- p.append(segEl)
+ for (const seg of tabbed.segments) {
+ const segEl = document.createElement('span')
+ segEl.className = `page-hf-tabseg page-hf-tabseg-${seg.anchor}`
+ segEl.style.left = hfSegLeftCss(seg, tabbed)
+ for (const run of seg.runs) {
+ const span = document.createElement('span')
+ span.textContent = display(run.text)
+ applyRunStyle(span, run)
+ segEl.append(span)
+ }
+ line.append(segEl)
+ }
+ if (!single) p.append(line)
}
host.append(p)
continue
@@ -1129,6 +1290,7 @@ export function makeGapHfEl(opts: {
}
host.append(p)
}
+ if (tabOver > 0) wrap.style.setProperty('--hf-tab-over', `${tabOver.toFixed(1)}px`)
return wrap
}
diff --git a/apps/docs/src/renderer/editor/image-drop.ts b/apps/docs/src/renderer/editor/image-drop.ts
new file mode 100644
index 0000000..fa0a3ef
--- /dev/null
+++ b/apps/docs/src/renderer/editor/image-drop.ts
@@ -0,0 +1,82 @@
+import type { Editor } from '@tiptap/core'
+import { TextSelection } from '@tiptap/pm/state'
+import type { Node as PmNode } from '@tiptap/pm/model'
+import { insertImageFromDataUrl } from '../components/ribbon-tabs'
+import { t } from '../i18n/locale'
+
+/** same formats as Insert > Picture and the clipboard lane */
+const IMAGE_MIME: Record = {
+ png: 'image/png',
+ jpg: 'image/jpeg',
+ jpeg: 'image/jpeg',
+ gif: 'image/gif',
+}
+const ACCEPTED = new Set(Object.values(IMAGE_MIME))
+
+export function droppedImageMime(file: { name: string; type: string }): string | null {
+ if (ACCEPTED.has(file.type)) return file.type
+ if (file.type) return null
+ const ext = /\.([a-z0-9]+)$/i.exec(file.name)?.[1]?.toLowerCase()
+ return ext ? (IMAGE_MIME[ext] ?? null) : null
+}
+
+export function imageFilesFromDataTransfer(dt: DataTransfer | null | undefined): File[] {
+ if (!dt) return []
+ return [...dt.files].filter((file) => droppedImageMime(file) !== null)
+}
+
+/** dragover sees no File objects yet — only the item kinds and types */
+export function isImageFileDrag(dt: DataTransfer | null | undefined): boolean {
+ if (!dt) return false
+ return [...dt.items].some((item) => item.kind === 'file' && ACCEPTED.has(item.type))
+}
+
+export function nearestTextSelection(doc: PmNode, pos: number): TextSelection | null {
+ const clamped = Math.max(0, Math.min(pos, doc.content.size))
+ const sel = TextSelection.near(doc.resolve(clamped))
+ return sel instanceof TextSelection ? sel : null
+}
+
+export async function insertImageFilesAt(
+ editor: Editor,
+ files: File[],
+ pos: number,
+): Promise {
+ const sel = nearestTextSelection(editor.state.doc, pos)
+ if (!sel) return 0
+ editor.view.dispatch(editor.state.tr.setSelection(sel))
+ let inserted = 0
+ for (const file of files) {
+ const mime = droppedImageMime(file)
+ if (!mime) continue
+ const dataUrl = await readImageDataUrl(file, mime)
+ if (!dataUrl) continue
+ if (await insertImageFromDataUrl(editor, dataUrl, t('ribbonPictureLabel', { name: file.name })))
+ inserted++
+ }
+ return inserted
+}
+
+export function insertImageFilesAtCoords(
+ editor: Editor,
+ files: File[],
+ coords: { left: number; top: number },
+): boolean {
+ if (!editor.isEditable || files.length === 0) return false
+ const hit = editor.view.posAtCoords(coords)
+ if (!hit) return false
+ insertImageFilesAt(editor, files, hit.pos).catch((err) => console.error('image drop failed', err))
+ return true
+}
+
+function readImageDataUrl(file: File, mime: string): Promise {
+ return new Promise((resolve) => {
+ const reader = new FileReader()
+ reader.onload = () => {
+ const payload = typeof reader.result === 'string' ? reader.result.split(',')[1] : undefined
+ resolve(payload ? `data:${mime};base64,${payload}` : null)
+ }
+ reader.onerror = () => resolve(null)
+ reader.readAsDataURL(file)
+ })
+}
diff --git a/apps/docs/src/renderer/editor/justify-shrink.ts b/apps/docs/src/renderer/editor/justify-shrink.ts
index acc3171..d2167f8 100644
--- a/apps/docs/src/renderer/editor/justify-shrink.ts
+++ b/apps/docs/src/renderer/editor/justify-shrink.ts
@@ -54,8 +54,10 @@ const SPACE_SHRINK_MAX = 0.25
const SHRINK_VS_STRETCH = 0.5
/** total overshoot (px) so Chromium's breaker definitely pulls the word */
const SHRINK_EPS = 0.5
-/** measurement noise floor (px): smaller imbalances are not real shrink state */
-const NOISE = 0.25
+/** imbalance floor (px): Blink breaks lines in 1/64px LayoutUnits, so any
+ * overflow of one unit or more is a real wrap (a Cyrillic Times line that
+ * Word fits by twip rounding overflows Chromium by ~1/64px) */
+const NOISE = 1 / 128
export function decideLineShrinks(lines: ShrinkLine[]): Array {
return lines.map((line) => {
@@ -147,9 +149,17 @@ function spaceAdvancePx(cs: CSSStyleDeclaration): number {
return spaceCtx.measureText(' ').width + (parseFloat(cs.letterSpacing) || 0)
}
-/** same rendered line = the boxes overlap vertically by more than a hairline */
-function sameLine(a: WordBox, b: WordBox): boolean {
- return a.top < b.bottom - 1 && a.bottom > b.top + 1
+/** same rendered line = the boxes share more than half the shorter box's height.
+ * Glyph boxes (ascent+descent) are taller than tight line-heights (w:line < 240
+ * auto, or a 1.0 face factor under Blink's Mac ascent bump), so consecutive
+ * lines overlap by a few px and a hairline test would chain the whole
+ * paragraph into one line */
+export function sameLine(
+ a: { top: number; bottom: number },
+ b: { top: number; bottom: number },
+): boolean {
+ const overlap = Math.min(a.bottom, b.bottom) - Math.max(a.top, b.top)
+ return overlap > Math.min(a.bottom - a.top, b.bottom - b.top) / 2
}
class JustifyShrinkView {
diff --git a/apps/docs/src/renderer/editor/line-numbers.ts b/apps/docs/src/renderer/editor/line-numbers.ts
new file mode 100644
index 0000000..cf3fa62
--- /dev/null
+++ b/apps/docs/src/renderer/editor/line-numbers.ts
@@ -0,0 +1,334 @@
+import type { LineNumbering, SectionInfo } from '@genoffice/docx-engine'
+import { sectionBidi, sectionColGeom } from '../pagination-sections'
+import type { BlockBox, BlockMetaOf } from '../pagination-types'
+import { pageFramesFromGaps } from './pagination-gaps'
+
+/** Word's gap for an omitted w:distance (measured against Word output: 0.25in). */
+export const LINE_NUMBER_DEFAULT_DISTANCE_TWIPS = 360
+
+const twipsToPx = (twips: number) => (twips / 1440) * 96
+const NUMBER_BOX_W = 64
+
+/** subtrees inside a block that are not body text: page-gap widgets, float hosts, repeated table headers */
+const SKIP_SELECTOR =
+ '.page-gap, .page-gap-inline, .page-gap-cut, .page-float-host, .page-float-carry, .page-repeat-header'
+
+export interface LineRect {
+ top: number
+ bottom: number
+ left: number
+ right: number
+}
+
+/** Merge inline fragment rects into line boxes: fragments sharing most of their vertical extent form one line. */
+export function groupLineRects(rects: LineRect[]): LineRect[] {
+ const lines: LineRect[] = []
+ for (const r of [...rects].sort((a, b) => a.top - b.top)) {
+ if (r.bottom - r.top <= 0) continue
+ const cur = lines[lines.length - 1]
+ if (cur) {
+ const overlap = Math.min(cur.bottom, r.bottom) - Math.max(cur.top, r.top)
+ if (overlap >= 0.5 * Math.min(cur.bottom - cur.top, r.bottom - r.top)) {
+ cur.top = Math.min(cur.top, r.top)
+ cur.bottom = Math.max(cur.bottom, r.bottom)
+ cur.left = Math.min(cur.left, r.left)
+ cur.right = Math.max(cur.right, r.right)
+ continue
+ }
+ }
+ lines.push({ ...r })
+ }
+ return lines
+}
+
+/** Line boxes of one paragraph element (viewport coords) from its text, inline images and line breaks. */
+export function paragraphLineRects(el: HTMLElement): LineRect[] {
+ const rects: LineRect[] = []
+ const push = (list: DOMRectList) => {
+ for (const r of Array.from(list)) {
+ if (r.height > 0) rects.push({ top: r.top, bottom: r.bottom, left: r.left, right: r.right })
+ }
+ }
+ const walker = document.createTreeWalker(el, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, {
+ acceptNode: (node) => {
+ if (node instanceof Element) {
+ if (node.matches(SKIP_SELECTOR)) return NodeFilter.FILTER_REJECT
+ return node.tagName === 'IMG' || node.tagName === 'BR'
+ ? NodeFilter.FILTER_ACCEPT
+ : NodeFilter.FILTER_SKIP
+ }
+ return NodeFilter.FILTER_ACCEPT
+ },
+ })
+ const range = document.createRange()
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
+ if (node instanceof Element) {
+ push(node.getClientRects())
+ } else if (node.nodeValue && node.nodeValue.length > 0) {
+ range.selectNodeContents(node)
+ push(range.getClientRects())
+ }
+ }
+ return groupLineRects(rects)
+}
+
+export interface LineRef {
+ page: number
+ col: number
+ top: number
+ section: number
+}
+
+/**
+ * Number lines in reading order (page, column, top). Every line counts; a label
+ * is emitted only for multiples of countBy. Restart per page / section per w:restart.
+ */
+export function numberLines(
+ lines: T[],
+ lnOf: (section: number) => LineNumbering | undefined,
+): Array<{ line: T; label: string }> {
+ const sorted = [...lines].sort((a, b) => a.page - b.page || a.col - b.col || a.top - b.top)
+ const out: Array<{ line: T; label: string }> = []
+ let n = 0
+ let started = false
+ let prevPage = -1
+ let prevSection = -1
+ for (const line of sorted) {
+ const ln = lnOf(line.section)
+ if (!ln) continue
+ const restart =
+ !started ||
+ (ln.restart === 'newPage' && line.page !== prevPage) ||
+ (ln.restart === 'newSection' && line.section !== prevSection)
+ n = restart ? ln.start : n + 1
+ started = true
+ prevPage = line.page
+ prevSection = line.section
+ if (n % ln.countBy === 0) out.push({ line, label: String(n) })
+ }
+ return out
+}
+
+export const hasLineNumbering = (sections: SectionInfo[]): boolean =>
+ sections.some((s) => s.settings.lineNumbers !== undefined)
+
+const lnOfSections = (sections: SectionInfo[]) => (i: number) =>
+ sections[Math.min(i, sections.length - 1)]?.settings.lineNumbers
+
+const distancePx = (ln: LineNumbering) =>
+ twipsToPx(ln.distance ?? LINE_NUMBER_DEFAULT_DISTANCE_TWIPS)
+
+/** left edge of each text column (reading order) relative to the left margin (px);
+ * a w:bidi section fills its columns right-to-left */
+export function columnLefts(s: SectionInfo): number[] {
+ const geom = sectionColGeom(s)
+ const xs: number[] = []
+ let x = 0
+ for (let c = 0; c < geom.cols; c++) {
+ xs.push(x)
+ x += geom.widths[c] + (geom.gaps[c] ?? 0)
+ }
+ return sectionBidi(s) ? xs.map((left, c) => x - left - geom.widths[c]) : xs
+}
+
+/** reading-order index of the column whose left edge is the rightmost one at or before x
+ * (the leftmost column when x precedes them all); lefts may be mirrored (w:bidi) */
+export function columnAt(lefts: number[], x: number): number {
+ let col = -1
+ for (let c = 0; c < lefts.length; c++) {
+ if (x >= lefts[c] - 0.5 && (col < 0 || lefts[c] > lefts[col])) col = c
+ }
+ if (col >= 0) return col
+ return lefts.reduce((best, left, c) => (left < lefts[best] ? c : best), 0)
+}
+
+/** Word's "Line Number" style is the default paragraph font: copy it from the document root. */
+function applyDocFont(layer: HTMLElement, docRoot: Element): void {
+ const cs = getComputedStyle(docRoot)
+ layer.style.fontFamily = cs.fontFamily
+ layer.style.fontSize = cs.fontSize
+ layer.style.color = cs.color
+}
+
+function appendMark(
+ layer: HTMLElement,
+ cls: string,
+ top: number,
+ height: number,
+ right: number,
+ label: string,
+): void {
+ const el = document.createElement('div')
+ el.className = cls
+ el.style.top = `${top}px`
+ el.style.height = `${height}px`
+ el.style.lineHeight = `${height}px`
+ el.style.left = `${right - NUMBER_BOX_W}px`
+ el.style.width = `${NUMBER_BOX_W}px`
+ el.textContent = label
+ layer.appendChild(el)
+}
+
+const FLOAT_WRAP_RE = /(?:^|\s)img-wrap-(?:square|tight|through)-(?:left|right)(?:\s|$)/
+
+/** blocks whose lines Word does not count: tables, protected objects, floats (same set as the canvas path's `floated`) */
+const skipBlock = (el: HTMLElement) =>
+ el.tagName === 'TABLE' ||
+ el.hasAttribute('data-doc-protected') ||
+ el.classList.contains('pv-prune-spacer') ||
+ el.classList.contains('page-float-host') ||
+ el.classList.contains('page-float-carry') ||
+ FLOAT_WRAP_RE.test(el.className)
+
+interface CanvasLine extends LineRef {
+ height: number
+ right: number
+}
+
+/**
+ * Canvas line numbers (sectPr w:lnNumType): one absolutely positioned label per
+ * counted line on the page wrap, right-aligned `distance` before the text column.
+ * Tables, protected objects and w:suppressLineNumbers paragraphs are skipped;
+ * header/footer strips live outside the block list.
+ */
+export function syncLineNumbers(
+ wrap: HTMLElement,
+ pm: HTMLElement,
+ blocks: BlockBox[],
+ sections: SectionInfo[],
+ zoomFactor: number,
+ metaOf?: BlockMetaOf,
+ first?: { left: number; width: number },
+): void {
+ let layer = wrap.querySelector(':scope > .page-line-numbers') as HTMLElement | null
+ if (!hasLineNumbering(sections)) {
+ layer?.remove()
+ return
+ }
+ if (!layer) {
+ layer = document.createElement('div')
+ layer.className = 'page-line-numbers'
+ wrap.appendChild(layer)
+ }
+ layer.textContent = ''
+ applyDocFont(layer, pm)
+ const frames = pageFramesFromGaps(wrap, zoomFactor, first)
+ const wr = wrap.getBoundingClientRect()
+ const lines: CanvasLine[] = []
+ for (const b of blocks) {
+ if (!b.el || b.tableRows || b.floated || skipBlock(b.el)) continue
+ const sec = Math.min(b.section ?? 0, sections.length - 1)
+ const ln = sections[sec]?.settings.lineNumbers
+ if (!ln) continue
+ if (b.docxIndex !== undefined && metaOf?.(b.docxIndex)?.suppressLineNumbers) continue
+ const set = sections[sec].settings
+ const xs = columnLefts(sections[sec])
+ for (const r of paragraphLineRects(b.el)) {
+ const top = (r.top - wr.top) / zoomFactor
+ const height = (r.bottom - r.top) / zoomFactor
+ const mid = top + height / 2
+ const page = frames.findIndex((f) => mid >= f.top && mid < f.bottom)
+ if (page < 0) continue
+ const textLeft = frames[page].left + twipsToPx(set.marginLeft)
+ const rel = (r.left - wr.left) / zoomFactor - textLeft
+ const col = columnAt(xs, rel)
+ lines.push({
+ page,
+ col,
+ top,
+ height,
+ section: sec,
+ right: textLeft + xs[col] - distancePx(ln),
+ })
+ }
+ }
+ for (const { line, label } of numberLines(lines, lnOfSections(sections))) {
+ appendMark(layer, 'page-line-number', line.top, line.height, line.right, label)
+ }
+}
+
+interface PreviewLine extends LineRef {
+ host: HTMLElement
+ height: number
+ right: number
+}
+
+/**
+ * Pagination preview / print copy: labels per .pv-page sheet, measured on the
+ * cloned blocks inside each page window (.pv-clip). Column = the .pv-col index;
+ * the label x comes from the section's margin and column geometry (page-relative).
+ * The layer lives inside .pv-sheet so it follows the zoom and the markup scale.
+ */
+export function syncPreviewLineNumbers(
+ root: HTMLElement,
+ sections: SectionInfo[],
+ metaOf?: BlockMetaOf,
+): void {
+ const pages = Array.from(root.querySelectorAll('.pv-page'))
+ if (!hasLineNumbering(sections)) {
+ for (const p of pages) p.querySelector('.pv-line-numbers')?.remove()
+ return
+ }
+ const sectionOfIdx = (idx: number, fallback: number) => {
+ const i = sections.findIndex((s) => idx >= s.firstBlockIndex && idx <= s.lastBlockIndex)
+ return i >= 0 ? i : fallback
+ }
+ const lines: PreviewLine[] = []
+ pages.forEach((pageEl, page) => {
+ const host = pageEl.querySelector(':scope > .pv-sheet') ?? pageEl
+ host.querySelector(':scope > .pv-line-numbers')?.remove()
+ const hostRect = host.getBoundingClientRect()
+ const k =
+ hostRect.width / (host.offsetWidth || parseFloat(pageEl.style.width) || hostRect.width) || 1
+ const pageSection = Number(pageEl.getAttribute('data-pv-section') ?? -1)
+ for (const clip of Array.from(pageEl.querySelectorAll('.pv-clip'))) {
+ if (clip.closest('.pv-footnotes')) continue
+ const colEl = clip.closest('.pv-col')
+ const col = colEl?.parentElement ? Array.from(colEl.parentElement.children).indexOf(colEl) : 0
+ const clipRect = clip.getBoundingClientRect()
+ const content = clip.querySelector('.pv-content')
+ if (!content) continue
+ for (const el of Array.from(content.children) as HTMLElement[]) {
+ if (skipBlock(el)) continue
+ const idx = Number(el.getAttribute('data-idx'))
+ const sec = Math.min(
+ Number.isFinite(idx) && el.hasAttribute('data-idx')
+ ? sectionOfIdx(idx, pageSection)
+ : pageSection,
+ sections.length - 1,
+ )
+ const ln = sections[sec]?.settings.lineNumbers
+ if (!ln) continue
+ if (el.hasAttribute('data-idx') && metaOf?.(idx)?.suppressLineNumbers) continue
+ const colLeft =
+ twipsToPx(sections[sec].settings.marginLeft) + (columnLefts(sections[sec])[col] ?? 0)
+ for (const r of paragraphLineRects(el)) {
+ const mid = (r.top + r.bottom) / 2
+ if (mid < clipRect.top || mid >= clipRect.bottom) continue
+ lines.push({
+ host,
+ page,
+ col,
+ section: sec,
+ top: (r.top - hostRect.top) / k,
+ height: (r.bottom - r.top) / k,
+ right: colLeft - distancePx(ln),
+ })
+ }
+ }
+ }
+ })
+ const layers = new Map()
+ for (const { line, label } of numberLines(lines, lnOfSections(sections))) {
+ let layer = layers.get(line.host)
+ if (!layer) {
+ layer = document.createElement('div')
+ layer.className = 'pv-line-numbers'
+ const content = line.host.querySelector('.pv-content')
+ if (content) applyDocFont(layer, content)
+ line.host.appendChild(layer)
+ layers.set(line.host, layer)
+ }
+ appendMark(layer, 'pv-line-number', line.top, line.height, line.right, label)
+ }
+}
diff --git a/apps/docs/src/renderer/editor/marks.ts b/apps/docs/src/renderer/editor/marks.ts
index 186518f..fa67562 100644
--- a/apps/docs/src/renderer/editor/marks.ts
+++ b/apps/docs/src/renderer/editor/marks.ts
@@ -6,9 +6,22 @@ import { cssCsFontFamily, cssRunFontFamily } from '../line-metrics'
import { isEastAsianFontName } from '../font-list'
import { t } from '../i18n/locale'
import { dkBackground } from './dark-page'
+import { runBorderDecls } from './run-border'
import { fillInk } from './shading-ink'
import { textColorDecls } from './text-color'
-import {} from '@genoffice/docx-engine'
+import { parseTextOutlineAttr, textOutlineDecl } from './text-outline'
+import {
+ charScaleXDecls,
+ doubleStrikeDecl,
+ glowDecl,
+ paperColorEffect,
+ parseGlowAttr,
+ parseTextEffectAttr,
+ positionDecl,
+ textEffectDecls,
+} from './text-effects'
+import { symbolGlyph, symbolPuaChar } from '@genoffice/docx-engine'
+import { symbolFontCovers } from '../font-check'
/**
* Custom schema mirroring the docx-engine Block model 1:1.
@@ -255,6 +268,40 @@ export const RefFieldMark = Mark.create({
},
})
+/** w:sym glyph: the text is the display character, the attrs the font + hex
+ * char the run regenerates with; non-inclusive so typed text stays plain */
+export const SymMark = Mark.create({
+ name: 'docSym',
+ inclusive: false,
+ // innermost mark: an undecoded glyph exists only in its symbol font, which
+ // must win over the run's own font-family (document data, hence inline)
+ priority: 90,
+ addAttributes() {
+ return { font: { default: '' }, char: { default: '' } }
+ },
+ parseHTML() {
+ return [{ tag: 'span[data-sym-char]' }]
+ },
+ renderHTML({ mark }) {
+ const font = String(mark.attrs.font)
+ const char = String(mark.attrs.char)
+ const glyph = symbolGlyph(font, char)
+ const pua = symbolPuaChar(char)
+ // the font draws its own glyph when installed (runsToInline then feeds it the
+ // private-use code); an undecoded glyph exists only in that font either way
+ const ownFont = !!font && pua !== null && (glyph === pua || symbolFontCovers(font, pua))
+ return [
+ 'span',
+ {
+ 'data-sym-font': font,
+ 'data-sym-char': char,
+ ...(ownFont ? { style: `font-family:"${font.replace(/"/g, '')}"` } : {}),
+ },
+ 0,
+ ]
+ },
+})
+
/** Revision display mode (synced by App; in original mode the extension below restores old formatting via decorations) */
export const revisionDisplayState = { mode: 'all' as 'all' | 'none' | 'original' }
@@ -366,6 +413,22 @@ export const InstrFieldMark = Mark.create({
},
})
+/** Content-control checkbox (w14:checkbox): the text is the box glyph, `sdtPr` the control's
+ * properties written back around it. Clicking the glyph toggles it (checkbox-toggle.ts). */
+export const CtrlCheckboxMark = Mark.create({
+ name: 'ctrlCheckbox',
+ inclusive: false,
+ addAttributes() {
+ return { sdtPr: { default: '' } }
+ },
+ parseHTML() {
+ return [{ tag: 'span[data-ctrl-checkbox]' }]
+ },
+ renderHTML() {
+ return ['span', { 'data-ctrl-checkbox': '', class: 'doc-checkbox-control' }, 0]
+ },
+})
+
/**
* font-family chain → dual-slot font attrs, inverting renderHTML's encoding:
* the Latin slot is the chain's first Latin family, the eastAsia slot its first
@@ -415,9 +478,16 @@ const CLIPBOARD_TEXT_STYLE_TYPES: Record 0 ? h - (targetPx - extraPx) : 0
+ return { style: `height:${h}px`, ...(extra > 0 ? { 'data-split-extra': extra.toFixed(1) } : {}) }
+}
+
/** Apply/replace the split-row height patches (an empty list clears them). */
export function setRowFills(
view: EditorView,
- fills: Array<{ el: Element; targetPx: number }>,
+ fills: Array<{ el: Element; targetPx: number; extraPx?: number }>,
): void {
const decos: Decoration[] = []
for (const [i, fill] of fills.entries()) {
+ const attrs = rowFillAttrs(fill.targetPx, fill.extraPx)
try {
const $inside = view.state.doc.resolve(view.posAtDOM(fill.el, 0))
for (let d = $inside.depth; d > 0; d--) {
if ($inside.node(d).type.name !== 'docTableRow') continue
decos.push(
- Decoration.node(
- $inside.before(d),
- $inside.after(d),
- { style: `height:${Math.round(fill.targetPx)}px` },
- { key: `row-fill-${i}-${Math.round(fill.targetPx)}` },
- ),
+ Decoration.node($inside.before(d), $inside.after(d), attrs, {
+ key: `row-fill-${i}-${attrs.style}-${attrs['data-split-extra'] ?? ''}`,
+ }),
)
break
}
@@ -173,27 +183,80 @@ export const FloatVShiftsExtension = Extension.create({
},
})
-/** Apply/replace the anchored-table shifts (an empty list clears them). */
+/** transaction meta set when the set of flowed floating tables changed: the
+ * reflow moves real layout, so the pagination pass must run again */
+export const floatFlowChangedMeta = 'paginationFloatFlowChanged'
+
+/** element inside a CSS-floated (not flowed) w:tblpPr table */
+export function insideFloatTable(el: Element): boolean {
+ const t = el.parentElement?.closest('.doc-table-float-left, .doc-table-float-right')
+ return !!t && !t.classList.contains('doc-table-float-flow')
+}
+
+/** Apply/replace the anchored-table shifts, the over-page float flows and the
+ * float-carry spacers (an empty list clears them). A `flow` entry renders the
+ * floating table in normal flow (doc-table-float-flow) instead of shifting it.
+ * A `carryPx` entry puts a flow spacer of that height before `el` (the anchor
+ * paragraph of a split floating table starts beside the table's last portion;
+ * the spacer is real flow space, unlike a page gap). */
export function setFloatVShifts(
view: EditorView,
- shifts: Array<{ el: Element; dyPx: number }>,
+ shifts: Array<{ el: Element; dyPx: number; flow?: boolean; carryPx?: number }>,
): void {
const decos: Decoration[] = []
+ const flowKeys: string[] = []
for (const [i, shift] of shifts.entries()) {
+ if (shift.carryPx !== undefined) {
+ const carry = Math.round(shift.carryPx * 10) / 10
+ if (carry < 0.5) continue
+ try {
+ const pos = view.state.doc.resolve(view.posAtDOM(shift.el, 0)).before(1)
+ decos.push(
+ Decoration.widget(
+ pos,
+ () => {
+ const div = document.createElement('div')
+ div.className = 'page-float-carry'
+ div.contentEditable = 'false'
+ div.style.height = `${carry}px`
+ return div
+ },
+ { side: -1, key: `tblp-carry-${i}-${carry}` },
+ ),
+ )
+ } catch {
+ /* stale element: skip this round */
+ }
+ continue
+ }
const dy = Math.round(shift.dyPx * 10) / 10
- if (dy < 0.5) continue
+ if (!shift.flow && Math.abs(dy) < 0.5) continue
try {
const $inside = view.state.doc.resolve(view.posAtDOM(shift.el, 0))
for (let d = $inside.depth; d > 0; d--) {
- if ($inside.node(d).type.name !== 'docTable') continue
- decos.push(
- Decoration.node(
- $inside.before(d),
- $inside.after(d),
- { style: `--tblp-dy:${dy}px`, 'data-tblp-dy': String(dy) },
- { key: `tblp-dy-${i}-${dy}` },
- ),
- )
+ const name = $inside.node(d).type.name
+ if (name !== 'docTable' && name !== 'docProtected') continue
+ const from = $inside.before(d)
+ if (shift.flow) {
+ flowKeys.push(String(from))
+ decos.push(
+ Decoration.node(
+ from,
+ $inside.after(d),
+ { class: 'doc-table-float-flow' },
+ { key: `tblp-flow-${i}`, flow: true },
+ ),
+ )
+ } else {
+ decos.push(
+ Decoration.node(
+ from,
+ $inside.after(d),
+ { style: `--tblp-dy:${dy}px`, 'data-tblp-dy': String(dy) },
+ { key: `tblp-dy-${i}-${dy}` },
+ ),
+ )
+ }
break
}
} catch {
@@ -202,8 +265,18 @@ export function setFloatVShifts(
}
const next = DecorationSet.create(view.state.doc, decos)
const prev = floatVKey.getState(view.state)
- if (!prev || !sameGaps(prev, next))
- view.dispatch(view.state.tr.setMeta(floatVKey, next).setMeta('addToHistory', false))
+ if (!prev || !sameGaps(prev, next)) {
+ const prevFlow = (prev?.find(undefined, undefined, (spec) => spec.flow === true) ?? [])
+ .map((d) => String(d.from))
+ .sort()
+ const flowChanged = prevFlow.join(',') !== flowKeys.sort().join(',')
+ view.dispatch(
+ view.state.tr
+ .setMeta(floatVKey, next)
+ .setMeta(floatFlowChangedMeta, flowChanged)
+ .setMeta('addToHistory', false),
+ )
+ }
}
export interface GapMetrics {
@@ -219,6 +292,10 @@ export interface GapMetrics {
sectionMarginLeft?: number
sectionMarginRight?: number
sectionMarginTop?: number
+ /** the next page's left edge and width on the shared paper (differing-width
+ * documents center narrower pages); absent = the page spans the paper */
+ pageLeft?: number
+ pageWidth?: number
}
/** height of the gray inter-page band inside a page gap */
@@ -229,6 +306,10 @@ export type GapKind = 'block' | 'inline' | 'table' | 'cut' | 'cell'
export function makeGapEl(m: GapMetrics, kind: GapKind, cols?: number): HTMLElement {
const gap = document.createElement(kind === 'table' ? 'tr' : 'div')
gap.contentEditable = 'false'
+ if (m.pageLeft !== undefined && m.pageWidth !== undefined) {
+ gap.style.setProperty('--gap-page-x', `${m.pageLeft}px`)
+ gap.style.setProperty('--gap-page-w', `${m.pageWidth}px`)
+ }
if (kind === 'cut') {
// in-row table break cut point: zero-height dashed marker (takes no layout height, coordinate bookkeeping unchanged)
gap.className = 'page-gap-cut'
@@ -307,7 +388,15 @@ export type PageGapSpec = {
/** table gaps: the host table's real column count (the spanning cell's colSpan
* must not widen the column grid — see makeGapEl) */
cols?: number
-} & ({ el: HTMLElement } | { pos: number; kind?: Exclude })
+} & (
+ | {
+ el: HTMLElement
+ /** invisible spacer of this height instead of a page gap: the anchor
+ * paragraph of a split floating table skips the table's in-table gaps */
+ carryPx?: number
+ }
+ | { pos: number; kind?: Exclude }
+)
/** Rebuild all page gaps (an empty list clears them); each gap carries its own margins (sections differ) */
export function setPageGaps(
@@ -345,6 +434,23 @@ export function setPageGaps(
try {
const $inside = view.state.doc.resolve(view.posAtDOM(gap.el, 0))
pos = $inside.before(1)
+ if (gap.carryPx !== undefined) {
+ const carry = Math.round(gap.carryPx)
+ decos.push(
+ Decoration.widget(
+ pos,
+ () => {
+ const div = document.createElement('div')
+ div.className = 'page-gap page-gap-carry'
+ div.contentEditable = 'false'
+ div.style.height = `${carry}px`
+ return div
+ },
+ { side: -1, key: `page-gap-carry-${ordinal}-${carry}` },
+ ),
+ )
+ continue
+ }
if (gap.suppressLeadMt)
decos.push(
Decoration.node(
@@ -363,7 +469,7 @@ export function setPageGaps(
}
// boundaryY in the key: a reused widget must not keep a stale boundary
// (cols too: a table-structure edit must rebuild the spanning cell)
- const mKey = `${metrics.marginTop},${metrics.marginBottom},${metrics.marginLeft},${metrics.marginRight},${Math.round(gap.pullUp ?? 0)},${Math.round(gap.boundaryY ?? -1)},${gap.cols ?? 0}`
+ const mKey = `${metrics.marginTop},${metrics.marginBottom},${metrics.marginLeft},${metrics.marginRight},${Math.round(gap.pullUp ?? 0)},${Math.round(gap.boundaryY ?? -1)},${gap.cols ?? 0},${Math.round(metrics.pageLeft ?? -1)}`
decos.push(
Decoration.widget(
pos,
@@ -470,17 +576,31 @@ export function syncCutOverlays(
}
}
+export type PageBorderSideName = 'top' | 'right' | 'bottom' | 'left'
+
export interface PageBorderSide {
- /** CSS border shorthand for this side */
- css: string
+ /** CSS border shorthand for this side (absent for tiled art patterns) */
+ css?: string
+ /** tiled art-border approximation: background of a strip along this side */
+ art?: PageBorderArtStrip
/** border inset from the paper edge (CSS px, unzoomed) */
insetPx: number
}
+export interface PageBorderArtStrip {
+ /** pattern height (CSS px, unzoomed) = the strip's thickness */
+ sizePx: number
+ backgroundImage: string
+ backgroundSize: string
+ backgroundRepeat: string
+}
+
export interface PageBorderStyle {
/** pages the border applies to (w:pgBorders w:display); undefined = all pages */
display?: 'firstPage' | 'notFirstPage'
- sides: Partial>
+ /** w:zOrder="back": paint behind the page text */
+ zOrder?: 'back'
+ sides: Partial>
}
/** Two/three-line OOXML border styles: CSS `double` is the closest match. */
@@ -501,7 +621,7 @@ const DOUBLE_BORDER_VALS = new Set([
const DASHED_BORDER_VALS = new Set(['dashed', 'dashSmallGap', 'dotDash', 'dotDotDash'])
-/** OOXML page-border line → CSS border shorthand. Decorative/art vals fall back to solid. */
+/** OOXML page-border line → CSS border shorthand. */
function pageBorderLineCss(val: string, widthPt: number, color: string): string {
const px = Math.max(1, Math.round((widthPt * 96) / 72))
if (DASHED_BORDER_VALS.has(val)) return `${px}px dashed ${color}`
@@ -511,18 +631,189 @@ function pageBorderLineCss(val: string, widthPt: number, color: string): string
return `${px}px solid ${color}`
}
+/**
+ * Word's art borders are bitmaps shipped with Office, tiled along the side at
+ * w:sz points of height. Approximation by pattern family: stitches/teeth → a
+ * zigzag line, pictogram rows (flowers, gems, people, food, …) → a dot row in
+ * the bitmap's main colour, dash/block rows → CSS dashed, line-work → CSS
+ * double, and single-rule bitmaps → a solid rule.
+ */
+type ArtFamily = 'zigzag' | 'dots' | 'dashes' | 'double' | 'solid'
+
+const ART_ZIGZAG = new Set([
+ 'zigZag',
+ 'zigZagStitch',
+ 'crossStitch',
+ 'sawtooth',
+ 'sawtoothGray',
+ 'sharksTeeth',
+ 'waveline',
+ 'classicalWave',
+ 'lightning1',
+ 'lightning2',
+ 'triangles',
+ 'triangle1',
+ 'triangle2',
+ 'triangleParty',
+ 'zanyTriangles',
+ 'pyramids',
+ 'pyramidsAbove',
+ 'heebieJeebies',
+ 'marqueeToothed',
+])
+
+const ART_DASHES = new Set([
+ 'basicBlackDashes',
+ 'basicWhiteDashes',
+ 'basicBlackSquares',
+ 'basicWhiteSquares',
+ 'couponCutoutDashes',
+ 'checkedBarBlack',
+ 'checkedBarColor',
+ 'checkered',
+ 'film',
+ 'decoBlocks',
+ 'mosaic',
+ 'quadrants',
+ 'shadowedSquares',
+ 'eclipsingSquares1',
+ 'eclipsingSquares2',
+ 'circlesRectangles',
+ 'postageStamp',
+ 'marquee',
+])
+
+const ART_DOUBLE = new Set([
+ 'handmade1',
+ 'handmade2',
+ 'twistedLines1',
+ 'twistedLines2',
+ 'basicThinLines',
+ 'basicWideInline',
+ 'basicWideMidline',
+ 'basicWideOutline',
+ 'weavingAngles',
+ 'weavingBraid',
+ 'weavingRibbon',
+ 'weavingStrips',
+ 'chainLink',
+ 'doubleD',
+ 'papyrus',
+ 'tornPaper',
+ 'tornPaperBlack',
+ 'woodwork',
+ 'xIllusions',
+ 'hypnotic',
+ 'crazyMaze',
+ 'celticKnotwork',
+ 'vine',
+ 'gradient',
+ 'decoArch',
+ 'decoArchColor',
+ 'fans',
+ 'northwest',
+ 'southwest',
+ 'seattle',
+ 'safari',
+ 'swirligig',
+ 'cornerTriangles',
+ 'certificateBanner',
+])
+
+const ART_SOLID = new Set(['whiteFlowers'])
+
+/** Main colour (and outline ink) of the coloured bitmaps; monochrome ones take w:color / black. */
+const ART_COLORS: Record = {
+ zigZagStitch: { fill: '#E2E2E2' },
+ gems: { fill: '#BFBFBF', ink: '#000000' },
+ cakeSlice: { fill: '#FEEDC9', ink: '#000000' },
+ peopleHats: { fill: '#FEFE7F', ink: '#BFBFBF' },
+}
+
+function artFamilyOf(val: string): ArtFamily {
+ if (ART_ZIGZAG.has(val)) return 'zigzag'
+ if (ART_DASHES.has(val)) return 'dashes'
+ if (ART_DOUBLE.has(val)) return 'double'
+ if (ART_SOLID.has(val)) return 'solid'
+ return 'dots'
+}
+
+function svgTile(size: number, body: string): string {
+ const svg = `${body} `
+ return `url("data:image/svg+xml,${encodeURIComponent(svg)}")`
+}
+
+/** Art side → CSS: a strip pattern for zigzag/dot rows, a border shorthand otherwise. */
+function pageBorderArtCss(
+ side: PageBorderSideName,
+ val: string,
+ heightPt: number,
+ color: string | undefined,
+): Pick {
+ const size = Math.max(2, Math.round((heightPt * 96) / 72))
+ const known = ART_COLORS[val]
+ const fill = color ?? known?.fill ?? (/Gray/.test(val) ? '#BFBFBF' : '#000000')
+ const ink = color ? undefined : known?.ink
+ const family = artFamilyOf(val)
+ const horizontal = side === 'top' || side === 'bottom'
+ if (family === 'dashes') return { css: `${size}px dashed ${fill}` }
+ if (family === 'double') return { css: `${Math.max(3, Math.round(size / 2))}px double ${fill}` }
+ if (family === 'solid') return { css: `${Math.max(1, Math.round(size / 8))}px solid ${fill}` }
+ let body: string
+ if (family === 'zigzag') {
+ const lo = (size * 0.15).toFixed(2)
+ const hi = (size * 0.85).toFixed(2)
+ const mid = (size / 2).toFixed(2)
+ const points = horizontal
+ ? `0,${hi} ${mid},${lo} ${size},${hi}`
+ : `${hi},0 ${lo},${mid} ${hi},${size}`
+ body = ` `
+ } else {
+ const r = (size * 0.32).toFixed(2)
+ const stroke = ink ? ` stroke="${ink}" stroke-width="1"` : ''
+ body = ` `
+ }
+ return {
+ art: {
+ sizePx: size,
+ backgroundImage: svgTile(size, body),
+ backgroundSize: `${size}px ${size}px`,
+ backgroundRepeat: horizontal ? 'repeat-x' : 'repeat-y',
+ },
+ }
+}
+
+/** Inline style of the art strip hugging `side` inside the page-border box. */
+export function pageBorderArtStripStyle(
+ side: PageBorderSideName,
+ art: PageBorderArtStrip,
+): Record {
+ const thickness = `${art.sizePx}px`
+ const place: Record =
+ side === 'top' || side === 'bottom'
+ ? { left: '0', right: '0', height: thickness, [side]: '0' }
+ : { top: '0', bottom: '0', width: thickness, [side]: '0' }
+ return {
+ ...place,
+ backgroundImage: art.backgroundImage,
+ backgroundSize: art.backgroundSize,
+ backgroundRepeat: art.backgroundRepeat,
+ }
+}
+
interface PageBorderSection {
pageBorder: boolean
pageBorderProps?: {
display?: 'firstPage' | 'notFirstPage'
offsetFrom?: 'page' | 'text'
+ zOrder?: 'back'
spacePt: number
widthPt: number
color?: string
sides?: Partial<
Record<
- 'top' | 'right' | 'bottom' | 'left',
- { val: string; widthPt: number; spacePt: number; color?: string }
+ PageBorderSideName,
+ { val: string; widthPt: number; spacePt: number; color?: string; art?: true }
>
>
}
@@ -554,7 +845,7 @@ export function pageBorderStyleOf(section: PageBorderSection): PageBorderStyle |
}
const sides: PageBorderStyle['sides'] = {}
// legacy single-box fallback: pageBorder set without parse-side details
- const fallback: { val: string; widthPt: number; spacePt: number; color?: string } = {
+ const fallback: { val: string; widthPt: number; spacePt: number; color?: string; art?: true } = {
val: 'single',
widthPt: p?.widthPt ?? 0.75,
spacePt: p?.spacePt ?? 24,
@@ -564,14 +855,78 @@ export function pageBorderStyleOf(section: PageBorderSection): PageBorderStyle |
for (const name of ['top', 'right', 'bottom', 'left'] as const) {
const line = declared ? declared[name] : fallback
if (!line) continue
+ const insetPx = inset(margins[name], line.spacePt)
+ if (line.art) {
+ const color = line.color ? `#${line.color}` : undefined
+ sides[name] = { ...pageBorderArtCss(name, line.val, line.widthPt, color), insetPx }
+ continue
+ }
// w:color absent/auto on a parsed side = automatic (black), never a sibling side's color
const color = `#${line.color ?? '000000'}`
- sides[name] = {
- css: pageBorderLineCss(line.val, line.widthPt, color),
- insetPx: inset(margins[name], line.spacePt),
- }
+ sides[name] = { css: pageBorderLineCss(line.val, line.widthPt, color), insetPx }
}
- return { ...(p?.display ? { display: p.display } : {}), sides }
+ return {
+ ...(p?.display ? { display: p.display } : {}),
+ ...(p?.zOrder ? { zOrder: p.zOrder } : {}),
+ sides,
+ }
+}
+
+export interface PageFrame {
+ top: number
+ bottom: number
+ /** horizontal extent on the page wrap (differing-width documents center narrower pages) */
+ left: number
+ width: number
+}
+
+/**
+ * Page frames on the canvas: vertical bounds span between gap decorations (gap =
+ * prev bottom margin + band + next top margin; zero-height cut markers are
+ * boundaries too). The first page takes `first`, every later page the geometry
+ * its gap carries (--gap-page-x/w) or, for markers without one, its predecessor's.
+ */
+export function pageFramesFromGaps(
+ wrap: HTMLElement,
+ zoomFactor: number,
+ first?: { left: number; width: number },
+): PageFrame[] {
+ const wr = wrap.getBoundingClientRect()
+ const paper = wrap.querySelector('.doc-page')
+ const paperRect = paper?.getBoundingClientRect()
+ const paperX = paperRect ? (paperRect.left - wr.left) / zoomFactor : 0
+ first ??= { left: 0, width: (paperRect?.width ?? wr.width) / zoomFactor }
+ // the carry spacer of a split floating table displaces the flow like a gap
+ // but is no page turn (the table's own in-table gap at the same Y is)
+ const gaps = Array.from(
+ wrap.querySelectorAll('.page-gap:not(.page-gap-carry), .page-gap-cut'),
+ )
+ .map((g) => {
+ const r = g.getBoundingClientRect()
+ const cs = getComputedStyle(g)
+ const mb = parseFloat(cs.getPropertyValue('--gap-mb')) || 0
+ const mt = parseFloat(cs.getPropertyValue('--gap-mt')) || 0
+ const x = parseFloat(g.style.getPropertyValue('--gap-page-x'))
+ const w = parseFloat(g.style.getPropertyValue('--gap-page-w'))
+ return {
+ top: (r.top - wr.top) / zoomFactor,
+ height: r.height / zoomFactor,
+ mb,
+ mt,
+ page: Number.isFinite(x) && Number.isFinite(w) ? { left: x, width: w } : null,
+ }
+ })
+ .sort((a, b) => a.top - b.top)
+ const frames: PageFrame[] = []
+ let geom = first
+ let top = 0
+ for (const g of gaps) {
+ frames.push({ top, bottom: g.top + g.mb, left: paperX + geom.left, width: geom.width })
+ geom = g.page ?? geom
+ top = g.top + g.height - g.mt
+ }
+ frames.push({ top, bottom: wr.height / zoomFactor, left: paperX + geom.left, width: geom.width })
+ return frames
}
/**
@@ -584,6 +939,7 @@ export function syncPageBorders(
wrap: HTMLElement,
style: PageBorderStyle | null,
zoomFactor: number,
+ first?: { left: number; width: number },
): void {
let layer = wrap.querySelector(':scope > .page-border-overlays') as HTMLElement | null
if (!style) {
@@ -595,26 +951,14 @@ export function syncPageBorders(
layer.className = 'page-border-overlays'
wrap.appendChild(layer)
}
+ // zOrder=back: the paper (.doc-page) is the editor root and owns its DOM, so
+ // the layer stays a sibling and blends under the text instead (CSS)
+ layer.classList.toggle('page-border-overlays-back', style.zOrder === 'back')
layer.textContent = ''
- const wr = wrap.getBoundingClientRect()
- // page bounds: spans between gap decorations (gap = prev bottom margin +
- // band + next top margin; zero-height cut markers are boundaries too)
- const gaps = Array.from(wrap.querySelectorAll('.page-gap, .page-gap-cut'))
- .map((g) => {
- const r = g.getBoundingClientRect()
- const cs = getComputedStyle(g)
- const mb = parseFloat(cs.getPropertyValue('--gap-mb')) || 0
- const mt = parseFloat(cs.getPropertyValue('--gap-mt')) || 0
- return { top: (r.top - wr.top) / zoomFactor, height: r.height / zoomFactor, mb, mt }
- })
- .sort((a, b) => a.top - b.top)
- const bounds = [0]
- for (const g of gaps) bounds.push(g.top + g.mb, g.top + g.height - g.mt)
- bounds.push(wr.height / zoomFactor)
const { sides } = style
- for (let i = 0, page = 0; i + 1 < bounds.length; i += 2) {
- const [top, bottom] = [bounds[i], bounds[i + 1]]
- if (bottom - top <= 10) continue
+ let page = 0
+ for (const f of pageFramesFromGaps(wrap, zoomFactor, first)) {
+ if (f.bottom - f.top <= 10) continue
const pageIdx = page++
if (style.display === 'firstPage' && pageIdx > 0) continue
if (style.display === 'notFirstPage' && pageIdx === 0) continue
@@ -622,14 +966,57 @@ export function syncPageBorders(
el.className = 'page-border-overlay'
const insetTop = sides.top?.insetPx ?? 0
const insetBottom = sides.bottom?.insetPx ?? 0
- el.style.top = `${top + insetTop}px`
- el.style.left = `${sides.left?.insetPx ?? 0}px`
- el.style.right = `${sides.right?.insetPx ?? 0}px`
- el.style.height = `${bottom - top - insetTop - insetBottom}px`
- if (sides.top) el.style.borderTop = sides.top.css
- if (sides.right) el.style.borderRight = sides.right.css
- if (sides.bottom) el.style.borderBottom = sides.bottom.css
- if (sides.left) el.style.borderLeft = sides.left.css
+ const insetLeft = sides.left?.insetPx ?? 0
+ const insetRight = sides.right?.insetPx ?? 0
+ el.style.top = `${f.top + insetTop}px`
+ el.style.left = `${f.left + insetLeft}px`
+ el.style.width = `${f.width - insetLeft - insetRight}px`
+ el.style.height = `${f.bottom - f.top - insetTop - insetBottom}px`
+ for (const name of ['top', 'right', 'bottom', 'left'] as const) {
+ const side = sides[name]
+ if (!side) continue
+ if (side.css)
+ el.style[`border${name[0].toUpperCase()}${name.slice(1)}` as 'borderTop'] = side.css
+ if (side.art) {
+ const strip = document.createElement('div')
+ strip.className = 'page-border-art'
+ Object.assign(strip.style, pageBorderArtStripStyle(name, side.art))
+ el.appendChild(strip)
+ }
+ }
+ layer.appendChild(el)
+ }
+}
+
+/**
+ * Differing-width documents: the shared .doc-page paper goes transparent and each
+ * page paints its own sheet (paper color + shadow) at its centered position, so a
+ * portrait page next to a landscape one keeps its real width. null clears the layer.
+ */
+export function syncPageSheets(
+ wrap: HTMLElement,
+ zoomFactor: number,
+ first: { left: number; width: number } | null,
+): void {
+ let layer = wrap.querySelector(':scope > .page-sheets') as HTMLElement | null
+ if (!first) {
+ layer?.remove()
+ return
+ }
+ if (!layer) {
+ layer = document.createElement('div')
+ layer.className = 'page-sheets'
+ wrap.appendChild(layer)
+ }
+ layer.textContent = ''
+ for (const f of pageFramesFromGaps(wrap, zoomFactor, first)) {
+ if (f.bottom - f.top <= 10) continue
+ const el = document.createElement('div')
+ el.className = 'page-sheet'
+ el.style.top = `${f.top}px`
+ el.style.height = `${f.bottom - f.top}px`
+ el.style.left = `${f.left}px`
+ el.style.width = `${f.width}px`
layer.appendChild(el)
}
}
@@ -728,6 +1115,8 @@ export function syncFloatShifts(
for (const el of Array.from(
pm.querySelectorAll('.page-gap, .page-float-host, .page-repeat-header'),
)) {
+ // gap rows inside a floating table grow only the float's own box
+ if (insideFloatTable(el)) continue
const r = el.getBoundingClientRect()
// true slice boundary when known: the widget can sit at the flow end
// while its boundary lies inside trailing float-spill space, which would
@@ -888,6 +1277,7 @@ export function syncAnchorBands(pm: HTMLElement, factor: number): void {
if (
el.classList.contains('page-gap') ||
el.classList.contains('page-float-host') ||
+ el.classList.contains('page-float-carry') ||
el.classList.contains('page-repeat-header')
) {
continue
@@ -963,11 +1353,18 @@ export function alignTableGapFills(pm: HTMLElement, factor: number): void {
// ('-32.0px' would read back as '-32px' and defeat the dirty checks)
const px = (v: number) => `${Math.round(v * 10) / 10}px`
const pmRect = pm.getBoundingClientRect()
- const width = px(pmRect.width / factor)
for (const fill of Array.from(fills)) {
const cell = fill.parentElement
if (!cell) continue
- const left = px((pmRect.left - cell.getBoundingClientRect().left) / factor)
+ // differing-width documents: the fill covers the table's own page, not the paper
+ const gap = fill.closest('.page-gap')
+ const pageX = parseFloat(gap?.style.getPropertyValue('--gap-page-x') ?? '')
+ const pageW = parseFloat(gap?.style.getPropertyValue('--gap-page-w') ?? '')
+ const onPage = Number.isFinite(pageX) && Number.isFinite(pageW)
+ const left = px(
+ (pmRect.left - cell.getBoundingClientRect().left) / factor + (onPage ? pageX : 0),
+ )
+ const width = px(onPage ? pageW : pmRect.width / factor)
if (fill.style.left !== left) fill.style.left = left
if (fill.style.width !== width) fill.style.width = width
// inset:0 from the stylesheet would over-constrain against the explicit width
@@ -1005,6 +1402,17 @@ export function alignGapHfStrips(pm: HTMLElement, bodyLeftPx: number, factor: nu
if (Math.abs(delta) < 0.5) continue
el.style.left = `${((parseFloat(el.style.left) || 0) + delta).toFixed(1)}px`
}
+ // floating header images and footnote areas carry their paper x; an image's own
+ // rect includes the anchor translate, so re-anchor from the positioned host's origin
+ for (const el of Array.from(pm.querySelectorAll('.page-gap [data-paper-x]'))) {
+ const host = el.offsetParent
+ if (!host) continue
+ const left = (
+ parseFloat(el.dataset.paperX!) -
+ (host.getBoundingClientRect().left - pmLeft) / factor
+ ).toFixed(1)
+ if (el.style.left !== `${left}px`) el.style.left = `${left}px`
+ }
}
/** remove all float display shifts (leaving print view) */
diff --git a/apps/docs/src/renderer/editor/para-border-merge.ts b/apps/docs/src/renderer/editor/para-border-merge.ts
index bbebaf7..253e403 100644
--- a/apps/docs/src/renderer/editor/para-border-merge.ts
+++ b/apps/docs/src/renderer/editor/para-border-merge.ts
@@ -21,11 +21,14 @@ export interface ParaBorderAttrs {
function normLines(raw: string | null | undefined): string {
if (!raw) return ''
try {
- const parsed = JSON.parse(raw) as Record
+ const parsed = JSON.parse(raw) as Record<
+ string,
+ { color?: string; szPt?: number; spacePt?: number } | undefined
+ >
return (['t', 'b', 'l', 'r'] as const)
.map((side) => {
const l = parsed?.[side]
- return l ? `${side}:${l.color ?? ''}/${l.szPt ?? ''}` : ''
+ return l ? `${side}:${l.color ?? ''}/${l.szPt ?? ''}/${l.spacePt ?? ''}` : ''
})
.join('|')
} catch {
diff --git a/apps/docs/src/renderer/editor/para-frame.ts b/apps/docs/src/renderer/editor/para-frame.ts
new file mode 100644
index 0000000..a5e9497
--- /dev/null
+++ b/apps/docs/src/renderer/editor/para-frame.ts
@@ -0,0 +1,63 @@
+import type { ParaFrame, TextFlowDirection } from '@genoffice/docx-engine'
+
+/** CSS writing mode for a w:textDirection value (frames and section blocks share it) */
+export function textFlowCss(dir: TextFlowDirection | null | undefined): string[] {
+ if (dir === 'tbRl') return ['writing-mode:vertical-rl']
+ if (dir === 'tbRlV') return ['writing-mode:vertical-rl', 'text-orientation:sideways']
+ if (dir === 'btLr') return ['writing-mode:sideways-lr']
+ return []
+}
+
+const pt = (twips: number) => `${(twips / 20).toFixed(2)}pt`
+
+/**
+ * Inline styles + classes for a w:framePr paragraph. The frame is a fixed-width
+ * box floated at its horizontal position (page-anchored x is measured from the
+ * page edge, so the section's left margin is subtracted through the
+ * --doc-margin-left variable); body text wraps beside it for wrap=around/
+ * through/tight/auto. Vertical anchors other than "text" are approximated by the
+ * frame's flow position.
+ */
+export function paraFrameCss(
+ frame: ParaFrame,
+ dir: TextFlowDirection | null | undefined,
+): { classes: string[]; styles: string[] } {
+ const styles: string[] = ['box-sizing:border-box', `width:${pt(frame.wTwips)}`]
+ const flow = textFlowCss(dir)
+ if (frame.hTwips) {
+ // sideways text: the height is the line length, so it is fixed even for
+ // atLeast (an auto orthogonal box would take the page height instead)
+ const fixed = frame.hRule === 'exact' || flow.length > 0
+ styles.push(`${fixed ? 'height' : 'min-height'}:${pt(frame.hTwips)}`)
+ if (frame.hRule === 'exact') styles.push('overflow:hidden')
+ }
+ styles.push(...flow)
+ // a centered frame cannot float (auto margins do not center floats): it takes its own line
+ const wraps =
+ frame.wrap === 'around' ||
+ frame.wrap === 'through' ||
+ frame.wrap === 'tight' ||
+ frame.wrap === 'auto'
+ const floats = wraps && frame.xAlign !== 'center'
+ const side = frame.xAlign === 'right' || frame.xAlign === 'outside' ? 'right' : 'left'
+ const classes = ['doc-para-frame']
+ if (floats) {
+ classes.push('doc-para-frame-float')
+ styles.push(`float:${side}`)
+ if (frame.hSpaceTwips)
+ styles.push(`margin-${side === 'left' ? 'right' : 'left'}:${pt(frame.hSpaceTwips)}`)
+ }
+ if (frame.xAlign === 'center') {
+ styles.push('margin-left:auto', 'margin-right:auto')
+ } else if (!frame.xAlign) {
+ const x = pt(frame.xTwips)
+ styles.push(
+ frame.hAnchor === 'margin' || frame.hAnchor === 'text'
+ ? `margin-left:${x}`
+ : `margin-left:calc(${x} - var(--doc-margin-left, 0px))`,
+ )
+ }
+ if (frame.vAnchor === 'text' && frame.yTwips > 0) styles.push(`margin-top:${pt(frame.yTwips)}`)
+ if (frame.vSpaceTwips) styles.push(`margin-bottom:${pt(frame.vSpaceTwips)}`)
+ return { classes, styles }
+}
diff --git a/apps/docs/src/renderer/editor/paste-options.ts b/apps/docs/src/renderer/editor/paste-options.ts
new file mode 100644
index 0000000..3b2a68b
--- /dev/null
+++ b/apps/docs/src/renderer/editor/paste-options.ts
@@ -0,0 +1,240 @@
+/**
+ * Paste options for foreign (non-ProseMirror) HTML payloads: web pages, Word,
+ * mail clients. Plain Ctrl+V keeps the source formatting (Word's factory
+ * default); this module adds the two other Word paste modes and the plumbing
+ * the floating post-paste chip and the ribbon Paste button share:
+ *
+ * - 'source' keep source formatting (today's behavior, the default)
+ * - 'merge' merge formatting: keep emphasis (bold/italic/underline/links)
+ * and block structure, but text formats like typing at the
+ * insertion point (caret docTextStyle + paragraph format)
+ * - 'text' keep text only: route through the plain-text lane
+ *
+ * The mode of a paste is decided when the paste EVENT arrives — ProseMirror
+ * parses the clipboard before handlePaste runs, so transformPasted cannot ask
+ * the event (same lesson as the r181 foreign-paste flag, which this replaces).
+ */
+import type {
+ Fragment as PmFragment,
+ Mark,
+ Node as PmNode,
+ ResolvedPos,
+ Schema,
+} from '@tiptap/pm/model'
+import { Fragment } from '@tiptap/pm/model'
+import type { EditorState, SelectionBookmark, Transaction } from '@tiptap/pm/state'
+import type { Step } from '@tiptap/pm/transform'
+import { PARA_FORMAT_ATTRS } from './caret-marks'
+import { isForeignPasteHtml } from './paste-web-html'
+import { TRACK_IGNORE } from './revisions'
+
+export type PasteMode = 'source' | 'merge' | 'text'
+
+const MODE_KEY = 'aidocs.pasteFromOtherApps'
+
+/** The user's default mode for pasting from other programs (Word's
+ * "Pasting from other programs" option; factory default = keep source). */
+export function defaultPasteMode(): PasteMode {
+ const stored = localStorage.getItem(MODE_KEY)
+ return stored === 'merge' || stored === 'text' ? stored : 'source'
+}
+
+export function setDefaultPasteMode(mode: PasteMode): void {
+ localStorage.setItem(MODE_KEY, mode)
+}
+
+// ── per-paste handshake ────────────────────────────────────────────────────
+// beginForeignPaste (DOM paste handler / ribbon button / chip re-apply) →
+// transformPasted consumes the mode → the handlePaste lanes read the consumed
+// mode (they run after transformPasted and re-parse or re-route themselves).
+
+let pendingMode: PasteMode | null = null
+let overrideMode: PasteMode | null = null
+let consumedMode: PasteMode | null = null
+let rerouteToText = false
+
+/** Chip re-applies force their mode for exactly the next foreign paste. */
+export function forceNextPasteMode(mode: PasteMode): void {
+ overrideMode = mode
+}
+
+/** Called with the clipboard HTML when a paste event arrives. Returns true
+ * (and arms the per-paste mode) only for foreign fragments — our own
+ * clipboard HTML keeps its exact semantics, drops never arm anything. */
+export function beginForeignPaste(html: string): boolean {
+ consumedMode = null
+ rerouteToText = false
+ if (!html || !isForeignPasteHtml(html)) {
+ pendingMode = null
+ overrideMode = null
+ return false
+ }
+ pendingMode = overrideMode ?? defaultPasteMode()
+ overrideMode = null
+ return true
+}
+
+/** transformPasted: take the armed mode (once per paste). */
+export function consumeForeignPaste(): PasteMode | null {
+ const mode = pendingMode
+ pendingMode = null
+ consumedMode = mode
+ if (mode === 'text') rerouteToText = true
+ return mode
+}
+
+/** The mode transformPasted consumed for the paste handlePaste is handling —
+ * the wholesale empty-paragraph lane re-parses the HTML itself and must
+ * apply the same mode. */
+export function lastForeignPasteMode(): PasteMode | null {
+ return consumedMode
+}
+
+/** handlePaste: a text-mode foreign paste diverts to the plain-text lane. */
+export function takeTextReroute(): boolean {
+ const flag = rerouteToText
+ rerouteToText = false
+ return flag
+}
+
+// ── caret context ──────────────────────────────────────────────────────────
+
+/** The insertion point's docTextStyle mark — the exact style typing there
+ * would produce (storedMarks precedence handled by the caller). */
+export function caretStyleMark(marks: readonly Mark[], schema: Schema): Mark | null {
+ const type = schema.marks.docTextStyle
+ return type ? (marks.find((mark) => mark.type === type) ?? null) : null
+}
+
+/** The insertion paragraph's formatting attrs (r178 allowlist — identity and
+ * annotation attrs never clone), or null outside any paragraph. */
+export function caretParaFormat($pos: ResolvedPos, schema: Schema): Record | null {
+ const paragraph = schema.nodes.docParagraph
+ if (!paragraph) return null
+ for (let depth = $pos.depth; depth >= 1; depth--) {
+ const node = $pos.node(depth)
+ if (node.type === paragraph) {
+ const picked: Record = {}
+ for (const key of PARA_FORMAT_ATTRS) if (key in node.attrs) picked[key] = node.attrs[key]
+ return picked
+ }
+ }
+ return null
+}
+
+// ── merge formatting ───────────────────────────────────────────────────────
+
+/**
+ * Word's Merge Formatting: pasted text formats like typing at the insertion
+ * point — every run's docTextStyle is replaced by the caret's (or removed,
+ * so the text follows the document default exactly like the surrounding
+ * text), every paragraph takes the insertion paragraph's format attrs.
+ * Emphasis marks (bold/italic/underline/links…) and block structure stay;
+ * list/numbering attrs are outside the allowlist and survive. Table subtrees
+ * are left alone, matching the source-mode pushdown/fill.
+ */
+export function mergeFormattingFragment(
+ fragment: PmFragment,
+ schema: Schema,
+ style: Mark | null,
+ paraAttrs: Record | null,
+): PmFragment {
+ const styleType = schema.marks.docTextStyle
+ const paragraph = schema.nodes.docParagraph
+ const mapped: PmNode[] = []
+ fragment.forEach((node) => {
+ if (node.type.spec.tableRole === 'table') {
+ mapped.push(node)
+ return
+ }
+ if (node.isText) {
+ let marks = styleType ? node.marks.filter((mark) => mark.type !== styleType) : node.marks
+ if (style) marks = style.addToSet(marks)
+ mapped.push(node.mark(marks))
+ return
+ }
+ const content = mergeFormattingFragment(node.content, schema, style, paraAttrs)
+ if (node.type === paragraph && paraAttrs) {
+ mapped.push(node.type.create({ ...node.attrs, ...paraAttrs }, content, node.marks))
+ } else {
+ mapped.push(node.copy(content))
+ }
+ })
+ return Fragment.from(mapped)
+}
+
+// ── post-paste chip payload ────────────────────────────────────────────────
+
+export type PastePayload = { html: string; text: string; mode: PasteMode }
+
+let chipPayload: PastePayload | null = null
+
+/** Stashed by the paste entry points; the App transaction listener takes it
+ * when the paste transaction lands and shows the chip. Payloads without
+ * prose (image-only fragments) never stash — there is nothing to re-format. */
+export function stashPastePayload(payload: PastePayload | null): void {
+ if (payload) {
+ try {
+ const body = new window.DOMParser().parseFromString(payload.html, 'text/html').body
+ if (!(body.textContent ?? '').trim()) payload = null
+ } catch {
+ payload = null
+ }
+ }
+ chipPayload = payload
+}
+
+export function takePastePayload(): PastePayload | null {
+ const payload = chipPayload
+ chipPayload = null
+ return payload
+}
+
+// ── chip re-apply ──────────────────────────────────────────────────────────
+// A mode change must see the insertion point the ORIGINAL paste saw — caret
+// marks, paragraph format, the empty-paragraph wholesale lane — not the
+// pasted content. Re-pasting over the pasted range reads the source
+// formatting back (merge/text no-op) and never qualifies for the wholesale
+// lane (a heading re-applied onto its own text gets demoted). So a re-apply
+// undoes the paste, puts the caret back exactly as it was, and pastes again.
+
+export type PasteRestore = {
+ /** inverse of the paste's steps, in application order */
+ steps: Step[]
+ selection: SelectionBookmark
+ storedMarks: readonly Mark[] | null
+}
+
+/** Snapshot taken when the paste transaction lands: `before` is the state
+ * the paste started from, `transactions` the paste plus its appended
+ * transactions. Null when the two disagree (the paste did not start from
+ * the state we saw). */
+export function capturePasteRestore(
+ before: EditorState,
+ transactions: readonly Transaction[],
+): PasteRestore | null {
+ if (transactions[0]?.before !== before.doc) return null
+ const steps: Step[] = []
+ for (const tr of transactions) {
+ tr.steps.forEach((step, index) => steps.push(step.invert(tr.docs[index]!)))
+ }
+ steps.reverse()
+ return { steps, selection: before.selection.getBookmark(), storedMarks: before.storedMarks }
+}
+
+/** Undo the paste and restore the insertion point (selection and pending
+ * marks), or null when the document no longer accepts the inverse steps. */
+export function revertPaste(state: EditorState, restore: PasteRestore): Transaction | null {
+ const tr = state.tr
+ try {
+ for (const step of restore.steps) if (tr.maybeStep(step).failed) return null
+ // Taking back our own paste is not an authored deletion; the re-paste that
+ // follows in the same tick joins this step in one undo event.
+ return tr
+ .setSelection(restore.selection.resolve(tr.doc))
+ .setStoredMarks(restore.storedMarks)
+ .setMeta(TRACK_IGNORE, true)
+ } catch {
+ return null
+ }
+}
diff --git a/apps/docs/src/renderer/editor/paste-text.ts b/apps/docs/src/renderer/editor/paste-text.ts
index 74f399a..2e4c12e 100644
--- a/apps/docs/src/renderer/editor/paste-text.ts
+++ b/apps/docs/src/renderer/editor/paste-text.ts
@@ -9,16 +9,22 @@
import type { ResolvedPos } from '@tiptap/pm/model'
import { Fragment, Slice } from '@tiptap/pm/model'
import type { EditorView } from '@tiptap/pm/view'
+import { PARA_FORMAT_ATTRS } from './caret-marks'
/**
- * The text of a paste whose entire payload is one single-cell table carrying
- * no formatting of its own, or null for everything else. Companion to the
- * single-cell unwrap: that paste is semantically text, so
- * it must take the insertion point's formatting like typing — the HTML parse
- * lane keeps no marks for a bare cell and fell back to the theme font (alpha
- * ledger r176: a Sheets cell pasted into Docs as the theme font). A cell with
- * formatting elements of its own (a rich-text cell) keeps the HTML lane; a
- * style attribute on the td itself is not that — the unwrap never kept it.
+ * The text of a paste whose entire payload is one single-COLUMN table of
+ * cells carrying no formatting of their own, or null for everything else.
+ * Companion to the single-cell unwrap: such a paste is semantically lines of
+ * text, so it must take the insertion point's formatting like typing — the
+ * HTML parse lane keeps no marks for bare cells and built an invisible
+ * borderless table instead (fixed layout, source row heights, bottom
+ * alignment), which reads as gapped, indented stray lines (r176 follow-up:
+ * a column of Sheets cells pasted into Docs; the 1x1 case was r176 itself).
+ * The result equals what the plain-text clipboard flavor would paste, so
+ * Ctrl+V and paste-as-text agree for unformatted cells. A cell with
+ * formatting elements of its own (a rich-text cell), a multi-column table,
+ * or prose/media around the table keeps the HTML lane; a style attribute on
+ * the td itself is not that — the unwrap never kept it.
*/
export function singleCellPasteText(html: string): string | null {
if (!/ | null = null
+ for (let depth = $context.depth; depth >= 1; depth--) {
+ const node = $context.node(depth)
+ if (node.type === paragraph) {
+ const picked: Record = {}
+ for (const key of PARA_FORMAT_ATTRS) if (key in node.attrs) picked[key] = node.attrs[key]
+ attrs = picked
+ break
+ }
+ }
// the default parser's line handling: consecutive breaks collapse to one split
const blocks = text
.split(/(?:\r\n?|\n)+/)
- .map((line) => paragraph.create(null, line ? schema.text(line, marks) : null))
+ .map((line) => paragraph.create(attrs, line ? schema.text(line, marks) : null))
// open ends so single-line text merges inline into the destination paragraph
return new Slice(Fragment.from(blocks), 1, 1)
}
diff --git a/apps/docs/src/renderer/editor/paste-web-html.ts b/apps/docs/src/renderer/editor/paste-web-html.ts
new file mode 100644
index 0000000..b5e082c
--- /dev/null
+++ b/apps/docs/src/renderer/editor/paste-web-html.ts
@@ -0,0 +1,159 @@
+/**
+ * Web-HTML paste font handling (r181): text copied from a website pasted into
+ * a document landed in the theme font instead of the text around it.
+ *
+ * Two gaps compound:
+ * 1. Browsers put the copied site's styles on BLOCK elements when whole
+ * paragraphs are selected (`text
`), but the
+ * docTextStyle mark only parses `span` styles — a whole-paragraph web
+ * copy lost its font/size/color entirely.
+ * 2. Sites styled with only generic families (`font-family: sans-serif` —
+ * e.g. Wikipedia) produce no concrete face after the family-chain filter,
+ * so the pasted run has no font at all and renders in the document
+ * default, visibly different from the surrounding text.
+ *
+ * The pushdown fixes 1 at the HTML level; the fill fixes 2 at the slice
+ * level by giving font-less pasted text the insertion point's font slots —
+ * the same "formats like typing" rule the plain-text lane already follows.
+ * Both apply only to FOREIGN fragments: our own clipboard HTML carries
+ * ProseMirror's data-pm-slice wrapper and must keep its exact semantics.
+ */
+import type { Fragment as PmFragment, Mark, MarkType, Schema } from '@tiptap/pm/model'
+import { Fragment } from '@tiptap/pm/model'
+
+/** Our own copies (and any other ProseMirror editor's) carry a data-pm-slice
+ * wrapper; explicit run payloads carry data-doc-style. Everything else is a
+ * foreign fragment: browsers, Word, spreadsheets. */
+export function isForeignPasteHtml(html: string): boolean {
+ return !html.includes('data-pm-slice') && !html.includes('data-doc-style')
+}
+
+const PUSHDOWN_PROPS = ['font-family', 'font-size', 'color'] as const
+
+/** Table subtrees are left alone: spreadsheet payloads route through the
+ * cell-unwrap lanes, and web-table cell styling keeps today's behavior. */
+const TABLE_SUBTREE = /^(TABLE|THEAD|TBODY|TFOOT|TR|TD|TH)$/
+
+/**
+ * Copy block-level inline font/size/color declarations down onto the spans
+ * the mark parser reads. Every text node outside table subtrees gets its
+ * nearest ancestor declaration per property, either on its existing direct
+ * span parent (without overriding what that span declares itself) or via a
+ * new wrapping span. Returns the input unchanged on any parse failure.
+ */
+export function pushDownWebInlineStyles(html: string): string {
+ try {
+ const doc = new window.DOMParser().parseFromString(html, 'text/html')
+ const body = doc.body
+ const textNodes: Text[] = []
+ const collect = (el: Element): void => {
+ for (const child of [...el.childNodes]) {
+ if (child.nodeType === 3 /* TEXT_NODE */) {
+ if ((child.textContent ?? '').trim()) textNodes.push(child as Text)
+ } else if (child.nodeType === 1 /* ELEMENT_NODE */) {
+ const tag = (child as Element).tagName
+ if (TABLE_SUBTREE.test(tag) || tag === 'SCRIPT' || tag === 'STYLE') continue
+ collect(child as Element)
+ }
+ }
+ }
+ collect(body)
+ if (textNodes.length === 0) return html
+
+ // nearest inline declaration per property, from the text node's element
+ // chain up to (and including) body — blocks and spans alike
+ const effective = (node: Text, prop: string): string => {
+ for (let el = node.parentElement; el; el = el.parentElement) {
+ const v = el.style.getPropertyValue(prop)
+ if (v) return v
+ if (el === body) break
+ }
+ return ''
+ }
+
+ let changed = false
+ for (const node of textNodes) {
+ const parent = node.parentElement
+ if (!parent) continue
+ const wanted: Array<[string, string]> = []
+ for (const prop of PUSHDOWN_PROPS) {
+ const v = effective(node, prop)
+ if (v) wanted.push([prop, v])
+ }
+ if (wanted.length === 0) continue
+ if (parent.tagName === 'SPAN') {
+ // `wanted` skipped what the span declares itself, so this only adds
+ // the inherited values; nested or shared spans included, since every
+ // text child inherits the same chain
+ for (const [prop, v] of wanted) {
+ if (!parent.style.getPropertyValue(prop)) {
+ parent.style.setProperty(prop, v)
+ changed = true
+ }
+ }
+ } else {
+ const span = doc.createElement('span')
+ for (const [prop, v] of wanted) span.style.setProperty(prop, v)
+ parent.insertBefore(span, node)
+ span.appendChild(node)
+ changed = true
+ }
+ }
+ return changed ? body.innerHTML : html
+ } catch {
+ return html
+ }
+}
+
+const FONT_SLOT_ATTRS = ['font', 'fontAscii', 'csFont', 'eaSlotEmpty'] as const
+
+/** The docTextStyle font-slot attrs of the insertion point, or null when the
+ * caret text carries no explicit font (pasting there stays font-less and
+ * follows the document default exactly like the surrounding text). */
+export function caretFontSlots(
+ marks: readonly Mark[],
+ markType: MarkType,
+): Record | null {
+ const style = marks.find((m) => m.type === markType)
+ if (!style) return null
+ const slots: Record = {}
+ for (const attr of FONT_SLOT_ATTRS) {
+ if (style.attrs[attr] != null) slots[attr] = style.attrs[attr]
+ }
+ return 'font' in slots || 'fontAscii' in slots || 'csFont' in slots ? slots : null
+}
+
+/**
+ * Give every pasted text run that ends up with no concrete font the
+ * insertion point's font slots (size/color/etc. keep the source values —
+ * only the unresolved font falls back, like Word mapping an unknown face).
+ * Tables are skipped, matching the pushdown: cell text keeps inheriting.
+ */
+export function fillMissingRunFonts(
+ fragment: PmFragment,
+ slots: Record,
+ schema: Schema,
+): PmFragment {
+ const markType = schema.marks.docTextStyle
+ if (!markType) return fragment
+ const mapped: import('@tiptap/pm/model').Node[] = []
+ fragment.forEach((node) => {
+ if (node.type.spec.tableRole === 'table') {
+ mapped.push(node)
+ return
+ }
+ if (node.isText) {
+ const style = node.marks.find((m) => m.type === markType)
+ if (style && (style.attrs.font || style.attrs.fontAscii || style.attrs.csFont)) {
+ mapped.push(node)
+ return
+ }
+ const attrs = style ? { ...style.attrs, ...slots } : slots
+ const mark = markType.create(attrs)
+ mapped.push(node.mark(mark.addToSet(node.marks)))
+ return
+ }
+ mapped.push(node.copy(fillMissingRunFonts(node.content, slots, schema)))
+ })
+ return Fragment.from(mapped)
+}
diff --git a/apps/docs/src/renderer/editor/protected-render.ts b/apps/docs/src/renderer/editor/protected-render.ts
index dbf3a82..11a8dee 100644
--- a/apps/docs/src/renderer/editor/protected-render.ts
+++ b/apps/docs/src/renderer/editor/protected-render.ts
@@ -26,13 +26,23 @@ import {
textHasComplexScript,
textHasHangul,
WORD_AUTO_SPACING_PT,
+ SPACE_ONLY_RE,
} from '../line-metrics'
import { custGeomBackgroundCss, shapeBackgroundCss, shapeTextInsetsPx } from './shape-svg'
import { pictureTransformFns, quarterTurnInsetPx, quarterTurnMarginCss } from './image-rotation'
-import { DK_SIDE, dkBackground, dkBorder, dkColor } from './dark-page'
+import { DK_SIDE, dkBackground, dkBorder, dkColor, type DkBorderSide } from './dark-page'
+import { hfCellGeometry, hfCellParaStyle, hfRowStyle } from './hf-dom'
import { INLINE_RULE_CLASS, inlineRuleDecls } from './inline-rule'
import { fillInk } from './shading-ink'
import { textColorDecls } from './text-color'
+import { textOutlineDecl } from './text-outline'
+import {
+ doubleStrikeDecl,
+ glowDecl,
+ paperColorEffect,
+ positionDecl,
+ textEffectDecls,
+} from './text-effects'
import { t } from '../i18n/locale'
import {
lumHex,
@@ -43,6 +53,7 @@ import {
type TableModel,
type TableParagraph,
type TextboxDisplay,
+ type TextboxParaDisplay,
} from '@genoffice/docx-engine'
/**
@@ -76,6 +87,16 @@ import { cellClipTwips, inferredBidi } from './convert'
const jumpHint = () =>
navigator.platform.toLowerCase().includes('mac') ? t('editorJumpHintMac') : t('editorJumpHintWin')
+/** w:leader glyphs Word repeats at their natural advance (heavy = bold underscores) */
+const TOC_LEADER_GLYPH: Record, string> = {
+ none: '',
+ dot: '.',
+ hyphen: '-',
+ underscore: '_',
+ heavy: '_',
+ middleDot: '\u00b7',
+}
+
/** Rendering of a field result; safe visible text becomes editable on double-click. */
export function renderFieldSpec(field: FieldDisplay): DomSpec | null {
if (field.kind === 'tocLine') {
@@ -85,6 +106,8 @@ export function renderFieldSpec(field: FieldDisplay): DomSpec | null {
title: jumpHint(),
}
if (field.anchor) attrs['data-toc-anchor'] = field.anchor
+ const titleAttrs: Record = { class: 'doc-toc-title', contenteditable: 'false' }
+ if (field.runStyleId) titleAttrs['data-style'] = field.runStyleId
// direct pPr/run metrics of the entry paragraph beat the inherited body size
const tocStyles: string[] = []
if (field.szHalfPoints) tocStyles.push(`font-size:${field.szHalfPoints / 2}pt`)
@@ -115,10 +138,17 @@ export function renderFieldSpec(field: FieldDisplay): DomSpec | null {
'div',
attrs,
...num,
- ['span', { class: 'doc-toc-title', contenteditable: 'false' }, field.left || '\u00a0'],
- // real dot glyphs (clipped to the free width), not a border decoration:
+ ['span', titleAttrs, field.left || '\u00a0'],
+ // real leader 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-dots${field.leader === 'heavy' ? ' doc-toc-leader-heavy' : ''}`,
+ contenteditable: 'false',
+ },
+ TOC_LEADER_GLYPH[field.leader ?? 'dot'].repeat(220),
+ ],
['span', { class: 'doc-toc-page', contenteditable: 'false' }, field.right ?? ''],
]
}
@@ -156,7 +186,22 @@ export function renderFieldSpec(field: FieldDisplay): DomSpec | null {
}
// formatted result runs (italic citations, a drop-cap letter before body
// text); the wrapper keeps the dominant size for the line strut
- if (field.runs) return ['div', attrs, ...field.runs.flatMap((r) => runSpanSpecs(r))]
+ // EQ layouts: the MathML host is empty in the spec; buildProtectedDom fills it
+ if (field.runs)
+ return [
+ 'div',
+ attrs,
+ ...field.runs.flatMap((r) => {
+ if (!r.math) return runSpanSpecs(r)
+ const [, style] = textSpanSpec({ ...r, link: undefined }) as [string, object]
+ const attrs = {
+ ...style,
+ class: 'doc-inline-math doc-field-math',
+ 'data-omml': r.math.omml,
+ }
+ return [['span', attrs, r.text] as DomSpec]
+ }),
+ ]
return ['div', attrs, field.left]
}
return null
@@ -218,16 +263,30 @@ function pointColor(chart: ChartDisplay, s: number, i: number): string {
* editable on double-click, everything else stays protected.
*/
export function renderChartSpec(chart: ChartDisplay): DomSpec {
- const children: DomSpec[] = []
+ const frame: DomSpec[] = []
if (chart.title !== undefined) {
- children.push([
+ frame.push([
'div',
{ class: 'doc-chart-title', contenteditable: 'false' },
chart.title || '\u00a0',
])
}
// SVG preview drawn imperatively after mount (renderSpec has no SVG namespace)
- children.push(['div', { class: 'doc-chart-canvas' }])
+ frame.push(['div', { class: 'doc-chart-canvas' }])
+ // the chart-area border encloses title + plot; an inset shadow keeps the
+ // wp:extent box size, which a CSS border would grow
+ const children: DomSpec[] = [
+ [
+ 'div',
+ {
+ class: 'doc-chart-frame',
+ style:
+ `width:${chartPlotWidth(chart)}px` +
+ (chart.frameLine ? `;box-shadow:inset 0 0 0 1px #${chart.frameLine}` : ''),
+ },
+ ...frame,
+ ],
+ ]
const colCount = Math.max(chart.categories.length, ...chart.series.map((s) => s.values.length))
const headCells: DomSpec[] = [['th', { class: 'doc-chart-corner' }, '\u00a0']]
@@ -292,6 +351,70 @@ interface ChartGeom {
/** side-legend gutters; pies center in the remaining box (axes use left/right) */
sideLeft?: number
sideRight?: number
+ /** a data table under the plot carries the category texts */
+ noCatLabels?: boolean
+}
+
+export function chartPlotWidth(chart: ChartDisplay): number {
+ return Math.min(chart.widthPx ?? 560, CHART_MAX_WIDTH_PX)
+}
+
+/** c:marker/c:size default (5pt) in px */
+const MARKER_PX = (5 * 96) / 72
+
+/** Office's automatic marker symbol sequence by series index */
+const MARKER_SHAPES = ['diamond', 'square', 'triangle', 'x', 'star', 'circle', 'plus', 'dash']
+
+function drawMarker(svg: Element, x: number, y: number, s: number, color: string): void {
+ const h = MARKER_PX / 2
+ const shape = MARKER_SHAPES[s % MARKER_SHAPES.length]
+ const line = (x1: number, y1: number, x2: number, y2: number) =>
+ svgEl(svg, 'line', {
+ x1: String(x1),
+ y1: String(y1),
+ x2: String(x2),
+ y2: String(y2),
+ stroke: color,
+ 'stroke-width': '1.5',
+ })
+ if (shape === 'square') {
+ svgEl(svg, 'rect', {
+ x: String(x - h),
+ y: String(y - h),
+ width: String(MARKER_PX),
+ height: String(MARKER_PX),
+ fill: color,
+ })
+ } else if (shape === 'diamond') {
+ svgEl(svg, 'polygon', {
+ points: `${x},${y - h} ${x + h},${y} ${x},${y + h} ${x - h},${y}`,
+ fill: color,
+ })
+ } else if (shape === 'triangle') {
+ svgEl(svg, 'polygon', {
+ points: `${x},${y - h} ${x + h},${y + h} ${x - h},${y + h}`,
+ fill: color,
+ })
+ } else if (shape === 'circle') {
+ svgEl(svg, 'circle', { cx: String(x), cy: String(y), r: String(h), fill: color })
+ } else if (shape === 'dash') {
+ svgEl(svg, 'rect', {
+ x: String(x - h),
+ y: String(y - 1.5),
+ width: String(MARKER_PX),
+ height: '3',
+ fill: color,
+ })
+ } else {
+ if (shape !== 'plus') {
+ line(x - h, y - h, x + h, y + h)
+ line(x - h, y + h, x + h, y - h)
+ }
+ if (shape !== 'x') {
+ line(x - h, y, x + h, y)
+ line(x, y - h, x, y + h)
+ }
+ }
}
/** widest a chart draws at; the resize handle clamps to this too so mouseup never snaps back */
@@ -310,13 +433,14 @@ export function drawChartSvg(dom: HTMLElement, chart: ChartDisplay | null): void
// legend itself, like Word/LibreOffice output. Pie legends list the
// categories (one colored slice each), not the series.
const isPie = chart.kind === 'pie'
+ const isRadar = chart.kind === 'radar'
const legendNames = isPie
? chart.categories
: chart.series.map((s, i) => s.name ?? t('editorChartSeries', { num: i + 1 }))
const legendColor = (i: number) => (isPie ? pointColor(chart, 0, i) : seriesColor(chart, i))
- const showLegend = isPie
- ? legendNames.length > 0
- : chart.series.length > 1 || chart.series.some((s) => s.name)
+ const showLegend =
+ !chart.noLegend &&
+ (isPie ? legendNames.length > 0 : chart.series.length > 1 || chart.series.some((s) => s.name))
// the title row renders above the SVG but Word draws the title inside the
// drawing extent; shrink the plot so title + plot together fill heightPx,
// or pagination gains ~22px per titled chart and drifts
@@ -326,15 +450,29 @@ export function drawChartSvg(dom: HTMLElement, chart: ChartDisplay | null): void
const catLabelPx = (s: string) =>
[...s].reduce((w, ch) => w + (isCjk(ch.codePointAt(0) ?? 0) ? 10 : 7), 0)
const maxCatPx = Math.max(0, ...chart.categories.map(catLabelPx))
- const width = Math.min(chart.widthPx ?? 560, CHART_MAX_WIDTH_PX)
+ const width = chartPlotWidth(chart)
// l/r/tr legends stack vertically in a side gutter, like Word; other
// positions (and legacy models without legendPos) keep the bottom row
const sideLegend =
showLegend && (chart.legendPos === 'l' || chart.legendPos === 'r' || chart.legendPos === 'tr')
+ const topLegend = showLegend && chart.legendPos === 't'
const legendW = sideLegend
? Math.min(Math.round(width * 0.35), 20 + Math.max(0, ...legendNames.map(catLabelPx)))
: 0
const legendLeft = sideLegend && chart.legendPos === 'l'
+ const cartesian = !isPie && !isRadar
+ const xTitle = cartesian && !chart.xAxis?.deleted ? chart.xAxis?.title : undefined
+ const yTitle = cartesian && !chart.yAxis?.deleted ? chart.yAxis?.title : undefined
+ const tableRowH = 14
+ const dataTable =
+ chart.dataTable &&
+ cartesian &&
+ chart.kind !== 'scatter' &&
+ chart.kind !== 'bubble' &&
+ !(chart.kind === 'bar' && chart.horizontal)
+ ? chart.dataTable
+ : undefined
+ const tableH = dataTable ? (chart.series.length + 1) * tableRowH : 0
const geom: ChartGeom = {
width,
height: (chart.heightPx ?? 240) - titleRowPx,
@@ -342,11 +480,16 @@ export function drawChartSvg(dom: HTMLElement, chart: ChartDisplay | null): void
// charts, and a gutter wider than the plot would flip plotW negative
left:
(chart.kind === 'bar' && chart.horizontal ? Math.min(140, width * 0.4, 16 + maxCatPx) : 46) +
- (legendLeft ? legendW : 0),
+ (legendLeft ? legendW : 0) +
+ (yTitle ? 14 : 0),
right: 12 + (sideLegend && !legendLeft ? legendW : 0),
- top: 12,
- bottom: 26 + (showLegend && !sideLegend ? 18 : 0),
+ top: 12 + (topLegend ? 18 : 0),
+ bottom:
+ (dataTable ? 4 + tableH : 26) +
+ (showLegend && !sideLegend && !topLegend ? 18 : 0) +
+ (xTitle ? 14 : 0),
...(sideLegend ? (legendLeft ? { sideLeft: legendW } : { sideRight: legendW }) : {}),
+ ...(dataTable ? { noCatLabels: true } : {}),
}
const svg = document.createElementNS(SVG_NS, 'svg')
svg.setAttribute('viewBox', `0 0 ${geom.width} ${geom.height}`)
@@ -354,11 +497,73 @@ export function drawChartSvg(dom: HTMLElement, chart: ChartDisplay | null): void
svg.style.width = `${geom.width}px`
svg.style.height = `${geom.height}px`
- if (chart.kind === 'pie') drawPie(svg, chart, geom)
+ if (isPie) drawPie(svg, chart, geom)
+ else if (isRadar) drawRadar(svg, chart, geom)
else if (chart.kind === 'scatter' || chart.kind === 'bubble') drawScatter(svg, chart, geom)
else if (chart.kind === 'bar' && chart.horizontal) drawAxesHorizontal(svg, chart, geom)
else drawAxes(svg, chart, geom)
+ if (dataTable) drawDataTable(svg, chart, geom, dataTable, tableRowH)
+ const plotMidY = geom.top + (geom.height - geom.top - geom.bottom) / 2
+ if (yTitle) {
+ const x = (legendLeft ? legendW : 0) + 10
+ svgEl(
+ svg,
+ 'text',
+ {
+ x: String(x),
+ y: String(plotMidY),
+ class: 'doc-chart-axis-title',
+ 'text-anchor': 'middle',
+ transform: `rotate(-90 ${x} ${plotMidY})`,
+ },
+ yTitle,
+ )
+ }
+ if (xTitle) {
+ const legendRow = showLegend && !sideLegend && !topLegend ? 18 : 0
+ svgEl(
+ svg,
+ 'text',
+ {
+ x: String(geom.left + (geom.width - geom.left - geom.right) / 2),
+ y: String(geom.height - legendRow - 4),
+ class: 'doc-chart-axis-title',
+ 'text-anchor': 'middle',
+ },
+ xTitle,
+ )
+ }
+
+ // line-like series get a line key (with the marker); fills get a swatch
+ const lineKey =
+ chart.kind === 'line' ||
+ (isRadar && chart.radarStyle !== 'filled') ||
+ (chart.kind === 'scatter' && chart.series.some((s) => s.line))
+ const drawKey = (x: number, y: number, i: number) => {
+ if (lineKey) {
+ svgEl(svg, 'line', {
+ x1: String(x - 3),
+ y1: String(y + 4),
+ x2: String(x + 11),
+ y2: String(y + 4),
+ stroke: legendColor(i),
+ 'stroke-width': '2',
+ })
+ if (chart.markers) drawMarker(svg, x + 4, y + 4, i, legendColor(i))
+ } else {
+ svgEl(svg, 'rect', {
+ x: String(x),
+ y: String(y),
+ width: '8',
+ height: '8',
+ fill: legendColor(i),
+ })
+ }
+ }
+ // stacked charts list the top series first in a side legend, like Word
+ const order = legendNames.map((_, i) => i)
+ if (sideLegend && chart.grouping && !(chart.kind === 'bar' && chart.horizontal)) order.reverse()
if (sideLegend) {
const entryH = 16
const x0 = legendLeft ? 4 : geom.width - legendW + 4
@@ -366,39 +571,28 @@ export function drawChartSvg(dom: HTMLElement, chart: ChartDisplay | null): void
chart.legendPos === 'tr'
? geom.top
: Math.max(geom.top, (geom.height - legendNames.length * entryH) / 2)
- legendNames.forEach((name, i) => {
- const y = y0 + entryH * i
- svgEl(svg, 'rect', {
- x: String(x0),
- y: String(y),
- width: '8',
- height: '8',
- fill: legendColor(i),
- })
+ order.forEach((i, row) => {
+ const y = y0 + entryH * row
+ drawKey(x0, y, i)
svgEl(
svg,
'text',
{ x: String(x0 + 12), y: String(y + 8), class: 'doc-chart-axis-label' },
- name,
+ legendNames[i],
)
})
} else if (showLegend) {
const slot = geom.width / legendNames.length
+ const rowY = topLegend ? 4 : geom.height - 15
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: legendColor(i),
- })
+ drawKey(cx - Math.min(name.length * 3.2, slot / 2 - 14) - 12, rowY, i)
svgEl(
svg,
'text',
{
x: String(cx),
- y: String(geom.height - 7),
+ y: String(rowY + 8),
class: 'doc-chart-axis-label',
'text-anchor': 'middle',
},
@@ -410,6 +604,109 @@ export function drawChartSvg(dom: HTMLElement, chart: ChartDisplay | null): void
canvas.replaceChildren(svg)
}
+/** axis lines: value axis at the plot edge, category axis on the zero line */
+function drawAxisLines(
+ svg: SVGElement,
+ chart: ChartDisplay,
+ geom: ChartGeom,
+ zeroY: number,
+ zeroX: number,
+): void {
+ const xLine = chart.xAxis && !chart.xAxis.deleted ? chart.xAxis.line : undefined
+ const yLine = chart.yAxis && !chart.yAxis.deleted ? chart.yAxis.line : undefined
+ if (xLine) {
+ svgEl(svg, 'line', {
+ x1: String(geom.left),
+ y1: String(zeroY),
+ x2: String(geom.width - geom.right),
+ y2: String(zeroY),
+ stroke: `#${xLine}`,
+ 'stroke-width': '1',
+ })
+ }
+ if (yLine) {
+ svgEl(svg, 'line', {
+ x1: String(zeroX),
+ y1: String(geom.top),
+ x2: String(zeroX),
+ y2: String(geom.height - geom.bottom),
+ stroke: `#${yLine}`,
+ 'stroke-width': '1',
+ })
+ }
+}
+
+/** c:dTable under the category axis: category header row, one row per series, keys in the row header */
+function drawDataTable(
+ svg: SVGElement,
+ chart: ChartDisplay,
+ geom: ChartGeom,
+ table: NonNullable,
+ rowH: number,
+): void {
+ const cols = Math.max(chart.categories.length, ...chart.series.map((s) => s.values.length), 1)
+ const x0 = 4
+ const x1 = geom.left
+ const xEnd = geom.width - geom.right
+ const slotW = (xEnd - x1) / cols
+ const yTop = geom.height - geom.bottom
+ const yEnd = yTop + rowH * (chart.series.length + 1)
+ const stroke = `#${table.line ?? '000000'}`
+ const line = (xa: number, ya: number, xb: number, yb: number) =>
+ svgEl(svg, 'line', {
+ x1: String(xa),
+ y1: String(ya),
+ x2: String(xb),
+ y2: String(yb),
+ stroke,
+ 'stroke-width': '1',
+ })
+ if (table.outline) {
+ // the empty corner cell above the row header has no border, like Word
+ line(x1, yTop, xEnd, yTop)
+ line(x0, yTop + rowH, x0, yEnd)
+ line(x0, yEnd, xEnd, yEnd)
+ line(xEnd, yTop, xEnd, yEnd)
+ }
+ if (table.horz) {
+ for (let r = 1; r <= chart.series.length; r++) line(x0, yTop + rowH * r, xEnd, yTop + rowH * r)
+ }
+ if (table.vert) {
+ for (let c = 0; c < cols; c++) line(x1 + slotW * c, yTop, x1 + slotW * c, yEnd)
+ }
+ const cell = (x: number, y: number, text: string, anchor: string) =>
+ svgEl(
+ svg,
+ 'text',
+ {
+ x: String(x),
+ y: String(y + rowH - 4),
+ class: 'doc-chart-axis-label',
+ 'text-anchor': anchor,
+ },
+ text,
+ )
+ chart.categories.forEach((cat, c) => {
+ if (c < cols) cell(x1 + slotW * c + slotW / 2, yTop, cat, 'middle')
+ })
+ chart.series.forEach((ser, s) => {
+ const y = yTop + rowH * (s + 1)
+ if (table.keys) {
+ svgEl(svg, 'rect', {
+ x: String(x0 + 3),
+ y: String(y + 3),
+ width: '8',
+ height: '8',
+ fill: seriesColor(chart, s),
+ })
+ }
+ cell(x0 + (table.keys ? 14 : 4), y, ser.name ?? t('editorChartSeries', { num: s + 1 }), 'start')
+ ser.values.forEach((v, c) => {
+ if (v !== null && c < cols) cell(x1 + slotW * c + slotW / 2, y, String(v), 'middle')
+ })
+ })
+}
+
function svgEl(
parent: Element,
tag: string,
@@ -445,7 +742,9 @@ function stackSums(
/** bar / line / area charts share the same axes and scale */
function drawAxes(svg: SVGElement, chart: ChartDisplay, geom: ChartGeom): void {
const cols = Math.max(chart.categories.length, ...chart.series.map((s) => s.values.length), 1)
- const stacked = (chart.kind === 'bar' || chart.kind === 'area') && chart.grouping !== undefined
+ const stacked =
+ (chart.kind === 'bar' || chart.kind === 'area' || chart.kind === 'line') &&
+ chart.grouping !== undefined
const pct = stacked && chart.grouping === 'percentStacked'
const sums = stacked ? stackSums(chart, cols) : null
// percentStacked: each value becomes its share of the category's absolute total
@@ -481,6 +780,7 @@ function drawAxes(svg: SVGElement, chart: ChartDisplay, geom: ChartGeom): void {
y2: String(y),
class: 'doc-chart-grid',
})
+ if (chart.yAxis?.deleted) continue
svgEl(
svg,
'text',
@@ -493,10 +793,11 @@ function drawAxes(svg: SVGElement, chart: ChartDisplay, geom: ChartGeom): void {
formatAxisValue(v) + (pct ? '%' : ''),
)
}
+ drawAxisLines(svg, chart, geom, yOf(0), geom.left)
// category labels
chart.categories.forEach((cat, c) => {
- if (c >= cols) return
+ if (c >= cols || geom.noCatLabels || chart.xAxis?.deleted) return
svgEl(
svg,
'text',
@@ -576,12 +877,17 @@ function drawAxes(svg: SVGElement, chart: ChartDisplay, geom: ChartGeom): void {
tops.forEach((v, c) => (bases[c] = v))
})
} else {
- // line / area / other: one polyline per series through slot centers
+ // line / area / other: one polyline per series through slot centers;
+ // stacked lines climb on the running total of the series below
+ const bases = new Array(cols).fill(0)
chart.series.forEach((ser, s) => {
const points = ser.values
- .map((value, c) =>
- value === null ? null : `${geom.left + slotW * c + slotW / 2},${yOf(value)}`,
- )
+ .map((value, c) => {
+ if (value === null || c >= cols) return null
+ const v = stacked ? bases[c] + norm(value, c) : value
+ if (stacked) bases[c] = v
+ return `${geom.left + slotW * c + slotW / 2},${yOf(v)}`
+ })
.filter((p): p is string => p !== null)
if (points.length === 0) return
if (chart.kind === 'area' && points.length > 1) {
@@ -603,13 +909,137 @@ function drawAxes(svg: SVGElement, chart: ChartDisplay, geom: ChartGeom): void {
if (chart.markers) {
for (const p of points) {
const [x, y] = p.split(',')
- svgEl(svg, 'circle', { cx: x, cy: y, r: '2.5', fill: seriesColor(chart, s) })
+ drawMarker(svg, Number(x), Number(y), s, seriesColor(chart, s))
}
}
})
}
}
+/** radar: one spoke per category, polygon rings at the value steps, series as closed outlines (filled: opaque) */
+function drawRadar(svg: SVGElement, chart: ChartDisplay, geom: ChartGeom): void {
+ const cols = Math.max(chart.categories.length, ...chart.series.map((s) => s.values.length), 1)
+ const values = chart.series.flatMap((s) => s.values).filter((v): v is number => v !== null)
+ 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
+ let max = Math.ceil(rawMax / step) * step || step
+ if (rawMax > 0 && max <= rawMax + 1e-9) max += step
+ const span = max - min || 1
+ const availW = geom.width - (geom.sideLeft ?? 0) - (geom.sideRight ?? 0)
+ const plotH = geom.height - geom.top - geom.bottom
+ const cx = (geom.sideLeft ?? 0) + availW / 2
+ const cy = geom.top + plotH / 2
+ // category labels sit outside the outer ring
+ const r = Math.max(10, Math.min(availW, plotH) / 2 - 24)
+ const angleOf = (c: number) => -Math.PI / 2 + (Math.PI * 2 * c) / cols
+ const rOf = (v: number) => (r * (v - min)) / span
+ const pt = (c: number, v: number) => {
+ const rr = rOf(v)
+ return `${cx + rr * Math.cos(angleOf(c))},${cy + rr * Math.sin(angleOf(c))}`
+ }
+
+ const steps = Math.max(1, Math.round(span / step))
+ for (let i = 1; i <= steps; i++) {
+ const v = min + step * i
+ const ring = Array.from({ length: cols }, (_, c) => pt(c, v)).join(' ')
+ svgEl(svg, 'polygon', { points: ring, fill: 'none', class: 'doc-chart-grid' })
+ }
+ for (let c = 0; c < cols; c++) {
+ const [x, y] = pt(c, max).split(',')
+ svgEl(svg, 'line', { x1: String(cx), y1: String(cy), x2: x, y2: y, class: 'doc-chart-grid' })
+ }
+ if (!chart.yAxis?.deleted) {
+ for (let i = 0; i <= steps; i++) {
+ const v = min + step * i
+ svgEl(
+ svg,
+ 'text',
+ {
+ x: String(cx - 4),
+ y: String(cy - rOf(v) + 3),
+ class: 'doc-chart-axis-label',
+ 'text-anchor': 'end',
+ },
+ formatAxisValue(v),
+ )
+ }
+ }
+ if (!chart.xAxis?.deleted) {
+ chart.categories.forEach((cat, c) => {
+ if (c >= cols) return
+ const a = angleOf(c)
+ const cos = Math.cos(a)
+ const sin = Math.sin(a)
+ svgEl(
+ svg,
+ 'text',
+ {
+ x: String(cx + (r + 6) * cos),
+ y: String(cy + (r + 6) * sin + (sin > 0.1 ? 10 : sin < -0.1 ? -2 : 3)),
+ class: 'doc-chart-axis-label',
+ 'text-anchor': cos > 0.1 ? 'start' : cos < -0.1 ? 'end' : 'middle',
+ },
+ cat,
+ )
+ })
+ }
+
+ chart.series.forEach((ser, s) => {
+ const vertices = Array.from({ length: cols }, (_, c) => {
+ const v = ser.values[c]
+ return v === null || v === undefined ? null : pt(c, v)
+ })
+ const points = vertices.filter((p): p is string => p !== null)
+ if (points.length === 0) return
+ const color = seriesColor(chart, s)
+ if (chart.radarStyle === 'filled') {
+ // a gap pulls the filled outline to the center instead of skipping the spoke
+ svgEl(svg, 'polygon', {
+ points: vertices.map((p) => p ?? `${cx},${cy}`).join(' '),
+ fill: color,
+ stroke: color,
+ 'stroke-width': '1',
+ })
+ } else if (points.length === cols) {
+ svgEl(svg, 'polygon', {
+ points: points.join(' '),
+ fill: 'none',
+ stroke: color,
+ 'stroke-width': '2',
+ })
+ } else {
+ // gaps break the outline (dispBlanksAs gap); runs wrap around the last spoke
+ const runs: string[][] = []
+ const start = vertices.findIndex((p) => p === null)
+ let run: string[] = []
+ for (let i = 1; i <= cols; i++) {
+ const p = vertices[(start + i) % cols]
+ if (p === null) {
+ if (run.length > 1) runs.push(run)
+ run = []
+ } else run.push(p)
+ }
+ if (run.length > 1) runs.push(run)
+ for (const r of runs) {
+ svgEl(svg, 'polyline', {
+ points: r.join(' '),
+ fill: 'none',
+ stroke: color,
+ 'stroke-width': '2',
+ })
+ }
+ }
+ if (chart.markers) {
+ for (const p of points) {
+ const [x, y] = p.split(',')
+ drawMarker(svg, Number(x), Number(y), s, color)
+ }
+ }
+ })
+}
+
/** scatter / bubble: numeric x-y plot; bubble radius scales by point size (area-true) */
function drawScatter(svg: SVGElement, chart: ChartDisplay, geom: ChartGeom): void {
interface Pt {
@@ -661,6 +1091,7 @@ function drawScatter(svg: SVGElement, chart: ChartDisplay, geom: ChartGeom): voi
y2: String(y),
class: 'doc-chart-grid',
})
+ if (chart.yAxis?.deleted) continue
svgEl(
svg,
'text',
@@ -673,6 +1104,7 @@ function drawScatter(svg: SVGElement, chart: ChartDisplay, geom: ChartGeom): voi
formatAxisValue(v),
)
}
+ drawAxisLines(svg, chart, geom, yOf(Math.max(ay.min, 0)), xOf(Math.max(ax.min, 0)))
// x labels: date/text categories sit under their own data points (Word puts
// the cached texts along the axis); numeric x gets plain scale ticks
@@ -680,7 +1112,9 @@ function drawScatter(svg: SVGElement, chart: ChartDisplay, geom: ChartGeom): voi
chart.categories.length === 0 ||
chart.categories.every((c) => c === '' || Number.isFinite(Number(c)))
const labelY = String(geom.height - geom.bottom + 14)
- if (catNumeric) {
+ if (chart.xAxis?.deleted) {
+ // no labels
+ } else if (catNumeric) {
const xSteps = Math.max(1, Math.round(ax.span / ax.step))
for (let i = 0; i <= xSteps; i++) {
const v = ax.min + ax.step * i
@@ -727,6 +1161,10 @@ function drawScatter(svg: SVGElement, chart: ChartDisplay, geom: ChartGeom): voi
if (chart.kind === 'scatter' && !chart.markers && chart.series[s]?.line) return
for (const p of points) {
const bubble = chart.kind === 'bubble' && p.size !== null && maxSize > 0
+ if (!bubble && chart.kind === 'scatter') {
+ drawMarker(svg, xOf(p.x), yOf(p.y), s, color)
+ continue
+ }
const r = bubble ? Math.max(3, rMax * Math.sqrt(Math.abs(p.size!) / maxSize)) : 3
svgEl(svg, 'circle', {
cx: String(xOf(p.x)),
@@ -775,6 +1213,7 @@ function drawAxesHorizontal(svg: SVGElement, chart: ChartDisplay, geom: ChartGeo
y2: String(geom.height - geom.bottom),
class: 'doc-chart-grid',
})
+ if (chart.xAxis?.deleted) continue
svgEl(
svg,
'text',
@@ -787,9 +1226,10 @@ function drawAxesHorizontal(svg: SVGElement, chart: ChartDisplay, geom: ChartGeo
formatAxisValue(v) + (pct ? '%' : ''),
)
}
+ drawAxisLines(svg, chart, geom, geom.height - geom.bottom, xOf(0))
chart.categories.forEach((cat, c) => {
- if (c >= rows) return
+ if (c >= rows || chart.yAxis?.deleted) return
svgEl(
svg,
'text',
@@ -854,15 +1294,24 @@ function drawPie(svg: SVGElement, chart: ChartDisplay, geom: ChartGeom): void {
const total = values.reduce((a, b) => a + b, 0)
if (total <= 0) return
const availW = geom.width - (geom.sideLeft ?? 0) - (geom.sideRight ?? 0)
- const cx = (geom.sideLeft ?? 0) + availW / 2
- const cy = geom.height / 2
- const r = Math.min(availW, geom.height) / 2 - 16
+ // only a top legend row shifts the pie; the default margins keep the old centering
+ const topRow = geom.top - 12
+ const availH = geom.height - topRow
+ const cx0 = (geom.sideLeft ?? 0) + availW / 2
+ const cy0 = topRow + availH / 2
+ const labels = chart.dataLabels
+ const explode = Math.min(Math.max(chart.explosionPct ?? 0, 0), 400) / 100
+ // exploded slices and outside labels stay within the box: shrink the radius
+ const r = Math.max(8, (Math.min(availW, availH) / 2 - (labels ? 28 : 16)) / (1 + explode))
const ri = (r * Math.min(Math.max(chart.holePct ?? 0, 0), 90)) / 100
const single = values.filter((v) => v > 0).length === 1
let angle = -Math.PI / 2
values.forEach((value, i) => {
if (value === 0) return
const sweep = (value / total) * Math.PI * 2
+ const mid = angle + sweep / 2
+ const cx = cx0 + r * explode * Math.cos(mid)
+ const cy = cy0 + r * explode * Math.sin(mid)
const x1 = cx + r * Math.cos(angle)
const y1 = cy + r * Math.sin(angle)
const ix1 = cx + ri * Math.cos(angle)
@@ -886,6 +1335,32 @@ function drawPie(svg: SVGElement, chart: ChartDisplay, geom: ChartGeom): void {
d = `M ${cx} ${cy} L ${x1} ${y1} A ${r} ${r} 0 ${large} 1 ${x2} ${y2} Z`
}
svgEl(svg, 'path', { d, fill: pointColor(chart, 0, i), stroke: '#fff', 'stroke-width': '1' })
+ if (!labels) return
+ const parts: string[] = []
+ if (labels.cat) parts.push(chart.categories[i] ?? '')
+ if (labels.val) parts.push(String(value))
+ if (labels.pct) parts.push(`${Math.round((value / total) * 100)}%`)
+ const text = parts.join(', ')
+ // bestFit: inside the slice when the arc at the label radius fits the text, else just outside
+ const inside = sweep * r * 0.65 >= text.length * 6 && !single
+ const lr = inside ? Math.max(ri, r * 0.65) : r + 10
+ svgEl(
+ svg,
+ 'text',
+ {
+ x: String(cx + lr * Math.cos(mid)),
+ y: String(cy + lr * Math.sin(mid) + 3),
+ class: inside ? 'doc-chart-axis-label doc-chart-label-in' : 'doc-chart-axis-label',
+ 'text-anchor': inside
+ ? 'middle'
+ : Math.cos(mid) > 0.1
+ ? 'start'
+ : Math.cos(mid) < -0.1
+ ? 'end'
+ : 'middle',
+ },
+ text,
+ )
})
}
@@ -1131,7 +1606,7 @@ function textSpanSpec(run: Run, autoSpace?: boolean, leadPad = false): DomSpec {
const kerning = fontKerningCss(run)
const runStyle = [
// authored color stays the declaration; the --dk-c twin feeds the dark page (dark-page.ts)
- run.color ? textColorDecls(run.color).join(';') : '',
+ run.color && !paperColorEffect(run.textEffect) ? textColorDecls(run.color).join(';') : '',
run.bold ? 'font-weight:700' : run.bold === false ? 'font-weight:normal' : '',
run.italic ? 'font-style:italic' : run.italic === false ? 'font-style:normal' : '',
run.underline ? 'text-decoration:underline' : '',
@@ -1145,6 +1620,11 @@ function textSpanSpec(run: Run, autoSpace?: boolean, leadPad = false): DomSpec {
run.sizeHalfPoints ? `font-size:${run.sizeHalfPoints / 2}pt` : '',
letterSpacing ? `letter-spacing:${letterSpacing}` : '',
kerning ? `font-kerning:${kerning}` : '',
+ run.textOutline ? textOutlineDecl(run.textOutline) : '',
+ run.textEffect ? textEffectDecls(run.textEffect).join(';') : '',
+ run.dstrike ? doubleStrikeDecl() : '',
+ run.glow ? glowDecl(run.glow) : '',
+ run.positionHalfPoints ? positionDecl(run.positionHalfPoints) : '',
run.caps === 'all' ? 'text-transform:uppercase' : '',
run.caps === 'small' ? 'font-variant-caps:small-caps' : '',
run.caps === 'none' ? 'text-transform:none;font-variant-caps:normal' : '',
@@ -1156,13 +1636,16 @@ function textSpanSpec(run: Run, autoSpace?: boolean, leadPad = false): DomSpec {
const content = autoSpace === false ? [run.text] : padSegments(run.text, leadPad)
// hyperlink runs keep the editable path's look (.doc-link) and real href;
// App-level click handling prevents in-place navigation (jump on mod+click)
+ const attrs: Record = {}
+ if (runStyle) attrs.style = runStyle
+ if (run.styleId) attrs['data-style'] = run.styleId
if (run.link?.href) {
- const attrs: Record = { class: 'doc-link', href: run.link.href }
+ attrs.class = 'doc-link'
+ attrs.href = run.link.href
if (run.link.tooltip) attrs.title = run.link.tooltip
- if (runStyle) attrs.style = runStyle
return ['a', attrs, ...content]
}
- return runStyle ? ['span', { style: runStyle }, ...content] : ['span', {}, ...content]
+ return ['span', attrs, ...content]
}
/** run spans with pads at run-boundary CJK-Latin seams (empty runs keep their span, no pad) */
@@ -1180,6 +1663,38 @@ function runSpansWithPads(runs: Run[], autoSpace?: boolean): DomSpec[] {
return out
}
+/** camelCase style record (hf-dom helpers) as inline CSS text */
+function styleText(style: Record): string {
+ return Object.entries(style)
+ .map(([k, v]) => `${k.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}:${v}`)
+ .join(';')
+}
+
+/** table row inside a textbox: the header/footer layout-table row markup
+ * (flex columns sized by the cells, per-cell borders / shading / margins) */
+function textboxRowSpec(para: TextboxParaDisplay): DomSpec {
+ const cells = (para.cells ?? []).map((cell): DomSpec => {
+ const geom = hfCellGeometry(cell)
+ const decls = [styleText(geom.style)]
+ // document content colors (w:shd / borders) plus their dark-page twins
+ if (cell.fill) decls.push(`background-color:#${cell.fill}`, dkBackground(`#${cell.fill}`))
+ for (const [side, css] of Object.entries(geom.borders)) {
+ decls.push(dkBorder(side as DkBorderSide, css))
+ }
+ const lines = (cell.paras.length > 0 ? cell.paras : [[]]).map((runs, k): DomSpec => {
+ const attrs: Record = { class: 'page-hf-cell-para' }
+ const style = styleText(hfCellParaStyle(cell.paraProps?.[k]))
+ if (style) attrs.style = style
+ return runs.length === 0 ? ['div', attrs, ' '] : ['div', attrs, ...runSpansWithPads(runs)]
+ })
+ return ['div', { class: 'page-hf-cell', style: decls.filter(Boolean).join(';') }, ...lines]
+ })
+ const attrs: Record = { class: 'doc-textbox-row page-hf-row' }
+ const style = styleText(hfRowStyle(para.row))
+ if (style) attrs.style = style
+ return ['div', attrs, ...cells]
+}
+
export function renderTextboxSpec(box: TextboxDisplay): DomSpec {
const style = textboxBoxStyle(box)
const boxAttrs: Record = {
@@ -1193,20 +1708,32 @@ export function renderTextboxSpec(box: TextboxDisplay): DomSpec {
}
// page-absolute X: the column-layout counter-translate keys on this
if (box.floating && box.pageRelX) boxAttrs['data-page-rel-x'] = '1'
+ // wrapNone/front/behind boxes never open pages: Word clips them at their
+ // anchor's page edge (a letterhead's page-tall art box must not add a page)
+ if (box.floating && !box.bandTopPx && !box.bandBottomPx && !box.wrapSide) {
+ boxAttrs['data-no-spill'] = '1'
+ }
const paras: DomSpec[] = box.paras.map((para) => {
+ if (para.cells) return textboxRowSpec(para)
const spans: DomSpec[] = runSpansWithPads(para.runs, para.autoSpace)
const text = para.runs.map((r) => r.text).join('')
// same line strut as body/cell paragraphs (factor by run fonts + run-size
// strut + grid snapping); inheriting the page's computed line-height
// instead inflated every CJK textbox line to the body's pixel value
const fontStyles: string[] = []
- if (text) {
+ if (text && !SPACE_ONLY_RE.test(text)) {
fontStyles.push(`--doc-line-factor:${runsLineFactor(para.runs, text)}`)
const fam = runsDeclaredFontFamily(para.runs)
if (fam) fontStyles.push(`font-family:${fam}`)
const strut = runStrutHalfPoints(para.runs)
if (strut) fontStyles.push(...strutFontCss(strut))
+ } else {
+ // space-only paragraph: the mark sizes the line (Word probe 2026-09-11),
+ // with the Latin factor like body/cell empties, never the space run
+ fontStyles.push('--doc-line-factor:var(--doc-line-factor-latin,1.2)')
+ if (para.emptyRunSizeHalfPoints)
+ fontStyles.push(`font-size:${para.emptyRunSizeHalfPoints / 2}pt`)
}
const lineMult = cssAutoLineMult(para.lineRule, para.lineRawTwips, para.lineSpacing)
const lh = cssLineHeight(para.lineRule, para.lineRawTwips, para.lineSpacing)
@@ -1260,6 +1787,7 @@ function runStrutHalfPoints(runs: Run[]): { halfPoints: number; uniform: boolean
let max: number | null = null
let min: number | null = null
for (const run of runs) {
+ if (SPACE_ONLY_RE.test(run.text)) continue
if (run.sizeHalfPoints == null) return null
max = Math.max(max ?? 0, run.sizeHalfPoints)
min = Math.min(min ?? Infinity, run.sizeHalfPoints)
@@ -1328,7 +1856,9 @@ function cellParaSpec(
// explicit per-paragraph direction (same rule as the editor's blockAttrs):
// a bidiVisual table's dir="rtl" mirrors columns but must not reorder cell text
styles.push(fmt?.bidi || inferredBidi(fmt, runs ?? undefined) ? 'direction:rtl' : 'direction:ltr')
- if (text) {
+ // a space-only paragraph is sized by its mark like an empty one (Word probe 2026-09-11)
+ const markSized = !text || SPACE_ONLY_RE.test(text)
+ if (!markSized) {
// Korean cells break at spaces like Word (same rule as the editor's blockAttrs)
if (textHasHangul(text) && fmt?.wordWrap !== false) {
styles.push('word-break:keep-all', 'overflow-wrap:anywhere')
@@ -1354,12 +1884,17 @@ function cellParaSpec(
if (fmt?.spaceAfterAuto) styles.push(`margin-bottom:${cssGridSpacingPt(WORD_AUTO_SPACING_PT)}`)
else if (fmt?.spaceAfter) styles.push(`margin-bottom:${cssGridSpacingPt(fmt.spaceAfter / 20)}`)
// Word sizes an empty line by the paragraph mark / empty run (same as blockAttrs)
- if (!text && !pictureOnly && fmt?.emptyRunSizeHalfPoints) {
+ if (markSized && !pictureOnly && fmt?.emptyRunSizeHalfPoints) {
styles.push(`font-size:${fmt.emptyRunSizeHalfPoints / 2}pt`)
}
// Western mark faces only (same scoping as blockAttrs): empty cells keep
// the Latin-factor rule instead of growing to a CJK mark face
- if (!text && !pictureOnly && fmt?.emptyRunFontFamily && !isCjkFontName(fmt.emptyRunFontFamily)) {
+ if (
+ markSized &&
+ !pictureOnly &&
+ fmt?.emptyRunFontFamily &&
+ !isCjkFontName(fmt.emptyRunFontFamily)
+ ) {
const fam = fmt.emptyRunFontFamily
styles.push(`--doc-line-factor:${lineHeightFactor(fam)}`, `font-family:${cssFontFamily(fam)}`)
}
@@ -1367,7 +1902,7 @@ function cellParaSpec(
const classes: string[] = []
// empty paragraphs get the Latin factor (.doc-table .doc-p-empty) and a line box
if (pictureOnly) classes.push('doc-p-picture')
- else if (!text) classes.push('doc-p-empty')
+ else if (markSized) classes.push('doc-p-empty')
// the sp-auto-* cell rules (styles.css) zero the auto margins at the cell boundaries
if (fmt?.spaceBeforeAuto) classes.push('sp-auto-b')
if (fmt?.spaceAfterAuto) classes.push('sp-auto-a')
@@ -1375,6 +1910,35 @@ function cellParaSpec(
return content.length > 0 ? ['div', attrs, ...content] : ['div', attrs, ['br', {}]]
}
+/** anchored shapes/textboxes of a table cell: a zero-width float strut whose
+ * height reserves the lowest box bottom (Word grows the row to hold them) */
+export function cellBoxesSpec(boxes: TextboxDisplay[]): DomSpec {
+ if (boxes.length === 0) return ['div', { class: 'doc-cell-boxes' }]
+ let bottom = 0
+ for (const b of boxes) {
+ bottom = Math.max(bottom, (b.offsetYEmu ?? 0) / 9525 + (b.heightPx ?? b.minHeightPx ?? 0))
+ }
+ return [
+ 'div',
+ {
+ class: 'doc-cell-boxes',
+ contenteditable: 'false',
+ style: bottom > 0 ? `height:${bottom.toFixed(1)}px` : '',
+ },
+ ...boxes.map((b): DomSpec => {
+ const spec = renderTextboxSpec(b)
+ if (b.floating) return spec
+ const left = (b.offsetXEmu ?? 0) / 9525
+ const top = (b.offsetYEmu ?? 0) / 9525
+ return [
+ 'div',
+ { style: `position:absolute;left:${left.toFixed(1)}px;top:${top.toFixed(1)}px` },
+ spec,
+ ]
+ }),
+ ]
+}
+
/** read-only DOM spec from the display model (vMerge -> rowSpan);
* nested = rendered inside a cell, capped at the cell instead of spilling into page margins */
export function renderTableSpec(model: TableModel, nested = false): DomSpec {
@@ -1457,14 +2021,27 @@ export function renderTableSpec(model: TableModel, nested = false): DomSpec {
const nested = cell.nestedTables ?? []
const anchorOf = (i: number) =>
Math.min(cell.nestedTableAnchors?.[i] ?? paraBlocks.length, paraBlocks.length)
+ // anchored shapes group before their anchor paragraph (same strut as the
+ // editable docCellBoxes node), so read-only and nested cells draw them too
+ const boxGroups = new Map()
+ ;(cell.anchoredBoxes ?? []).forEach((b, i) => {
+ const at = Math.min(cell.anchoredBoxAnchors?.[i] ?? 0, paraBlocks.length)
+ boxGroups.set(at, [...(boxGroups.get(at) ?? []), b])
+ })
const content: unknown[] = []
let ni = 0
+ const boxesAt = (pi: number) => {
+ const group = boxGroups.get(pi)
+ if (group) content.push(cellBoxesSpec(group))
+ }
paraBlocks.forEach((blk, pi) => {
while (ni < nested.length && anchorOf(ni) <= pi)
content.push(renderTableSpec(nested[ni++], true))
+ boxesAt(pi)
content.push(blk)
})
while (ni < nested.length) content.push(renderTableSpec(nested[ni++], true))
+ boxesAt(paraBlocks.length)
if (content.length === 0) content.push('\u00a0')
const clip = cellClipTwips(model, ri, cell, rowSpan)
const wm = cellWritingMode(cell.textDirection ?? null)
@@ -1503,7 +2080,7 @@ export function renderTableSpec(model: TableModel, nested = false): DomSpec {
const tableChildren: unknown[] = []
const colPx = !model.widthPct
- ? model.colWidthsTwips?.map((w) => Math.max(24, Math.round(w / 15)))
+ ? model.colWidthsTwips?.map((w) => Math.max(1, Math.round(w / 15)))
: undefined
if (colPx) {
tableChildren.push(['colgroup', {}, ...colPx.map((w) => ['col', { style: `width:${w}px` }])])
diff --git a/apps/docs/src/renderer/editor/run-border.ts b/apps/docs/src/renderer/editor/run-border.ts
new file mode 100644
index 0000000..d2e3a29
--- /dev/null
+++ b/apps/docs/src/renderer/editor/run-border.ts
@@ -0,0 +1,49 @@
+import type { Run } from '@genoffice/docx-engine'
+import { dkBorder } from './dark-page'
+
+type RunBorder = NonNullable
+
+const BORDER_STYLES: Record = {
+ dotted: 'dotted',
+ dashed: 'dashed',
+ dashSmallGap: 'dashed',
+ dotDash: 'dashed',
+ dotDotDash: 'dashed',
+ double: 'double',
+ triple: 'double',
+ thinThickSmallGap: 'double',
+ thickThinSmallGap: 'double',
+ thinThickMediumGap: 'double',
+ thickThinMediumGap: 'double',
+ inset: 'inset',
+ outset: 'outset',
+ threeDEmboss: 'ridge',
+ threeDEngrave: 'groove',
+}
+
+export function parseRunBorderAttr(json: string): RunBorder | undefined {
+ try {
+ const v = JSON.parse(json) as RunBorder
+ return v && typeof v.val === 'string' && typeof v.sz === 'number' ? v : undefined
+ } catch {
+ return undefined
+ }
+}
+
+/** `0.75pt solid #000000` for a character border (w:sz is eighths of a point; Word draws at least 1/4pt) */
+export function runBorderCss(bdr: RunBorder): string {
+ const style = BORDER_STYLES[bdr.val] ?? 'solid'
+ const color = bdr.color ? `#${bdr.color}` : 'currentColor'
+ return `${Math.max(bdr.sz, 2) / 8}pt ${style} ${color}`
+}
+
+/** inline declarations for the docTextStyle span: border, the w:space text gap, dark-page twins */
+export function runBorderDecls(json: string): string[] {
+ const bdr = parseRunBorderAttr(json)
+ if (!bdr) return []
+ const border = runBorderCss(bdr)
+ const decls = [`border:${border}`]
+ if (bdr.space) decls.push(`padding:${bdr.space}pt`)
+ if (bdr.color) decls.push(...(['t', 'r', 'b', 'l'] as const).map((s) => dkBorder(s, border)))
+ return decls
+}
diff --git a/apps/docs/src/renderer/editor/settled-measure.ts b/apps/docs/src/renderer/editor/settled-measure.ts
index 4e3bc2d..7d22849 100644
--- a/apps/docs/src/renderer/editor/settled-measure.ts
+++ b/apps/docs/src/renderer/editor/settled-measure.ts
@@ -4,7 +4,7 @@ import type { EditorView } from '@tiptap/pm/view'
/** CSS floats: the only layout where a paragraph's vertical position changes its line breaks */
const FLOAT_SELECTOR =
'[class*="-wrap-square-"], [class*="-wrap-tight-"], [class*="-wrap-through-"], ' +
- '[class*="doc-table-float-"], .doc-cell-boxes'
+ '[class*="doc-table-float-"]:not(.doc-table-float-flow), .doc-cell-boxes'
interface Entry {
node: ProseMirrorNode
diff --git a/apps/docs/src/renderer/editor/text-effects.ts b/apps/docs/src/renderer/editor/text-effects.ts
new file mode 100644
index 0000000..16b8791
--- /dev/null
+++ b/apps/docs/src/renderer/editor/text-effects.ts
@@ -0,0 +1,98 @@
+import type { TextEffect, TextGlow } from '@genoffice/docx-engine'
+
+const TEXT_EFFECTS: ReadonlySet = new Set(['outline', 'emboss', 'imprint', 'shadow'])
+
+export function parseTextEffectAttr(raw: unknown): TextEffect | undefined {
+ return typeof raw === 'string' && TEXT_EFFECTS.has(raw) ? (raw as TextEffect) : undefined
+}
+
+/** Word draws embossed/engraved glyphs in the paper colour: only the offset shadow shows */
+export function paperColorEffect(effect: TextEffect | undefined): boolean {
+ return effect === 'emboss' || effect === 'imprint'
+}
+
+export function textEffectDecls(effect: TextEffect): string[] {
+ switch (effect) {
+ case 'outline':
+ return ['-webkit-text-stroke:0.5px currentColor', '-webkit-text-fill-color:transparent']
+ case 'emboss':
+ return ['color:var(--docs-paper)', 'text-shadow:1px 1px 0 var(--docs-paper-ink-mid)']
+ case 'imprint':
+ return ['color:var(--docs-paper)', 'text-shadow:-1px -1px 0 var(--docs-paper-ink-mid)']
+ case 'shadow':
+ return ['text-shadow:1px 1px 0 var(--docs-paper-ink-soft)']
+ }
+}
+
+function cssColor(hex: string, alpha: number | undefined): string {
+ const n = parseInt(hex, 16)
+ return alpha !== undefined && alpha < 1
+ ? `rgba(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255},${alpha})`
+ : `#${hex}`
+}
+
+/** two blur layers: one Gaussian alone fades far below Word's dense halo */
+export function glowDecl(glow: TextGlow): string {
+ const c = cssColor(glow.color, glow.alpha)
+ return `text-shadow:0 0 ${glow.radiusPt / 2}pt ${c},0 0 ${glow.radiusPt}pt ${c}`
+}
+
+export function doubleStrikeDecl(): string {
+ return 'text-decoration:line-through double'
+}
+
+export function parseGlowAttr(raw: string): TextGlow | undefined {
+ try {
+ const g = JSON.parse(raw) as Partial
+ if (typeof g.color !== 'string' || typeof g.radiusPt !== 'number') return undefined
+ return {
+ color: g.color,
+ radiusPt: g.radiusPt,
+ ...(g.alpha !== undefined ? { alpha: g.alpha } : {}),
+ }
+ } catch {
+ return undefined
+ }
+}
+
+export function positionDecl(halfPoints: number): string {
+ return `vertical-align:${halfPoints / 2}pt`
+}
+
+/** w:w on a whitespace-free run: {s: scale factor, gapEm: estimated width change in em} */
+export interface CharScaleX {
+ s: number
+ gapEm: number
+}
+
+export function charScaleXAttr(text: string, scalePct: number, perCharEm: number): string {
+ const chars = [...text].length
+ return JSON.stringify({
+ s: scalePct / 100,
+ gapEm: Math.round(perCharEm * chars * 1000) / 1000,
+ })
+}
+
+/** glyphs compress like Word; the negative margin hands the saved width back to the line */
+export function charScaleXDecls(json: string): string[] {
+ let v: Partial
+ try {
+ v = JSON.parse(json) as Partial
+ } catch {
+ return []
+ }
+ if (typeof v.s !== 'number' || typeof v.gapEm !== 'number' || !(v.s > 0)) return []
+ return [
+ 'display:inline-block',
+ `transform:scaleX(${v.s})`,
+ 'transform-origin:0 50%',
+ `margin-right:${v.gapEm}em`,
+ ]
+}
+
+/** text-align for a paragraph w:jc; distribute spreads every line, the last one included */
+export function textAlignDecl(align: string): string {
+ return align === 'distribute'
+ ? 'text-align:justify;text-align-last:justify;text-justify:distribute'
+ : `text-align:${align}`
+}
diff --git a/apps/docs/src/renderer/editor/text-outline.ts b/apps/docs/src/renderer/editor/text-outline.ts
new file mode 100644
index 0000000..39cb2c5
--- /dev/null
+++ b/apps/docs/src/renderer/editor/text-outline.ts
@@ -0,0 +1,29 @@
+import type { TextOutline } from '@genoffice/docx-engine'
+
+/** CSS value for a w14:textOutline stroke (`-webkit-text-stroke`) */
+export function textOutlineCssValue(o: TextOutline): string {
+ const n = parseInt(o.color, 16)
+ const color =
+ o.alpha !== undefined && o.alpha < 1
+ ? `rgba(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255},${o.alpha})`
+ : `#${o.color}`
+ return `${o.widthPt}pt ${color}`
+}
+
+export function textOutlineDecl(o: TextOutline): string {
+ return `-webkit-text-stroke:${textOutlineCssValue(o)}`
+}
+
+export function parseTextOutlineAttr(raw: string): TextOutline | undefined {
+ try {
+ const o = JSON.parse(raw) as Partial
+ if (typeof o.color !== 'string' || typeof o.widthPt !== 'number') return undefined
+ return {
+ color: o.color,
+ widthPt: o.widthPt,
+ ...(o.alpha !== undefined ? { alpha: o.alpha } : {}),
+ }
+ } catch {
+ return undefined
+ }
+}
diff --git a/apps/docs/src/renderer/editor/trailing-table-exit.ts b/apps/docs/src/renderer/editor/trailing-table-exit.ts
index a52eaed..630fad4 100644
--- a/apps/docs/src/renderer/editor/trailing-table-exit.ts
+++ b/apps/docs/src/renderer/editor/trailing-table-exit.ts
@@ -1,6 +1,7 @@
import { Extension } from '@tiptap/core'
import { GapCursor } from '@tiptap/pm/gapcursor'
import { Plugin, PluginKey, TextSelection } from '@tiptap/pm/state'
+import { TRACK_IGNORE } from './revisions'
const key = new PluginKey('trailingTableExit')
@@ -28,7 +29,9 @@ export const TrailingTableExitExtension = Extension.create({
if (!paragraph) return null
const pos = newState.doc.content.size
const transaction = newState.tr.insert(pos, paragraph)
+ // leaving the table is navigation, not authoring: no revision mark
return transaction
+ .setMeta(TRACK_IGNORE, true)
.setSelection(TextSelection.create(transaction.doc, pos + 1))
.scrollIntoView()
},
diff --git a/apps/docs/src/renderer/file-actions.ts b/apps/docs/src/renderer/file-actions.ts
index a95b28f..a25f42a 100644
--- a/apps/docs/src/renderer/file-actions.ts
+++ b/apps/docs/src/renderer/file-actions.ts
@@ -50,8 +50,9 @@ import {
type PendingNumbering,
} from './doc-state'
import { docStyleCss } from './doc-style-css'
+import { setNoteNumFmts } from './note-format'
import type { CompareEntry } from './editor/compare'
-import { blocksToPmDoc, pmDocToSavePlan, type PmNode } from './editor/convert'
+import { blocksToPmDoc, pmDocOptions, pmDocToSavePlan, type PmNode } from './editor/convert'
import { TABLE_TRAILING_SKIP } from './editor/extensions'
import { TRACK_IGNORE } from './editor/revisions'
import {
@@ -251,6 +252,7 @@ function resetEditorHistory(editor: Editor): void {
/** doc-level layout inputs living outside CSS: default tab grid + hyphenation lang */
function applyDocLayoutSettings(editor: Editor, parsed: ParsedDocFull): void {
+ setNoteNumFmts({ footnote: parsed.footnoteProps, endnote: parsed.endnoteProps })
editor.storage.tabStops.defaultTabStopTwips = parsed.defaultTabStopTwips ?? null
// Word 2013+ justified lines pull words up by shrinking spaces; legacy
// compatibility modes (and new blank docs) never do
@@ -338,7 +340,10 @@ export async function loadFile(
ctx.editor.storage.listNumbering.docDefaults = parsed.docDefaults
ctx.editor.storage.listNumbering.defs = parsed.numbering
applyDocLayoutSettings(ctx.editor, parsed)
- setContentPhased(phasedHostFor(ctx), blocksToPmDoc(parsed.blocks, readSections(parsed)))
+ setContentPhased(
+ phasedHostFor(ctx),
+ blocksToPmDoc(parsed.blocks, readSections(parsed), pmDocOptions(parsed)),
+ )
resetEditorHistory(ctx.editor)
noteDocumentSwapped()
ctx.setDoc({
@@ -420,11 +425,7 @@ export async function loadFile(
// until an explicit/automatic save lands it on the original path.
ctx.dirtyRef.current = openedFileStartsDirty(result)
const missing = checkMissingFonts(collectDocFonts(parsed))
- const verticalText = readSections(parsed).some((s) => s.settings.textDirection)
- if (verticalText) {
- // visible degradation: vertical writing is not rendered yet, never silently
- ctx.setStatus(t('appVerticalTextNotice'))
- } else if (missing.length > 0) {
+ if (missing.length > 0) {
const names = missing
.slice(0, 3)
.map((m) => (m.substitute ? `${m.name} → ${m.substitute}` : m.name))
@@ -461,7 +462,9 @@ export async function newFile(ctx: FileActionContext): Promise {
+ const debug = (window as unknown as { __pageDebug?: PageDebug }).__pageDebug
+ return Array.isArray(debug?.slices) ? debug.slices.length : 0
+}
+
+export interface DocumentReadiness {
+ /** a document loaded from disk is mounted in the editor */
+ opened: boolean
+ /** the boot open landed on the untitled blank fallback: the input is unreadable */
+ failed: boolean
+}
+
+const UNREADABLE = 'the input document did not open (corrupt, unsupported or password-protected)'
+
+/**
+ * Resolves once a document is open and its pagination has produced the same
+ * slice count twice in a row — the settle test the Word-fidelity harness
+ * uses, so headless exports the layout the editor would have shown.
+ */
+export async function waitForDocumentSettled(
+ readiness: () => DocumentReadiness,
+ options: HeadlessWaitOptions = {},
+): Promise {
+ const { timeoutMs = 180_000, pollMs = 300 } = options
+ const deadline = Date.now() + timeoutMs
+ // A corrupt input is answered with a blank untitled document, not an error;
+ // waiting out the full budget for it would only delay the same verdict.
+ await pollUntilReady(
+ () => {
+ if (readiness().failed) throw new Error(UNREADABLE)
+ return readiness().opened
+ },
+ UNREADABLE,
+ { timeoutMs, pollMs },
+ )
+ // Async @font-face loads change line-break points, so pagination is only
+ // trustworthy once the faces the document asked for have settled.
+ await documentFontsSettled()
+ let stable = 0
+ let last = -1
+ while (Date.now() <= deadline) {
+ const count = pageSliceCount()
+ if (count >= 1) {
+ stable = count === last ? stable + 1 : 0
+ last = count
+ if (stable >= 2) return
+ }
+ await headlessSleep(pollMs)
+ }
+ // Out of budget: a page count that never stabilized is still exportable,
+ // a document that produced none is not.
+ if (last >= 1) return
+ throw new Error('pagination produced no pages')
+}
+
+/** Wait for the document, then run one of the GUI's own exports against a fixed path. */
+export function runHeadlessDocumentExport(
+ outPath: string,
+ readiness: () => DocumentReadiness,
+ exportFile: (outPath: string) => Promise,
+ options?: HeadlessWaitOptions,
+): Promise {
+ return runHeadlessRendererExport(
+ outPath,
+ () => waitForDocumentSettled(readiness, options),
+ exportFile,
+ )
+}
diff --git a/apps/docs/src/renderer/html-export.ts b/apps/docs/src/renderer/html-export.ts
index af5ef4a..62562b0 100644
--- a/apps/docs/src/renderer/html-export.ts
+++ b/apps/docs/src/renderer/html-export.ts
@@ -99,6 +99,14 @@ const CHROME_PSEUDO_CONTENT = /attr\(\s*data-(?:ppr-change-label|sdt-alias)\s*\)
const INTERNAL_FONTS = /,\s*"(?:[A-Za-z ]+ GO|GenOffice [A-Za-z ]+)"/g
+/** tab leaders are an absolutely positioned glyph run clipped to the tab
+ * advance on screen; inline styles cannot clip a pseudo, so export a border */
+const LEADER_BORDER: Record = {
+ 'doc-tab-leader-dot': 'dotted',
+ 'doc-tab-leader-middleDot': 'dotted',
+ 'doc-tab-leader-hyphen': 'dashed',
+}
+
const SIDES = ['top', 'right', 'bottom', 'left'] as const
const TAG_DISPLAY: Record = {
@@ -397,7 +405,9 @@ function serializeNode(
host && el.offsetLeft + el.offsetWidth / 2 > host.clientWidth / 2 ? 'right' : 'left'
decls.push(`float:${side}`, 'margin:4px 8px')
}
- const before = pseudo(el, cs, '::before', win)
+ const leader = Object.keys(LEADER_BORDER).find((c) => el.classList.contains(c))
+ if (leader) decls.push(`border-bottom:1px ${LEADER_BORDER[leader]} currentColor`)
+ const before = leader ? '' : pseudo(el, cs, '::before', win)
const after = pseudo(el, cs, '::after', win)
const attrs: string[] = []
for (const a of KEEP_ATTRS) {
diff --git a/apps/docs/src/renderer/i18n/ai/ar.ts b/apps/docs/src/renderer/i18n/ai/ar.ts
index b65fbde..9a15836 100644
--- a/apps/docs/src/renderer/i18n/ai/ar.ts
+++ b/apps/docs/src/renderer/i18n/ai/ar.ts
@@ -122,6 +122,14 @@ export const ar = {
aiSumReadBlocks: 'قراءة الكتل',
aiSumReadBlocksRange: 'قراءة الكتل {start}-{end}',
aiSumInsertContent: 'إدراج محتوى',
+ aiSumWriteDocument: 'تمت كتابة المحتوى',
+ aiSumWriteDocumentFailed: 'فشلت الكتابة',
+ aiSumWriteDocumentPartial: 'تمت كتابة جزء من المحتوى',
+ aiWritingDocument: 'جارٍ كتابة المستند · {blocks} كتلة',
+ aiPartialTitle: 'لم تتم كتابة سوى جزء من المحتوى',
+ aiPartialBody: 'وصلت {blocks} كتلة قبل توقف الكتابة. هل تريد الاحتفاظ بهذا الجزء أو تجاهله؟',
+ aiPartialAdopt: 'احتفاظ',
+ aiPartialDiscard: 'تجاهل',
aiSumInsertedBlocks: 'تم إدراج {count} كتلة',
aiSumCreateDocument: 'إنشاء مستند جديد',
aiSumCreatedDocument: 'تم إنشاء {name}',
diff --git a/apps/docs/src/renderer/i18n/ai/cs.ts b/apps/docs/src/renderer/i18n/ai/cs.ts
index d2a564a..8475275 100644
--- a/apps/docs/src/renderer/i18n/ai/cs.ts
+++ b/apps/docs/src/renderer/i18n/ai/cs.ts
@@ -125,6 +125,15 @@ export const cs = {
aiSumReadBlocks: 'Přečteny bloky',
aiSumReadBlocksRange: 'Přečteny bloky {start}–{end}',
aiSumInsertContent: 'Vložit obsah',
+ aiSumWriteDocument: 'Obsah napsán',
+ aiSumWriteDocumentFailed: 'Psaní se nezdařilo',
+ aiSumWriteDocumentPartial: 'Obsah napsán částečně',
+ aiWritingDocument: 'Píšu dokument · {blocks} bloků',
+ aiPartialTitle: 'Napsala se jen část obsahu',
+ aiPartialBody:
+ 'Dorazilo {blocks} bloků, než se psaní přerušilo. Ponechat tuto část, nebo zahodit?',
+ aiPartialAdopt: 'Ponechat',
+ aiPartialDiscard: 'Zahodit',
aiSumInsertedBlocks: 'Vloženo bloků: {count}',
aiSumCreateDocument: 'Vytvořit nový dokument',
aiSumCreatedDocument: 'Vytvořeno {name}',
diff --git a/apps/docs/src/renderer/i18n/ai/de.ts b/apps/docs/src/renderer/i18n/ai/de.ts
index 46a3463..1ff46b1 100644
--- a/apps/docs/src/renderer/i18n/ai/de.ts
+++ b/apps/docs/src/renderer/i18n/ai/de.ts
@@ -128,6 +128,15 @@ export const de = {
aiSumReadBlocks: 'Blöcke lesen',
aiSumReadBlocksRange: 'Blöcke {start}-{end} lesen',
aiSumInsertContent: 'Inhalt einfügen',
+ aiSumWriteDocument: 'Inhalt geschrieben',
+ aiSumWriteDocumentFailed: 'Schreiben fehlgeschlagen',
+ aiSumWriteDocumentPartial: 'Inhalt teilweise geschrieben',
+ aiWritingDocument: 'Dokument wird geschrieben · {blocks} Blöcke',
+ aiPartialTitle: 'Der Inhalt wurde nur teilweise geschrieben',
+ aiPartialBody:
+ '{blocks} Blöcke sind angekommen, bevor das Schreiben abbrach. Diesen Teil behalten oder verwerfen?',
+ aiPartialAdopt: 'Behalten',
+ aiPartialDiscard: 'Verwerfen',
aiSumInsertedBlocks: '{count} Block/Blöcke eingefügt',
aiSumCreateDocument: 'Neues Dokument erstellen',
aiSumCreatedDocument: '{name} erstellt',
diff --git a/apps/docs/src/renderer/i18n/ai/en.ts b/apps/docs/src/renderer/i18n/ai/en.ts
index a86501a..0629b4d 100644
--- a/apps/docs/src/renderer/i18n/ai/en.ts
+++ b/apps/docs/src/renderer/i18n/ai/en.ts
@@ -123,6 +123,15 @@ export const en = {
aiSumReadBlocks: 'Read blocks',
aiSumReadBlocksRange: 'Read blocks {start}-{end}',
aiSumInsertContent: 'Insert content',
+ aiSumWriteDocument: 'Wrote the content',
+ aiSumWriteDocumentFailed: 'Writing failed',
+ aiSumWriteDocumentPartial: 'Wrote part of the content',
+ aiWritingDocument: 'Writing the document · {blocks} blocks',
+ aiPartialTitle: 'Only part of the content was written',
+ aiPartialBody:
+ '{blocks} blocks arrived before the writing stopped. Keep this part or discard it?',
+ aiPartialAdopt: 'Keep',
+ aiPartialDiscard: 'Discard',
aiSumInsertedBlocks: 'Inserted {count} block(s)',
aiSumCreateDocument: 'Create new document',
aiSumCreatedDocument: 'Created {name}',
diff --git a/apps/docs/src/renderer/i18n/ai/es.ts b/apps/docs/src/renderer/i18n/ai/es.ts
index 06b2725..cbc63c1 100644
--- a/apps/docs/src/renderer/i18n/ai/es.ts
+++ b/apps/docs/src/renderer/i18n/ai/es.ts
@@ -127,6 +127,15 @@ export const es = {
aiSumReadBlocks: 'Leer bloques',
aiSumReadBlocksRange: 'Leer bloques {start}-{end}',
aiSumInsertContent: 'Insertar contenido',
+ aiSumWriteDocument: 'Contenido redactado',
+ aiSumWriteDocumentFailed: 'Falló la redacción',
+ aiSumWriteDocumentPartial: 'Contenido redactado parcialmente',
+ aiWritingDocument: 'Redactando el documento · {blocks} bloques',
+ aiPartialTitle: 'Solo se redactó parte del contenido',
+ aiPartialBody:
+ 'Llegaron {blocks} bloques antes de que la redacción se detuviera. ¿Conservar esta parte o descartarla?',
+ aiPartialAdopt: 'Conservar',
+ aiPartialDiscard: 'Descartar',
aiSumInsertedBlocks: '{count} bloque(s) insertado(s)',
aiSumCreateDocument: 'Crear documento nuevo',
aiSumCreatedDocument: '{name} creado',
diff --git a/apps/docs/src/renderer/i18n/ai/fr.ts b/apps/docs/src/renderer/i18n/ai/fr.ts
index bff5bfc..3b4301e 100644
--- a/apps/docs/src/renderer/i18n/ai/fr.ts
+++ b/apps/docs/src/renderer/i18n/ai/fr.ts
@@ -126,6 +126,15 @@ export const fr = {
aiSumReadBlocks: 'Lire les blocs',
aiSumReadBlocksRange: 'Lire les blocs {start}-{end}',
aiSumInsertContent: 'Insérer du contenu',
+ aiSumWriteDocument: 'Contenu rédigé',
+ aiSumWriteDocumentFailed: 'Échec de la rédaction',
+ aiSumWriteDocumentPartial: 'Contenu partiellement rédigé',
+ aiWritingDocument: 'Rédaction du document · {blocks} blocs',
+ aiPartialTitle: "Le contenu n'a été rédigé qu'en partie",
+ aiPartialBody:
+ "{blocks} blocs sont arrivés avant l'arrêt de la rédaction. Conserver cette partie ou l'abandonner ?",
+ aiPartialAdopt: 'Conserver',
+ aiPartialDiscard: 'Abandonner',
aiSumInsertedBlocks: '{count} bloc(s) inséré(s)',
aiSumCreateDocument: 'Créer un nouveau document',
aiSumCreatedDocument: '{name} créé',
diff --git a/apps/docs/src/renderer/i18n/ai/he.ts b/apps/docs/src/renderer/i18n/ai/he.ts
index 2c7ac09..e71b8ce 100644
--- a/apps/docs/src/renderer/i18n/ai/he.ts
+++ b/apps/docs/src/renderer/i18n/ai/he.ts
@@ -119,6 +119,14 @@ export const he = {
aiSumReadBlocks: 'קריאת בלוקים',
aiSumReadBlocksRange: 'קריאת בלוקים {start}-{end}',
aiSumInsertContent: 'הוספת תוכן',
+ aiSumWriteDocument: 'התוכן נכתב',
+ aiSumWriteDocumentFailed: 'הכתיבה נכשלה',
+ aiSumWriteDocumentPartial: 'נכתב חלק מהתוכן',
+ aiWritingDocument: 'כותב את המסמך · {blocks} בלוקים',
+ aiPartialTitle: 'נכתב רק חלק מהתוכן',
+ aiPartialBody: 'התקבלו {blocks} בלוקים לפני שהכתיבה נעצרה. לשמור את החלק הזה או להשליך?',
+ aiPartialAdopt: 'לשמור',
+ aiPartialDiscard: 'להשליך',
aiSumInsertedBlocks: 'הוספו {count} בלוקים',
aiSumCreateDocument: 'יצירת מסמך חדש',
aiSumCreatedDocument: '{name} נוצר',
diff --git a/apps/docs/src/renderer/i18n/ai/hi.ts b/apps/docs/src/renderer/i18n/ai/hi.ts
index 72f2c45..5104afa 100644
--- a/apps/docs/src/renderer/i18n/ai/hi.ts
+++ b/apps/docs/src/renderer/i18n/ai/hi.ts
@@ -124,6 +124,14 @@ export const hi = {
aiSumReadBlocks: 'ब्लॉक पढ़ें',
aiSumReadBlocksRange: 'ब्लॉक {start}-{end} पढ़ें',
aiSumInsertContent: 'सामग्री सम्मिलित करें',
+ aiSumWriteDocument: 'सामग्री लिख दी',
+ aiSumWriteDocumentFailed: 'लिखने में विफल',
+ aiSumWriteDocumentPartial: 'सामग्री का कुछ हिस्सा लिखा',
+ aiWritingDocument: 'दस्तावेज़ लिखा जा रहा है · {blocks} ब्लॉक',
+ aiPartialTitle: 'सामग्री का केवल एक हिस्सा लिखा गया',
+ aiPartialBody: 'लिखना रुकने से पहले {blocks} ब्लॉक मिले। इस हिस्से को रखें या छोड़ दें?',
+ aiPartialAdopt: 'रखें',
+ aiPartialDiscard: 'छोड़ें',
aiSumInsertedBlocks: '{count} ब्लॉक सम्मिलित किए गए',
aiSumCreateDocument: 'नया दस्तावेज़ बनाएँ',
aiSumCreatedDocument: '{name} बनाया गया',
diff --git a/apps/docs/src/renderer/i18n/ai/id.ts b/apps/docs/src/renderer/i18n/ai/id.ts
index 298a8a4..fae0a6c 100644
--- a/apps/docs/src/renderer/i18n/ai/id.ts
+++ b/apps/docs/src/renderer/i18n/ai/id.ts
@@ -124,6 +124,14 @@ export const id = {
aiSumReadBlocks: 'Baca blok',
aiSumReadBlocksRange: 'Baca blok {start}-{end}',
aiSumInsertContent: 'Sisipkan konten',
+ aiSumWriteDocument: 'Konten ditulis',
+ aiSumWriteDocumentFailed: 'Penulisan gagal',
+ aiSumWriteDocumentPartial: 'Sebagian konten ditulis',
+ aiWritingDocument: 'Menulis dokumen · {blocks} blok',
+ aiPartialTitle: 'Hanya sebagian konten yang ditulis',
+ aiPartialBody: '{blocks} blok diterima sebelum penulisan terhenti. Simpan bagian ini atau buang?',
+ aiPartialAdopt: 'Simpan',
+ aiPartialDiscard: 'Buang',
aiSumInsertedBlocks: '{count} blok disisipkan',
aiSumCreateDocument: 'Buat dokumen baru',
aiSumCreatedDocument: '{name} dibuat',
diff --git a/apps/docs/src/renderer/i18n/ai/it.ts b/apps/docs/src/renderer/i18n/ai/it.ts
index 3a9d5d7..c7447a1 100644
--- a/apps/docs/src/renderer/i18n/ai/it.ts
+++ b/apps/docs/src/renderer/i18n/ai/it.ts
@@ -128,6 +128,15 @@ export const it = {
aiSumReadBlocks: 'Lettura blocchi',
aiSumReadBlocksRange: 'Lettura blocchi {start}-{end}',
aiSumInsertContent: 'Inserisci contenuto',
+ aiSumWriteDocument: 'Contenuto scritto',
+ aiSumWriteDocumentFailed: 'Scrittura non riuscita',
+ aiSumWriteDocumentPartial: 'Contenuto scritto in parte',
+ aiWritingDocument: 'Scrittura del documento · {blocks} blocchi',
+ aiPartialTitle: 'È stata scritta solo una parte del contenuto',
+ aiPartialBody:
+ 'Sono arrivati {blocks} blocchi prima che la scrittura si interrompesse. Conservare questa parte o scartarla?',
+ aiPartialAdopt: 'Conserva',
+ aiPartialDiscard: 'Scarta',
aiSumInsertedBlocks: '{count} blocco/i inserito/i',
aiSumCreateDocument: 'Crea nuovo documento',
aiSumCreatedDocument: '{name} creato',
diff --git a/apps/docs/src/renderer/i18n/ai/ja.ts b/apps/docs/src/renderer/i18n/ai/ja.ts
index a1ded97..c09f0d1 100644
--- a/apps/docs/src/renderer/i18n/ai/ja.ts
+++ b/apps/docs/src/renderer/i18n/ai/ja.ts
@@ -124,6 +124,15 @@ export const ja = {
aiSumReadBlocks: 'ブロックを読み取り',
aiSumReadBlocksRange: 'ブロック {start}-{end} を読み取り',
aiSumInsertContent: 'コンテンツを挿入',
+ aiSumWriteDocument: '本文を作成しました',
+ aiSumWriteDocumentFailed: '本文の作成に失敗しました',
+ aiSumWriteDocumentPartial: '本文の一部を作成しました',
+ aiWritingDocument: '文書を作成中 · {blocks} ブロック',
+ aiPartialTitle: '本文の一部しか作成されませんでした',
+ aiPartialBody:
+ '{blocks} ブロックを受信した時点で作成が中断しました。この部分を採用しますか、破棄しますか?',
+ aiPartialAdopt: '採用',
+ aiPartialDiscard: '破棄',
aiSumInsertedBlocks: '{count} 個のブロックを挿入',
aiSumCreateDocument: '新規ドキュメントを作成',
aiSumCreatedDocument: '{name} を作成しました',
diff --git a/apps/docs/src/renderer/i18n/ai/ko.ts b/apps/docs/src/renderer/i18n/ai/ko.ts
index dfd9b95..f5c969f 100644
--- a/apps/docs/src/renderer/i18n/ai/ko.ts
+++ b/apps/docs/src/renderer/i18n/ai/ko.ts
@@ -122,6 +122,14 @@ export const ko = {
aiSumReadBlocks: '블록 읽기',
aiSumReadBlocksRange: '블록 {start}-{end} 읽기',
aiSumInsertContent: '내용 삽입',
+ aiSumWriteDocument: '본문을 작성했습니다',
+ aiSumWriteDocumentFailed: '본문 작성 실패',
+ aiSumWriteDocumentPartial: '본문 일부를 작성했습니다',
+ aiWritingDocument: '문서 작성 중 · {blocks}개 블록',
+ aiPartialTitle: '본문이 일부만 작성되었습니다',
+ aiPartialBody: '{blocks}개 블록을 받은 뒤 작성이 중단되었습니다. 이 부분을 사용할까요, 버릴까요?',
+ aiPartialAdopt: '사용',
+ aiPartialDiscard: '버리기',
aiSumInsertedBlocks: '블록 {count}개 삽입',
aiSumCreateDocument: '새 문서 만들기',
aiSumCreatedDocument: '{name} 생성됨',
diff --git a/apps/docs/src/renderer/i18n/ai/ms.ts b/apps/docs/src/renderer/i18n/ai/ms.ts
index c74e0cd..3fff201 100644
--- a/apps/docs/src/renderer/i18n/ai/ms.ts
+++ b/apps/docs/src/renderer/i18n/ai/ms.ts
@@ -124,6 +124,15 @@ export const ms = {
aiSumReadBlocks: 'Baca blok',
aiSumReadBlocksRange: 'Baca blok {start}-{end}',
aiSumInsertContent: 'Sisipkan kandungan',
+ aiSumWriteDocument: 'Kandungan ditulis',
+ aiSumWriteDocumentFailed: 'Penulisan gagal',
+ aiSumWriteDocumentPartial: 'Sebahagian kandungan ditulis',
+ aiWritingDocument: 'Menulis dokumen · {blocks} blok',
+ aiPartialTitle: 'Hanya sebahagian kandungan ditulis',
+ aiPartialBody:
+ '{blocks} blok diterima sebelum penulisan terhenti. Simpan bahagian ini atau buang?',
+ aiPartialAdopt: 'Simpan',
+ aiPartialDiscard: 'Buang',
aiSumInsertedBlocks: '{count} blok disisipkan',
aiSumCreateDocument: 'Cipta dokumen baharu',
aiSumCreatedDocument: '{name} dicipta',
diff --git a/apps/docs/src/renderer/i18n/ai/nl.ts b/apps/docs/src/renderer/i18n/ai/nl.ts
index 900aed7..cc75202 100644
--- a/apps/docs/src/renderer/i18n/ai/nl.ts
+++ b/apps/docs/src/renderer/i18n/ai/nl.ts
@@ -126,6 +126,15 @@ export const nl = {
aiSumReadBlocks: 'Blokken lezen',
aiSumReadBlocksRange: 'Blokken {start}-{end} lezen',
aiSumInsertContent: 'Inhoud invoegen',
+ aiSumWriteDocument: 'Inhoud geschreven',
+ aiSumWriteDocumentFailed: 'Schrijven mislukt',
+ aiSumWriteDocumentPartial: 'Inhoud gedeeltelijk geschreven',
+ aiWritingDocument: 'Document wordt geschreven · {blocks} blokken',
+ aiPartialTitle: 'Slechts een deel van de inhoud is geschreven',
+ aiPartialBody:
+ '{blocks} blokken kwamen aan voordat het schrijven stopte. Dit deel behouden of weggooien?',
+ aiPartialAdopt: 'Behouden',
+ aiPartialDiscard: 'Weggooien',
aiSumInsertedBlocks: '{count} blok(ken) ingevoegd',
aiSumCreateDocument: 'Nieuw document maken',
aiSumCreatedDocument: '{name} aangemaakt',
diff --git a/apps/docs/src/renderer/i18n/ai/pl.ts b/apps/docs/src/renderer/i18n/ai/pl.ts
index 9fb91da..c9bb2ae 100644
--- a/apps/docs/src/renderer/i18n/ai/pl.ts
+++ b/apps/docs/src/renderer/i18n/ai/pl.ts
@@ -125,6 +125,15 @@ export const pl = {
aiSumReadBlocks: 'Odczyt bloków',
aiSumReadBlocksRange: 'Odczyt bloków {start}-{end}',
aiSumInsertContent: 'Wstaw treść',
+ aiSumWriteDocument: 'Napisano treść',
+ aiSumWriteDocumentFailed: 'Pisanie nie powiodło się',
+ aiSumWriteDocumentPartial: 'Napisano część treści',
+ aiWritingDocument: 'Pisanie dokumentu · {blocks} bloków',
+ aiPartialTitle: 'Napisano tylko część treści',
+ aiPartialBody:
+ 'Dotarło {blocks} bloków, zanim pisanie zostało przerwane. Zachować tę część czy odrzucić?',
+ aiPartialAdopt: 'Zachowaj',
+ aiPartialDiscard: 'Odrzuć',
aiSumInsertedBlocks: 'Wstawiono bloków: {count}',
aiSumCreateDocument: 'Utwórz nowy dokument',
aiSumCreatedDocument: 'Utworzono {name}',
diff --git a/apps/docs/src/renderer/i18n/ai/pt.ts b/apps/docs/src/renderer/i18n/ai/pt.ts
index e20a63b..f03ca6b 100644
--- a/apps/docs/src/renderer/i18n/ai/pt.ts
+++ b/apps/docs/src/renderer/i18n/ai/pt.ts
@@ -127,6 +127,15 @@ export const pt = {
aiSumReadBlocks: 'Ler blocos',
aiSumReadBlocksRange: 'Ler blocos {start}-{end}',
aiSumInsertContent: 'Inserir conteúdo',
+ aiSumWriteDocument: 'Conteúdo escrito',
+ aiSumWriteDocumentFailed: 'Falha ao escrever',
+ aiSumWriteDocumentPartial: 'Conteúdo escrito parcialmente',
+ aiWritingDocument: 'Escrevendo o documento · {blocks} blocos',
+ aiPartialTitle: 'Apenas parte do conteúdo foi escrita',
+ aiPartialBody:
+ '{blocks} blocos chegaram antes de a escrita parar. Manter esta parte ou descartar?',
+ aiPartialAdopt: 'Manter',
+ aiPartialDiscard: 'Descartar',
aiSumInsertedBlocks: '{count} bloco(s) inserido(s)',
aiSumCreateDocument: 'Criar novo documento',
aiSumCreatedDocument: '{name} criado',
diff --git a/apps/docs/src/renderer/i18n/ai/ru.ts b/apps/docs/src/renderer/i18n/ai/ru.ts
index c16e733..02ca7e2 100644
--- a/apps/docs/src/renderer/i18n/ai/ru.ts
+++ b/apps/docs/src/renderer/i18n/ai/ru.ts
@@ -125,6 +125,15 @@ export const ru = {
aiSumReadBlocks: 'Чтение блоков',
aiSumReadBlocksRange: 'Чтение блоков {start}-{end}',
aiSumInsertContent: 'Вставка содержимого',
+ aiSumWriteDocument: 'Текст написан',
+ aiSumWriteDocumentFailed: 'Не удалось написать текст',
+ aiSumWriteDocumentPartial: 'Текст написан частично',
+ aiWritingDocument: 'Пишу документ · {blocks} блоков',
+ aiPartialTitle: 'Текст написан лишь частично',
+ aiPartialBody:
+ 'Получено {blocks} блоков, после чего написание прервалось. Оставить эту часть или отменить?',
+ aiPartialAdopt: 'Оставить',
+ aiPartialDiscard: 'Отменить',
aiSumInsertedBlocks: 'Вставлено блоков: {count}',
aiSumCreateDocument: 'Создание нового документа',
aiSumCreatedDocument: 'Создан {name}',
diff --git a/apps/docs/src/renderer/i18n/ai/th.ts b/apps/docs/src/renderer/i18n/ai/th.ts
index 845de8a..37203e8 100644
--- a/apps/docs/src/renderer/i18n/ai/th.ts
+++ b/apps/docs/src/renderer/i18n/ai/th.ts
@@ -122,6 +122,14 @@ export const th = {
aiSumReadBlocks: 'อ่านบล็อก',
aiSumReadBlocksRange: 'อ่านบล็อก {start}-{end}',
aiSumInsertContent: 'แทรกเนื้อหา',
+ aiSumWriteDocument: 'เขียนเนื้อหาแล้ว',
+ aiSumWriteDocumentFailed: 'เขียนเนื้อหาไม่สำเร็จ',
+ aiSumWriteDocumentPartial: 'เขียนเนื้อหาได้บางส่วน',
+ aiWritingDocument: 'กำลังเขียนเอกสาร · {blocks} บล็อก',
+ aiPartialTitle: 'เขียนเนื้อหาได้เพียงบางส่วน',
+ aiPartialBody: 'ได้รับ {blocks} บล็อกก่อนที่การเขียนจะหยุดลง ต้องการเก็บส่วนนี้ไว้หรือทิ้ง?',
+ aiPartialAdopt: 'เก็บไว้',
+ aiPartialDiscard: 'ทิ้ง',
aiSumInsertedBlocks: 'แทรก {count} บล็อก',
aiSumCreateDocument: 'สร้างเอกสารใหม่',
aiSumCreatedDocument: 'สร้าง {name} แล้ว',
diff --git a/apps/docs/src/renderer/i18n/ai/zh-TW.ts b/apps/docs/src/renderer/i18n/ai/zh-TW.ts
index 81871c3..089affe 100644
--- a/apps/docs/src/renderer/i18n/ai/zh-TW.ts
+++ b/apps/docs/src/renderer/i18n/ai/zh-TW.ts
@@ -117,6 +117,14 @@ export const zhTW = {
aiSumReadBlocks: '讀取區塊內容',
aiSumReadBlocksRange: '讀取區塊 {start}-{end}',
aiSumInsertContent: '插入內容',
+ aiSumWriteDocument: '撰寫文件',
+ aiSumWriteDocumentFailed: '文件撰寫失敗',
+ aiSumWriteDocumentPartial: '文件只撰寫了一部分',
+ aiWritingDocument: '正在撰寫文件 · {blocks} 塊',
+ aiPartialTitle: '內容只產生了一部分',
+ aiPartialBody: '已收到 {blocks} 個內容區塊,產生中斷了。採用這部分,還是放棄?',
+ aiPartialAdopt: '採用',
+ aiPartialDiscard: '放棄',
aiSumInsertedBlocks: '插入 {count} 個區塊',
aiSumCreateDocument: '建立新文件',
aiSumCreatedDocument: '已建立 {name}',
diff --git a/apps/docs/src/renderer/i18n/ai/zh.ts b/apps/docs/src/renderer/i18n/ai/zh.ts
index ae3562a..ee9a915 100644
--- a/apps/docs/src/renderer/i18n/ai/zh.ts
+++ b/apps/docs/src/renderer/i18n/ai/zh.ts
@@ -115,6 +115,14 @@ export const zh = {
aiSumReadBlocks: '读取块内容',
aiSumReadBlocksRange: '读取块 {start}-{end}',
aiSumInsertContent: '插入内容',
+ aiSumWriteDocument: '撰写文档',
+ aiSumWriteDocumentFailed: '文档撰写失败',
+ aiSumWriteDocumentPartial: '文档只撰写了一部分',
+ aiWritingDocument: '正在撰写文档 · {blocks} 块',
+ aiPartialTitle: '内容只生成了一部分',
+ aiPartialBody: '已收到 {blocks} 个内容块,生成中断了。采用这部分,还是放弃?',
+ aiPartialAdopt: '采用',
+ aiPartialDiscard: '放弃',
aiSumInsertedBlocks: '插入 {count} 个块',
aiSumCreateDocument: '新建文档',
aiSumCreatedDocument: '已创建 {name}',
diff --git a/apps/docs/src/renderer/i18n/app/ar.ts b/apps/docs/src/renderer/i18n/app/ar.ts
index a125677..7178a15 100644
--- a/apps/docs/src/renderer/i18n/app/ar.ts
+++ b/apps/docs/src/renderer/i18n/app/ar.ts
@@ -245,6 +245,11 @@ export const ar = {
appCopy: 'نسخ',
appPaste: 'لصق',
appPastePlain: 'لصق كنص عادي',
+ appPasteOptions: 'خيارات اللصق',
+ appPasteKeepSource: 'الاحتفاظ بتنسيق المصدر',
+ appPasteMergeFormat: 'دمج التنسيق',
+ appPasteTextOnly: 'الاحتفاظ بالنص فقط',
+ appPasteRememberDefault: 'استخدام هذا الخيار دائمًا',
appFontMenu: 'الخط…',
appParagraphMenu: 'فقرة…',
appUpdateField: 'تحديث الحقل',
diff --git a/apps/docs/src/renderer/i18n/app/cs.ts b/apps/docs/src/renderer/i18n/app/cs.ts
index 14bffd4..96737b2 100644
--- a/apps/docs/src/renderer/i18n/app/cs.ts
+++ b/apps/docs/src/renderer/i18n/app/cs.ts
@@ -248,6 +248,11 @@ export const cs = {
appCopy: 'Kopírovat',
appPaste: 'Vložit',
appPastePlain: 'Vložit jako prostý text',
+ appPasteOptions: 'Možnosti vložení',
+ appPasteKeepSource: 'Zachovat zdrojové formátování',
+ appPasteMergeFormat: 'Sloučit formátování',
+ appPasteTextOnly: 'Zachovat pouze text',
+ appPasteRememberDefault: 'Vždy použít tuto volbu',
appFontMenu: 'Písmo…',
appParagraphMenu: 'Odstavec…',
appUpdateField: 'Aktualizovat pole',
diff --git a/apps/docs/src/renderer/i18n/app/de.ts b/apps/docs/src/renderer/i18n/app/de.ts
index 250f6f8..cff8cc3 100644
--- a/apps/docs/src/renderer/i18n/app/de.ts
+++ b/apps/docs/src/renderer/i18n/app/de.ts
@@ -258,6 +258,11 @@ export const de = {
appCopy: 'Kopieren',
appPaste: 'Einfügen',
appPastePlain: 'Als unformatierten Text einfügen',
+ appPasteOptions: 'Einfügeoptionen',
+ appPasteKeepSource: 'Ursprüngliche Formatierung beibehalten',
+ appPasteMergeFormat: 'Formatierung zusammenführen',
+ appPasteTextOnly: 'Nur den Text übernehmen',
+ appPasteRememberDefault: 'Immer diese Auswahl verwenden',
appFontMenu: 'Schriftart…',
appParagraphMenu: 'Absatz…',
appUpdateField: 'Feld aktualisieren',
diff --git a/apps/docs/src/renderer/i18n/app/en.ts b/apps/docs/src/renderer/i18n/app/en.ts
index 7a771f6..3665c68 100644
--- a/apps/docs/src/renderer/i18n/app/en.ts
+++ b/apps/docs/src/renderer/i18n/app/en.ts
@@ -244,6 +244,11 @@ export const en = {
appCopy: 'Copy',
appPaste: 'Paste',
appPastePlain: 'Paste as Plain Text',
+ appPasteOptions: 'Paste Options',
+ appPasteKeepSource: 'Keep Source Formatting',
+ appPasteMergeFormat: 'Merge Formatting',
+ appPasteTextOnly: 'Keep Text Only',
+ appPasteRememberDefault: 'Always use this choice',
appFontMenu: 'Font…',
appParagraphMenu: 'Paragraph…',
appUpdateField: 'Update Field',
diff --git a/apps/docs/src/renderer/i18n/app/es.ts b/apps/docs/src/renderer/i18n/app/es.ts
index 21de1a0..28a4b4c 100644
--- a/apps/docs/src/renderer/i18n/app/es.ts
+++ b/apps/docs/src/renderer/i18n/app/es.ts
@@ -254,6 +254,11 @@ export const es = {
appCopy: 'Copiar',
appPaste: 'Pegar',
appPastePlain: 'Pegar como texto sin formato',
+ appPasteOptions: 'Opciones de pegado',
+ appPasteKeepSource: 'Mantener formato de origen',
+ appPasteMergeFormat: 'Combinar formato',
+ appPasteTextOnly: 'Mantener solo texto',
+ appPasteRememberDefault: 'Usar siempre esta opción',
appFontMenu: 'Fuente…',
appParagraphMenu: 'Párrafo…',
appUpdateField: 'Actualizar campo',
diff --git a/apps/docs/src/renderer/i18n/app/fr.ts b/apps/docs/src/renderer/i18n/app/fr.ts
index 867eaf9..86b7bfe 100644
--- a/apps/docs/src/renderer/i18n/app/fr.ts
+++ b/apps/docs/src/renderer/i18n/app/fr.ts
@@ -258,6 +258,11 @@ export const fr = {
appCopy: 'Copier',
appPaste: 'Coller',
appPastePlain: 'Coller en texte brut',
+ appPasteOptions: 'Options de collage',
+ appPasteKeepSource: 'Conserver la mise en forme source',
+ appPasteMergeFormat: 'Fusionner la mise en forme',
+ appPasteTextOnly: 'Conserver le texte uniquement',
+ appPasteRememberDefault: 'Toujours utiliser ce choix',
appFontMenu: 'Police…',
appParagraphMenu: 'Paragraphe…',
appUpdateField: 'Mettre à jour le champ',
diff --git a/apps/docs/src/renderer/i18n/app/he.ts b/apps/docs/src/renderer/i18n/app/he.ts
index 9f367c7..b3fd720 100644
--- a/apps/docs/src/renderer/i18n/app/he.ts
+++ b/apps/docs/src/renderer/i18n/app/he.ts
@@ -243,6 +243,11 @@ export const he = {
appCopy: 'העתקה',
appPaste: 'הדבקה',
appPastePlain: 'הדבקה כטקסט רגיל',
+ appPasteOptions: 'אפשרויות הדבקה',
+ appPasteKeepSource: 'שמור על עיצוב המקור',
+ appPasteMergeFormat: 'מזג עיצוב',
+ appPasteTextOnly: 'שמור טקסט בלבד',
+ appPasteRememberDefault: 'השתמש תמיד בבחירה זו',
appFontMenu: 'גופן…',
appParagraphMenu: 'פסקה…',
appUpdateField: 'עדכון שדה',
diff --git a/apps/docs/src/renderer/i18n/app/hi.ts b/apps/docs/src/renderer/i18n/app/hi.ts
index 1cf0e03..d8f7ce4 100644
--- a/apps/docs/src/renderer/i18n/app/hi.ts
+++ b/apps/docs/src/renderer/i18n/app/hi.ts
@@ -248,6 +248,11 @@ export const hi = {
appCopy: 'कॉपी करें',
appPaste: 'चिपकाएँ',
appPastePlain: 'सादे टेक्स्ट के रूप में चिपकाएँ',
+ appPasteOptions: 'चिपकाने के विकल्प',
+ appPasteKeepSource: 'स्रोत स्वरूपण बनाए रखें',
+ appPasteMergeFormat: 'स्वरूपण मर्ज करें',
+ appPasteTextOnly: 'केवल पाठ रखें',
+ appPasteRememberDefault: 'हमेशा यही विकल्प उपयोग करें',
appFontMenu: 'फ़ॉन्ट…',
appParagraphMenu: 'अनुच्छेद…',
appUpdateField: 'फ़ील्ड अपडेट करें',
diff --git a/apps/docs/src/renderer/i18n/app/id.ts b/apps/docs/src/renderer/i18n/app/id.ts
index 17970b9..0b28e9d 100644
--- a/apps/docs/src/renderer/i18n/app/id.ts
+++ b/apps/docs/src/renderer/i18n/app/id.ts
@@ -250,6 +250,11 @@ export const id = {
appCopy: 'Salin',
appPaste: 'Tempel',
appPastePlain: 'Tempel sebagai Teks Biasa',
+ appPasteOptions: 'Opsi Tempel',
+ appPasteKeepSource: 'Pertahankan Format Sumber',
+ appPasteMergeFormat: 'Gabungkan Format',
+ appPasteTextOnly: 'Pertahankan Teks Saja',
+ appPasteRememberDefault: 'Selalu gunakan pilihan ini',
appFontMenu: 'Font…',
appParagraphMenu: 'Paragraf…',
appUpdateField: 'Perbarui Bidang',
diff --git a/apps/docs/src/renderer/i18n/app/it.ts b/apps/docs/src/renderer/i18n/app/it.ts
index 6a9c735..cf2c414 100644
--- a/apps/docs/src/renderer/i18n/app/it.ts
+++ b/apps/docs/src/renderer/i18n/app/it.ts
@@ -252,6 +252,11 @@ export const it = {
appCopy: 'Copia',
appPaste: 'Incolla',
appPastePlain: 'Incolla come testo normale',
+ appPasteOptions: 'Opzioni Incolla',
+ appPasteKeepSource: 'Mantieni formattazione originale',
+ appPasteMergeFormat: 'Unisci formattazione',
+ appPasteTextOnly: 'Mantieni solo il testo',
+ appPasteRememberDefault: 'Usa sempre questa scelta',
appFontMenu: 'Carattere…',
appParagraphMenu: 'Paragrafo…',
appUpdateField: 'Aggiorna campo',
diff --git a/apps/docs/src/renderer/i18n/app/ja.ts b/apps/docs/src/renderer/i18n/app/ja.ts
index ea1fea5..a60a97b 100644
--- a/apps/docs/src/renderer/i18n/app/ja.ts
+++ b/apps/docs/src/renderer/i18n/app/ja.ts
@@ -269,6 +269,11 @@ export const ja = {
appCopy: 'コピー',
appPaste: '貼り付け',
appPastePlain: 'テキストのみ保持して貼り付け',
+ appPasteOptions: '貼り付けのオプション',
+ appPasteKeepSource: '元の書式を保持',
+ appPasteMergeFormat: '書式を結合',
+ appPasteTextOnly: 'テキストのみ保持',
+ appPasteRememberDefault: '常にこの設定を使用',
appFontMenu: 'フォント…',
appParagraphMenu: '段落…',
appUpdateField: 'フィールド更新',
diff --git a/apps/docs/src/renderer/i18n/app/ko.ts b/apps/docs/src/renderer/i18n/app/ko.ts
index 1e43f70..1e5ed24 100644
--- a/apps/docs/src/renderer/i18n/app/ko.ts
+++ b/apps/docs/src/renderer/i18n/app/ko.ts
@@ -269,6 +269,11 @@ export const ko = {
appCopy: '복사',
appPaste: '붙여넣기',
appPastePlain: '텍스트만 붙여넣기',
+ appPasteOptions: '붙여넣기 옵션',
+ appPasteKeepSource: '원본 서식 유지',
+ appPasteMergeFormat: '서식 병합',
+ appPasteTextOnly: '텍스트만 유지',
+ appPasteRememberDefault: '항상 이 선택 사용',
appFontMenu: '글꼴…',
appParagraphMenu: '단락…',
appUpdateField: '필드 업데이트',
diff --git a/apps/docs/src/renderer/i18n/app/ms.ts b/apps/docs/src/renderer/i18n/app/ms.ts
index 9307922..2859ea9 100644
--- a/apps/docs/src/renderer/i18n/app/ms.ts
+++ b/apps/docs/src/renderer/i18n/app/ms.ts
@@ -252,6 +252,11 @@ export const ms = {
appCopy: 'Salin',
appPaste: 'Tampal',
appPastePlain: 'Tampal sebagai Teks Biasa',
+ appPasteOptions: 'Pilihan Tampal',
+ appPasteKeepSource: 'Kekalkan Pemformatan Sumber',
+ appPasteMergeFormat: 'Gabungkan Pemformatan',
+ appPasteTextOnly: 'Kekalkan Teks Sahaja',
+ appPasteRememberDefault: 'Sentiasa guna pilihan ini',
appFontMenu: 'Fon…',
appParagraphMenu: 'Perenggan…',
appUpdateField: 'Kemas Kini Medan',
diff --git a/apps/docs/src/renderer/i18n/app/nl.ts b/apps/docs/src/renderer/i18n/app/nl.ts
index 5c99b12..da08617 100644
--- a/apps/docs/src/renderer/i18n/app/nl.ts
+++ b/apps/docs/src/renderer/i18n/app/nl.ts
@@ -258,6 +258,11 @@ export const nl = {
appCopy: 'Kopiëren',
appPaste: 'Plakken',
appPastePlain: 'Plakken als platte tekst',
+ appPasteOptions: 'Plakopties',
+ appPasteKeepSource: 'Opmaak van bron behouden',
+ appPasteMergeFormat: 'Opmaak samenvoegen',
+ appPasteTextOnly: 'Alleen tekst behouden',
+ appPasteRememberDefault: 'Altijd deze keuze gebruiken',
appFontMenu: 'Lettertype…',
appParagraphMenu: 'Alinea…',
appUpdateField: 'Veld bijwerken',
diff --git a/apps/docs/src/renderer/i18n/app/pl.ts b/apps/docs/src/renderer/i18n/app/pl.ts
index ba86f33..f569362 100644
--- a/apps/docs/src/renderer/i18n/app/pl.ts
+++ b/apps/docs/src/renderer/i18n/app/pl.ts
@@ -253,6 +253,11 @@ export const pl = {
appCopy: 'Kopiuj',
appPaste: 'Wklej',
appPastePlain: 'Wklej jako zwykły tekst',
+ appPasteOptions: 'Opcje wklejania',
+ appPasteKeepSource: 'Zachowaj formatowanie źródłowe',
+ appPasteMergeFormat: 'Scal formatowanie',
+ appPasteTextOnly: 'Zachowaj tylko tekst',
+ appPasteRememberDefault: 'Zawsze używaj tego wyboru',
appFontMenu: 'Czcionka…',
appParagraphMenu: 'Akapit…',
appUpdateField: 'Aktualizuj pole',
diff --git a/apps/docs/src/renderer/i18n/app/pt.ts b/apps/docs/src/renderer/i18n/app/pt.ts
index c10ce56..9dff2cb 100644
--- a/apps/docs/src/renderer/i18n/app/pt.ts
+++ b/apps/docs/src/renderer/i18n/app/pt.ts
@@ -249,6 +249,11 @@ export const pt = {
appCopy: 'Copiar',
appPaste: 'Colar',
appPastePlain: 'Colar como texto sem formatação',
+ appPasteOptions: 'Opções de Colagem',
+ appPasteKeepSource: 'Manter Formatação Original',
+ appPasteMergeFormat: 'Mesclar Formatação',
+ appPasteTextOnly: 'Manter Somente Texto',
+ appPasteRememberDefault: 'Usar sempre esta opção',
appFontMenu: 'Fonte…',
appParagraphMenu: 'Parágrafo…',
appUpdateField: 'Atualizar campo',
diff --git a/apps/docs/src/renderer/i18n/app/ru.ts b/apps/docs/src/renderer/i18n/app/ru.ts
index 3dab327..0acedc2 100644
--- a/apps/docs/src/renderer/i18n/app/ru.ts
+++ b/apps/docs/src/renderer/i18n/app/ru.ts
@@ -250,6 +250,11 @@ export const ru = {
appCopy: 'Копировать',
appPaste: 'Вставить',
appPastePlain: 'Вставить как обычный текст',
+ appPasteOptions: 'Параметры вставки',
+ appPasteKeepSource: 'Сохранить исходное форматирование',
+ appPasteMergeFormat: 'Объединить форматирование',
+ appPasteTextOnly: 'Сохранить только текст',
+ appPasteRememberDefault: 'Всегда использовать этот вариант',
appFontMenu: 'Шрифт…',
appParagraphMenu: 'Абзац…',
appUpdateField: 'Обновить поле',
diff --git a/apps/docs/src/renderer/i18n/app/th.ts b/apps/docs/src/renderer/i18n/app/th.ts
index 2dd5495..c7af8a8 100644
--- a/apps/docs/src/renderer/i18n/app/th.ts
+++ b/apps/docs/src/renderer/i18n/app/th.ts
@@ -248,6 +248,11 @@ export const th = {
appCopy: 'คัดลอก',
appPaste: 'วาง',
appPastePlain: 'วางเป็นข้อความธรรมดา',
+ appPasteOptions: 'ตัวเลือกการวาง',
+ appPasteKeepSource: 'คงการจัดรูปแบบต้นฉบับ',
+ appPasteMergeFormat: 'ผสานการจัดรูปแบบ',
+ appPasteTextOnly: 'เก็บข้อความเท่านั้น',
+ appPasteRememberDefault: 'ใช้ตัวเลือกนี้เสมอ',
appFontMenu: 'ฟอนต์…',
appParagraphMenu: 'ย่อหน้า…',
appUpdateField: 'อัปเดตเขตข้อมูล',
diff --git a/apps/docs/src/renderer/i18n/app/zh-TW.ts b/apps/docs/src/renderer/i18n/app/zh-TW.ts
index 7907708..e8fc0e9 100644
--- a/apps/docs/src/renderer/i18n/app/zh-TW.ts
+++ b/apps/docs/src/renderer/i18n/app/zh-TW.ts
@@ -238,6 +238,11 @@ export const zhTW = {
appCopy: '複製',
appPaste: '貼上',
appPastePlain: '貼上為純文字',
+ appPasteOptions: '貼上選項',
+ appPasteKeepSource: '保留來源格式設定',
+ appPasteMergeFormat: '合併格式設定',
+ appPasteTextOnly: '只保留文字',
+ appPasteRememberDefault: '一律使用此選項',
appFontMenu: '字型…',
appParagraphMenu: '段落…',
appUpdateField: '更新功能變數',
diff --git a/apps/docs/src/renderer/i18n/app/zh.ts b/apps/docs/src/renderer/i18n/app/zh.ts
index ea6ec5e..143a9f6 100644
--- a/apps/docs/src/renderer/i18n/app/zh.ts
+++ b/apps/docs/src/renderer/i18n/app/zh.ts
@@ -258,6 +258,11 @@ export const zh = {
appCopy: '复制',
appPaste: '粘贴',
appPastePlain: '粘贴为纯文本',
+ appPasteOptions: '粘贴选项',
+ appPasteKeepSource: '保留源格式',
+ appPasteMergeFormat: '合并格式',
+ appPasteTextOnly: '仅保留文本',
+ appPasteRememberDefault: '始终使用此选项',
appFontMenu: '字体…',
appParagraphMenu: '段落…',
appUpdateField: '更新域',
diff --git a/apps/docs/src/renderer/i18n/strings-zotero.ts b/apps/docs/src/renderer/i18n/strings-zotero.ts
index 0a1277f..14409cb 100644
--- a/apps/docs/src/renderer/i18n/strings-zotero.ts
+++ b/apps/docs/src/renderer/i18n/strings-zotero.ts
@@ -15,6 +15,8 @@ export const zoteroStrings = defineStrings({
zoteroRemoveCodes: '移除域代码',
zoteroConnectionError: '无法连接 Zotero。请先启动 Zotero,并保持桌面程序运行。',
zoteroOperationError: 'Zotero 操作失败。',
+ zoteroNoteFieldsUnsupported:
+ '此文档的脚注或尾注中含有 Zotero 引文,GenOffice 目前还不能更新它们。为保持参考文献表完整,已停用此文档的 Zotero 命令。',
zoteroGroup: 'Zotero',
},
en: {
@@ -30,6 +32,8 @@ export const zoteroStrings = defineStrings({
zoteroRemoveCodes: 'Remove Field Codes',
zoteroConnectionError: 'Unable to connect to Zotero. Start Zotero and keep it running.',
zoteroOperationError: 'The Zotero operation failed.',
+ zoteroNoteFieldsUnsupported:
+ 'This document has Zotero citations in footnotes or endnotes, which GenOffice cannot update yet. Zotero commands are turned off here so the bibliography stays intact.',
zoteroGroup: 'Zotero',
},
ja: {
@@ -45,6 +49,8 @@ export const zoteroStrings = defineStrings({
zoteroRemoveCodes: 'フィールドコードを削除',
zoteroConnectionError: 'Zotero に接続できません。Zotero を起動したままにしてください。',
zoteroOperationError: 'Zotero の操作に失敗しました。',
+ zoteroNoteFieldsUnsupported:
+ 'この文書の脚注または文末脚注に Zotero の引用が含まれていますが、GenOffice はまだ更新できません。参考文献一覧を保つため、この文書では Zotero コマンドを無効にしています。',
zoteroGroup: 'Zotero',
},
ko: {
@@ -60,6 +66,8 @@ export const zoteroStrings = defineStrings({
zoteroRemoveCodes: '필드 코드 제거',
zoteroConnectionError: 'Zotero에 연결할 수 없습니다. Zotero를 실행한 상태로 유지하세요.',
zoteroOperationError: 'Zotero 작업에 실패했습니다.',
+ zoteroNoteFieldsUnsupported:
+ '이 문서의 각주 또는 미주에 Zotero 인용이 있으며 GenOffice는 아직 이를 업데이트할 수 없습니다. 참고문헌을 그대로 유지하기 위해 이 문서에서는 Zotero 명령이 비활성화되었습니다.',
zoteroGroup: 'Zotero',
},
fr: {
@@ -77,6 +85,8 @@ export const zoteroStrings = defineStrings({
zoteroConnectionError:
'Impossible de se connecter à Zotero. Démarrez Zotero et laissez-le ouvert.',
zoteroOperationError: "L'opération Zotero a échoué.",
+ zoteroNoteFieldsUnsupported:
+ 'Ce document contient des citations Zotero dans les notes de bas de page ou de fin, que GenOffice ne peut pas encore mettre à jour. Les commandes Zotero sont désactivées ici afin de préserver la bibliographie.',
zoteroGroup: 'Zotero',
},
de: {
@@ -93,6 +103,8 @@ export const zoteroStrings = defineStrings({
zoteroConnectionError:
'Verbindung mit Zotero nicht möglich. Starten Sie Zotero und lassen Sie es geöffnet.',
zoteroOperationError: 'Der Zotero-Vorgang ist fehlgeschlagen.',
+ zoteroNoteFieldsUnsupported:
+ 'Dieses Dokument enthält Zotero-Zitate in Fuß- oder Endnoten, die GenOffice noch nicht aktualisieren kann. Die Zotero-Befehle sind hier deaktiviert, damit das Literaturverzeichnis intakt bleibt.',
zoteroGroup: 'Zotero',
},
es: {
@@ -108,6 +120,8 @@ export const zoteroStrings = defineStrings({
zoteroRemoveCodes: 'Eliminar códigos de campo',
zoteroConnectionError: 'No se puede conectar con Zotero. Inicie Zotero y manténgalo abierto.',
zoteroOperationError: 'La operación de Zotero ha fallado.',
+ zoteroNoteFieldsUnsupported:
+ 'Este documento tiene citas de Zotero en notas al pie o al final que GenOffice aún no puede actualizar. Los comandos de Zotero están desactivados aquí para mantener intacta la bibliografía.',
zoteroGroup: 'Zotero',
},
th: {
@@ -123,6 +137,8 @@ export const zoteroStrings = defineStrings({
zoteroRemoveCodes: 'ลบรหัสเขตข้อมูล',
zoteroConnectionError: 'ไม่สามารถเชื่อมต่อกับ Zotero ได้ โปรดเปิด Zotero ทิ้งไว้',
zoteroOperationError: 'การดำเนินการ Zotero ล้มเหลว',
+ zoteroNoteFieldsUnsupported:
+ 'เอกสารนี้มีการอ้างอิง Zotero ในเชิงอรรถหรืออ้างอิงท้ายเรื่อง ซึ่ง GenOffice ยังอัปเดตไม่ได้ คำสั่ง Zotero จึงถูกปิดไว้เพื่อรักษาบรรณานุกรมให้ครบถ้วน',
zoteroGroup: 'Zotero',
},
id: {
@@ -140,6 +156,8 @@ export const zoteroStrings = defineStrings({
zoteroConnectionError:
'Tidak dapat terhubung ke Zotero. Jalankan Zotero dan biarkan tetap terbuka.',
zoteroOperationError: 'Operasi Zotero gagal.',
+ zoteroNoteFieldsUnsupported:
+ 'Dokumen ini memiliki sitasi Zotero di catatan kaki atau catatan akhir yang belum dapat diperbarui GenOffice. Perintah Zotero dinonaktifkan di sini agar daftar pustaka tetap utuh.',
zoteroGroup: 'Zotero',
},
ru: {
@@ -156,6 +174,8 @@ export const zoteroStrings = defineStrings({
zoteroConnectionError:
'Не удалось подключиться к Zotero. Запустите Zotero и оставьте его открытым.',
zoteroOperationError: 'Операция Zotero завершилась с ошибкой.',
+ zoteroNoteFieldsUnsupported:
+ 'В сносках или концевых сносках этого документа есть цитаты Zotero, которые GenOffice пока не может обновлять. Команды Zotero здесь отключены, чтобы библиография осталась целой.',
zoteroGroup: 'Zotero',
},
ar: {
@@ -171,6 +191,8 @@ export const zoteroStrings = defineStrings({
zoteroRemoveCodes: 'إزالة رموز الحقول',
zoteroConnectionError: 'تعذر الاتصال بـ Zotero. شغّل Zotero واتركه مفتوحًا.',
zoteroOperationError: 'فشلت عملية Zotero.',
+ zoteroNoteFieldsUnsupported:
+ 'يحتوي هذا المستند على استشهادات Zotero في الحواشي السفلية أو الختامية، ولا يستطيع GenOffice تحديثها بعد. تم تعطيل أوامر Zotero هنا للحفاظ على قائمة المراجع سليمة.',
zoteroGroup: 'Zotero',
},
pt: {
@@ -187,6 +209,8 @@ export const zoteroStrings = defineStrings({
zoteroConnectionError:
'Não foi possível conectar ao Zotero. Inicie o Zotero e mantenha-o aberto.',
zoteroOperationError: 'A operação do Zotero falhou.',
+ zoteroNoteFieldsUnsupported:
+ 'Este documento tem citações do Zotero em notas de rodapé ou de fim que o GenOffice ainda não consegue atualizar. Os comandos do Zotero estão desativados aqui para manter a bibliografia intacta.',
zoteroGroup: 'Zotero',
},
it: {
@@ -203,6 +227,8 @@ export const zoteroStrings = defineStrings({
zoteroRemoveCodes: 'Rimuovi codici di campo',
zoteroConnectionError: 'Impossibile connettersi a Zotero. Avvia Zotero e lascialo aperto.',
zoteroOperationError: "L'operazione Zotero non è riuscita.",
+ zoteroNoteFieldsUnsupported:
+ 'Questo documento contiene citazioni Zotero nelle note a piè di pagina o di chiusura, che GenOffice non può ancora aggiornare. I comandi Zotero sono disattivati qui per mantenere intatta la bibliografia.',
zoteroGroup: 'Zotero',
},
pl: {
@@ -218,6 +244,8 @@ export const zoteroStrings = defineStrings({
zoteroRemoveCodes: 'Usuń kody pól',
zoteroConnectionError: 'Nie można połączyć się z Zotero. Uruchom Zotero i pozostaw je otwarte.',
zoteroOperationError: 'Operacja Zotero nie powiodła się.',
+ zoteroNoteFieldsUnsupported:
+ 'Ten dokument zawiera cytowania Zotero w przypisach dolnych lub końcowych, których GenOffice nie potrafi jeszcze aktualizować. Polecenia Zotero są tu wyłączone, aby bibliografia pozostała nienaruszona.',
zoteroGroup: 'Zotero',
},
cs: {
@@ -233,6 +261,8 @@ export const zoteroStrings = defineStrings({
zoteroRemoveCodes: 'Odebrat kódy polí',
zoteroConnectionError: 'K Zoteru se nelze připojit. Spusťte Zotero a nechte je otevřené.',
zoteroOperationError: 'Operace Zotero se nezdařila.',
+ zoteroNoteFieldsUnsupported:
+ 'Tento dokument obsahuje citace Zotero v poznámkách pod čarou nebo vysvětlivkách, které GenOffice zatím neumí aktualizovat. Příkazy Zotero jsou zde vypnuté, aby bibliografie zůstala nedotčená.',
zoteroGroup: 'Zotero',
},
nl: {
@@ -250,6 +280,8 @@ export const zoteroStrings = defineStrings({
zoteroConnectionError:
'Kan geen verbinding maken met Zotero. Start Zotero en laat het geopend.',
zoteroOperationError: 'De Zotero-bewerking is mislukt.',
+ zoteroNoteFieldsUnsupported:
+ 'Dit document bevat Zotero-citaties in voet- of eindnoten die GenOffice nog niet kan bijwerken. Zotero-opdrachten zijn hier uitgeschakeld zodat de bibliografie intact blijft.',
zoteroGroup: 'Zotero',
},
ms: {
@@ -267,6 +299,8 @@ export const zoteroStrings = defineStrings({
zoteroConnectionError:
'Tidak dapat menyambung ke Zotero. Mulakan Zotero dan biarkannya terbuka.',
zoteroOperationError: 'Operasi Zotero gagal.',
+ zoteroNoteFieldsUnsupported:
+ 'Dokumen ini mempunyai petikan Zotero dalam nota kaki atau nota hujung yang belum boleh dikemas kini oleh GenOffice. Perintah Zotero dimatikan di sini supaya bibliografi kekal utuh.',
zoteroGroup: 'Zotero',
},
he: {
@@ -282,6 +316,8 @@ export const zoteroStrings = defineStrings({
zoteroRemoveCodes: 'הסרת קודי שדה',
zoteroConnectionError: 'לא ניתן להתחבר ל-Zotero. יש להפעיל את Zotero ולהשאיר אותו פתוח.',
zoteroOperationError: 'פעולת Zotero נכשלה.',
+ zoteroNoteFieldsUnsupported:
+ 'מסמך זה מכיל ציטוטים של Zotero בהערות שוליים או הערות סיום, ש-GenOffice עדיין אינו יכול לעדכן. פקודות Zotero מושבתות כאן כדי לשמור על הביבליוגרפיה שלמה.',
zoteroGroup: 'Zotero',
},
hi: {
@@ -297,6 +333,8 @@ export const zoteroStrings = defineStrings({
zoteroRemoveCodes: 'फ़ील्ड कोड हटाएँ',
zoteroConnectionError: 'Zotero से कनेक्ट नहीं हो सका। Zotero शुरू करें और उसे खुला रखें।',
zoteroOperationError: 'Zotero कार्रवाई विफल रही।',
+ zoteroNoteFieldsUnsupported:
+ 'इस दस्तावेज़ के फ़ुटनोट या एंडनोट में Zotero उद्धरण हैं, जिन्हें GenOffice अभी अपडेट नहीं कर सकता। ग्रंथसूची को सुरक्षित रखने के लिए यहाँ Zotero कमांड बंद हैं।',
zoteroGroup: 'Zotero',
},
'zh-TW': {
@@ -312,6 +350,8 @@ export const zoteroStrings = defineStrings({
zoteroRemoveCodes: '移除欄位代碼',
zoteroConnectionError: '無法連線至 Zotero。請先啟動 Zotero,並保持桌面程式執行。',
zoteroOperationError: 'Zotero 操作失敗。',
+ zoteroNoteFieldsUnsupported:
+ '此文件的註腳或章節附註中含有 Zotero 引文,GenOffice 目前還無法更新它們。為保持參考文獻完整,已停用此文件的 Zotero 命令。',
zoteroGroup: 'Zotero',
},
})
diff --git a/apps/docs/src/renderer/line-metrics.ts b/apps/docs/src/renderer/line-metrics.ts
index 3967488..296b28d 100644
--- a/apps/docs/src/renderer/line-metrics.ts
+++ b/apps/docs/src/renderer/line-metrics.ts
@@ -186,8 +186,26 @@ const KO_FONT_RE =
* 1.7371, Meiryo 1.9429, YaHei 1.7143, Yu 1.44) instead of the macOS
* substitutes LO measured. Unprobed names keep their LO values until probed.
*/
+/** Word's own symbol faces (Office DFonts symbol.ttf 5.00i, Wingdings 5.03,
+ * Webdings 5.00), hhea = win totals over 2048: Symbol 2059+450, Wingdings
+ * 1841+432, Wingdings 2 1727+432, Wingdings 3 1900+432, Webdings 1638+410.
+ * Word row pitch 16.33px @10pt on a regression sample = the
+ * Symbol run (the macOS Symbol.ttf, 1436+612, is not what Word lays out with) */
+const SYMBOL_FACE_FACTORS: Record = {
+ symbol: 1.2251,
+ wingdings: 1.1099,
+ 'wingdings 2': 1.0542,
+ 'wingdings 3': 1.1387,
+ webdings: 1.0,
+}
+
+/** Segoe UI text family (not the Emoji/Symbol/Historic/Print/Script cuts) */
+const SEGOE_UI_TEXT_RE = /^segoe ui( (light|semilight|semibold|black|variable))?$/
+
export function lineHeightFactor(fontFamily: string): number {
const f = fontFamily.toLowerCase()
+ const symbolFace = SYMBOL_FACE_FACTORS[f.trim()]
+ if (symbolFace !== undefined) return symbolFace
// Aptos (M365 cloud face): Word probe 2026-08-22 measured 1.22, same as Calibri
if (f.includes('aptos')) return 1.22
// PMingLiU/MingLiU (Word probe: Office ships the real face at 1.3029)
@@ -205,7 +223,9 @@ export function lineHeightFactor(fontFamily: string): number {
// the KO_FONT_RE value below
if (/nanum ?myeongjo|나눔 ?명조/.test(f)) return 1.5
// Korean faces (Word probe 2026-08-13: Malgun 1.7371, Batang class 1.3029)
- if (KO_FONT_RE.test(f)) return /malgun|맑은/.test(f) ? 1.7371 : 1.3029
+ if (KO_FONT_RE.test(f)) {
+ return /malgun|맑은/.test(f) || krSansVariantSubstituted(fontFamily) ? 1.7371 : 1.3029
+ }
// Japanese faces: MS (P)Mincho/Gothic substitute into the Hiragino class
// (1.7); Meiryo 1.775. Yu Mincho/Gothic: Word probe 2026-08-13 measured
// exactly 1.44 at 10.5/12pt with Office's own yumin.ttf (the old 2.2667 was
@@ -316,6 +336,10 @@ export function lineHeightFactor(fontFamily: string): number {
if (f.includes('century') && !f.includes('gothic')) return 1.206
// Book Antiqua ships with Office (probe 2026-08-23; the old 1.1 was LO-era)
if (f.includes('book antiqua')) return 1.21
+ // Segoe UI text cuts are M365 cloud fonts Word downloads and renders real:
+ // hhea 2210/514/0 over 2048, Word PDF pitch 15.96pt @12pt (probe 2026-09-11);
+ // the symbol/emoji and script cuts keep the old value
+ if (SEGOE_UI_TEXT_RE.test(f)) return 1.3301
if (f.includes('segoe')) return 1.15
if (/nyala|ebrima|abyssinica|ethiopic/.test(f)) return 1.0514
// Tamil faces: Word renders missing Noto Sans Tamil / Latha with Latha
@@ -325,6 +349,9 @@ export function lineHeightFactor(fontFamily: string): number {
// fonts — keep their own metrics (probe 2026-08-23, prod-corpus sweep)
if (f.includes('lato')) return 1.2
if (f.includes('trebuchet')) return 1.1615
+ // macOS Supplemental + Office face, hhea 2257/597/0 over 2048; Word pitch
+ // 15.75pt @11pt on a regression sample (incl. 0.5pt row border)
+ if (f.includes('comic sans')) return 1.3936
if (f === 'inter' || f.startsWith('inter ')) return 1.21
if (f.includes('ubuntu')) return 1.15
if (f.includes('avenir')) return 1.369
@@ -485,6 +512,10 @@ export function computeLineHeight(
return lineRawTwips * TWIPS_TO_PX
}
if (lineRule === 'atLeast' && lineRawTwips !== undefined) {
+ // line="0" atLeast is the one non-exact form that never snaps: natural
+ // height (Word probe 2026-09-11: Meiryo UI 10pt on a 350-twip grid lays
+ // 16.56pt, not the 17.5pt cell; atLeast 200/330 still floor at the cell)
+ if (lineRawTwips === 0) return naturalLineH
// at least: the floor value at face value, but never below the snapped
// single height (snapped == natural when there is no grid)
return Math.max(lineRawTwips * TWIPS_TO_PX, snapped)
@@ -527,6 +558,7 @@ export const BUNDLED_FONTS = new Set([
'Carlito GO',
'Aptos GO',
'Aptos Display GO',
+ 'Century Gothic GO',
'Caladea',
'Liberation Serif',
'Liberation Sans',
@@ -649,6 +681,18 @@ export function krNameLineFactor(font: string): number | null {
return missing && panoseSerifHint(font) === 'sans' ? 1.7371 : 1.3029
}
+/**
+ * Missing Noto/Source Han KR variant whose fontTable PANOSE says sans: Word
+ * substitutes Malgun Gothic wholesale (probe 2026-09-11: Noto Sans KR with
+ * PANOSE 020B.. lays hangul and Latin in MalgunGothic at 1.7371), while the
+ * same name without a fontTable hint stays Batang-ward (probe 2026-08-13).
+ */
+export function krSansVariantSubstituted(font: string): boolean {
+ const head = font.split(',')[0].replace(/['"]/g, '').normalize('NFKC').trim()
+ if (!/^(?:noto|source han) (?:sans|serif)(?: cjk)? ?(?:kr|k)\b/i.test(head)) return false
+ return (isBundledFont(head) || !isFontAvailable(head)) && panoseSerifHint(head) === 'sans'
+}
+
/** missing BIZ UD face: Word substitutes Yu Gothic (sans, 1.44) whatever the name says */
export function bizUdSubstituted(font: string): boolean {
const head = font.split(',')[0].replace(/['"]/g, '').trim()
@@ -694,6 +738,16 @@ export function cssFontFamily(font: string, followAltName = true): string {
return `${chain(font, 'Palatino Linotype', 'Palatino', 'Book Antiqua', BOX, CJK_SERIF)},serif`
if (f === 'arial' || f.startsWith('arial '))
return `${chain(font, 'Liberation Sans', CJK_SANS)},sans-serif`
+ // Segoe UI is an M365 cloud font Word renders real; where it is missing the
+ // size-adjusted Helvetica alias (fonts.css) carries its narrower advances
+ if (SEGOE_UI_TEXT_RE.test(f))
+ return `${chain(font, 'Segoe UI GO', 'Noto Sans CJK GO', 'GenOffice PUA Blank')},sans-serif`
+ // Consolas is Office-only: the size-adjusted Menlo alias (fonts.css) carries its advances
+ if (f.includes('consolas')) return `${chain(font, 'Consolas GO', CJK_SANS)},monospace`
+ // Century Gothic is Office-only too: the per-case size-adjusted Liberation
+ // Sans alias (fonts.css) carries its wide lowercase / narrow capitals
+ if (f.includes('century gothic'))
+ return `${chain(font, 'Century Gothic GO', CJK_SANS)},sans-serif`
if (MONO_FONT_RE.test(f))
return `${chain(font, 'Menlo', 'Courier New', 'Liberation Mono', CJK_SANS)},monospace`
// Nunito Sans is an Office cloud font Word renders real; the size-adjusted
@@ -765,11 +819,17 @@ export function cssFontFamily(font: string, followAltName = true): string {
nfkc,
)
) {
- const sans = /kufi|sans|dubai|segoe/i.test(nfkc)
- // Traditional/Simplified Arabic are compact naskh faces; the size-adjusted
- // alias (fonts.css) keeps advances near Word's, other Arabic names keep the
- // unscaled subset
- const compact = /\b(traditional|simplified) arabic\b/i.test(nfkc)
+ // an installed kufi/sans face renders as such; a missing one substitutes to
+ // Times New Roman in Word like every other missing Arabic name (probe
+ // 2026-09-11: Noto Kufi Arabic list items came back as TimesNewRomanPSMT).
+ // The bundled Noto Sans Arabic subset answers the canvas probe but is not
+ // an installed face.
+ const sans =
+ /kufi|sans|dubai|segoe/i.test(nfkc) && !isBundledFont(font) && isFontAvailable(font)
+ // Traditional/Simplified Arabic are compact naskh faces Word renders real
+ // (M365 cloud fonts); the per-face size-adjusted aliases (fonts.css) carry
+ // their advances, other Arabic names keep the unscaled subset
+ const compact = /\b(traditional|simplified) arabic\b/i.exec(nfkc)?.[1].toLowerCase()
// declared Noto Arabic names would resolve to the bundled unscaled subsets
// (~13% wider than Word); the literal head must go so the 'W' alias wins
const scaled = /^noto (naskh|sans) arabic$/i.test(nfkc.trim())
@@ -791,7 +851,9 @@ export function cssFontFamily(font: string, followAltName = true): string {
? ['Naskh Digits GO', 'Noto Naskh Arabic TNR']
: [
compact
- ? 'Noto Naskh Arabic TA'
+ ? compact === 'traditional'
+ ? 'Noto Naskh Arabic TA'
+ : 'Noto Naskh Arabic SA'
: scaled
? 'Noto Naskh Arabic W'
: 'Noto Naskh Arabic',
@@ -812,8 +874,10 @@ export function cssFontFamily(font: string, followAltName = true): string {
nfkc,
)
if (cjkVariant) {
- const serif = /serif/i.test(cjkVariant[1]) || missingLocally()
const region = cjkVariant[2].toLowerCase()
+ const isKr = region === 'kr' || region === 'k'
+ const sansSub = isKr && krSansVariantSubstituted(font)
+ const serif = /serif/i.test(cjkVariant[1]) || (missingLocally() && !sansSub)
const chainFor =
region === 'jp'
? serif
@@ -836,8 +900,7 @@ export function cssFontFamily(font: string, followAltName = true): string {
// hangul stays Batang (M3 probe sample 13); the alias claims printable
// ASCII only, everything else falls through per glyph. Installed names and
// Malgun/Batang declares keep the Latin-normalized subsets untouched.
- const isKr = region === 'kr' || region === 'k'
- const krLatin = isKr && missingLocally() ? ['KR Theme Latin GO'] : []
+ const krLatin = isKr && missingLocally() && !sansSub ? ['KR Theme Latin GO'] : []
// Word substitutes a missing face per script, whatever region the name
// claims: hangul lands on Batang (1em, Word probe 2026-09-06). The
// SC/TC/JP chains carry no hangul, so without this tail Chromium falls to
@@ -1296,6 +1359,9 @@ export function cssGridSpacingPt(pt: number): string {
*/
export const WORD_AUTO_SPACING_PT = 14
+/** space-only run text: never sizes a line, the paragraph mark does (Word probe 2026-09-11) */
+export const SPACE_ONLY_RE = /^[ \u00a0\u3000]+$/
+
export function cssLineHeight(
lineRule: 'auto' | 'atLeast' | 'exact' | undefined,
lineRawTwips: number | undefined,
@@ -1305,8 +1371,8 @@ export function cssLineHeight(
if (lineRule === 'exact' && lineRawTwips) return `${(lineRawTwips / 20).toFixed(1)}pt`
if (lineRule === 'atLeast' && lineRawTwips != null) {
// atLeast: face value, but never below the grid-snapped single height
- // (Word probe 2026-08-22); line="0" atLeast degrades to single spacing
- if (lineRawTwips === 0) return `var(--doc-line-grid, calc(${FACTOR} * 1em))`
+ // (Word probe 2026-08-22); line="0" atLeast is natural height off the grid
+ if (lineRawTwips === 0) return `calc(${FACTOR} * 1em)`
return `max(${(lineRawTwips / 20).toFixed(1)}pt, var(--doc-line-grid, calc(${FACTOR} * 1em)))`
}
const m = lineSpacing ?? (lineRule === 'auto' && lineRawTwips ? lineRawTwips / 240 : undefined)
@@ -1932,6 +1998,14 @@ export const FOOTNOTE_SEPARATOR_H = 16
* Header/footer part height estimate (px): per-paragraph line-box model. Capacity
* input for body push-down (body top = max(marginTop, headerDist + header height)).
*/
+interface HfLineSpacingLike {
+ lineRule?: 'auto' | 'atLeast' | 'exact'
+ lineRawTwips?: number
+ lineSpacing?: number
+ spaceBefore?: number
+ spaceAfter?: number
+}
+
interface HfRunLike {
text: string
font?: string
@@ -1958,7 +2032,7 @@ export function estimateHfHeight(
paras?: Array<{
runs: HfRunLike[]
/** layout-table row: per-cell paragraph stacks (row height = tallest cell) */
- cells?: Array<{ paras: HfRunLike[][] }>
+ cells?: Array<{ paras: HfRunLike[][]; paraProps?: Array }>
/** declared w:trHeight (twips): floors the row, or fixes it under hRule exact */
row?: { heightTwips?: number; heightRule?: 'atLeast' | 'exact' }
/** floating-textbox content: drawn at the anchor, no strip flow height */
@@ -2012,7 +2086,7 @@ export function estimateHfHeight(
: part.text.trim()
? part.text.split('\n').map((t) => ({ runs: [{ text: t }] }))
: []
- const lineH = (runs: HfRunLike[], rich?: HfPara) =>
+ const lineH = (runs: HfRunLike[], rich?: HfLineSpacingLike) =>
computeLineMetrics({
runs: runs.map((r) => ({
text: r.text,
@@ -2047,9 +2121,9 @@ export function estimateHfHeight(
height += Math.max(
declared,
...p.cells.map((c) =>
- (c.paras.length > 0 ? c.paras : [[]]).reduce((s, runs) => {
+ (c.paras.length > 0 ? c.paras : [[]]).reduce((s, runs, k) => {
const imgH = Math.max(0, ...runs.map((r) => r.image?.heightPx ?? 0))
- return s + Math.max(lineH(runs), imgH)
+ return s + Math.max(lineH(runs, c.paraProps?.[k]), imgH)
}, 0),
),
)
diff --git a/apps/docs/src/renderer/main.tsx b/apps/docs/src/renderer/main.tsx
index 7d9a15a..f98a14f 100644
--- a/apps/docs/src/renderer/main.tsx
+++ b/apps/docs/src/renderer/main.tsx
@@ -14,8 +14,12 @@ import '@genoffice/ui/ai-scope-quote.css'
import './styles.css'
import './fonts/fonts.css'
import { applyAiPanelPrefs, installScreenTips } from '@genoffice/ui'
+import { setAltChunkHtmlConverter } from '@genoffice/docx-engine'
installScreenTips()
+if (window.desktop?.convertAltChunkHtml) {
+ setAltChunkHtmlConverter((html) => window.desktop.convertAltChunkHtml(html))
+}
function applyTheme(theme: UiTheme): void {
if (theme === 'system') document.documentElement.removeAttribute('data-theme')
diff --git a/apps/docs/src/renderer/note-format.ts b/apps/docs/src/renderer/note-format.ts
index 5ce8695..40e734f 100644
--- a/apps/docs/src/renderer/note-format.ts
+++ b/apps/docs/src/renderer/note-format.ts
@@ -1,4 +1,18 @@
-/** Word's default endnote numbering is lowercase roman (footnotes stay arabic) — the visual cue that separates the two note kinds. */
+import type { NoteProps } from '@genoffice/docx-engine'
+
+export type NoteKind = 'footnote' | 'endnote'
+
+/** Word's default numbering: footnotes arabic, endnotes lowercase roman — the visual cue that separates the two note kinds. */
+const DEFAULT_FMT: Record = { footnote: 'decimal', endnote: 'lowerRoman' }
+
+/** current document's w:numFmt per note kind (set on load, before the body renders its reference marks) */
+const numFmt: Record = { ...DEFAULT_FMT }
+
+export function setNoteNumFmts(props: { footnote?: NoteProps; endnote?: NoteProps }): void {
+ numFmt.footnote = props.footnote?.numFmt ?? DEFAULT_FMT.footnote
+ numFmt.endnote = props.endnote?.numFmt ?? DEFAULT_FMT.endnote
+}
+
const ROMAN: Array<[number, string]> = [
[1000, 'm'],
[900, 'cm'],
@@ -28,6 +42,40 @@ export function toRoman(n: number): string {
return out
}
-export function noteMarkText(kind: 'footnote' | 'endnote', no: number): string {
- return kind === 'endnote' ? toRoman(no) : String(no)
+function toLetter(n: number): string {
+ if (!Number.isFinite(n) || n < 1) return String(n)
+ const idx = (Math.floor(n) - 1) % 26
+ const reps = Math.floor((Math.floor(n) - 1) / 26) + 1
+ return String.fromCharCode(97 + idx).repeat(reps)
+}
+
+/** Word's chicago sequence: * † ‡ §, doubled on each wrap */
+const CHICAGO = ['*', '†', '‡', '§']
+function toChicago(n: number): string {
+ if (!Number.isFinite(n) || n < 1) return String(n)
+ const idx = (Math.floor(n) - 1) % CHICAGO.length
+ const reps = Math.floor((Math.floor(n) - 1) / CHICAGO.length) + 1
+ return CHICAGO[idx].repeat(reps)
+}
+
+/** display text of note number `n` in a w:numFmt (unknown formats fall back to decimal) */
+export function formatNoteNumber(fmt: string | undefined, n: number): string {
+ switch (fmt) {
+ case 'lowerRoman':
+ return toRoman(n)
+ case 'upperRoman':
+ return toRoman(n).toUpperCase()
+ case 'lowerLetter':
+ return toLetter(n)
+ case 'upperLetter':
+ return toLetter(n).toUpperCase()
+ case 'chicago':
+ return toChicago(n)
+ default:
+ return String(n)
+ }
+}
+
+export function noteMarkText(kind: NoteKind, no: number): string {
+ return formatNoteNumber(numFmt[kind], no)
}
diff --git a/apps/docs/src/renderer/pagination-hf.ts b/apps/docs/src/renderer/pagination-hf.ts
index 4ddbb97..747daf6 100644
--- a/apps/docs/src/renderer/pagination-hf.ts
+++ b/apps/docs/src/renderer/pagination-hf.ts
@@ -61,6 +61,19 @@ export function hasPrintableHeaderFooter(input: {
})
}
+/** Header/footer variant a page renders: the titlePg first page of its section
+ * takes 'first', an even page under evenAndOddHeaders takes 'even' */
+export function hfVariantOf(
+ titlePg: boolean | undefined,
+ firstOfSection: boolean,
+ evenOddHf: boolean,
+ pageNo: number,
+): 'first' | 'even' | 'default' {
+ if (titlePg && firstOfSection) return 'first'
+ if (evenOddHf && pageNo % 2 === 0) return 'even'
+ return 'default'
+}
+
/** Displayed page number per page: restart at the section's pgNumType w:start, otherwise continue;
* evenPage/oddPage section breaks skip a number to fix parity (when not restarting) */
export function pageNumbers(slices: PageSlice[], sections: SectionInfo[]): number[] {
diff --git a/apps/docs/src/renderer/pagination-lines.ts b/apps/docs/src/renderer/pagination-lines.ts
index 127178a..c764f8c 100644
--- a/apps/docs/src/renderer/pagination-lines.ts
+++ b/apps/docs/src/renderer/pagination-lines.ts
@@ -2,7 +2,9 @@
// line-split re-slice, table row cut positions and line anchors.
import { rangeSlot } from './dom-range'
import { applyBlockMeta } from './pagination-measure'
+import { blockInlineExtraPx } from './pagination-sections'
import {
+ columnLineSplits,
computeSectionedSlicesF2,
insertParityBlanks,
sectionFirstPages,
@@ -10,7 +12,11 @@ import {
import type {
BlockBox,
BlockMetaOf,
+ ColWrapRequest,
+ ColWrapTable,
PageSlice,
+ RowCellBox,
+ RowSplitPatch,
SectionGeom,
SliceOutputs,
TableRowBox,
@@ -36,7 +42,9 @@ export function sliceWithLineSplit(
out?: SliceOutputs,
): PageSlice[] {
if (metaOf) applyBlockMeta(blocks, metaOf, zoomFactor)
- let slices = computeSectionedSlicesF2(blocks, geoms, totalHeight, out)
+ const outs: SliceOutputs = out ?? {}
+ outs.colWrapRequests ??= []
+ let slices = computeSectionedSlicesF2(blocks, geoms, totalHeight, outs)
// re-slicing can surface new candidate blocks (a block pushed to a page top only
// after an earlier block gained line data) — iterate to a fixed point, bounded.
// The cascade can run one block per page boundary (a dense two-column grid doc
@@ -45,12 +53,221 @@ export function sliceWithLineSplit(
const maxPasses = Math.max(3, Math.min(24, slices.length))
for (let i = 0; i < maxPasses; i++) {
const changed = fillLineBoxes(blocks, geoms, zoomFactor, slices, metaOf)
- if (!changed) break
- slices = computeSectionedSlicesF2(blocks, geoms, totalHeight, out)
+ const wrapped = fillColWraps(blocks, colWrapRequestsOf(blocks, slices, geoms, outs), zoomFactor)
+ if (!changed && !wrapped) break
+ slices = computeSectionedSlicesF2(blocks, geoms, totalHeight, outs)
}
return insertParityBlanks(slices, geoms)
}
+/** Balance requests plus the tables every line-cut paragraph between unequal
+ * columns needs for its split shape (tail height at the second width). */
+function colWrapRequestsOf(
+ blocks: BlockBox[],
+ slices: PageSlice[],
+ geoms: SectionGeom[],
+ out: SliceOutputs,
+): ColWrapRequest[] {
+ const reqs = [...(out.colWrapRequests ?? [])]
+ const colWidthsOf = (s: number) => geoms[Math.max(0, Math.min(s, geoms.length - 1))]?.colWidths
+ for (const sp of columnLineSplits(blocks, slices, colWidthsOf)) {
+ if (sp.tailBottom !== undefined) continue
+ reqs.push({
+ blockTop: blocks[sp.bi].top,
+ headWidthPx: sp.headWidthPx,
+ tailWidthPx: sp.tailWidthPx,
+ })
+ }
+ return reqs
+}
+
+const colWrapCache = new WeakMap()
+
+/** Formatting the probe depends on: the paragraph's own text properties and the
+ * markup of its runs (inline sizes, indents); pagination widgets (the split
+ * float, in-block gaps) are layout state, not formatting. Width and height are
+ * deliberately absent: the split itself changes both. */
+function colWrapSig(el: HTMLElement, zoomFactor: number): string {
+ const cs = getComputedStyle(el)
+ const props = [
+ cs.fontFamily,
+ cs.fontSize,
+ cs.lineHeight,
+ cs.textIndent,
+ cs.textAlign,
+ cs.letterSpacing,
+ cs.wordSpacing,
+ cs.paddingLeft,
+ cs.paddingRight,
+ cs.paddingTop,
+ cs.paddingBottom,
+ cs.marginLeft,
+ cs.marginRight,
+ cs.direction,
+ ].join('|')
+ let h = 5381
+ for (const n of Array.from(el.childNodes)) {
+ if (
+ n instanceof Element &&
+ (n.classList.contains('doc-col-split-float') || n.classList.contains('page-gap'))
+ )
+ continue
+ const text = n instanceof Element ? n.outerHTML : (n.textContent ?? '')
+ for (let i = 0; i < text.length; i++) h = ((h << 5) + h + text.charCodeAt(i)) | 0
+ }
+ return `${lineSampleFontEpoch}:${Math.round(zoomFactor * 1000)}:${props}:${h}`
+}
+
+const sameWraps = (t: { headWidthPx: number; tailWidthPx: number }, r: ColWrapRequest) =>
+ Math.abs(t.headWidthPx - r.headWidthPx) < 0.5 && Math.abs(t.tailWidthPx - r.tailWidthPx) < 0.5
+
+/**
+ * Attach the requested ColWrapTables (probeColWrap, cached per element and text
+ * until the text or fonts change). Returns whether any block gained a table (the
+ * caller re-slices).
+ */
+export function fillColWraps(
+ blocks: BlockBox[],
+ requests: ColWrapRequest[],
+ zoomFactor: number,
+ probe: typeof probeColWrap = probeColWrap,
+): boolean {
+ let changed = false
+ for (const req of requests) {
+ const b = blocks.find((x) => x.el && Math.abs(x.top - req.blockTop) < 0.5)
+ if (!b?.el) continue
+ if (b.colWraps?.some((t) => sameWraps(t, req))) continue
+ const sig = colWrapSig(b.el, zoomFactor)
+ let entry = colWrapCache.get(b.el)
+ if (!entry || entry.sig !== sig) {
+ entry = { sig, tables: [] }
+ colWrapCache.set(b.el, entry)
+ }
+ let table = entry.tables.find((t) => sameWraps(t, req))
+ if (!table) {
+ const probed = probe(b.el, req.headWidthPx, req.tailWidthPx, zoomFactor)
+ if (!probed) continue
+ table = probed
+ entry.tables.push(table)
+ }
+ b.colWraps = [...(b.colWraps ?? []), table]
+ changed = true
+ }
+ return changed
+}
+
+/** Hidden probe copy of the canvas page: same classes/inline vars as the
+ * ProseMirror root (so the clone inherits every page rule), measuring state,
+ * zero-height overflow box that contains the probe's oversized float. */
+function probeHost(pm: HTMLElement): HTMLElement | null {
+ const parent = pm.parentElement
+ if (!parent) return null
+ const wrap = document.createElement('div')
+ wrap.className = `${pm.className} measuring-columns doc-col-probe`
+ const style = pm.getAttribute('style')
+ if (style) wrap.setAttribute('style', style)
+ const dir = pm.getAttribute('dir')
+ if (dir) wrap.setAttribute('dir', dir)
+ wrap.setAttribute('aria-hidden', 'true')
+ Object.assign(wrap.style, {
+ position: 'absolute',
+ left: '0',
+ top: '0',
+ boxSizing: 'border-box',
+ width: `${pm.offsetWidth}px`,
+ height: '0',
+ overflow: 'hidden',
+ visibility: 'hidden',
+ pointerEvents: 'none',
+ columnCount: 'auto',
+ })
+ parent.appendChild(wrap)
+ return wrap
+}
+
+/** The float that rewraps part of a straddling paragraph (same element in the
+ * probe and on the canvas, see setColumnLayout) */
+export function splitFloatStyle(
+ floatPx: number,
+ heightPx: number,
+ insetPx: number,
+ rtl: boolean | undefined,
+): string {
+ const r = (n: number) => Math.round(n * 100) / 100
+ return `float:${rtl ? 'left' : 'right'};width:${r(floatPx)}px;height:${r(heightPx)}px;shape-outside:inset(${r(insetPx)}px 0 0 0)`
+}
+
+const PROBE_FLOAT_H = 1e5
+
+/**
+ * Measure a paragraph split between two columns of different widths: a clone at
+ * the wider width carries the same leading float shape the canvas will use, so
+ * for every head line count k the probe reads the cut Y (lines wrapped at the
+ * head width) and the bottom of the remaining lines rewrapped at the tail width.
+ * Null when the paragraph has no measurable lines.
+ */
+export function probeColWrap(
+ el: HTMLElement,
+ headWidthPx: number,
+ tailWidthPx: number,
+ zoomFactor: number,
+): ColWrapTable | null {
+ const pm = el.parentElement
+ if (!pm) return null
+ const rtl = getComputedStyle(el).direction === 'rtl'
+ const wrap = probeHost(pm)
+ if (!wrap) return null
+ try {
+ const clone = el.cloneNode(true) as HTMLElement
+ clone.removeAttribute('data-col-patch')
+ clone.removeAttribute('data-idx')
+ for (const g of Array.from(
+ clone.querySelectorAll('.page-gap, .page-gap-inline, .page-float-host, .doc-col-split-float'),
+ ))
+ g.remove()
+ clone.classList.add('doc-col-block')
+ const wide = Math.max(headWidthPx, tailWidthPx)
+ clone.style.setProperty('--col-w', `${Math.max(0, wide - blockInlineExtraPx(el))}px`)
+ const fl = document.createElement('span')
+ fl.className = 'doc-col-split-float'
+ clone.insertBefore(fl, clone.firstChild)
+ wrap.appendChild(clone)
+ const cs = getComputedStyle(clone)
+ const padTop = (parseFloat(cs.paddingTop) || 0) + (parseFloat(cs.borderTopWidth) || 0)
+ const padBottom = (parseFloat(cs.paddingBottom) || 0) + (parseFloat(cs.borderBottomWidth) || 0)
+ const contentBottom = () => clone.getBoundingClientRect().height / zoomFactor - padBottom
+ const headNarrow = headWidthPx < tailWidthPx
+ const floatPx = Math.abs(headWidthPx - tailWidthPx)
+ const setFloat = (heightPx: number, insetPx: number) => {
+ fl.style.cssText = splitFloatStyle(floatPx, heightPx, insetPx, rtl)
+ }
+ setFloat(headNarrow ? PROBE_FLOAT_H : 0, 0)
+ const headLines = domLineRects(clone, zoomFactor)
+ const n = headLines.length
+ if (n === 0) return null
+ const bounds = lineBreakBoundaries(headLines)
+ if (bounds.length !== n - 1) return null
+ const headH = [0, ...bounds, contentBottom()]
+ // the float edge must not touch the line box on the other side of the cut
+ const shapeY = headH.map((_, k) =>
+ k === 0 ? 0 : k === n ? headH[n] : headNarrow ? headLines[k - 1].bottom : headLines[k].offset,
+ )
+ const tailH: number[] = new Array(n + 1).fill(0)
+ const tailBottom: number[] = new Array(n + 1).fill(headH[n])
+ for (let k = 0; k < n; k++) {
+ const at = Math.max(shapeY[k] - padTop, 0)
+ if (headNarrow) setFloat(at, 0)
+ else setFloat(PROBE_FLOAT_H, at)
+ const bottom = contentBottom()
+ tailBottom[k] = bottom
+ tailH[k] = Math.max(bottom - headH[k], 0)
+ }
+ return { headWidthPx, tailWidthPx, n, headH, tailH, tailBottom, shapeY }
+ } finally {
+ wrap.remove()
+ }
+}
+
/**
* Collect DOM line-box data for pagination candidate blocks (F2 model): blocks that
* cross a page bound, exceed one page, or were pushed wholesale to a page top (the
@@ -87,7 +304,14 @@ function lineSampleSig(el: HTMLElement, textH: number): string {
// costs one re-sample, so quantization errs toward invalidating.
const w = el.getBoundingClientRect().width
const nodes = el.getElementsByTagName('*').length
- return `${lineSampleFontEpoch}:${Math.round(textH * 4)}:${Math.round(w * 4)}:${nodes}:${h}`
+ // justify-shrink decorations move wrap points without changing text, height
+ // or (when a decoration migrates between lines) the descendant count (r177)
+ let js = 0
+ for (const sp of el.querySelectorAll('.doc-jshrink')) {
+ const per = Math.round((parseFloat(sp.style.wordSpacing) || 0) * -100)
+ js = (js * 33 + per + (sp.textContent?.length ?? 0)) | 0
+ }
+ return `${lineSampleFontEpoch}:${Math.round(textH * 4)}:${Math.round(w * 4)}:${nodes}:${h}:${js}`
}
export function fillLineBoxes(
@@ -240,6 +464,12 @@ export function fillLineBoxes(
// synthesize cut points at page height, equivalent to hard pixel cuts
for (let y = contentH; y < block.height; y += contentH) boundaries.push(y)
}
+ // a leading page break's line has no text rect, so its cut (the first text
+ // line's ink top) lands inside the first sampled line box: make it a boundary
+ for (const y of block.innerBreaks ?? []) {
+ if (y > 0.5 && y < textH - 0.5 && (boundaries.length === 0 || y < boundaries[0] - 1.5))
+ boundaries.unshift(y)
+ }
if (boundaries.length > 0) {
block.lineBoxes = tileBoxes(boundaries, textH)
changed = true
@@ -275,6 +505,45 @@ function outerTableRows(el: HTMLElement): HTMLElement[] {
)
}
+/** Preview rules for Word-style split rows: stamp each split tr (data-pv-split, cloned
+ * with the block) and, on the page each fragment lands on, translate / clip / hide
+ * the cells' children so only that fragment's lines show, at its top, while the
+ * clone stays a plain clip of the canvas flow */
+export function rowSplitCss(
+ splits: RowSplitPatch[],
+ blocks: BlockBox[],
+ slices: Array<{ start: number }>,
+): string {
+ const root = blocks[0]?.el?.parentElement
+ for (const el of root?.querySelectorAll('[data-pv-split]') ?? [])
+ el.removeAttribute('data-pv-split')
+ const pageOf = (y: number) => {
+ let pg = 0
+ while (pg + 1 < slices.length && slices[pg + 1].start <= y + 0.5) pg++
+ return pg
+ }
+ const px = (v: number) => `${v.toFixed(1)}px`
+ const out: string[] = []
+ splits.forEach((split, n) => {
+ const block = blocks.find((b) => b.tableRows && Math.abs(b.top - split.blockTop) < 0.5)
+ const tr = block?.el ? outerTableRows(block.el)[split.row] : undefined
+ if (!tr) return
+ tr.dataset.pvSplit = String(n)
+ for (const r of split.rules) {
+ const decl =
+ r.dy !== undefined
+ ? `transform:translateY(${px(r.dy)})`
+ : r.clipTop !== undefined || r.clipBottom !== undefined
+ ? `clip-path:inset(${px(r.clipTop ?? 0)} 0 ${px(r.clipBottom ?? 0)} 0)`
+ : 'visibility:hidden'
+ out.push(
+ `.pv-page[data-pv-page="${pageOf(r.from)}"] .pv-content tr[data-pv-split="${n}"] > :nth-child(${r.cell + 1}) > :nth-child(${r.tail ? 'n+' : ''}${r.child + 1}){${decl}}`,
+ )
+ }
+ })
+ return out.join('\n')
+}
+
/** Charge each footnote's height to the row holding its reference (bands and
* refs are both in document order); a count mismatch keeps the block-level
* reservation placed after the table */
@@ -312,7 +581,7 @@ function domTableRows(el: HTMLElement, blockHeight: number, zoomFactor: number):
}
return tileBoxes(tops, blockHeight).map((b, i) => {
if (!trs[i]) return { height: b.height }
- const { cuts, contentBottom } = rowCutYs(
+ const { cuts, contentBottom, cells } = rowCutYs(
trs[i],
b.offsetInBlock,
b.height,
@@ -320,6 +589,7 @@ function domTableRows(el: HTMLElement, blockHeight: number, zoomFactor: number):
gapAbove,
zoomFactor,
)
+ const splitExtra = parseFloat(trs[i].dataset.splitExtra ?? '')
return {
height: b.height,
contentBottom,
@@ -327,6 +597,8 @@ function domTableRows(el: HTMLElement, blockHeight: number, zoomFactor: number):
? { isHeader: trs[i].getAttribute('data-repeat-header') === '1' }
: {}),
...(cuts.length > 0 ? { cutYs: cuts } : {}),
+ ...(cells ? { cells } : {}),
+ ...(splitExtra > 0 ? { splitExtra } : {}),
}
})
}
@@ -335,7 +607,8 @@ const PARA_SELECTOR = 'p, h1, h2, h3, h4, h5, h6, .doc-li'
/** In-row safe cut points (relative to row top, px, ascending): line-level candidates
* per cell (Word breaks between any two lines), rejecting cuts that would cross a
- * line box in another cell. Also reports the lowest content-band bottom. */
+ * line box in another cell. Also reports the lowest content-band bottom and, for
+ * multi-cell rows, each cell's own line geometry (per-cell Word-style splitting). */
function rowCutYs(
tr: Element,
rowTop: number,
@@ -343,28 +616,55 @@ function rowCutYs(
elTop: number,
gapAbove: (top: number) => number,
zoomFactor: number,
-): { cuts: number[]; contentBottom: number } {
+): { cuts: number[]; contentBottom: number; cells?: RowCellBox[] } {
const cells = Array.from(tr.children).filter((c) => c.tagName === 'TD' || c.tagName === 'TH')
const range = rowRange()
const cellBands: Array> = []
const paraBands: Array> = []
+ const cellBoxes: RowCellBox[] = []
+ // exact-height clip boxes and vertical text are not line-splittable content
+ let cellsOk =
+ cells.length >= 2 && !tr.querySelector(':scope > * > .cell-clip, :scope > * > .cell-vert')
+ let paraSeq = 0
for (const cell of cells) {
const bands: Array<[number, number]> = []
const byPara = new Map>()
+ const paraIds = new Map()
+ const entries: Array<{ band: [number, number]; child: number; para: number }> = []
const toBand = (r: DOMRect): [number, number] => [
(r.top - elTop - gapAbove(r.top)) / zoomFactor - rowTop,
(r.bottom - elTop - gapAbove(r.bottom)) / zoomFactor - rowTop,
]
+ const childIndexOf = (node: Node | null): number => {
+ let e: Node | null = node
+ while (e && e.parentNode !== cell) e = e.parentNode
+ return e ? Array.prototype.indexOf.call(cell.children, e) : -1
+ }
+ const paraIdOf = (para: Element | null, child: number) => {
+ if (!para) return -1 - child
+ let id = paraIds.get(para)
+ if (id === undefined) {
+ id = paraSeq++
+ paraIds.set(para, id)
+ }
+ return id
+ }
+ const addEntry = (band: [number, number], node: Node, para: Element | null) => {
+ const child = childIndexOf(node)
+ if (child < 0) cellsOk = false
+ else entries.push({ band, child, para: paraIdOf(para, child) })
+ }
const walker = document.createTreeWalker(cell, NodeFilter.SHOW_TEXT)
for (let n = walker.nextNode(); n; n = walker.nextNode()) {
const parent = n.parentElement
if (parent?.closest('.page-gap, .page-float-host')) continue
- const para = parent?.closest(PARA_SELECTOR)
+ const para = parent?.closest(PARA_SELECTOR) ?? null
range.selectNodeContents(n)
for (const r of range.getClientRects()) {
if (r.height <= 0 || r.width <= 0) continue
const band = toBand(r)
bands.push(band)
+ addEntry(band, n, para)
if (para) {
const list = byPara.get(para) ?? []
list.push(band)
@@ -376,7 +676,11 @@ function rowCutYs(
// in-cell gap decorations may carry header/footer images: not row content
if (obj.closest('.page-gap, .page-float-host')) continue
const r = obj.getBoundingClientRect()
- if (r.height > 0 && r.width > 0) bands.push(toBand(r))
+ if (r.height > 0 && r.width > 0) {
+ const band = toBand(r)
+ bands.push(band)
+ addEntry(band, obj, obj.closest(PARA_SELECTOR))
+ }
}
// empty paragraphs above the cell's content are lines Word breaks between;
// trailing empty marks stay band-less (they drive the over-page tail fill)
@@ -390,15 +694,78 @@ function rowCutYs(
if (band[0] >= contentB - 0.5) continue
bands.push(band)
byPara.set(para, [band])
+ addEntry(band, para, para)
}
if (bands.length > 0) cellBands.push(bands)
for (const list of byPara.values()) paraBands.push(list)
+ if (cellsOk) cellBoxes.push(cellBoxOf(cell as HTMLElement, entries, zoomFactor))
}
const contentBottom = cellBands.reduce(
(max, bands) => bands.reduce((m, [, b]) => Math.max(m, b), max),
0,
)
- return { cuts: cellCutYs(cellBands, rowHeight, paraBands), contentBottom }
+ return {
+ cuts: cellCutYs(cellBands, rowHeight, paraBands),
+ contentBottom,
+ ...(cellsOk && cellBoxes.some((c) => c.lines.length > 0) ? { cells: cellBoxes } : {}),
+ }
+}
+
+/** Per-cell line geometry in top-aligned coordinates: a middle/bottom-aligned cell's
+ * content is measured where the canvas centered it, so the alignment offset is
+ * removed here (Word aligns within each row fragment, not the whole row) */
+function cellBoxOf(
+ cell: HTMLElement,
+ entries: Array<{ band: [number, number]; child: number; para: number }>,
+ zoomFactor: number,
+): RowCellBox {
+ const va = cell.style.verticalAlign
+ let alignDy = 0
+ let alignFrac = 0
+ const first = cell.firstElementChild
+ if ((va === 'middle' || va === 'bottom') && first && entries.length > 0) {
+ alignFrac = va === 'middle' ? 0.5 : 1
+ // rects are zoomed, computed lengths are not
+ const cs = getComputedStyle(cell)
+ const off =
+ (first.getBoundingClientRect().top - cell.getBoundingClientRect().top) / zoomFactor -
+ (parseFloat(getComputedStyle(first).marginTop) || 0) -
+ (parseFloat(cs.paddingTop) || 0) -
+ (parseFloat(cs.borderTopWidth) || 0)
+ alignDy = Math.max(0, off)
+ }
+ const shifted = alignDy
+ ? entries.map((e) => ({
+ ...e,
+ band: [e.band[0] - alignDy, e.band[1] - alignDy] as [number, number],
+ }))
+ : entries
+ return { ...cellLinesOf(shifted), alignDy, alignFrac }
+}
+
+/** Pure core of cellBoxOf: rect entries → clustered lines (same overlap rule as
+ * clusterLineBands), each line keeping the child index / paragraph id of its
+ * topmost rect */
+export function cellLinesOf(
+ entries: Array<{ band: [number, number]; child: number; para: number }>,
+): Pick {
+ const sorted = [...entries].sort((a, b) => a.band[0] - b.band[0])
+ const lines: Array<[number, number]> = []
+ const childOf: number[] = []
+ const paraOf: number[] = []
+ for (const e of sorted) {
+ const [top, bottom] = e.band
+ const last = lines[lines.length - 1]
+ const overlap = last ? last[1] - top : 0
+ const minH = last ? Math.min(last[1] - last[0], bottom - top) : 0
+ if (last && overlap > 1 && overlap > 0.4 * minH) last[1] = Math.max(last[1], bottom)
+ else {
+ lines.push([top, bottom])
+ childOf.push(e.child)
+ paraOf.push(e.para)
+ }
+ }
+ return { lines, childOf, paraOf }
}
/** Rects sharing vertical overlap collapse into one line interval. Same-line rects
diff --git a/apps/docs/src/renderer/pagination-measure.ts b/apps/docs/src/renderer/pagination-measure.ts
index 25e7c6f..f0d3863 100644
--- a/apps/docs/src/renderer/pagination-measure.ts
+++ b/apps/docs/src/renderer/pagination-measure.ts
@@ -6,6 +6,7 @@ import type {
FloatBox,
MeasuredContent,
PageNoteItem,
+ PageSlice,
} from './pagination-types'
/**
@@ -30,12 +31,20 @@ export function measureBlocks(
const sectBreaks = new Set()
let totalHeight = 0
let gapAccum = 0
+ // float-carry spacer (split floating table): real flow space that moves the
+ // anchor paragraph beside the last portion, so it is not a gap; its height
+ // is reported on the block it precedes
+ let carryApplied = 0
for (const el of Array.from(pm.children) as HTMLElement[]) {
const rect = el.getBoundingClientRect()
if (el.classList.contains('page-gap') || el.classList.contains('page-float-host')) {
gapAccum += rect.height
continue
}
+ if (el.classList.contains('page-float-carry')) {
+ carryApplied += rect.height / zoomFactor
+ continue
+ }
// floating-anchor boxes: absolute children of a zero-height wrapper; record
// shift-neutral virtual positions so pages can be extended to contain them
let wrapFloatBottom: number | undefined
@@ -60,9 +69,27 @@ export function measureBlocks(
pinned,
pageRelV: (box as HTMLElement).dataset.pageRelV === '1',
...((box as HTMLElement).dataset.pageRelFrom === 'page' ? { pageRelFromPage: true } : {}),
+ ...((box as HTMLElement).dataset.noSpill === '1' ? { noSpill: true } : {}),
})
}
}
+ // run-level page-relative pictures re-pin like floating boxes (origin = hosting paragraph)
+ for (const img of Array.from(
+ el.querySelectorAll('.doc-inline-img-anchor > img[data-page-rel-v="1"]'),
+ )) {
+ const b = img.getBoundingClientRect()
+ if (b.height <= 0) continue
+ const applied = parseFloat(img.dataset.pageFloatDy ?? '0') || 0
+ floats.push({
+ el: img,
+ top: (b.top - origin - gapAccum) / zoomFactor - applied,
+ height: b.height / zoomFactor,
+ anchorTop: (rect.top - origin - gapAccum) / zoomFactor,
+ pinned: false,
+ pageRelV: true,
+ ...(img.dataset.pageRelFrom === 'page' ? { pageRelFromPage: true } : {}),
+ })
+ }
// sectPr-only paragraph: the section-break mark itself has no height in Word
// (its editor chip must not occupy a page or hold a forced break's page open),
// but its boundary must stay visible to liveSections or the section merges away
@@ -120,15 +147,17 @@ export function measureBlocks(
: parseFloat(inlineMult || getComputedStyle(el).getPropertyValue('--doc-line-mult')) || 1
breakOnlyLineH = box / Math.max(1, mult)
}
- // a single break with no text before it: Word starts this block's own content
- // on a new page, so it maps to breakBefore (breakAfter only pushes the next block)
- let leadingBreak = false
- if (breakEls.length === 1 && (el.textContent ?? '').trim()) {
- const r = document.createRange()
- r.setStart(el, 0)
- r.setEndBefore(breakEls[0])
- leadingBreak = !r.toString().trim()
- }
+ // breaks with no text before them lead the block: the break line stays on
+ // the current page and the block's text starts the next one (Word), so the
+ // last leading break cuts like a mid-paragraph break; a field break has no
+ // line of its own and maps to breakBefore. Breaks with no text after it
+ // trail (breakAfter pushes the next block). Every break character turns the
+ // page, so a run of N adjacent breaks leaves N-1 blank sheets. Text is
+ // measured outside the break nodes (a field break carries its own label).
+ let hasText = false
+ let leadingCount = 0
+ let trailingCount = 0
+ let leadingCut = false
// a column break with nothing before it moves the whole paragraph (its own
// line included) to the next column top; a break-only paragraph likewise
let leadingColBreak = false
@@ -143,35 +172,52 @@ export function measureBlocks(
// the next block. Y = the post-break line's ink top, element-relative and
// net of inline gaps a previous pass already inserted there
const innerBreaks: number[] = []
- let trailingBreak = hasBreak
- if (hasBreak && !leadingBreak) {
+ if (hasBreak) {
const gapRects = Array.from(el.querySelectorAll('.page-gap-inline')).map((g) =>
g.getBoundingClientRect(),
)
const gapAbove = (y: number) => gapRects.reduce((s, g) => (g.top <= y ? s + g.height : s), 0)
const r = document.createRange()
- breakEls.forEach((b, i) => {
+ const brs = breakEls.map((b) => {
r.setStart(el, 0)
r.setEndBefore(b)
const before = r.toString().trim() !== ''
r.setStartAfter(b)
r.setEnd(el, el.childNodes.length)
const after = r.toString().trim() !== ''
- if (i === breakEls.length - 1) trailingBreak = !after
- if (!before || !after || !b.classList.contains('doc-page-br')) return
- const first = Array.from(r.getClientRects()).find((c) => c.height > 0 && c.width > 0)
- if (first) innerBreaks.push((first.top - rect.top - gapAbove(first.top)) / zoomFactor)
+ return { b, before, after }
+ })
+ hasText = brs.some((x) => x.before || x.after)
+ leadingCount = brs.filter((x) => !x.before).length
+ trailingCount = brs.filter((x) => !x.after).length
+ brs.forEach(({ b, before, after }, i) => {
+ if (!after || !b.classList.contains('doc-page-br')) return
+ if (!before && i !== leadingCount - 1) return
+ r.setStartAfter(b)
+ r.setEnd(el, el.childNodes.length)
+ const first = Array.from(r.getClientRects?.() ?? []).find(
+ (c) => c.height > 0 && c.width > 0,
+ )
+ if (!first) return
+ innerBreaks.push((first.top - rect.top - gapAbove(first.top)) / zoomFactor)
+ if (!before) leadingCut = true
})
}
- const floated =
- /(?:^|\s)img-wrap-(?:square|tight|through)-(?:left|right)(?:\s|$)/.test(el.className) ||
+ const leadingBreak = hasText && leadingCount > 0 && !leadingCut
+ const floatTable =
el.classList.contains('doc-table-float-left') ||
el.classList.contains('doc-table-float-right')
+ const floatFlowed = floatTable && el.classList.contains('doc-table-float-flow')
+ const floated =
+ /(?:^|\s)img-wrap-(?:square|tight|through)-(?:left|right)(?:\s|$)/.test(el.className) ||
+ el.classList.contains('doc-para-frame-float') ||
+ (floatTable && !floatFlowed)
// page/margin-anchored floated table: strip the applied --tblp-dy shift so
// the engine sees the natural flow position (float margins move only the
// float's own box, so no gapAccum contribution)
const relVy = floated ? parseFloat(el.dataset.tblpVy ?? '') : NaN
const relVAnchor = el.dataset.tblpVanchor
+ const relVSpec = el.dataset.tblpVspec
const relVApplied = Number.isFinite(relVy) ? parseFloat(el.dataset.tblpDy ?? '') || 0 : 0
const emptyPara = !(el.textContent ?? '').trim() && !el.querySelector('img')
// non-reflowable blocks keep their rendered width in any column (tables,
@@ -186,17 +232,29 @@ export function measureBlocks(
top: top - relVApplied,
height,
...(floated ? { floated: true } : {}),
+ ...(floatTable ? { floatTable: true } : {}),
+ ...(floatFlowed ? { floatFlowed: true } : {}),
...(liftPx > 0 ? { liftPx } : {}),
...(bandKeep ? { bandKeep: true } : {}),
...(bandKeep && wrapFloatBottom !== undefined ? { floatBottom: wrapFloatBottom } : {}),
...(Number.isFinite(relVy) && (relVAnchor === 'page' || relVAnchor === 'margin')
- ? { pageRelVyPx: relVy, pageRelVAnchor: relVAnchor }
+ ? {
+ pageRelVyPx: relVy,
+ pageRelVAnchor: relVAnchor,
+ ...(relVSpec === 'top' || relVSpec === 'center' || relVSpec === 'bottom'
+ ? { pageRelVSpec: relVSpec }
+ : {}),
+ }
: {}),
...(emptyPara ? { emptyPara: true } : {}),
- ...(fixedWidth ? { fixedWidthPx: rect.width / zoomFactor } : {}),
+ ...(fixedWidth
+ ? { fixedWidthPx: rect.width / zoomFactor }
+ : { widthPx: rect.width / zoomFactor }),
breakBefore: el.classList.contains('page-break-before') || leadingBreak || undefined,
breakBeforeBr: leadingBreak || undefined,
- breakAfter: (hasBreak && !leadingBreak && trailingBreak) || undefined,
+ ...(hasText && leadingCount > 1 ? { extraBreaksBefore: leadingCount - 1 } : {}),
+ breakAfter: trailingCount > 0 || undefined,
+ ...(trailingCount > 1 ? { extraBreaksAfter: trailingCount - 1 } : {}),
...(innerBreaks.length > 0 ? { innerBreaks } : {}),
colBreakBefore: leadingColBreak || undefined,
colBreakAfter: (hasColBreak && !leadingColBreak) || undefined,
@@ -204,8 +262,12 @@ export function measureBlocks(
el,
...(breakOnlyLineH !== undefined ? { breakOnlyLineH } : {}),
...(idxAttr ? { docxIndex: parseInt(idxAttr, 10) } : {}),
+ ...(carryApplied > 0 ? { carryAppliedPx: carryApplied } : {}),
})
- gapAccum += innerGap
+ carryApplied = 0
+ // a CSS float's in-table gaps grow only the float's own box: the blocks
+ // after it stack where they would without them
+ if (!floated) gapAccum += innerGap
totalHeight = Math.max(totalHeight, top + height)
}
// inter-block CSS margin (space after): rect height excludes it, but it occupies
@@ -244,17 +306,83 @@ export function measureBlocks(
export function endnotesAnchorY(pm: HTMLElement, baseTop: number, factor: number): number | null {
for (let i = pm.children.length - 1; i >= 0; i--) {
const el = pm.children[i] as HTMLElement
- if (el.classList.contains('page-gap') || el.classList.contains('page-float-host')) continue
+ if (
+ el.classList.contains('page-gap') ||
+ el.classList.contains('page-float-host') ||
+ el.classList.contains('page-float-carry')
+ )
+ continue
const rect = el.getBoundingClientRect()
if (rect.height <= 0) continue
- return (rect.bottom - baseTop) / factor
+ return (rect.bottom - baseTop) / factor + (parseFloat(getComputedStyle(el).marginBottom) || 0)
}
return null
}
+/**
+ * Space after of the flow's last text block (px). measureBlocks folds inter-block
+ * margins into the preceding block, but nothing follows the last one, while Word
+ * still lays a note area out below that paragraph's space after.
+ */
+export function trailingSpaceAfterPx(blocks: BlockBox[]): number {
+ let last: BlockBox | undefined
+ for (const b of blocks) {
+ if (!b.el || b.height <= 0) continue
+ if (!last || b.top + b.height > last.top + last.height) last = b
+ }
+ if (!last?.el || last.spaceAfterPx) return 0
+ return parseFloat(getComputedStyle(last.el).marginBottom) || 0
+}
+
+/**
+ * Per-page flow-coordinate bottom of the body text (w:footnotePr w:pos="beneathText":
+ * Word starts the note area right under the last line instead of at the page bottom).
+ * A block's footnote reservation is virtual space below its text and is excluded;
+ * virtual blocks (endnote area, float spill) are not text. The flow's last block
+ * contributes its space after (the page's window is clamped by the caller).
+ */
+export function pageTextEnds(blocks: BlockBox[], slices: PageSlice[]): number[] {
+ const text = blocks.filter((b) => b.el || b.docxIndex !== undefined)
+ const bottomOf = (b: BlockBox) => b.top + b.height - (b.footnoteExtraPx ?? 0)
+ const flowEnd = text.reduce((m, b) => Math.max(m, bottomOf(b)), 0)
+ const trailing = trailingSpaceAfterPx(blocks)
+ return slices.map((s) => {
+ let end = s.start
+ for (const b of text) {
+ const bottom = bottomOf(b)
+ if (b.top >= s.end || bottom <= s.start) continue
+ end = Math.max(end, Math.min(bottom, s.end))
+ }
+ if (flowEnd > s.start && flowEnd <= s.end + 0.5) end = Math.max(end, flowEnd + trailing)
+ return end
+ })
+}
+
+/**
+ * Page placement of the footnote area (height 0 = none on the page). top is null
+ * for Word's default bottom anchor; w:pos="beneathText" puts it right under the
+ * last body line (regioned pages keep the bottom anchor, their text end is per
+ * column). vOffset is the page's w:vAlign shift, which moves the body and the
+ * area alike. Endnote rows on a beneath-text page start below that footnote area
+ * (Word stacks footnotes, then endnotes): endnoteShift is added to their top; an
+ * area clamped to the content bottom shifts them only as far as its real bottom.
+ */
+export function noteAreaPlacement(
+ height: number,
+ textEnd: number | undefined,
+ slice: Pick,
+ geom: { pageH: number; mTop: number; mBottom: number; headerH: number; vOffset: number },
+): { top: number | null; endnoteShift: number } {
+ if (height <= 0 || textEnd === undefined || slice.regions) return { top: null, endnoteShift: 0 }
+ const beneath = geom.mTop + geom.headerH + geom.vOffset + (textEnd - slice.start)
+ const top = Math.min(beneath, geom.pageH - geom.mBottom - height)
+ return { top, endnoteShift: top + height - beneath }
+}
+
/**
* Endnote layout: endnotes gather at the end of the document
- * (or section) right after the body, flowing to later pages when they don't fit.
+ * (or section) right after the body (below its last space after), flowing to later
+ * pages when they don't fit.
* Before slicing, the endnotes area is appended as a virtual block at flow end: one
* line box per endnote (separator height merged into the first), widowControl off →
* page breaks are allowed between any entries. Returns the endnotes area's top Y.
@@ -266,7 +394,7 @@ export function appendEndnotesBlock(
separatorH: number,
): { totalHeight: number; top: number } | null {
if (items.length === 0) return null
- const top = totalHeight
+ const top = totalHeight + trailingSpaceAfterPx(blocks)
const lineBoxes: Array<{ offsetInBlock: number; height: number }> = []
let off = 0
for (let i = 0; i < items.length; i++) {
@@ -307,7 +435,7 @@ export function appendFloatSpillBlock(
// page — Word never opens a page for them, and their measured tops are not
// flow extents (pinned = page coords, pageRelV = anchor + page offset)
for (const f of floats) {
- if (!f.pinned && !f.pageRelV) bottom = Math.max(bottom, f.top + f.height)
+ if (!f.pinned && !f.pageRelV && !f.noSpill) bottom = Math.max(bottom, f.top + f.height)
}
bottom -= bottomOverhangPx
if (bottom <= totalHeight + 1) return null
diff --git a/apps/docs/src/renderer/pagination-sections.ts b/apps/docs/src/renderer/pagination-sections.ts
index ab07966..f3ef082 100644
--- a/apps/docs/src/renderer/pagination-sections.ts
+++ b/apps/docs/src/renderer/pagination-sections.ts
@@ -1,13 +1,15 @@
// Section geometry: page box, margins, columns, doc-grid pitch and the
// per-block column / width / vertical-alignment specs derived from sections.
-import type { SectionInfo, SectionSettings } from '@genoffice/docx-engine'
+import type { SectionInfo, SectionSettings, TextFlowDirection } from '@genoffice/docx-engine'
+import { columnLineSplits } from './pagination-slices'
import type {
BlockBox,
ColumnBlockPlacement,
PageSlice,
SectionGeom,
SectionHfHeights,
+ ColumnSplitShape,
} from './pagination-types'
const twipsToPx = (twips: number) => (twips / 1440) * 96
@@ -29,8 +31,21 @@ export function sectionPageBox(set: SectionSettings): {
}
}
-/** Body top = max(marginTop, headerDist + header height) */
+/** Shared canvas paper: the widest section's page (px); narrower pages are centered on it. */
+export function paperWidthPx(sections: SectionInfo[], fallback?: SectionSettings): number {
+ const widths = sections.map((s) => twipsToPx(s.settings.pageWidth))
+ if (fallback) widths.push(twipsToPx(fallback.pageWidth))
+ return widths.length > 0 ? Math.max(...widths) : 0
+}
+
+/** Left edge of a section's page on the shared paper (px); Word centers pages of differing widths. */
+export function pageLeftPx(set: SectionSettings, paperW: number): number {
+ return Math.max(0, (paperW - twipsToPx(set.pageWidth)) / 2)
+}
+
+/** Body top = max(marginTop, headerDist + header height); a fixed (negative pgMar) margin ignores the header */
export function effectiveTopPx(set: SectionSettings, headerPx: number): number {
+ if (set.marginTopFixed) return twipsToPx(set.marginTop)
const dist = twipsToPx(set.headerDist ?? 720)
return Math.max(twipsToPx(set.marginTop), headerPx > 0 ? dist + headerPx : 0)
}
@@ -52,6 +67,7 @@ export function canvasContentTopPx(
/** Body bottom margin = max(marginBottom, footerDist + footer height) */
export function effectiveBottomPx(set: SectionSettings, footerPx: number): number {
+ if (set.marginBottomFixed) return twipsToPx(set.marginBottom)
const dist = twipsToPx(set.footerDist ?? 720)
return Math.max(twipsToPx(set.marginBottom), footerPx > 0 ? dist + footerPx : 0)
}
@@ -164,8 +180,13 @@ export function sectionBidi(s: SectionInfo): boolean {
* column width plus a per-column constant translate mapping its stacked
* single-flow position into the column slot. dy = region top − the column
* start's offset from the page start (negative for later columns/regions:
- * they pull up over the vacated stacked space). Blocks are placed whole by
- * their top; floated/eless blocks are skipped.
+ * they pull up over the vacated stacked space). Blocks are placed by their
+ * top. A paragraph cut at a line boundary between columns of different widths
+ * (w:equalWidth="0") takes the wider width plus a split shape that rewraps
+ * the head or the tail at the narrower one (columnLineSplits); any other
+ * block whose lines run on into narrower columns takes the narrowest of them
+ * (a narrow-wrapped head beats a tail clipped by its column).
+ * Floated/eless blocks are skipped.
*/
export function columnLayoutSpecs(
blocks: BlockBox[],
@@ -174,10 +195,53 @@ export function columnLayoutSpecs(
): ColumnBlockPlacement[] {
const specs: ColumnBlockPlacement[] = []
if (blocks.length === 0) return specs
- let bi = 0
+ const splitOf = new Map()
+ const colWidthsOf = (si: number) => {
+ const sec = sections[Math.max(0, Math.min(si, sections.length - 1))]
+ if (!sec) return undefined
+ const geom = sectionColGeom(sec)
+ return geom.cols > 1 ? geom.widths : undefined
+ }
+ for (const sp of columnLineSplits(blocks, slices, colWidthsOf)) {
+ const b = blocks[sp.bi]
+ if (!b.el) continue
+ const cs = getComputedStyle(b.el)
+ const padTop = (parseFloat(cs.paddingTop) || 0) + (parseFloat(cs.borderTopWidth) || 0)
+ const headNarrow = sp.headWidthPx < sp.tailWidthPx
+ // no table (the probe failed): the current text bottom bounds the float and
+ // the edge sits a hair past the midpoint cut, inside the cut line's box
+ const tailBottom = sp.tailBottom ?? b.height - (b.spaceAfterPx ?? 0) - (b.footnoteExtraPx ?? 0)
+ const edge = sp.shapeY ?? (headNarrow ? sp.cutY - 1 : sp.cutY + 1)
+ const rtl = cs.direction === 'rtl'
+ splitOf.set(sp.bi, {
+ widthPx: Math.max(sp.headWidthPx, sp.tailWidthPx),
+ floatPx: Math.abs(sp.headWidthPx - sp.tailWidthPx),
+ heightPx: Math.max((headNarrow ? edge : tailBottom) - padTop, 0),
+ insetPx: headNarrow ? 0 : Math.max(edge - padTop, 0),
+ ...(rtl ? { rtl } : {}),
+ })
+ }
+ type Col = {
+ start: number
+ end: number
+ section: number
+ widthPx: number | undefined
+ dx: number
+ dy: number
+ natural: boolean
+ }
+ const cols: Col[] = []
for (const slice of slices) {
if (!slice.regions) {
- while (bi < blocks.length && blocks[bi].top < slice.end - 0.5) bi++
+ cols.push({
+ start: slice.start,
+ end: slice.end,
+ section: -1,
+ widthPx: undefined,
+ dx: 0,
+ dy: 0,
+ natural: true,
+ })
continue
}
for (const region of slice.regions) {
@@ -199,29 +263,142 @@ export function columnLayoutSpecs(
const dx = geom.cols > 1 ? (rtl ? totalW - (xs[c] ?? 0) - w : (xs[c] ?? 0)) : 0
const dy = region.top - (col.start - slice.start)
const widthPx = geom.cols > 1 ? w : undefined
- if (widthPx === undefined && Math.abs(dx) < 0.01 && Math.abs(dy) < 0.01) {
+ cols.push({
+ start: col.start,
+ end: col.end,
+ section: region.section,
+ widthPx,
+ dx,
+ dy,
// untouched single-column region at its natural place: no decorations
- while (bi < blocks.length && blocks[bi].top < col.end - 0.5) bi++
- continue
- }
- while (bi < blocks.length && blocks[bi].top < col.end - 0.5) {
- const b = blocks[bi]
- bi++
- if (!b.el || b.floated) continue
- if (b.top < col.start - 0.5) continue
- specs.push({
- el: b.el,
- ...(widthPx !== undefined ? { widthPx: blockColumnWidth(b.el, widthPx) } : {}),
- dx,
- dy,
- })
- }
+ natural: widthPx === undefined && Math.abs(dx) < 0.01 && Math.abs(dy) < 0.01,
+ })
}
}
}
+ let bi = 0
+ cols.forEach((col, k) => {
+ while (bi < blocks.length && blocks[bi].top < col.end - 0.5) {
+ const b = blocks[bi]
+ const split = splitOf.get(bi)
+ bi++
+ if (col.natural || !b.el || b.floated) continue
+ if (b.top < col.start - 0.5) continue
+ let widthPx = col.widthPx
+ if (split && widthPx !== undefined) {
+ const { widthPx: w, ...shape } = split
+ specs.push({
+ el: b.el,
+ widthPx: blockColumnWidth(b.el, w),
+ dx: col.dx,
+ dy: col.dy,
+ split: shape,
+ })
+ continue
+ }
+ if (widthPx !== undefined) {
+ const bottom = b.top + b.height - (b.footnoteExtraPx ?? 0) - (b.spaceAfterPx ?? 0)
+ for (let j = k + 1; j < cols.length && cols[j].start < bottom - 0.5; j++) {
+ const next = cols[j]
+ if (next.section !== col.section || next.widthPx === undefined) break
+ widthPx = Math.min(widthPx, next.widthPx)
+ }
+ }
+ specs.push({
+ el: b.el,
+ ...(widthPx !== undefined ? { widthPx: blockColumnWidth(b.el, widthPx) } : {}),
+ dx: col.dx,
+ dy: col.dy,
+ })
+ }
+ })
return specs
}
+export interface WidthPassState {
+ sig: string
+ runs: number
+ /** widths applied by the last two passes, by block */
+ last: Map
+ prev: Map
+ /** blocks caught ping-ponging between columns: pinned to the narrower width */
+ forced: Map
+}
+
+export const newWidthPassState = (): WidthPassState => ({
+ sig: '',
+ runs: 0,
+ last: new Map(),
+ prev: new Map(),
+ forced: new Map(),
+})
+
+/** a document edit: the pins and the cycle history belong to the old flow */
+export function resetWidthPassHistory(state: WidthPassState): void {
+ state.runs = 0
+ state.last = new Map()
+ state.prev = new Map()
+ state.forced.clear()
+}
+
+/**
+ * Follow-up pass gate for wrap widths that depend on where a block lands
+ * (w:equalWidth="0" columns): a block's width is that of the column its
+ * measured height puts it in, so a pass whose widths differ from the previous
+ * pass's changed the line breaks and asks for one more measurement. A block
+ * straddling the column boundary may have no fixed point (wide in the first
+ * column it is short enough to start in the second, narrow there it is tall
+ * enough to start in the first — Word rewraps it mid-paragraph, which one DOM
+ * width cannot); once the widths repeat the pass before last, such blocks
+ * are pinned to their narrower width, which wraps complete inside either
+ * column instead of being clipped by the narrow one. Pins apply to `specs`
+ * in place and hold until the caller resets the history (a document edit).
+ * Bounded to maxRuns consecutive re-passes.
+ */
+export function widthPassGate(
+ state: WidthPassState,
+ specs: ColumnBlockPlacement[],
+ maxRuns = 6,
+): boolean {
+ const pin = () => {
+ for (const s of specs) {
+ const f = state.forced.get(s.el)
+ if (f !== undefined && !s.split && s.widthPx !== undefined && s.widthPx > f) s.widthPx = f
+ }
+ }
+ const snapshot = () => new Map(specs.map((s) => [s.el, Math.round(s.widthPx ?? -1)]))
+ const sigOf = (m: Map) => [...m.values()].join(',')
+ // a split's float geometry changes line breaks like a width does
+ const splitSig = () =>
+ specs.some((s) => s.split)
+ ? `|${specs.map((s) => (s.split ? `${Math.round(s.split.heightPx)}/${Math.round(s.split.insetPx)}` : '')).join(',')}`
+ : ''
+ pin()
+ let cur = snapshot()
+ let sig = sigOf(cur)
+ if (`${sig}${splitSig()}` === state.sig) {
+ state.runs = 0
+ return false
+ }
+ if (cur.size === state.prev.size && sig === sigOf(state.prev)) {
+ for (const [el, w] of cur) {
+ const before = state.last.get(el)
+ if (before !== undefined && before > 0 && w > 0 && before !== w) {
+ state.forced.set(el, Math.min(w, before))
+ }
+ }
+ pin()
+ cur = snapshot()
+ sig = sigOf(cur)
+ }
+ state.prev = state.last
+ state.last = cur
+ state.sig = `${sig}${splitSig()}`
+ if (state.runs >= maxRuns) return false
+ state.runs++
+ return true
+}
+
const isTableBlock = (el: HTMLElement) =>
el.tagName === 'TABLE' || el.getAttribute('data-doc-protected') === 'table'
@@ -230,7 +407,12 @@ const isTableBlock = (el: HTMLElement) =>
* sized to the full column overflows its window by its indent and the
* preview clips the last glyphs of every line */
function blockColumnWidth(el: HTMLElement, colW: number): number {
- if (isTableBlock(el) || el.style.width) return colW
+ return Math.max(0, colW - blockInlineExtraPx(el))
+}
+
+/** horizontal margins/padding/borders the block loses from its column width (0 for tables and fixed-width blocks) */
+export function blockInlineExtraPx(el: HTMLElement): number {
+ if (isTableBlock(el) || el.style.width) return 0
const cs = getComputedStyle(el)
let extra = (parseFloat(cs.marginLeft) || 0) + (parseFloat(cs.marginRight) || 0)
if (cs.boxSizing !== 'border-box') {
@@ -240,7 +422,7 @@ function blockColumnWidth(el: HTMLElement, colW: number): number {
(parseFloat(cs.borderLeftWidth) || 0) +
(parseFloat(cs.borderRightWidth) || 0)
}
- return Math.max(0, colW - extra)
+ return extra
}
/**
@@ -255,11 +437,14 @@ function blockColumnWidth(el: HTMLElement, colW: number): number {
* sections'): preview clones render into per-section wrap widths, so any
* container-relative block would reflow there. Tables keep their inline min()
* width and get the section geometry via --doc-content-w / --doc-margin-* instead.
+ * Pages narrower than the shared paper (the widest section) are centered on it
+ * like Word: their blocks carry that page offset as pageDx.
*/
export function sectionWidthSpecs(
blocks: BlockBox[],
sections: SectionInfo[],
geoms: SectionGeom[],
+ paperW = paperWidthPx(sections),
): ColumnBlockPlacement[] {
const canvasW = geoms[0]?.contentWidth
// the canvas pads by sections[0] (App.tsx's canvasSection): placement offsets
@@ -272,7 +457,7 @@ export function sectionWidthSpecs(
const widthDiffers =
g.contentWidth !== undefined && Math.abs(g.contentWidth - (canvasW ?? 0)) > 0.5
const insetDiffers = Math.abs(twipsToPx(set.marginLeft) - canvasInsetLeftPx) > 0.5
- return widthDiffers || insetDiffers
+ return widthDiffers || insetDiffers || pageLeftPx(set, paperW) > 0.5
}
if (canvasW === undefined || !geoms.some((_, i) => differsAt(i))) return []
const specs: ColumnBlockPlacement[] = []
@@ -288,6 +473,7 @@ export function sectionWidthSpecs(
// own section's left margin; dx composes with column/vAlign translates
dx: (set ? twipsToPx(set.marginLeft) : 0) - canvasInsetLeftPx,
dy: 0,
+ pageDx: set ? pageLeftPx(set, paperW) : 0,
contentWPx: w,
marginLeftPx: set ? twipsToPx(set.marginLeft) : 0,
marginRightPx: set ? twipsToPx(set.marginRight) : 0,
@@ -303,6 +489,29 @@ export function sectionWidthSpecs(
return specs
}
+/**
+ * Per-block top margin for documents whose sections disagree on w:pgMar top:
+ * page-relative anchor offsets subtract their own section's top margin
+ * (--doc-margin-top) to land in content coordinates, and the single .doc-page
+ * injection only knows the canvas section's. Uniform docs get no specs.
+ */
+export function sectionTopMarginSpecs(
+ blocks: BlockBox[],
+ sections: SectionInfo[],
+): ColumnBlockPlacement[] {
+ const tops = sections.map((s) => (s.settings ? twipsToPx(s.settings.marginTop) : undefined))
+ const known = tops.filter((t): t is number => t !== undefined)
+ if (known.length === 0 || known.every((t) => Math.abs(t - known[0]) < 0.5)) return []
+ const specs: ColumnBlockPlacement[] = []
+ for (const b of blocks) {
+ if (!b.el) continue
+ const si = Math.max(0, Math.min(b.section ?? 0, tops.length - 1))
+ const t = tops[si]
+ if (t !== undefined) specs.push({ el: b.el, dx: 0, dy: 0, marginTopPx: t })
+ }
+ return specs
+}
+
/**
* Per-block docGrid pitch for documents whose sections disagree on the typed
* line grid (mixed pitches, or typed + untyped): each block carries its own
@@ -379,7 +588,8 @@ export function vAlignShiftSpecs(
for (const slice of slices) {
const va = sections[slice.section]?.settings.vAlign
if (va !== 'center' && va !== 'bottom') continue
- if (slice.regions) continue
+ // vertical-text pages: contentHeight is the sideways fill, not free vertical space
+ if (slice.regions || geoms[slice.section]?.vertical) continue
const colH = geoms[slice.section]?.contentHeight ?? 0
const free = colH - (slice.end - slice.start)
if (free < 1) continue
@@ -401,6 +611,79 @@ export function vAlignShiftSpecs(
return specs
}
+/** sectPr w:textDirection modes the renderer lays out sideways (lrTbV and unknown values stay horizontal) */
+export function sectionVertical(set: SectionSettings | undefined): TextFlowDirection | undefined {
+ const d = set?.textDirection
+ return d === 'tbRl' || d === 'tbRlV' || d === 'btLr' ? d : undefined
+}
+
+/**
+ * Where a block of a vertical-text page paints: `off` is its flow offset from
+ * the page start (negative for a paragraph continued from the previous page),
+ * `extentPx` its block-axis size. tbRl/tbRlV fill from the right edge, btLr from
+ * the left; the translate lifts the block's flow position back to the page top.
+ */
+export function verticalBlockShift(
+ mode: TextFlowDirection,
+ fillWidthPx: number,
+ off: number,
+ extentPx: number,
+): { dx: number; dy: number } {
+ return { dx: mode === 'btLr' ? off : fillWidthPx - off - extentPx, dy: 0 - off }
+}
+
+/**
+ * Per-block placement for pages of vertical-text sections. Blocks are measured
+ * horizontally at the line length (contentWidth) and paginated against the
+ * sideways fill extent (contentHeight); on display each becomes a writing-mode
+ * box as tall as the line length, translated to its sideways slot. The box's
+ * flow footprint is trimmed back to the measured one via margin-bottom so the
+ * page gap math stays that of a horizontal page (the last block also absorbs
+ * the flow beyond the physical body height).
+ */
+export function verticalTextSpecs(
+ blocks: BlockBox[],
+ slices: PageSlice[],
+ sections: SectionInfo[],
+ geoms: SectionGeom[],
+): ColumnBlockPlacement[] {
+ const specs: ColumnBlockPlacement[] = []
+ if (!sections.some((s) => sectionVertical(s.settings))) return specs
+ let bi = 0
+ for (const slice of slices) {
+ const si = Math.max(0, Math.min(slice.section, sections.length - 1))
+ const mode = sectionVertical(sections[si]?.settings)
+ const g = geoms[Math.min(si, geoms.length - 1)]
+ const lineLen = g?.contentWidth
+ if (!mode || !g || slice.regions || lineLen === undefined) {
+ while (bi < blocks.length && blocks[bi].top < slice.end - 0.5) bi++
+ continue
+ }
+ const page: BlockBox[] = []
+ while (bi < blocks.length && blocks[bi].top < slice.end - 0.5) {
+ const b = blocks[bi++]
+ if (b.el && !b.floated && b.top >= slice.start - 0.5) page.push(b)
+ }
+ const used = slice.end - slice.start
+ page.forEach((b, i) => {
+ const off = b.top - slice.start
+ const next = page[i + 1]
+ const marginBottomPx = next
+ ? next.top - b.top - lineLen
+ : Math.min(used, lineLen) - off - lineLen
+ specs.push({
+ el: b.el!,
+ // extras captured during measurement: with the writing-mode decoration
+ // applied, the physical margins no longer hold the indents
+ widthPx: Math.max(0, lineLen - (b.inlineExtraPx ?? blockInlineExtraPx(b.el!))),
+ ...verticalBlockShift(mode, g.contentHeight, off, b.height),
+ vertical: { mode, marginBottomPx, firstOnPage: i === 0 },
+ })
+ })
+ }
+ return specs
+}
+
/** SectionInfo[] → pagination geometry
* - continuous with unchanged page geometry: no forced break (content flows on the same page)
* - continuous with changed page geometry (width/height change, e.g. landscape → portrait): forced break
@@ -435,20 +718,26 @@ export function sectionGeoms(
}
const set = s.settings
const hf = hfHeights?.[i]
+ const vertical = sectionVertical(set)
const firstContentHeight =
- hf?.firstHeaderPx !== undefined || hf?.firstFooterPx !== undefined
+ !vertical && (hf?.firstHeaderPx !== undefined || hf?.firstFooterPx !== undefined)
? twipsToPx(set.pageHeight) -
effectiveTopPx(set, hf.firstHeaderPx ?? 0) -
effectiveBottomPx(set, hf.firstFooterPx ?? 0)
: undefined
+ const bodyH =
+ twipsToPx(set.pageHeight) -
+ effectiveTopPx(set, hf?.headerPx ?? 0) -
+ effectiveBottomPx(set, hf?.footerPx ?? 0)
+ const bodyW = twipsToPx(set.pageWidth - set.marginLeft - set.marginRight)
return {
- contentHeight:
- twipsToPx(set.pageHeight) -
- effectiveTopPx(set, hf?.headerPx ?? 0) -
- effectiveBottomPx(set, hf?.footerPx ?? 0),
+ // vertical text fills the page sideways: lines are bodyH long and stack across bodyW
+ contentHeight: vertical ? bodyW : bodyH,
...(firstContentHeight !== undefined ? { firstContentHeight } : {}),
- contentWidth: twipsToPx(set.pageWidth - set.marginLeft - set.marginRight),
+ contentWidth: vertical ? bodyH : bodyW,
+ ...(vertical ? { vertical } : {}),
topPx: effectiveTopPx(set, hf?.headerPx ?? 0),
+ pageHeightPx: twipsToPx(set.pageHeight),
forceBreak,
startType: s.startType,
// colWidths only for explicit-width columns: the narrower-column gate is
diff --git a/apps/docs/src/renderer/pagination-slices.ts b/apps/docs/src/renderer/pagination-slices.ts
index 9c9d918..72c231b 100644
--- a/apps/docs/src/renderer/pagination-slices.ts
+++ b/apps/docs/src/renderer/pagination-slices.ts
@@ -4,9 +4,12 @@ import { FOOTNOTE_SEPARATOR_H } from './line-metrics'
import type {
BlockBox,
PageSlice,
+ RowCellBox,
+ RowSplitRule,
SectionGeom,
SliceOutputs,
TableRowBox,
+ ColumnLineSplit,
} from './pagination-types'
/**
@@ -227,8 +230,12 @@ export function computeSectionedSlicesF2(
out?: SliceOutputs,
): PageSlice[] {
if (out?.rowFills) out.rowFills.length = 0
+ if (out?.rowSplits) out.rowSplits.length = 0
if (out?.floatVShifts) out.floatVShifts.length = 0
+ if (out?.floatFlows) out.floatFlows.length = 0
+ if (out?.floatSplits) out.floatSplits.length = 0
if (out?.oversizeClips) out.oversizeClips.length = 0
+ if (out?.colWrapRequests) out.colWrapRequests.length = 0
const total = Math.max(totalHeight, 0)
// sections whose every block collapsed to a zero-height chip (lone sectPr
// paragraphs) never appear in the measured blocks; they still claim their
@@ -255,7 +262,11 @@ export function computeSectionedSlicesF2(
type ColEntry = { y: number; repeatHeader?: { top: number; height: number } }
type Region = { top: number; height: number; section: number; cols: number; entries: ColEntry[] }
- const pages: Array<{ section: number; regions: Region[] }> = []
+ const pages: Array<{ section: number; regions: Region[]; continued?: true }> = []
+ // flow Y where a section began below the top of a page it does not own: its
+ // later pages are not its "first page" (Word ties titlePg to the page a
+ // section starts on, and that page keeps the host section's header/footer)
+ const midPageStart = new Map()
let pageStart = 0 // starting Y of the current page (absolute)
let curSection = initSection
@@ -267,7 +278,14 @@ export function computeSectionedSlicesF2(
let usedInCol = 0 // height used in the current column
let pendingBreak = false
let pendingForce = false
+ let pendingExtraBreaks = 0
let pendingColBreak = false
+ const queueBreakAfter = (b: BlockBox) => {
+ if (!b.breakAfter) return
+ pendingBreak = true
+ if (b.breakForce) pendingForce = true
+ pendingExtraBreaks = b.extraBreaksAfter ?? 0
+ }
// Word draws one footnote separator per page, not per referencing paragraph:
// the first footnote-bearing block on a page shrinks the page's usable height
// by the separator; carried to the next page when that block turns the page
@@ -344,10 +362,13 @@ export function computeSectionedSlicesF2(
regionTop = 0
// the section's first page renders the titlePg header/footer variant, so it
// gets its own capacity (same "first page" rule as sectionFirstPages)
- const firstOfSection = pages.length === 0 || pages[pages.length - 1].section !== section
+ const continued = (midPageStart.get(section) ?? Infinity) < y - 0.5
+ if (!continued) midPageStart.delete(section)
+ const firstOfSection =
+ !continued && (pages.length === 0 || pages[pages.length - 1].section !== section)
const g = geomOf(section)
contentH = Math.max((firstOfSection ? g.firstContentHeight : undefined) ?? g.contentHeight, 1)
- pages.push({ section, regions: [] })
+ pages.push({ section, regions: [], ...(continued ? { continued: true } : {}) })
openRegion(y, section, headerH, headerTop)
pageNoteSepPx = curBlockNotes ? FOOTNOTE_SEPARATOR_H : 0
pageFloatBottom = 0
@@ -378,6 +399,8 @@ export function computeSectionedSlicesF2(
if (region.cols <= 1 || regionBroke || runaway) return null
const startY = region.entries[0]?.y
if (startY === undefined || region.entries[0].repeatHeader) return null
+ const colWs = geomOf(region.section).colWidths
+ if (colWs && colWs.length === region.cols) return balanceUnequal(region, endBi, endY, colWs)
// boundary units: block tops always cuttable; in-block line starts cuttable
// per widow/orphan atomicity. Each unit carries the counted content height of
// its piece (0 for empty paragraph marks — they flow but don't add quota)
@@ -438,18 +461,162 @@ export function computeSectionedSlicesF2(
return maxExtent
}
+ /**
+ * Unequal column widths: the same text is taller in a narrower column, so a
+ * block's extent in a column is its measured height scaled by measured width /
+ * column width, and a paragraph is cut at a line boundary only where a
+ * ColWrapTable (offscreen probe: head at this column's width, tail rewrapped
+ * at the next one's) makes both parts exact. Two columns take the cut that
+ * minimizes the taller column, ties filling the left column first (Word's
+ * line quota); more columns cut nearest the width-normalized quota. A
+ * paragraph straddling the quota without a table is requested through
+ * out.colWrapRequests and the pass cuts on block tops meanwhile.
+ */
+ const balanceUnequal = (
+ region: Region,
+ endBi: number,
+ endY: number,
+ colWs: number[],
+ ): number | null => {
+ const startY = region.entries[0].y
+ type Piece = { y: number; h: number; w?: number; cut: boolean; b: BlockBox }
+ const pieces: Piece[] = []
+ let contentEnd = startY
+ for (let i = regionStartBi; i < endBi; i++) {
+ const b = blocks[i]
+ if (b.tableRows) return null
+ if (b.floated) continue
+ if (b.top + b.height < startY + 0.01 || b.top > endY - 0.01) continue
+ const y = Math.max(b.top, startY)
+ const bottom = Math.min(b.top + b.height, endY)
+ if (!b.emptyPara) contentEnd = Math.max(contentEnd, bottom)
+ pieces.push({
+ y,
+ h: b.emptyPara ? 0 : Math.max(bottom - y, 0),
+ ...(b.fixedWidthPx === undefined && b.widthPx ? { w: b.widthPx } : {}),
+ cut: b.top >= startY - 0.01,
+ b,
+ })
+ }
+ if (contentEnd - startY <= 0.01) return null
+ const sumW = colWs.reduce((a, w) => a + w, 0)
+ const avgW = sumW / colWs.length
+ const totalInk = pieces.reduce((a, p) => a + p.h * (p.w ?? avgW), 0)
+ if (totalInk <= 0.01) return null
+ const targetH = totalInk / sumW
+ const extentIn = (p: Piece, c: number) => (p.w ? (p.h * p.w) / colWs[c] : p.h)
+ const trailOf = (b: BlockBox) => (b.spaceAfterPx ?? 0) + (b.footnoteExtraPx ?? 0)
+ // undefined: not cuttable inside; null: cuttable, table not measured yet
+ const tableOf = (p: Piece, c: number) => {
+ if (!p.w || !p.b.el || p.b.keepLines || p.h <= 0.01) return undefined
+ if (Math.abs(colWs[c] - colWs[c + 1]) < 0.5) return undefined
+ return (
+ p.b.colWraps?.find(
+ (t) =>
+ Math.abs(t.headWidthPx - colWs[c]) < 0.5 &&
+ Math.abs(t.tailWidthPx - colWs[c + 1]) < 0.5,
+ ) ?? null
+ )
+ }
+ type Cand = { y: number; left: number; right: number; next: number; carry: number }
+ const cuts: number[] = []
+ let acc = 0
+ let prevCut = startY
+ let from = 0
+ for (let c = 0; c < colWs.length - 1; c++) {
+ const last = c === colWs.length - 2
+ // a probed paragraph moved whole into the next column is exact there too
+ const nextExt = (p: Piece) => {
+ const t = tableOf(p, c)
+ return t ? t.tailH[0] + trailOf(p.b) : extentIn(p, c + 1)
+ }
+ const rest: number[] = new Array(pieces.length + 1).fill(0)
+ for (let j = pieces.length - 1; j >= from; j--) rest[j] = rest[j + 1] + nextExt(pieces[j])
+ // the ideal cut sits near the quota but narrow columns waste more than the
+ // proportional estimate: probe the straddler and its neighbours
+ const want = new Set()
+ let q = acc
+ for (let j = from; j < pieces.length; j++) {
+ const ext = extentIn(pieces[j], c)
+ if (q < targetH + 0.01 && q + ext > targetH - 0.01) {
+ for (const m of [j - 1, j, j + 1]) if (m >= from && m < pieces.length) want.add(m)
+ }
+ q += ext
+ }
+ let best: Cand | null = null
+ const better = (x: Cand, y: Cand) =>
+ last
+ ? Math.max(x.left, x.right) < Math.max(y.left, y.right) - 0.01 ||
+ (Math.abs(Math.max(x.left, x.right) - Math.max(y.left, y.right)) <= 0.01 &&
+ x.left > y.left + 0.01)
+ : Math.abs(x.left - targetH) < Math.abs(y.left - targetH) - 0.01 ||
+ (Math.abs(Math.abs(x.left - targetH) - Math.abs(y.left - targetH)) <= 0.01 &&
+ x.left > y.left + 0.01)
+ const consider = (x: Cand) => {
+ if (x.left <= 0.01) return
+ if (!best || better(x, best)) best = x
+ }
+ let a = acc
+ for (let j = from; j < pieces.length; j++) {
+ const p = pieces[j]
+ const ext = extentIn(p, c)
+ if (p.cut && p.y > prevCut + 0.01)
+ consider({ y: p.y, left: a, right: rest[j], next: j, carry: 0 })
+ const table = tableOf(p, c)
+ if (table === null) {
+ if (want.has(j))
+ out?.colWrapRequests?.push({
+ blockTop: p.b.top,
+ headWidthPx: colWs[c],
+ tailWidthPx: colWs[c + 1],
+ })
+ } else if (table) {
+ const minKeep = p.b.widowControl !== false ? 2 : 1
+ for (let k = minKeep; k <= table.n - minKeep; k++) {
+ const y = p.b.top + table.headH[k]
+ if (y <= p.y + 0.01 || y >= endY - 0.01) continue
+ const tail = Math.min(table.tailH[k] + trailOf(p.b), p.h)
+ consider({
+ y,
+ left: a + (y - p.y),
+ right: tail + rest[j + 1],
+ next: j + 1,
+ carry: tail,
+ })
+ }
+ }
+ a += ext
+ }
+ consider({ y: endY, left: a, right: 0, next: pieces.length, carry: 0 })
+ const pick: Cand = best ?? { y: endY, left: a, right: 0, next: pieces.length, carry: 0 }
+ cuts.push(pick.y)
+ prevCut = pick.y
+ acc = pick.carry
+ from = pick.next
+ }
+ region.entries = [region.entries[0], ...cuts.map((y) => ({ y }))]
+ const cutEdges = [startY, ...cuts, endY].map((y) => Math.min(y, contentEnd))
+ let maxExtent = 0
+ for (let k = 1; k < cutEdges.length; k++)
+ maxExtent = Math.max(maxExtent, cutEdges[k] - cutEdges[k - 1])
+ region.height = maxExtent
+ return maxExtent
+ }
+
// usable column capacity: the page's footnote separator strip is not placeable
const capColH = () => colH - pageNoteSepPx
// capacity of a fresh page for the CURRENT block: the separator only follows
// blocks that carry footnotes (empty-page / one-page-height checks). A block
// of a section other than the page's owner would open that section's first
- // page (startPage: firstContentHeight when titlePg shortens it)
+ // page (startPage: firstContentHeight when titlePg shortens it) unless the
+ // section already began above it on this page (startPage: continued)
const freshColH = () => {
const g = geomOf(curSection)
+ const continued = (midPageStart.get(curSection) ?? Infinity) < blocks[curBi].top - 0.5
const fresh =
pages[pages.length - 1]?.section === curSection
? colH
- : Math.max(g.firstContentHeight ?? g.contentHeight, 1)
+ : Math.max((continued ? undefined : g.firstContentHeight) ?? g.contentHeight, 1)
return fresh - (curBlockNotes ? FOOTNOTE_SEPARATOR_H : 0)
}
// whether height h fits in the current column (runaway degrade: everything fits)
@@ -513,13 +680,15 @@ export function computeSectionedSlicesF2(
} else if (pageBlank() && !claimed && pageFloatBottom <= 0) {
const page = pages[pages.length - 1]
page.section = bSection
+ delete page.continued
page.regions.pop()
contentH = Math.max(g.firstContentHeight ?? g.contentHeight, 1)
openRegion(block.top, bSection)
- } else if (newCols !== colCount) {
- // continuous section changing column count: balance the closed multi-column
- // region (Word), then open a new region in the remaining page height; if the
- // page is used up, turn the page. An unbalanced region ends at its
+ } else if (newCols !== colCount || (colCount > 1 && !g.colBreakStart && !g.forceBreak)) {
+ // continuous section closing a multi-column region (a column-count change,
+ // or the same columns again — the "balance columns" idiom): balance the
+ // closed region (Word), then open a new region in the remaining page
+ // height; if the page is used up, turn the page. An unbalanced region ends at its
// tallest column's content, NOT the full column height: a short
// letterhead row split by an explicit column break must not eat the
// page (prod100r3/45 lost its whole first page to a 2-line region) —
@@ -537,12 +706,14 @@ export function computeSectionedSlicesF2(
if (regionBottom >= contentH - 1) {
startPage(block.top, bSection)
} else {
+ if (!g.forceBreak) midPageStart.set(bSection, block.top)
regionTop = regionBottom
openRegion(block.top, bSection)
}
} else {
- // column count unchanged: the flow continues in the current region.
- // nextColumn into a same-count section: advance one column at the boundary (no-op at a column top)
+ // single column kept, or nextColumn into a same-count section: the flow
+ // continues in the current region, advancing one column at the boundary (no-op at a column top)
+ if (!g.forceBreak) midPageStart.set(bSection, block.top)
if (g.colBreakStart && !colEmpty()) {
regionBroke = true
newColumn(block.top, bSection)
@@ -566,8 +737,13 @@ export function computeSectionedSlicesF2(
) {
startPage(breakY(block.top), curSection)
}
+ // further break characters in either run always turn the page (Word keeps
+ // one blank sheet per extra break, e.g. two Ctrl+Enter in a row)
+ const extraBreaks = pendingExtraBreaks + (block.extraBreaksBefore ?? 0)
+ for (let k = 0; k < extraBreaks; k++) startPage(breakY(block.top), curSection)
pendingBreak = false
pendingForce = false
+ pendingExtraBreaks = 0
// column break: change column (turn the page on the last column); no-op at column top
if ((pendingColBreak || block.colBreakBefore) && !colEmpty()) {
regionBroke = true
@@ -597,26 +773,113 @@ export function computeSectionedSlicesF2(
// CSS-floated block (wrapped image / w:tblpPr table): following block boxes
// stack ignoring it (only their line boxes shorten), so it consumes no column
// height — counting it would double-book the overlap and break pages early
+ // A floating table that does not fit splits at row boundaries (Word); only
+ // a row taller than a page defeats that: report the table for in-flow
+ // rendering, where the row itself page-breaks (a zero-height float would
+ // clip everything past the first page).
+ let flowing = false
+ if (block.floatTable && out?.floatFlows) {
+ const rows = block.tableRows
+ flowing =
+ block.height > contentH + 0.01 &&
+ !!rows?.length &&
+ rows.some((r) => !r.vMergeContinue && r.height > contentH + 0.01)
+ if (flowing) out.floatFlows.push({ blockTop: block.top })
+ }
+
if (block.floated) {
- if (!fits(block.height) && !colEmpty()) advance(block.top, curSection)
- // page/margin-anchored w:tblpY: shift the float down to its target Y on
- // the page it lands on (never up — flow position is the floor, like the
- // X clamp keeping floats on the page)
+ // whole-row cuts only: an in-row cut would leave the continuation where
+ // it is in the DOM, and the wrapping text follows the real box
+ const splitRows =
+ block.floatTable && !flowing && block.tableRows?.length
+ ? block.tableRows.map(
+ ({ height, cantSplit, isHeader, vMergeContinue, minHPx, notesPx }) => ({
+ height,
+ cantSplit,
+ isHeader,
+ vMergeContinue,
+ minHPx,
+ notesPx,
+ }),
+ )
+ : undefined
+ // the table opens on the next page when not even its first row (with the
+ // leading header rows) fits the remainder
+ const leadH = splitRows ? floatLeadHeight(splitRows, contentH) : block.height
+ if (!fits(leadH) && !colEmpty()) advance(block.top, curSection)
+ // page/margin-anchored w:tblpY: shift the float to its target Y on the
+ // page it lands on. Never up past content already placed (flow position
+ // is the floor, like the X clamp keeping floats on the page) — except at
+ // a page top, where the table may hang into the top margin like Word's
+ // page-anchored cover blocks. A table about to flow gets no shift: the
+ // flowed pass could not strip it and would not re-run.
let floatDy = 0
- if (block.pageRelVyPx !== undefined) {
- const target =
- block.pageRelVAnchor === 'page'
- ? block.pageRelVyPx - (geomOf(curSection).topPx ?? 0)
- : block.pageRelVyPx
- floatDy = Math.max(0, target - (regionTop + usedInCol))
+ if (block.pageRelVyPx !== undefined && !flowing) {
+ const topPx = geomOf(curSection).topPx ?? 0
+ const pageRel = block.pageRelVAnchor === 'page'
+ const spanH = pageRel ? (geomOf(curSection).pageHeightPx ?? topPx + contentH) : contentH
+ const spec = block.pageRelVSpec
+ const alignY =
+ spec === 'bottom'
+ ? spanH - block.height
+ : spec === 'center'
+ ? (spanH - block.height) / 2
+ : spec === 'top'
+ ? 0
+ : block.pageRelVyPx
+ const target = pageRel ? alignY - topPx : alignY
+ // single-column pages: the float's measured top is where CSS puts it
+ // (below an earlier float it stacked under); the virtual flow position
+ // stands in where columns make the DOM column-agnostic
+ const flowY = colCount === 1 ? block.top - pageStart : regionTop + usedInCol
+ floatDy = target - flowY
+ if (floatDy < 0) {
+ floatDy = pageBlank() ? Math.max(floatDy, pageRel ? -topPx - flowY : -flowY) : 0
+ }
out?.floatVShifts?.push({ blockTop: block.top, dyPx: floatDy })
}
pageFloatBottom = Math.max(pageFloatBottom, block.top + floatDy + block.height)
- place(0)
- if (block.breakAfter) {
- pendingBreak = true
- if (block.breakForce) pendingForce = true
+ if (splitRows && !fits(floatDy + block.height)) {
+ // Word: the portions before the last page fill their pages alone (the
+ // anchor paragraph moves with the last portion), so they charge the
+ // column like in-flow rows; the last portion is the float proper and
+ // charges nothing — the wrapping text beside it carries the extent
+ const used0 = usedInCol
+ place(floatDy)
+ const cutYs: number[] = []
+ _placeTable(
+ { ...block, top: block.top + floatDy },
+ splitRows,
+ freshColH(),
+ fits,
+ place,
+ () => Math.max(capColH() - usedInCol, 0),
+ colEmpty,
+ (y, section, headerH = 0) => {
+ advance(y, section, headerH, block.top)
+ cutYs.push(y)
+ },
+ curSection,
+ )
+ if (cutYs.length > 0) place(-usedInCol)
+ else place(used0 - usedInCol)
+ // the page turns reset the float bottom: the last portion still reaches
+ // the table's bottom on the closing page
+ pageFloatBottom = Math.max(pageFloatBottom, block.top + floatDy + block.height)
+ // a turn at the table's own top is the whole-table push above, not a split
+ const cuts = cutYs.filter((y) => y > block.top + floatDy + 0.5)
+ if (cuts.length > 0) {
+ out?.floatSplits?.push({
+ blockTop: block.top,
+ dyPx: floatDy,
+ cutYs: cuts,
+ carryPx: cuts[cuts.length - 1] - block.top,
+ })
+ }
+ } else {
+ place(0)
}
+ queueBreakAfter(block)
if (block.colBreakAfter) pendingColBreak = true
continue
}
@@ -631,10 +894,7 @@ export function computeSectionedSlicesF2(
pageFloatBottom = Math.max(pageFloatBottom, bandBottom)
if (!fits(block.height)) pendingBandBottom = Math.max(pendingBandBottom, bandBottom)
place(Math.min(block.height, Math.max(capColH() - usedInCol, 0)))
- if (block.breakAfter) {
- pendingBreak = true
- if (block.breakForce) pendingForce = true
- }
+ queueBreakAfter(block)
if (block.colBreakAfter) pendingColBreak = true
continue
}
@@ -650,10 +910,7 @@ export function computeSectionedSlicesF2(
if (block.breakOnlyLineH !== undefined) {
if (!fits(block.breakOnlyLineH) && !pageBlank()) startPage(block.top, curSection)
place(block.height)
- if (block.breakAfter) {
- pendingBreak = true
- if (block.breakForce) pendingForce = true
- }
+ queueBreakAfter(block)
if (block.colBreakAfter) pendingColBreak = true
continue
}
@@ -691,7 +948,16 @@ export function computeSectionedSlicesF2(
advance,
curSection,
out?.rowFills
- ? (row, targetPx) => out.rowFills!.push({ blockTop: block.top, row, targetPx })
+ ? (row, targetPx, extraPx) =>
+ out.rowFills!.push({
+ blockTop: block.top,
+ row,
+ targetPx,
+ ...(extraPx ? { extraPx } : {}),
+ })
+ : undefined,
+ out?.rowSplits
+ ? (row, rules) => out.rowSplits!.push({ blockTop: block.top, row, rules })
: undefined,
)
if (block.spaceAfterPx) place(block.spaceAfterPx) // space after the table (may overflow into the bottom margin)
@@ -699,10 +965,7 @@ export function computeSectionedSlicesF2(
// consumes capacity — the part not already charged to the rows' pages
const restNotes = (block.footnoteExtraPx ?? 0) - chargedNotes
if (restNotes > 0) place(restNotes)
- if (block.breakAfter) {
- pendingBreak = true
- if (block.breakForce) pendingForce = true
- }
+ queueBreakAfter(block)
if (block.colBreakAfter) pendingColBreak = true
continue
}
@@ -723,10 +986,7 @@ export function computeSectionedSlicesF2(
clipPx: Math.max(capColH() - usedInCol, 1),
})
place(block.height)
- if (block.breakAfter) {
- pendingBreak = true
- if (block.breakForce) pendingForce = true
- }
+ queueBreakAfter(block)
if (block.colBreakAfter) pendingColBreak = true
continue
}
@@ -756,18 +1016,38 @@ export function computeSectionedSlicesF2(
// chainEnd now points at the first non-keepNext block (the anchor), e.g. block[56]
// the actual keepNext chain is bi..chainEnd-1; the anchor is chainEnd
const lastKeepNextIdx = chainEnd - 1 // last keepNext block
- const anchorBlock = blocks[chainEnd] // anchor block (first non-keepNext)
- // a pageBreakBefore inside the chain truncates it (highest priority)
+ // a pageBreakBefore inside the chain truncates it (highest priority); so
+ // does a forced section start: a keepNext on the previous section's last
+ // paragraph cannot pull the next section back onto its page (Word)
+ const forcedSectStart = (k: number) => {
+ const sec = blocks[k]?.section ?? 0
+ return k > 0 && sec !== (blocks[k - 1].section ?? sec) && !!geomOf(sec).forceBreak
+ }
+ // a trailing w:br on a chain block ends the chain the same way (Word turns
+ // the page there, so the block cannot keep with the next one)
let effectiveChainEnd = lastKeepNextIdx
- for (let k = bi + 1; k <= lastKeepNextIdx; k++) {
- if (blocks[k].breakBefore || innerBroken(blocks[k])) {
+ for (let k = bi; k <= lastKeepNextIdx; k++) {
+ if (k > bi && (blocks[k].breakBefore || innerBroken(blocks[k]) || forcedSectStart(k))) {
effectiveChainEnd = k - 1
break
}
+ if (blocks[k].breakAfter) {
+ effectiveChainEnd = k
+ break
+ }
}
- // check whether the anchor has breakBefore (if so, the anchor is handled independently)
- const anchorHasBreak = anchorBlock?.breakBefore ?? false
+ // the keepNext blocks after the cut form their own chain
+ if (effectiveChainEnd < lastKeepNextIdx)
+ chainStart.fill(effectiveChainEnd + 1, effectiveChainEnd + 1, chainEnd + 1)
+ // the anchor is the block after the (possibly truncated) chain; one that
+ // breaks the page itself is handled independently
+ const anchorIdx = effectiveChainEnd + 1
+ const anchorBlock = blocks[anchorIdx]
+ const anchorHasBreak =
+ (anchorBlock?.breakBefore ?? false) ||
+ forcedSectStart(anchorIdx) ||
+ !!blocks[effectiveChainEnd].breakAfter
// compute the chain height (keepNext blocks) + the anchor's demand
let chainH = 0
@@ -821,10 +1101,7 @@ export function computeSectionedSlicesF2(
// place chain head through chain tail (the keepNext blocks)
for (let k = bi; k <= effectiveChainEnd; k++) place(blocks[k].height)
bi = effectiveChainEnd
- if (blocks[effectiveChainEnd].breakAfter) {
- pendingBreak = true
- if (blocks[effectiveChainEnd].breakForce) pendingForce = true
- }
+ queueBreakAfter(blocks[effectiveChainEnd])
if (blocks[effectiveChainEnd].colBreakAfter) pendingColBreak = true
continue
}
@@ -851,10 +1128,7 @@ export function computeSectionedSlicesF2(
colCount > 1,
(y, section) => startPage(breakY(y), section),
)
- if (block.breakAfter) {
- pendingBreak = true
- if (block.breakForce) pendingForce = true
- }
+ queueBreakAfter(block)
if (block.colBreakAfter) pendingColBreak = true
continue
}
@@ -898,10 +1172,7 @@ export function computeSectionedSlicesF2(
} else {
place(block.height)
}
- if (block.breakAfter) {
- pendingBreak = true
- if (block.breakForce) pendingForce = true
- }
+ queueBreakAfter(block)
if (block.colBreakAfter) pendingColBreak = true
continue
}
@@ -922,18 +1193,18 @@ export function computeSectionedSlicesF2(
colCount > 1,
(y, section) => startPage(breakY(y), section),
)
- if (block.breakAfter) {
- pendingBreak = true
- if (block.breakForce) pendingForce = true
- }
+ queueBreakAfter(block)
if (block.colBreakAfter) pendingColBreak = true
}
// a trailing page break keeps its deliberate blank last page (Word: the final
// paragraph mark lands after the break; LO dropping it is tdf#99090); a trailing
// column break advances the same way (new page when the last column is used)
- if (pendingBreak) startPage(Math.max(total, pageStart), curSection)
- else if (pendingColBreak && !colEmpty()) newColumn(Math.max(total, pageStart), curSection)
+ if (pendingBreak) {
+ for (let k = 0; k <= pendingExtraBreaks; k++) startPage(Math.max(total, pageStart), curSection)
+ } else if (pendingColBreak && !colEmpty()) {
+ newColumn(Math.max(total, pageStart), curSection)
+ }
// ── Output: flatten column starts into ranges, aggregate by page (pages with cols>1 regions get regions attached) ──
const flat: ColEntry[] = []
@@ -955,6 +1226,7 @@ export function computeSectionedSlicesF2(
start: first.y,
end: endOf.get(entries[entries.length - 1])!,
section: p.section,
+ ...(p.continued ? { continuedSection: true } : {}),
...(first.repeatHeader ? { repeatHeader: first.repeatHeader } : {}),
...(multiCol
? {
@@ -975,9 +1247,158 @@ export function computeSectionedSlicesF2(
})
}
+/**
+ * Word-style split of a multi-cell row: each cell breaks at its own line
+ * boundary (widow/orphan: a cut leaves >= 2 lines of a paragraph on each side;
+ * the widow rule carries lines over, the orphan rule moves the paragraph
+ * whole), the fragment fills the page and every cell's
+ * continuation lines start flush at the next page's top. `turn(placed, y)`
+ * places the finished fragment, opens the next page at row-relative `y` and
+ * returns its capacity. Rules (row-relative `from`) tell the preview, per
+ * fragment, how to translate/clip each cell's children. 'nofit' when no cell
+ * fits a line on this page (the caller may retry on a fresh page); null when
+ * the content fits and only the row's trailing padding overflows by more than
+ * a cell margin (legacy path).
+ */
+export function planRowSplit(
+ row: TableRowBox,
+ firstAvail: number,
+ contentH: number,
+ turn: (placed: number, y: number) => number,
+): { lastFragment: number; target: number; rules: RowSplitRule[] } | 'nofit' | null {
+ const cells = row.cells ?? []
+ const next = cells.map(() => 0)
+ const dy = cells.map(() => 0)
+ const rules: RowSplitRule[] = []
+ const lastBottom = (c: RowCellBox) => (c.lines.length ? c.lines[c.lines.length - 1][1] : 0)
+ const childTop = (c: RowCellBox, ch: number) =>
+ Math.min(...c.lines.filter((_, i) => c.childOf[i] === ch).map((l) => l[0]))
+ const childBottom = (c: RowCellBox, ch: number) =>
+ Math.max(...c.lines.filter((_, i) => c.childOf[i] === ch).map((l) => l[1]))
+ const naturalH = row.height - (row.splitExtra ?? 0)
+ const padB = Math.max(0, naturalH - Math.max(0, ...cells.map(lastBottom)))
+ let y = 0
+ let avail = firstAvail
+ let stalled = false
+ for (let frag = 0; frag < 256; frag++) {
+ let progressed = false
+ let held = false
+ const cutIdx = cells.map((c, k) => {
+ const j = next[k]
+ let fit = j
+ for (let i = j; i < c.lines.length; i++) {
+ if (c.lines[i][1] + dy[k] - y <= avail + 0.5) fit = i + 1
+ else break
+ }
+ const raw = fit
+ if (fit < c.lines.length && fit > j && c.paraOf[fit - 1] === c.paraOf[fit]) {
+ const p = c.paraOf[fit]
+ let start = fit
+ while (start > 0 && c.paraOf[start - 1] === p) start--
+ let end = fit
+ while (end < c.lines.length && c.paraOf[end] === p) end++
+ if (end - fit < 2) fit = end - 2
+ if (start >= j && fit - start < 2) fit = start
+ }
+ if (fit > j) progressed = true
+ else if (raw > j) held = true
+ return fit
+ })
+ if (!progressed) {
+ if (frag === 0) return 'nofit'
+ // a fresh page still holds no whole line: force one line per pending cell.
+ // The widow rule may hold fitting lines back for one page, not twice in a row
+ if (!held || stalled) {
+ held = false
+ cells.forEach((c, k) => {
+ if (next[k] < c.lines.length) cutIdx[k] = next[k] + 1
+ })
+ }
+ }
+ stalled = !progressed && held
+ const allDone = cutIdx.every((f, k) => f >= cells[k].lines.length)
+ if (allDone && frag === 0)
+ // every line fits and only the bottom cell margin hangs over: keep the row
+ // (the margin overflows into the page margin) instead of an empty continuation
+ return naturalH - avail <= 12 ? { lastFragment: naturalH, target: naturalH, rules: [] } : null
+ let target = 0
+ if (allDone) {
+ target = Math.max(0, ...cells.map((c, k) => lastBottom(c) + dy[k])) + padB
+ if (row.minHPx !== undefined) target = Math.max(target, y + Math.min(row.minHPx, contentH))
+ target = Math.max(target, naturalH)
+ }
+ // this fragment's lines sit at its top (top-aligned; a middle/bottom cell
+ // landing whole is aligned within the fragment); lines shown on other pages
+ // are clipped off the crossing children and later children are hidden
+ cells.forEach((c, k) => {
+ const start = next[k]
+ const end = cutIdx[k]
+ const from = y
+ if (c.lines.length === 0) return
+ // a cell finished on an earlier page: its canvas-aligned content must not show here
+ if (start >= c.lines.length) {
+ rules.push({ from, cell: k, child: 0, tail: true, hide: true })
+ return
+ }
+ if (start > 0 && c.alignDy > 0.5)
+ rules.push({ from, cell: k, child: 0, tail: true, dy: -c.alignDy })
+ let d = dy[k] - c.alignDy
+ if (start === 0 && end >= c.lines.length) {
+ const bottom = allDone ? target - padB : y + avail
+ d += c.alignFrac * Math.max(0, bottom - (lastBottom(c) + dy[k]))
+ }
+ const first = c.childOf[start]
+ if (Math.abs(d) > 0.05) rules.push({ from, cell: k, child: first, tail: true, dy: d })
+ const clipTop =
+ start > 0 && c.childOf[start - 1] === first
+ ? c.lines[start][0] - childTop(c, first)
+ : undefined
+ if (end >= c.lines.length) {
+ if (clipTop !== undefined) rules.push({ from, cell: k, child: first, clipTop })
+ return
+ }
+ const last = c.childOf[end]
+ if (end > 0 && c.childOf[end - 1] === last) {
+ const clipBottom = childBottom(c, last) - c.lines[end][0]
+ if (last === first && clipTop !== undefined)
+ rules.push({ from, cell: k, child: last, clipTop, clipBottom })
+ else {
+ if (clipTop !== undefined) rules.push({ from, cell: k, child: first, clipTop })
+ rules.push({ from, cell: k, child: last, clipBottom })
+ }
+ rules.push({ from, cell: k, child: last + 1, tail: true, hide: true })
+ } else {
+ if (clipTop !== undefined) rules.push({ from, cell: k, child: first, clipTop })
+ rules.push({ from, cell: k, child: last, tail: true, hide: true })
+ }
+ })
+ if (allDone) return { lastFragment: target - y, target, rules }
+ cells.forEach((c, k) => {
+ const fit = cutIdx[k]
+ next[k] = fit
+ if (fit < c.lines.length) dy[k] = y + avail - c.lines[fit][0]
+ })
+ y += avail
+ avail = turn(avail, y)
+ }
+ return null
+}
+
/**
* Place a table (row-level page breaking).
*/
+/** height a floating table needs on its first page: the leading header rows
+ * plus the first body row (a header block taller than the page cannot stay
+ * together, so only the first row counts) */
+function floatLeadHeight(rows: TableRowBox[], contentH: number): number {
+ let h = 0
+ let i = 0
+ for (; i < rows.length && rows[i].isHeader; i++) h += rows[i].height
+ if (h > contentH + 0.01) return rows[0].height
+ while (i < rows.length && rows[i].vMergeContinue) i++
+ return h + (rows[i]?.height ?? 0)
+}
+
function _placeTable(
block: BlockBox,
rows: TableRowBox[],
@@ -988,7 +1409,8 @@ function _placeTable(
pageEmpty: () => boolean,
newPage: (y: number, section: number, headerH?: number, headerTop?: number) => void,
curSection: number,
- onRowFill?: (row: number, targetPx: number) => void,
+ onRowFill?: (row: number, targetPx: number, extraPx?: number) => void,
+ onRowSplit?: (row: number, rules: RowSplitRule[]) => void,
): number {
// find header rows (the first N consecutive isHeader rows); a header block
// taller than a full page doesn't repeat (Word probe 2026-08-16: a block at
@@ -1059,6 +1481,35 @@ function _placeTable(
turnedForMinH = true
}
const keepWhole = row.isHeader && ri < leadHeaderRows && row.height <= contentH + 0.01
+ if (row.cells && !row.cantSplit && !keepWhole && onRowSplit) {
+ let firstFragment = true
+ const turn = (placed: number, y: number) => {
+ // the notes ride the first fragment (the references sit in the row head)
+ place(placed + (firstFragment ? notes : 0))
+ firstFragment = false
+ newPage(rowCursor + y, curSection, repeatH, block.top)
+ return remain()
+ }
+ let plan = planRowSplit(row, remain() - notes, contentH, turn)
+ if (plan === 'nofit' && !pageEmpty() && !turnedForMinH) {
+ newPage(rowCursor, curSection, repeatH, block.top)
+ turnedForMinH = true
+ plan = planRowSplit(row, remain() - notes, contentH, turn)
+ }
+ if (plan && plan !== 'nofit') {
+ place(plan.lastFragment + (firstFragment ? notes : 0))
+ const naturalH = row.height - (row.splitExtra ?? 0)
+ if (plan.target > naturalH + 0.5) onRowFill?.(ri, plan.target, plan.target - naturalH)
+ if (plan.rules.length > 0)
+ onRowSplit(
+ ri,
+ plan.rules.map((r) => ({ ...r, from: r.from + rowCursor })),
+ )
+ rowCursor += row.height
+ if (row.isHeader && ri < headerRows) placedHeader = true
+ continue
+ }
+ }
let cuts = !row.cantSplit && !keepWhole && row.cutYs ? [...row.cutYs] : []
let segTurns = 0
let lastTurnPrev = 0
@@ -1254,6 +1705,18 @@ function _placeParaBlock(
const bandH = noteBandHeights(block, lineBoxes)
if (totalH > contentH) {
+ // Word's orphan minimum still gates the first cut of an over-page paragraph:
+ // fewer than two lines fitting here start it on the next page (a photo pair
+ // whose turned second picture fills a page moves as a whole)
+ if (widowOn && nLines >= 2 && !pageEmpty()) {
+ let sumH = spaceBeforePx
+ let fitting = 0
+ for (; fitting < 2; fitting++) {
+ sumH += lineBoxes[fitting].height + (bandH?.[fitting] ?? 0)
+ if (!fits(sumH)) break
+ }
+ if (fitting < 2) newPage(block.top, curSection)
+ }
// paragraph exceeds one page: hard line-level cut
_hardCutLines(
block,
@@ -1384,9 +1847,11 @@ function _placeBrokenPara(
const lb = lineBoxes?.find((l) => l.offsetInBlock <= y && y < l.offsetInBlock + l.height)
return lb ? lb.offsetInBlock : y
}
- const cuts = [...new Set((block.innerBreaks ?? []).map(snap))]
- .filter((y) => y > 0.5 && y < textH - 0.5)
- .sort((a, b) => a - b)
+ const snapped = [...new Set((block.innerBreaks ?? []).map(snap))]
+ const cuts = snapped.filter((y) => y > 0.5 && y < textH - 0.5).sort((a, b) => a - b)
+ // a cut inside the first line box (a leading break line the sampler did not
+ // see) still turns the page: before the whole block
+ if (snapped.some((y) => y <= 0.5) && !pageEmpty()) forcePage(block.top, curSection)
if (cuts.length === 0) return false
let segStart = 0
cuts.push(textH)
@@ -1500,7 +1965,7 @@ export function insertParityBlanks(slices: PageSlice[], geoms: SectionGeom[]): P
export function sectionFirstPages(slices: PageSlice[]): boolean[] {
let prev = -1
return slices.map((s) => {
- const first = s.section !== prev
+ const first = s.section !== prev && !s.continuedSection
prev = s.section
return first
})
@@ -1547,3 +2012,81 @@ export function pageStartBlocks(blocks: BlockBox[], slices: PageSlice[]): number
}
return starts
}
+
+/**
+ * Paragraphs cut at a line boundary between two consecutive column windows of
+ * different widths (balanced or overflowing, within a region, across stacked
+ * regions or across a page turn): the head keeps the first window's width and
+ * the tail rewraps at the second's (ColumnBlockPlacement.split). The cut is
+ * matched against the block's ColWrapTable when it has one, else against its
+ * measured line boxes; a block spanning three windows gets one split only.
+ */
+export function columnLineSplits(
+ blocks: BlockBox[],
+ slices: PageSlice[],
+ colWidthsOf: (section: number) => number[] | undefined,
+): ColumnLineSplit[] {
+ const out: ColumnLineSplit[] = []
+ type Win = { start: number; w?: number }
+ const wins: Win[] = []
+ for (const slice of slices) {
+ if (!slice.regions) {
+ wins.push({ start: slice.start })
+ continue
+ }
+ for (const region of slice.regions) {
+ const ws = colWidthsOf(region.section)
+ region.columns.forEach((col, c) => wins.push({ start: col.start, w: ws?.[c] }))
+ }
+ }
+ const seen = new Set()
+ let bi = 0
+ for (let i = 0; i + 1 < wins.length; i++) {
+ const wc = wins[i].w
+ const wn = wins[i + 1].w
+ if (wc === undefined || wn === undefined || Math.abs(wc - wn) < 0.5) continue
+ const cut = wins[i + 1].start
+ while (bi < blocks.length && blocks[bi].top + blocks[bi].height <= cut + 0.5) bi++
+ let idx = -1
+ for (let j = bi; j < blocks.length && blocks[j].top < cut - 0.5; j++) {
+ const x = blocks[j]
+ if (x.floated || x.tableRows || x.fixedWidthPx !== undefined || !x.el) continue
+ if (cut < x.top + x.height - 0.5) {
+ idx = j
+ break
+ }
+ }
+ if (idx < 0 || seen.has(idx)) continue
+ const b = blocks[idx]
+ const off = cut - b.top
+ const table = b.colWraps?.find(
+ (t) => Math.abs(t.headWidthPx - wc) < 0.5 && Math.abs(t.tailWidthPx - wn) < 0.5,
+ )
+ // a balance cut comes from the table; an overflow cut from the measured
+ // line boxes (the two can disagree while the DOM still wraps at another width)
+ let k = -1
+ if (table) {
+ for (let m = 1; m < table.n; m++) {
+ if (Math.abs(table.headH[m] - off) < 1.5) {
+ k = m
+ break
+ }
+ }
+ }
+ const fromTable = k >= 1
+ if (!fromTable && b.lineBoxes) {
+ k = b.lineBoxes.findIndex((lb, m) => m >= 1 && Math.abs(lb.offsetInBlock - off) < 1.5)
+ }
+ if (k < 1) continue
+ seen.add(idx)
+ out.push({
+ bi: idx,
+ line: k,
+ headWidthPx: wc,
+ tailWidthPx: wn,
+ cutY: off,
+ ...(fromTable && table ? { tailBottom: table.tailBottom[k], shapeY: table.shapeY[k] } : {}),
+ })
+ }
+ return out
+}
diff --git a/apps/docs/src/renderer/pagination-types.ts b/apps/docs/src/renderer/pagination-types.ts
index e2ba267..73da067 100644
--- a/apps/docs/src/renderer/pagination-types.ts
+++ b/apps/docs/src/renderer/pagination-types.ts
@@ -1,6 +1,6 @@
// Records shared by the pagination modules: measured blocks, page slices,
// section geometry and the patch outputs of a slicing pass.
-import type { SectionInfo } from '@genoffice/docx-engine'
+import type { SectionInfo, TextFlowDirection, TextOutline } from '@genoffice/docx-engine'
export interface BlockBox {
top: number
@@ -10,8 +10,12 @@ export interface BlockBox {
/** breakBefore comes from a leading w:br (real break character, not the
* pageBreakBefore property): honored even on the document's blank first page */
breakBeforeBr?: boolean
+ /** further leading w:br beyond the first: each turns the page again (a blank sheet per break) */
+ extraBreaksBefore?: number
/** block ends with a page-break field (w:br type=page, no text after it): force a page break after it */
breakAfter?: boolean
+ /** further trailing w:br beyond the first: blank sheets between this block and the next */
+ extraBreaksAfter?: number
/** mid-paragraph page breaks (w:br type=page with text on both sides):
* element-relative Y of the line starting after each break (same space as
* lineBoxes offsets); the engine turns the page there and the text before
@@ -29,10 +33,22 @@ export interface BlockBox {
docxIndex?: number
/** owning section index (filled by assignSections) */
section?: number
+ /** horizontal margin/padding/border total read while measuring (vertical-text
+ * blocks: their writing-mode decoration would remap those margins later) */
+ inlineExtraPx?: number
/** CSS-floated block (square/tight/through image wrap, w:tblpPr table): the
* wrapped text beside it carries the vertical extent, so it consumes no
* column height itself (block boxes in normal flow stack ignoring floats) */
floated?: boolean
+ /** w:tblpPr table (floated or currently flowed by the engine, see floatFlowed) */
+ floatTable?: true
+ /** floating table the engine renders in normal flow because one of its rows
+ * is taller than a page (no row boundary can split it; a zero-height float
+ * would clip everything past the first page) */
+ floatFlowed?: true
+ /** height of the float-carry spacer already in front of this block (the
+ * anchor paragraph of a split floating table sits beside the last portion) */
+ carryAppliedPx?: number
/** floating-anchor wrapper whose height is a column-spanning wrap band:
* Word keeps the box on its anchor's page and lets the band overflow the
* bottom margin — fill the column instead of pushing the block whole */
@@ -46,6 +62,9 @@ export interface BlockBox {
* the engine resolves it into a --tblp-dy shift (SliceOutputs.floatVShifts) */
pageRelVyPx?: number
pageRelVAnchor?: 'page' | 'margin'
+ /** w:tblpYSpec keyword: the target is the anchor box edge/centre minus the
+ * block's own height instead of a fixed Y */
+ pageRelVSpec?: 'top' | 'center' | 'bottom'
/** inline-flowed w:tblpPr table with a negative text-relative w:tblpY: the
* block starts this many px above its flow position (Word hangs it above
* the anchor paragraph, into the top margin on a page start) */
@@ -59,6 +78,14 @@ export interface BlockBox {
/** non-reflowable block's rendered width (tables, protected textboxes/objects):
* such a block never advances into a narrower column (Word turns the page instead) */
fixedWidthPx?: number
+ /** rendered width (px) of a reflowable block: the unequal-column balance scales its height by measured / column width */
+ widthPx?: number
+ /** offscreen probes of this paragraph split between two columns of different
+ * widths (fillColWraps): for a cut after k lines wrapped at headWidthPx, the
+ * cut's in-block Y (headH[k]) and the height (tailH[k]) / bottom (tailBottom[k])
+ * of the remaining text rewrapped at tailWidthPx; k runs 0..n (n = line
+ * count at the head width). Same coordinate space as lineBoxes offsets. */
+ colWraps?: ColWrapTable[]
// ── F2 line-level page-split extensions ─────────────────────────────────
/**
@@ -137,6 +164,25 @@ export interface TableRowBox {
/** footnote heights of the row's references (px): the row only fits a page
* that also holds its notes */
notesPx?: number
+ /** per-cell line geometry of a multi-cell row (Word breaks each cell at its own
+ * line boundary); absent for single-cell rows and exact-height cells */
+ cells?: RowCellBox[]
+ /** px a previous split patch already added to the DOM tr (data-split-extra) */
+ splitExtra?: number
+}
+
+/** One cell of a splittable row, in top-aligned coordinates relative to the row top (px) */
+export interface RowCellBox {
+ /** clustered line bands [top, bottom], ascending */
+ lines: Array<[number, number]>
+ /** per line: index of the cell's direct child holding it (the preview's shift target) */
+ childOf: number[]
+ /** per line: paragraph id (lines sharing an id form one widow/orphan unit) */
+ paraOf: number[]
+ /** offset the canvas' vertical-align (middle/bottom) already applied to the content; 0 for top */
+ alignDy: number
+ /** 0 top, 0.5 middle, 1 bottom */
+ alignFrac: number
}
/** One column of a multi-column page: a content range in the continuous flow (in-column break semantics match pages) */
@@ -194,6 +240,9 @@ export interface PageSlice {
leadTable?: true
/** The page opens inside a native table that began on an earlier page (markTableSeamSlices). */
cutTable?: true
+ /** The owning section began mid-page on an earlier page (continuous break), so
+ * this is not its first page for w:titlePg header/footer selection. */
+ continuedSection?: true
}
/** Pagination geometry for one section */
@@ -208,6 +257,8 @@ export interface SectionGeom {
/** content-area top offset from the page edge (px, header-expanded top margin);
* resolves page-anchored w:tblpY targets into content coordinates */
topPx?: number
+ /** full page height (px): page-anchored bottom/center keyword targets */
+ pageHeightPx?: number
/** section start forces a page break (nextPage/evenPage/oddPage, or continuous with different page geometry) */
forceBreak: boolean
/** section break type: evenPage/oddPage need physical blank pages inserted to align parity */
@@ -218,6 +269,10 @@ export interface SectionGeom {
colWidths?: number[]
/** nextColumn start with the same column count as the previous section: advance one column at the boundary */
colBreakStart?: boolean
+ /** sectPr w:textDirection vertical flow: the flow axis is horizontal, so
+ * contentHeight is the page's side-margin width (fill extent) and
+ * contentWidth the body height (line length) */
+ vertical?: TextFlowDirection
}
/** A split declared-height row needs its DOM stretched: target total height for the row */
@@ -228,6 +283,8 @@ export interface RowFillPatch {
row: number
/** row total target height (px); the DOM tr gets it as a minimum */
targetPx: number
+ /** part of targetPx added for per-cell continuation shifts (stamped as data-split-extra) */
+ extraPx?: number
}
/** Page-anchored floated table: downward shift placing it at its w:tblpY target */
@@ -238,6 +295,24 @@ export interface FloatVShiftPatch {
dyPx: number
}
+/** Floating table with an over-page row: rendered in normal flow so the row page-breaks */
+export interface FloatFlowPatch {
+ blockTop: number
+}
+
+/** Floating table split at row boundaries across pages (Word: the portions
+ * before the last page fill their pages alone, the anchor paragraph and the
+ * wrapping text start beside the last portion) */
+export interface FloatSplitPatch {
+ blockTop: number
+ /** applied page/margin-anchored shift (the cuts are measured from top + dyPx) */
+ dyPx: number
+ /** virtual Y of each page turn inside the table (a following row's top) */
+ cutYs: number[]
+ /** virtual distance from the table's flow top to the last portion's top */
+ carryPx: number
+}
+
/** Single line taller than its column (oversized inline picture): renderer-baked page-bottom clip */
export interface OversizeClipPatch {
/** owning block's virtual top (block identity within one layout pass) */
@@ -246,10 +321,76 @@ export interface OversizeClipPatch {
clipPx: number
}
+/** Word-style split of a multi-cell row: per fragment (page starting at flow y
+ * `from`) the preview positions each cell's children so the fragment's lines sit
+ * at its top and everything else is clipped or hidden */
+export interface RowSplitRule {
+ from: number
+ cell: number
+ /** direct child index; `tail` = this child and all following siblings */
+ child: number
+ tail?: true
+ dy?: number
+ /** px of the child's top / bottom to clip (lines shown on another page) */
+ clipTop?: number
+ clipBottom?: number
+ hide?: true
+}
+
+export interface RowSplitPatch {
+ blockTop: number
+ row: number
+ rules: RowSplitRule[]
+}
+
export interface SliceOutputs {
rowFills?: RowFillPatch[]
+ rowSplits?: RowSplitPatch[]
floatVShifts?: FloatVShiftPatch[]
+ floatFlows?: FloatFlowPatch[]
+ floatSplits?: FloatSplitPatch[]
oversizeClips?: OversizeClipPatch[]
+ /** paragraphs the unequal-column balance wants to cut mid-paragraph but has no
+ * ColWrapTable for yet (fillColWraps measures them, then the slicer reruns) */
+ colWrapRequests?: ColWrapRequest[]
+}
+
+export interface ColWrapTable {
+ headWidthPx: number
+ tailWidthPx: number
+ /** line count at the head width */
+ n: number
+ headH: number[]
+ tailH: number[]
+ /** content-box bottom of the split paragraph */
+ tailBottom: number[]
+ /** where the float shape's edge sits for a cut after k lines: the head's
+ * last ink bottom (head narrower) or the tail's first ink top (tail
+ * narrower) — the midpoint cut Y can fall inside the neighbouring line box */
+ shapeY: number[]
+}
+
+export interface ColWrapRequest {
+ blockTop: number
+ headWidthPx: number
+ tailWidthPx: number
+}
+
+/** A paragraph cut at a line boundary between two columns of different widths:
+ * the head lines wrap at the first column's width, the tail at the second's */
+export interface ColumnLineSplit {
+ /** block index */
+ bi: number
+ /** head line count */
+ line: number
+ headWidthPx: number
+ tailWidthPx: number
+ /** in-block Y of the cut (lineBoxes space) */
+ cutY: number
+ /** in-block Y of the split paragraph's content bottom when known from a ColWrapTable */
+ tailBottom?: number
+ /** ColWrapTable.shapeY for this cut */
+ shapeY?: number
}
/** Per-section header/footer content heights (px); sectionGeoms uses these to compute body push-down */
@@ -272,6 +413,8 @@ export interface ColumnBlockPlacement {
/** owning section's side margins (--doc-margin-left/right overrides) */
marginLeftPx?: number
marginRightPx?: number
+ /** owning section's top margin (--doc-margin-top override) in docs whose sections disagree on it */
+ marginTopPx?: number
/** owning section's typed docGrid pitch (pt); 0 = untyped section in a
* mixed-grid doc (opts out like snapToGrid=0) */
gridPitchPt?: number
@@ -279,6 +422,36 @@ export interface ColumnBlockPlacement {
charSpacePt?: number
dx: number
dy: number
+ /** left edge of the block's page on the shared paper (--page-cx): pages narrower
+ * than the paper are centered; separate from dx so page-relative anchors can
+ * undo the column shift alone */
+ pageDx?: number
+ /** block of a vertical-text section: rendered as a writing-mode box whose
+ * flow footprint is trimmed back to the measured horizontal one (marginBottomPx) */
+ vertical?: VerticalBlockSpec
+ /** paragraph straddling two columns of different widths: widthPx is the wider
+ * one and a leading float shape narrows the head or the tail lines */
+ split?: ColumnSplitShape
+}
+
+/** Geometry of the float that rewraps part of a straddling paragraph (px,
+ * relative to the block's content-box top, same space as the float itself) */
+export interface ColumnSplitShape {
+ /** float width = difference of the two column widths */
+ floatPx: number
+ /** float height: the head's height (head narrower) or the tail's bottom (tail narrower) */
+ heightPx: number
+ /** shape-outside top inset: 0 for a narrower head, the head's height for a narrower tail */
+ insetPx: number
+ /** RTL section: the float sits on the left */
+ rtl?: boolean
+}
+
+export interface VerticalBlockSpec {
+ mode: TextFlowDirection
+ marginBottomPx: number
+ /** page-leading block keeps its space-before (it sets the flow start like a horizontal page) */
+ firstOnPage: boolean
}
export interface MeasuredContent {
@@ -304,6 +477,8 @@ export interface FloatBox {
* the page-relative Y; the box belongs at that offset on the anchor's page */
pageRelV: boolean
pageRelFromPage?: boolean
+ /** wrapNone/front/behind box: stays clipped on its anchor's page, never opens a trailing page */
+ noSpill?: boolean
}
/** Page-bottom footnote entry (number/text/estimated height): shared by canvas page gaps and the pagination preview */
@@ -332,6 +507,7 @@ export interface PageNoteItem {
sizeHalfPoints?: number
fontAscii?: string
caps?: 'all' | 'small' | 'none'
+ textOutline?: TextOutline
}>
>
}
@@ -343,6 +519,8 @@ export interface PageNoteItem {
export interface BlockMeta {
keepNext?: boolean
keepLines?: boolean
+ /** paragraph opted out of section line numbering (w:suppressLineNumbers) */
+ suppressLineNumbers?: boolean
/** pageBreakBefore (direct or style-level): force a page break before the block */
breakBefore?: boolean
/** false only when explicitly disabled (Word default on) */
diff --git a/apps/docs/src/renderer/styles.css b/apps/docs/src/renderer/styles.css
index 2d72eb6..5a8480e 100644
--- a/apps/docs/src/renderer/styles.css
+++ b/apps/docs/src/renderer/styles.css
@@ -2189,6 +2189,11 @@ th.cell-rev-del {
padding: 26px 24px 140px;
}
+.editor-scroll.image-drop-target .doc-page {
+ outline: 2px dashed var(--accent);
+ outline-offset: -2px;
+}
+
.doc-zoom {
width: fit-content;
margin: 0 auto;
@@ -2274,8 +2279,20 @@ th.cell-rev-del {
max-width: var(--col-w, 100%);
}
+/* a paragraph cut between two columns of different widths keeps one element at
+ the wider width; this leading float (columnLayoutSpecs split shape) shortens
+ the head lines or, via shape-outside, only the tail lines to the narrower
+ column. Structural like the width: kept while measuring and in clones. */
+.doc-page .doc-col-split-float {
+ display: block;
+ pointer-events: none;
+ user-select: none;
+}
+
+/* --page-cx: the block's page centered on a wider shared paper (differing-width
+ documents); page-relative anchors below undo the column shift only */
.editor-scroll .doc-page:not(.measuring-columns) .doc-col-block {
- transform: translate(var(--col-dx, 0px), var(--col-dy, 0px));
+ transform: translate(calc(var(--col-dx, 0px) + var(--page-cx, 0px)), var(--col-dy, 0px));
}
/* w:docGrid charSpace character grid (Word probes 2026-09-02): every character
@@ -2305,12 +2322,57 @@ th.cell-rev-del {
transform: translateX(calc(-1 * var(--col-dx, 0px)));
}
+/* sectPr w:textDirection sections (verticalTextSpecs): blocks are measured as
+ horizontal paragraphs wrapping at the line length (--col-w) and shown as
+ writing-mode boxes of that height, translated to their sideways slot. The
+ negative --vert-mb trims each box's flow footprint back to the measured one
+ so gaps and paper heights stay those of a horizontal page; only the
+ page-leading block keeps its space-before (it defines the flow start).
+ Not gated on .editor-scroll: preview clones position the same way, with
+ --pv-vdx/--pv-vdy overriding per page (verticalPageCss). */
+.doc-page:not(.measuring-columns) .doc-vert-block {
+ writing-mode: vertical-rl;
+ height: var(--col-w);
+ width: fit-content;
+ margin-bottom: var(--vert-mb, 0px) !important;
+ transform: translate(
+ var(--pv-vdx, calc(var(--col-dx, 0px) + var(--page-cx, 0px))),
+ var(--pv-vdy, var(--col-dy, 0px))
+ );
+}
+.doc-page:not(.measuring-columns) .doc-vert-block:not(.doc-vert-first) {
+ margin-top: 0 !important;
+}
+.doc-page:not(.measuring-columns) .doc-vert-tbRlV {
+ text-orientation: sideways;
+}
+.doc-page:not(.measuring-columns) .doc-vert-btLr {
+ writing-mode: sideways-lr;
+}
+
+/* w:framePr paragraph frame: fixed box beside which body text wraps (see para-frame.ts) */
+.doc-page .doc-para-frame {
+ position: relative;
+}
+
/* single-flow measuring state: transforms and the column-space pull-up must not
distort the 1-D virtual coordinates */
.editor-scroll .doc-page.measuring-columns .page-gap {
margin-top: 0 !important;
}
+/* natural-flow measuring state: in-paragraph gap widgets force a line break at
+ the PREVIOUS pass's cut position, so measuring with them in layout can only
+ re-confirm that cut even after decoration-only reflows (justify space-shrink)
+ moved the natural wrap points — a justified page-last line then stays
+ stretched sparse until an at-boundary edit (r177). Hidden, the
+ paragraph re-wraps naturally and every gapAbove/gapAccum read consistently
+ sees zero-height gaps, so the virtual coordinates stay gapless by layout
+ instead of by arithmetic. */
+.editor-scroll .doc-page.measuring-natural .page-gap-inline {
+ display: none !important;
+}
+
/* page border (w:pgBorders): per-page overlay boxes (see syncPageBorders);
border color/width are document data and come inline from the sectPr */
.page-border-overlays {
@@ -2324,6 +2386,21 @@ th.cell-rev-del {
position: absolute;
}
+/* w:zOrder=back: the layer cannot live under the text (the paper is the editor
+ root), so it multiplies into it: dark text stays readable over the pattern */
+.page-border-overlays-back {
+ mix-blend-mode: multiply;
+}
+
+.page-dark .page-border-overlays-back {
+ mix-blend-mode: screen;
+}
+
+/* art border approximation: tiled pattern strip along one side of the box */
+.page-border-art {
+ position: absolute;
+}
+
/* preview/print copy: same document-data border, one box per .pv-page sheet */
.pv-page-border {
position: absolute;
@@ -2331,6 +2408,28 @@ th.cell-rev-del {
z-index: 3;
}
+.pv-page-border-back {
+ z-index: -1;
+}
+
+/* line numbers (w:lnNumType): one label per counted line, right-aligned before the
+ text column (see syncLineNumbers / syncPreviewLineNumbers); font and color are
+ document data copied from the document root */
+.page-line-numbers,
+.pv-line-numbers {
+ position: absolute;
+ inset: 0;
+ pointer-events: none;
+ z-index: 3;
+}
+
+.page-line-number,
+.pv-line-number {
+ position: absolute;
+ text-align: right;
+ white-space: nowrap;
+}
+
/* ---- tab stops (w:tabs) ---- */
/* Paragraphs whose tabs were measured (TabStopExtension): tab chars get zero
@@ -2361,8 +2460,8 @@ th.cell-rev-del {
text-justify: none;
}
-/* tab with no room left on its line: Chromium still advances at least one
- space width per tab, which would overflow — a zero font lifts that floor */
+/* tab with no room left on its line (TabStopExtension collapses it to half a
+ space): a zero font keeps the character itself from adding to the line box */
.doc-tab-collapse {
font-size: 0;
}
@@ -2373,13 +2472,53 @@ th.cell-rev-del {
border-bottom: 1px solid currentColor;
}
-/* tab leader (w:leader) drawn across the tab gap */
-.doc-tab-leader-dot,
-.doc-tab-leader-middleDot {
- border-bottom: 1px dotted currentColor;
+/* first-line tab inside a hanging indent (TabStopExtension): a box of the
+ exact advance; the inner tab is zero-width and must not inherit the
+ paragraph's negative text-indent or alignment */
+.doc-tab-fixed {
+ display: inline-block;
+ tab-size: 0;
+ text-indent: 0;
+ text-align: left;
}
+
+/* right/center/decimal tab glued to the word after it (TabStopExtension):
+ Chromium treats the boundary from a white-space:pre tab to the following
+ text as unbreakable, so a TOC entry that outgrows its line wraps before
+ the tab instead of stranding the page number on the next line */
+.doc-tab-glue {
+ white-space: pre;
+}
+
+/* tab leader (w:leader): Word fills the gap with the run font's glyphs on
+ the baseline (TOC dots are periods at their natural advance), anchored at
+ the stop so the rows line up; a border would sit at the descender like an
+ underline. underscore/heavy stay borders: underscores abut into a line. */
+.doc-tab-leader-dot,
+.doc-tab-leader-middleDot,
.doc-tab-leader-hyphen {
- border-bottom: 1px dashed currentColor;
+ position: relative;
+}
+.doc-tab-leader-dot::before,
+.doc-tab-leader-middleDot::before,
+.doc-tab-leader-hyphen::before {
+ position: absolute;
+ inset: 0;
+ overflow: hidden;
+ white-space: nowrap;
+ direction: rtl;
+ line-height: normal;
+ pointer-events: none;
+ user-select: none;
+}
+.doc-tab-leader-dot::before {
+ content: '................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................';
+}
+.doc-tab-leader-middleDot::before {
+ content: '\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7\00B7';
+}
+.doc-tab-leader-hyphen::before {
+ content: '------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------';
}
.doc-tab-leader-underscore {
border-bottom: 1px solid currentColor;
@@ -2478,7 +2617,6 @@ th.cell-rev-del {
.page-hf {
position: absolute;
- left: 50%;
transform: translateX(-50%);
/* Word: header/footer strip spans the text column; paragraphs default to
left-aligned black text at the body size (alignment comes from w:jc).
@@ -2489,6 +2627,11 @@ th.cell-rev-del {
font-size: var(--hf-default-fs, 10.5pt);
color: var(--docs-paper-ink);
overflow: hidden;
+ /* tab stops past the right margin: the clip box widens into the margin by
+ --hf-tab-over (content box unchanged, so 100% still means the column) */
+ box-sizing: content-box;
+ padding-right: var(--hf-tab-over, 0px);
+ left: calc(50% + var(--hf-tab-over, 0px) / 2);
z-index: 1;
cursor: default;
}
@@ -3540,6 +3683,35 @@ th.cell-rev-del {
);
}
+/* differing-width documents (syncPageSheets): the shared paper goes transparent and
+ every page paints its own centered sheet; the gap band's inset shadow would run
+ past a narrower page's edges */
+.page-wrap.paper-mixed {
+ isolation: isolate;
+}
+
+.page-wrap.paper-mixed .doc-page {
+ background: transparent;
+ box-shadow: none;
+}
+
+.page-wrap.paper-mixed .page-gap::before {
+ box-shadow: none;
+}
+
+.page-sheets {
+ position: absolute;
+ inset: 0;
+ pointer-events: none;
+ z-index: -1;
+}
+
+.page-sheet {
+ position: absolute;
+ background: var(--page-bg, var(--docs-paper));
+ box-shadow: var(--docs-page-shadow);
+}
+
/* footnote area at the top of a page gap (previous page's bottom, Word behavior): the gap was already enlarged by the reserved height;
the estimated height differs from actual rendering by pixels, so overflow into the bottom-margin area is allowed (no clipping) */
.page-gap-notes {
@@ -3733,10 +3905,12 @@ th.cell-rev-del {
!important beats the inline border style; unscoped so pv clones and print match */
.pbdr-suppress-top {
border-top: none !important;
+ padding-top: 0 !important;
}
.pbdr-suppress-bottom {
border-bottom: none !important;
+ padding-bottom: 0 !important;
}
/* pagination preview: read-only overlay, one fixed-size box per page, content clone clipped via negative margin */
@@ -4119,7 +4293,16 @@ th.cell-rev-del {
text-align: start;
font-family: var(--li-marker-font, inherit);
font-size: calc(var(--li-marker-size, 1em) * var(--li-marker-scale, 1));
+ /* --li-marker-lh: 0 for scaled substitute glyphs; an oversized level w:sz sets the
+ marker's natural height (Word does not grid-snap the number like a run) */
line-height: var(--li-marker-lh, inherit);
+ /* w:lvl rPr color; the --dk-li-mc twin recolors it on the dark page */
+ color: var(--li-marker-color, inherit);
+}
+
+.page-dark .doc-li[style*='--dk-li-mc:']::before,
+.page-dark [data-stray-marker][style*='--dk-li-mc:'] .doc-li-stray::before {
+ color: var(--dk-li-mc);
}
.doc-li-bullet::before {
@@ -4176,10 +4359,44 @@ th.cell-rev-del {
margin-inline-start: calc(-1 * var(--li-hang, var(--style-li-hang, 0)));
}
-.doc-page .doc-li[data-suff='space'][data-marker]::before {
+.doc-page .doc-li[data-suff='space'][data-marker]:not([data-marker-pic])::before {
content: attr(data-marker) '\00a0';
}
+/* picture bullet (w:lvlPicBulletId): a 1em image box on the baseline like Word; the rest
+ of the hanging area becomes inline-end margin so the box stays logical (RTL mirrors) */
+.doc-page .doc-li[data-marker-pic]::before,
+.doc-page [data-stray-marker][data-marker-pic] .doc-li-stray::before {
+ content: '';
+ width: 1em;
+ min-width: 0;
+ height: 1em;
+ vertical-align: -0.1em;
+ background: var(--li-marker-pic) center / contain no-repeat;
+}
+
+.doc-page .doc-li[data-marker-pic]::before {
+ margin-inline-end: max(
+ 0px,
+ calc(var(--li-tab, var(--li-hang, var(--style-li-hang, 0.25in))) - 1em)
+ );
+}
+
+.doc-page [data-stray-marker][data-marker-pic] .doc-li-stray::before {
+ margin-inline-end: max(0px, calc(var(--li-tab, var(--li-hang, var(--style-li-hang, 0))) - 1em));
+}
+
+/* w:suff space/nothing on a picture level: one space after the image, or none */
+.doc-page .doc-li[data-suff][data-marker-pic]::before,
+.doc-page [data-stray-marker][data-suff][data-marker-pic] .doc-li-stray::before {
+ margin-inline-end: 0;
+}
+
+.doc-page .doc-li[data-suff='space'][data-marker-pic]::before,
+.doc-page [data-stray-marker][data-suff='space'][data-marker-pic] .doc-li-stray::before {
+ margin-inline-end: 0.25em;
+}
+
/* protected blocks (table / image / chart / math ...) */
.doc-protected {
position: relative;
@@ -4877,16 +5094,19 @@ body.docs-crop-active .doc-protected[data-doc-protected='image'] .doc-img-wrap {
the pv-clip (sized to the page's flow content) and resolve against the page
box. Their inline offsets are content-area coordinates: the page margins
(--pv-ml/--pv-mt, set per pv-page) shift them back onto the page. */
-.pv-page [data-pv-pagerel='1'] {
+.pv-page [data-pv-pagerel='1'],
+.pv-page .doc-anchor-origin[data-pv-pagerel='1'] {
position: static;
}
.pv-page [data-pv-pagerel='1'] > .doc-textbox[data-page-rel-v='1'],
-.pv-page [data-pv-pagerel='1'] > .doc-img-wrap[data-page-rel-v='1'] {
+.pv-page [data-pv-pagerel='1'] > .doc-img-wrap[data-page-rel-v='1'],
+.pv-page [data-pv-pagerel='1'] .doc-inline-img-anchor > img[data-page-rel-v='1'] {
translate: var(--pv-ml, 0px) var(--pv-mt, 0px);
}
/* page-edge V anchors keep their page Y under a header push; margin ones ride the body top (Word) */
.pv-page [data-pv-pagerel='1'] > .doc-textbox[data-page-rel-from='page'],
-.pv-page [data-pv-pagerel='1'] > .doc-img-wrap[data-page-rel-from='page'] {
+.pv-page [data-pv-pagerel='1'] > .doc-img-wrap[data-page-rel-from='page'],
+.pv-page [data-pv-pagerel='1'] .doc-inline-img-anchor > img[data-page-rel-from='page'] {
translate: var(--pv-ml, 0px) var(--pv-mt-page, var(--pv-mt, 0px));
}
@@ -4902,6 +5122,17 @@ body.docs-crop-active .doc-protected[data-doc-protected='image'] .doc-img-wrap {
.pv-page [data-pv-hoist='1'] > .doc-img-wrap {
translate: var(--pv-ml, 0px) calc(var(--pv-mt, 0px) + var(--pv-hoist-dy, 0px));
}
+/* centred / right-slot boxes (left:50% / right:0) now resolve against the page
+ box instead of the column: shift by the column's own offset within it */
+.pv-page [data-pv-hoist-slot='center'] > .doc-textbox,
+.pv-page [data-pv-hoist-slot='center'] > .doc-img-wrap {
+ translate: calc((var(--pv-ml, 0px) - var(--pv-mr, 0px)) / 2)
+ calc(var(--pv-mt, 0px) + var(--pv-hoist-dy, 0px));
+}
+.pv-page [data-pv-hoist-slot='right'] > .doc-textbox,
+.pv-page [data-pv-hoist-slot='right'] > .doc-img-wrap {
+ translate: calc(-1 * var(--pv-mr, 0px)) calc(var(--pv-mt, 0px) + var(--pv-hoist-dy, 0px));
+}
.ProseMirror-focused .doc-protected.doc-protected-textboxes.ProseMirror-selectednode {
border-color: var(--word-blue);
@@ -4977,6 +5208,18 @@ body.docs-crop-active .doc-protected[data-doc-protected='image'] .doc-img-wrap {
font-family: var(--li-marker-font, inherit);
font-size: calc(var(--li-marker-size, 1em) * var(--li-marker-scale, 1));
line-height: var(--li-marker-lh, inherit);
+ color: var(--li-marker-color, inherit);
+}
+
+/* same picture bullet as .doc-li[data-marker-pic]; listed after the text rule so it wins */
+.doc-textbox-para[data-marker-pic]::before {
+ content: '';
+ width: 1em;
+ min-width: 0;
+ height: 1em;
+ vertical-align: -0.1em;
+ margin-inline-end: max(0px, calc(var(--li-tab, var(--li-hang, 0)) - 1em));
+ background: var(--li-marker-pic) center / contain no-repeat;
}
/* numbered anchor paragraph (Word keeps it in the list): its stray line runs on the
@@ -4995,6 +5238,7 @@ body.docs-crop-active .doc-protected[data-doc-protected='image'] .doc-img-wrap {
font-family: var(--li-marker-font, inherit);
font-size: calc(var(--li-marker-size, 1em) * var(--li-marker-scale, 1));
line-height: var(--li-marker-lh, inherit);
+ color: var(--li-marker-color, inherit);
}
/* the wrapper carries the same flags as a .doc-li: clipped-in-cell, w:suff space/nothing */
@@ -5007,7 +5251,7 @@ body.docs-crop-active .doc-protected[data-doc-protected='image'] .doc-img-wrap {
margin-inline-start: calc(-1 * var(--li-hang, var(--style-li-hang, 0)));
}
-.doc-page [data-stray-marker][data-suff='space'] .doc-li-stray::before {
+.doc-page [data-stray-marker][data-suff='space']:not([data-marker-pic]) .doc-li-stray::before {
content: var(--li-marker) '\00a0';
}
@@ -5042,8 +5286,17 @@ body.docs-crop-active .doc-protected[data-doc-protected='image'] .doc-img-wrap {
);
}
+/* behind text at full opacity (Word); the page's stacking context keeps it above the paper */
.doc-inline-img--behind {
- opacity: 0.45;
+ z-index: -1;
+}
+
+/* page-relative run pictures ride the floating-box shift channel */
+.doc-inline-img-anchor > img[data-page-rel-v='1'] {
+ translate: 0 var(--page-float-dy, 0px);
+}
+.pv-clip .doc-inline-img-anchor > img[data-page-rel-v='1'] {
+ translate: none;
}
/* square/tight/through wrap: real CSS float so same-paragraph text wraps */
@@ -5275,7 +5528,6 @@ body.docs-crop-active .doc-protected[data-doc-protected='image'] .doc-img-wrap {
.doc-toc-line {
display: flex;
align-items: baseline;
- gap: 4px;
/* 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;
@@ -5306,18 +5558,23 @@ body.docs-crop-active .doc-protected[data-doc-protected='image'] .doc-img-wrap {
.doc-toc-num {
white-space: pre;
- margin-right: 4px;
+ margin-right: 8px;
}
+/* leader glyphs at the entry font's own advance (Word: a period every 0.25em
+ in Times, no extra tracking), starting right after the title */
.doc-toc-dots {
flex: 1;
min-width: 24px;
overflow: hidden;
white-space: nowrap;
- letter-spacing: 2px;
user-select: none;
}
+.doc-toc-leader-heavy {
+ font-weight: bold;
+}
+
/* tiptap injects `.ProseMirror [contenteditable="false"] { white-space: normal }`
* (0-2-0), beating the single-class rules above; mirror it to keep TOC lines
* from wrapping their leader dots into extra lines. */
@@ -5481,6 +5738,23 @@ body.docs-crop-active .doc-protected[data-doc-protected='image'] .doc-img-wrap {
fill: var(--docs-paper-ink-faint);
}
+.doc-chart-axis-title {
+ font:
+ 600 10px 'Segoe UI',
+ var(--ui-cjk),
+ sans-serif;
+ fill: var(--docs-paper-ink-dim);
+}
+
+.doc-chart-label-in {
+ fill: var(--docs-paper-ink-dim);
+}
+
+.doc-chart-frame {
+ max-width: 100%;
+ margin: 0 auto;
+}
+
/* 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) */
@@ -5780,6 +6054,11 @@ body.docs-crop-active .doc-protected[data-doc-protected='image'] .doc-img-wrap {
background: var(--docs-paper-field-bg);
}
+.doc-ref-field[data-instr-field='FORMCHECKBOX'],
+.doc-checkbox-control {
+ cursor: pointer;
+}
+
/* Bookmark / Cross-reference dialogs */
.modal-row {
display: flex;
@@ -5888,6 +6167,24 @@ body.docs-crop-active .doc-protected[data-doc-protected='image'] .doc-img-wrap {
margin: 2px 0 6px 12px;
}
+/* floating table with an over-page row: the engine flows it so the row page-breaks */
+.doc-table.doc-table-float-flow {
+ float: none;
+}
+
+/* split floating table: the anchor paragraph starts beside the last portion.
+ page-float-carry is flow space (kept in the gapless preview snapshot);
+ page-gap-carry skips the table's in-table gaps and paints no band */
+.page-float-carry,
+.page-gap-carry {
+ pointer-events: none;
+ user-select: none;
+}
+
+.page-gap-carry::before {
+ display: none;
+}
+
/* behind text: the absolutely positioned wrap drops under the flow's inline
content (negative z-index stays above the paper: no intermediate background) */
.img-wrap-behind > .doc-img-wrap {
@@ -9396,6 +9693,11 @@ ruby.doc-ruby rt {
font-size: 1em;
}
+/* EQ field layouts draw in the paragraph face like Word, not the UA math font */
+.doc-field-math math {
+ font-family: inherit;
+}
+
.doc-formula-edit {
position: absolute;
top: 2px;
@@ -9427,8 +9729,9 @@ ruby.doc-ruby rt {
.page-notes {
position: relative;
box-sizing: border-box;
- width: var(--page-w, 816px);
+ width: var(--last-page-w, var(--page-w, 816px));
margin: -100px auto 0;
+ margin-left: var(--last-page-x, auto);
padding: 8px 96px 28px;
background: var(--page-bg, var(--docs-paper));
font-size: 9pt;
@@ -9456,9 +9759,8 @@ ruby.doc-ruby rt {
anchored at the measured flow end (inline top), over the paper's padded tail */
.page-endnotes-anchored {
position: absolute;
- left: 0;
- right: 0;
- width: auto;
+ left: var(--last-page-x, 0px);
+ width: var(--last-page-w, 100%);
margin: 0;
padding-top: 8px;
background: none;
@@ -9505,10 +9807,18 @@ ruby.doc-ruby rt {
color: var(--word-blue);
}
-/* ---- References → Index: XE marks (invisible in Word, a small chip on screen) ---- */
+/* ---- References → Index: XE marks (hidden field codes: Word shows nothing
+ unless formatting marks are on, so the chip only appears with .show-marks) ---- */
.doc-xe-mark {
display: inline-block;
+ font-size: 0;
+ line-height: 0;
+ vertical-align: baseline;
+ cursor: default;
+}
+
+.show-marks .doc-xe-mark {
font-size: 9px;
line-height: 1.3;
color: var(--docs-paper-xe-ink);
@@ -9517,11 +9827,9 @@ ruby.doc-ruby rt {
border-radius: 2px;
padding: 0 3px;
margin: 0 1px;
- vertical-align: baseline;
- cursor: default;
}
-.doc-xe-mark::before {
+.show-marks .doc-xe-mark::before {
content: 'XE:' attr(data-xe-term);
}
@@ -9796,11 +10104,21 @@ ruby.doc-ruby rt {
}
/* table border / size tools */
+/* side by side: stacked, the three rows outgrow the fixed 80px band */
+.table-tool-borders {
+ flex-direction: row;
+ align-items: center;
+ gap: 8px;
+}
+
+.table-tool-borders .table-tool-grid {
+ flex: none;
+}
+
.table-border-opts {
display: flex;
gap: 6px;
align-items: center;
- margin-top: 4px;
}
.table-border-opts input[type='color'] {
@@ -10730,3 +11048,95 @@ tr > .page-gap-cut {
.doc-ea-quotes {
font-family: 'Noto Serif CJK SC';
}
+
+.ai-partial-card .ai-queue-hint {
+ padding: 0 10px 4px;
+ font-size: 12px;
+ color: var(--color-text-secondary);
+}
+
+/* ---- post-paste "Paste options" chip (Word parity) ---- */
+.paste-chip {
+ position: fixed;
+ z-index: 59;
+}
+
+.paste-chip-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 2px;
+ padding: 3px 6px;
+ border: 1px solid var(--border);
+ border-radius: var(--radius-6, 6px);
+ background: var(--surface);
+ color: var(--text);
+ box-shadow: var(--docs-shadow-menu);
+ cursor: pointer;
+}
+
+.paste-chip-btn:hover {
+ background: var(--hover);
+}
+
+.paste-chip-caret {
+ font-size: 9px;
+ color: var(--text-secondary);
+}
+
+.paste-chip-menu {
+ position: absolute;
+ top: calc(100% + 4px);
+ left: 0;
+ display: flex;
+ flex-direction: column;
+ min-width: 220px;
+ padding: 4px;
+ border: 1px solid var(--border);
+ border-radius: var(--radius-8, 8px);
+ background: var(--surface);
+ box-shadow: var(--docs-shadow-menu);
+}
+
+.paste-chip-item {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 6px 8px;
+ border: none;
+ border-radius: var(--radius-6, 6px);
+ background: none;
+ color: var(--text);
+ font-size: 13px;
+ text-align: left;
+ cursor: pointer;
+}
+
+.paste-chip-item:hover {
+ background: var(--hover);
+}
+
+.paste-chip-item.active {
+ font-weight: 600;
+}
+
+.paste-chip-check {
+ width: 14px;
+ flex: none;
+ text-align: center;
+}
+
+.paste-chip-sep {
+ height: 1px;
+ margin: 4px 6px;
+ background: var(--border);
+}
+
+.paste-chip-remember {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 6px 8px;
+ color: var(--text-secondary);
+ font-size: 12px;
+ cursor: pointer;
+}
diff --git a/apps/docs/src/renderer/zotero/controller.ts b/apps/docs/src/renderer/zotero/controller.ts
index 9250eb2..39081f2 100644
--- a/apps/docs/src/renderer/zotero/controller.ts
+++ b/apps/docs/src/renderer/zotero/controller.ts
@@ -1,6 +1,6 @@
import type { Editor } from '@tiptap/core'
import { TextSelection } from '@tiptap/pm/state'
-import { Fragment, type Mark, type Node as PmNode } from '@tiptap/pm/model'
+import { Fragment, Slice, type Mark, type Node as PmNode } from '@tiptap/pm/model'
import type { ZoteroRendererRequest } from '../../shared/ipc'
import { parseZoteroRtf, zoteroRtfToText, type ZoteroRtfParagraph, type ZoteroRtfRun } from './rtf'
@@ -97,13 +97,13 @@ export class ZoteroDocumentController {
case 'Document_cleanup':
case 'Document_complete':
return null
- case 'Document_insertText':
- this.editor
- .chain()
- .focus()
- .insertContent(zoteroRtfToText(String(args[1] ?? '')))
- .run()
+ case 'Document_insertText': {
+ // plain text: insertContent would parse Zotero's output as HTML
+ const { state, view } = this.editor
+ view.dispatch(state.tr.insertText(zoteroRtfToText(String(args[1] ?? ''))).scrollIntoView())
+ this.editor.commands.focus()
return null
+ }
case 'Document_convertPlaceholdersToFields':
return [[], [], [], []]
case 'Document_exportDocument':
@@ -139,7 +139,87 @@ export class ZoteroDocumentController {
}
}
+ /** Runs that lost their id (clipboard round trips keep the instruction but not the
+ * runtime attrs) get one written back onto the mark, so the id handed to Zotero in
+ * Document_getFields still resolves in the Field_* calls that follow. Adjacent runs
+ * with the same instruction form one field again. */
+ private assignMissingFieldIds(): void {
+ const { state } = this.editor
+ const type = state.schema.marks.instrField
+ if (!type) return
+ interface LostRun {
+ from: number
+ to: number
+ mark: Mark
+ blockIndex: number
+ blockStart: number
+ blockEnd: number
+ }
+ const lost: LostRun[] = []
+ let maxId = 0
+ state.doc.forEach((block, blockOffset, blockIndex) => {
+ block.descendants((node, relativePos) => {
+ if (!node.isText) return
+ const mark = node.marks.find(
+ (candidate) =>
+ candidate.type === type && ZOTERO_INSTR_RE.test(String(candidate.attrs.instr ?? '')),
+ )
+ if (!mark) return
+ const id = Number(mark.attrs.fieldId)
+ if (Number.isSafeInteger(id) && id > 0) maxId = Math.max(maxId, id)
+ else {
+ const from = blockOffset + 1 + relativePos
+ lost.push({
+ from,
+ to: from + node.nodeSize,
+ mark,
+ blockIndex,
+ blockStart: blockOffset + 1,
+ blockEnd: blockOffset + block.nodeSize - 1,
+ })
+ }
+ })
+ })
+ if (lost.length === 0) return
+ this.nextFieldId = Math.max(this.nextFieldId, maxId + 1)
+ // only runs that touch (or end one paragraph and open the next) rejoin: two
+ // copies of a citation with text between them stay two fields
+ const touches = (prev: LostRun, next: LostRun) =>
+ prev.blockIndex === next.blockIndex
+ ? prev.to === next.from
+ : next.blockIndex === prev.blockIndex + 1 &&
+ prev.to === prev.blockEnd &&
+ next.from === next.blockStart
+ const groups: LostRun[][] = []
+ for (const entry of lost) {
+ const group = groups[groups.length - 1]
+ const prev = group?.[group.length - 1]
+ if (prev && prev.mark.attrs.instr === entry.mark.attrs.instr && touches(prev, entry)) {
+ group.push(entry)
+ } else groups.push([entry])
+ }
+ let transaction = state.tr
+ for (const group of groups) {
+ const fieldId = this.nextFieldId++
+ group.forEach((entry, index) => {
+ const fieldPart =
+ group.length === 1
+ ? 'single'
+ : index === 0
+ ? 'begin'
+ : index === group.length - 1
+ ? 'end'
+ : 'inside'
+ transaction = transaction
+ .removeMark(entry.from, entry.to, type)
+ .addMark(entry.from, entry.to, type.create({ ...entry.mark.attrs, fieldId, fieldPart }))
+ })
+ }
+ this.editor.view.dispatch(transaction)
+ }
+
private fields(): ZoteroFieldRange[] {
+ this.assignMissingFieldIds()
const ranges = new Map()
this.editor.state.doc.forEach((block, blockOffset) => {
block.descendants((node, relativePos) => {
@@ -210,13 +290,9 @@ export class ZoteroDocumentController {
private fieldAtSelection(): ZoteroFieldRange | null {
const { from, to } = this.editor.state.selection
- return (
- this.fields().find(
- (field) =>
- field.segments.some((segment) => from >= segment.from && to <= segment.to) ||
- (field.blocks.length > 1 && from >= field.blockFrom && to <= field.blockTo),
- ) ?? null
- )
+ // the inline span from the first to the last field run: text typed inside a
+ // bibliography counts, text sharing its first or last paragraph does not
+ return this.fields().find((field) => from >= field.from && to <= field.to) ?? null
}
private requireField(value: unknown): ZoteroFieldRange {
@@ -234,10 +310,11 @@ export class ZoteroDocumentController {
if (noteType !== 0) {
throw new Error('Zotero footnote and endnote citations are not supported yet')
}
+ // fields() may dispatch (missing ids get assigned), so read the state after it
+ this.fields()
const { state, view } = this.editor
const type = state.schema.marks.instrField
if (!type) throw new Error('This document cannot store Zotero fields')
- this.fields()
const id = this.nextFieldId++
const mark = type.create({
instr: 'ADDIN ZOTERO_TEMP',
@@ -300,11 +377,13 @@ export class ZoteroDocumentController {
}
return template.node.type.create(attrs, Fragment.fromArray(contentFor(paragraph)))
})
- transaction = transaction.replaceWith(
- field.blockFrom,
- field.blockTo,
- Fragment.fromArray(nodes),
- )
+ const fillsBlocks = field.from === field.blockFrom + 1 && field.to === field.blockTo - 1
+ // a field sharing its first or last paragraph with other text (a "References"
+ // heading line, a citation with a paragraph break in its RTF) keeps that text:
+ // the open slice joins the new first/last paragraph into the existing ones
+ transaction = fillsBlocks
+ ? transaction.replaceWith(field.blockFrom, field.blockTo, Fragment.fromArray(nodes))
+ : transaction.replace(field.from, field.to, new Slice(Fragment.fromArray(nodes), 1, 1))
}
this.editor.view.dispatch(transaction)
}
@@ -365,8 +444,9 @@ export class ZoteroDocumentController {
private deleteField(value: unknown): void {
const field = this.requireField(value)
- const from = field.blocks.length > 1 ? field.blockFrom : field.from
- const to = field.blocks.length > 1 ? field.blockTo : field.to
+ const fillsBlocks = field.from === field.blockFrom + 1 && field.to === field.blockTo - 1
+ const from = field.blocks.length > 1 && fillsBlocks ? field.blockFrom : field.from
+ const to = field.blocks.length > 1 && fillsBlocks ? field.blockTo : field.to
this.editor.view.dispatch(this.editor.state.tr.delete(from, to))
}
@@ -379,8 +459,10 @@ export class ZoteroDocumentController {
this.editor.view.dispatch(transaction)
}
+ /** Zotero button sets: 0 OK, 1 OK/Cancel, 2 Yes/No, 3 Yes/No/Cancel; the reply is the
+ * button index counted from Cancel/No = 0, so Yes is 2 in the three-button set */
private displayAlert(message: string, buttons: number): number {
- if (buttons > 0) return window.confirm(message) ? 1 : 0
+ if (buttons > 0) return window.confirm(message) ? (buttons === 3 ? 2 : 1) : 0
window.alert(message)
return 0
}
diff --git a/apps/docs/src/shared/ipc.ts b/apps/docs/src/shared/ipc.ts
index 854ef90..87d8f7b 100644
--- a/apps/docs/src/shared/ipc.ts
+++ b/apps/docs/src/shared/ipc.ts
@@ -43,6 +43,7 @@ import type {
AiStreamRequest,
GenSparkAccountStatus,
} from '@genoffice/ai-provider'
+import type { HeadlessExportTarget } from '@genoffice/electron-utils/headless-export'
import type { FaceVerticalMetrics } from '@genoffice/font-metrics'
import type { AiPanelPrefs } from '@genoffice/ui'
@@ -244,6 +245,8 @@ export interface DesktopApi {
openDocxPath(path: string): Promise
/** decrypt-and-open a password-protected docx (path from a needsPassword result) */
openDocxDecrypt(path: string, password: string): Promise
+ /** w:altChunk HTML rendered through html2docx in a hidden window; null when conversion fails */
+ convertAltChunkHtml(html: string): Promise
/** Review > Protect: set (or clear with null) the desired next-save password;
* filePath null = document not saved yet, applied on its first successful save */
setDocPassword(filePath: string | null, password: string | null): Promise<{ ok: boolean }>
@@ -257,6 +260,10 @@ export interface DesktopApi {
consumeNewBlankDoc(): Promise
/** AI-authored content queued for this tab by create_document; one-shot, null when none */
consumeAiDocContent(): Promise
+ /** Headless export mode: the path and format this hidden renderer must export, null in normal use */
+ consumeHeadlessExport(): Promise
+ /** Headless export mode: report the export outcome so the main process can quit */
+ headlessExportDone(result: { ok: boolean; error?: string }): void
/** AI create_document: build a new standalone file and open it in a new tab */
createDocument(request: CreateDocumentRequest): Promise
/** receive documents opened from Finder/Explorer while the app is running */
diff --git a/apps/docs/tests/ai-doc-writer.test.ts b/apps/docs/tests/ai-doc-writer.test.ts
new file mode 100644
index 0000000..a3bcaa5
--- /dev/null
+++ b/apps/docs/tests/ai-doc-writer.test.ts
@@ -0,0 +1,286 @@
+import { describe, expect, it } from 'vitest'
+import { Editor } from '@tiptap/core'
+import { undoDepth } from '@tiptap/pm/history'
+import {
+ BLANK_BULLET_NUM_ID,
+ BLANK_ORDERED_NUM_ID,
+ buildBlankDocx,
+ parseDocx,
+} from '@genoffice/docx-engine'
+import { blocksToPmDoc } from '../src/renderer/editor/convert'
+import {
+ buildDocWriterRequest,
+ countFragmentBlocks,
+ DraftLanding,
+ extractFragment,
+ type AiDocWriter,
+} from '../src/renderer/ai/doc-writer'
+import { executeTool } from '../src/renderer/ai/tools'
+
+const NUM_IDS = { bullet: BLANK_BULLET_NUM_ID, ordered: BLANK_ORDERED_NUM_ID }
+
+async function createBlankEditor() {
+ const { editorExtensions } = await import('../src/renderer/editor/extensions')
+ const parsed = await parseDocx(await buildBlankDocx())
+ const editor = new Editor({
+ element: document.createElement('div'),
+ extensions: editorExtensions,
+ })
+ editor.commands.setContent(blocksToPmDoc(parsed.blocks) as never)
+ return editor
+}
+
+const texts = (editor: Editor) => {
+ const out: string[] = []
+ editor.state.doc.forEach((n) => out.push(n.textContent))
+ return out
+}
+
+const tick = () => new Promise((r) => setTimeout(r, 350))
+
+describe('extractFragment', () => {
+ it('drops chatter and fences around the fragment', () => {
+ expect(extractFragment('Here you go:\n```html\nT \na
\n```\n')).toBe(
+ 'T \na
',
+ )
+ expect(extractFragment('```html\nhalf')).toBe('
half')
+ expect(extractFragment('
a
\r\nb
')).toBe('a
\nb
')
+ })
+ it('counts top-level blocks roughly', () => {
+ expect(
+ countFragmentBlocks(
+ 'T a
',
+ ),
+ ).toBe(4)
+ })
+})
+
+describe('buildDocWriterRequest', () => {
+ it('carries the plan, title, context and request; the system prompt has the HTML rules', () => {
+ const { system, user } = buildDocWriterRequest(
+ { plan: 'intro, body', title: 'Guide', context: 'founded 1999', instruction: 'write it' },
+ '\n\nAnswer in French.',
+ )
+ expect(system).toContain('restricted HTML fragment only')
+ expect(system).toContain('Only these tags are allowed')
+ expect(system.endsWith('Answer in French.')).toBe(true)
+ expect(user).toContain('Title: Guide')
+ expect(user).toContain('intro, body')
+ expect(user).toContain('founded 1999')
+ expect(user).toContain('write it')
+ })
+})
+
+describe('DraftLanding', () => {
+ it('renders the growing fragment in place, swaps only changed blocks, and leaves no trace on finish', async () => {
+ const editor = await createBlankEditor()
+ const before = editor.state.doc
+ const depth = undoDepth(editor.state)
+ const draft = new DraftLanding(editor, NUM_IDS, { kind: 'whole' })
+ draft.update('Title \nfirst para')
+ await tick()
+ expect(texts(editor)).toEqual(['Title', 'first para', ''])
+ const titleNode = editor.state.doc.child(0)
+ draft.update('
Title \nfirst paragraph
\nsecond')
+ await tick()
+ expect(texts(editor)).toEqual(['Title', 'first paragraph', 'second', ''])
+ // the unchanged heading was kept, not re-inserted
+ expect(editor.state.doc.child(0)).toBe(titleNode)
+ // the draft is neither history nor a tracked change
+ expect(undoDepth(editor.state)).toBe(depth)
+ draft.finish()
+ expect(editor.state.doc.eq(before)).toBe(true)
+ })
+
+ it("follows the user's edits above the draft and reports the block it sits after", async () => {
+ const editor = await createBlankEditor()
+ editor.commands.setContent('
one
two
')
+ const draft = new DraftLanding(editor, NUM_IDS, { kind: 'after', index: 0 })
+ draft.update('draft
')
+ await tick()
+ expect(texts(editor)).toEqual(['one', 'draft', 'two'])
+ // the user inserts a paragraph at the very start
+ editor.view.dispatch(editor.state.tr.insert(0, editor.schema.nodes.docParagraph!.create()))
+ expect(draft.indexBefore()).toBe(1)
+ draft.update('draft
more
')
+ await tick()
+ expect(texts(editor)).toEqual(['', 'one', 'draft', 'more', 'two'])
+ draft.finish()
+ expect(texts(editor)).toEqual(['', 'one', 'two'])
+ })
+})
+
+describe('DraftLanding under user edits', () => {
+ it('re-anchors on the live document when the user edits inside the draft', async () => {
+ const editor = await createBlankEditor()
+ editor.commands.setContent('one
')
+ const draft = new DraftLanding(editor, NUM_IDS, { kind: 'after', index: 0 })
+ draft.update('alpha
beta
')
+ await tick()
+ expect(texts(editor)).toEqual(['one', 'alpha', 'beta'])
+ // the user types inside the first draft block: its size changes
+ const alphaPos = editor.state.doc.child(0).nodeSize + 1 + 'alpha'.length
+ editor.view.dispatch(editor.state.tr.insertText(' edited', alphaPos))
+ draft.update('alpha
beta
gamma
')
+ await tick()
+ expect(texts(editor)).toEqual(['one', 'alpha', 'beta', 'gamma'])
+ draft.finish()
+ expect(texts(editor)).toEqual(['one'])
+ })
+
+ it('finish returns the last fragment that rendered', async () => {
+ const editor = await createBlankEditor()
+ const draft = new DraftLanding(editor, NUM_IDS, { kind: 'whole' })
+ draft.update('ok
')
+ await tick()
+ draft.update('ok
\\frac{ ')
+ await tick()
+ expect(texts(editor)).toEqual(['ok', ''])
+ expect(draft.finish()).toBe('ok
')
+ })
+})
+
+describe('write_document tool', () => {
+ const writerOf = (html: string, truncated = false): AiDocWriter => ({
+ write: async (_spec, onProgress) => {
+ onProgress(html.slice(0, 10))
+ onProgress(html)
+ return { ok: true, html, truncated }
+ },
+ })
+
+ it('lands the streamed fragment as one regular insert on a blank document', async () => {
+ const editor = await createBlankEditor()
+ const exec = await executeTool(
+ editor,
+ { id: 't', name: 'write_document', input: { plan: 'a title and a paragraph' } },
+ NUM_IDS,
+ undefined,
+ undefined,
+ null,
+ undefined,
+ undefined,
+ writerOf('T body
'),
+ )
+ expect(exec.isError).toBeFalsy()
+ expect(exec.mutated).toBe(true)
+ expect(exec.output).toContain('2 block(s)')
+ expect(texts(editor)).toEqual(['T', 'body'])
+ // one undo step removes the whole write
+ expect(editor.commands.undo()).toBe(true)
+ expect(texts(editor)).toEqual([''])
+ })
+
+ it('refuses a whole-document write on a non-blank document without replaceDocument', async () => {
+ const editor = await createBlankEditor()
+ editor.commands.setContent('keep
')
+ const exec = await executeTool(
+ editor,
+ { id: 't', name: 'write_document', input: { plan: 'p' } },
+ NUM_IDS,
+ undefined,
+ undefined,
+ null,
+ undefined,
+ undefined,
+ writerOf('new
'),
+ )
+ expect(exec.isError).toBe(true)
+ expect(exec.output).toContain('afterBlockIndex')
+ expect(texts(editor)).toEqual(['keep'])
+ })
+
+ it('inserts after a block and flags a kept partial as incomplete', async () => {
+ const editor = await createBlankEditor()
+ editor.commands.setContent('one
two
')
+ const exec = await executeTool(
+ editor,
+ { id: 't', name: 'write_document', input: { plan: 'p', afterBlockIndex: 0 } },
+ NUM_IDS,
+ undefined,
+ undefined,
+ null,
+ undefined,
+ undefined,
+ writerOf('half
', true),
+ )
+ expect(exec.isError).toBeFalsy()
+ expect(exec.output).toContain('INCOMPLETE')
+ expect(texts(editor)).toEqual(['one', 'half', 'two'])
+ })
+
+ it('keeps the rendered draft when a kept partial ends mid-formula', async () => {
+ const editor = await createBlankEditor()
+ const writer: AiDocWriter = {
+ write: async (_spec, onProgress) => {
+ onProgress('ok
')
+ await tick()
+ onProgress('ok
\\frac{ ')
+ return { ok: true, html: 'ok
\\frac{ ', truncated: true }
+ },
+ }
+ const exec = await executeTool(
+ editor,
+ { id: 't', name: 'write_document', input: { plan: 'p' } },
+ NUM_IDS,
+ undefined,
+ undefined,
+ null,
+ undefined,
+ undefined,
+ writer,
+ )
+ expect(exec.isError).toBeFalsy()
+ expect(texts(editor)).toEqual(['ok'])
+ })
+
+ it('keeps text the user typed into a blank document while the draft streamed', async () => {
+ const editor = await createBlankEditor()
+ const writer: AiDocWriter = {
+ write: async (_spec, onProgress) => {
+ onProgress('draft
')
+ await tick()
+ // the user types below the draft meanwhile
+ editor.view.dispatch(editor.state.tr.insertText('mine', editor.state.doc.content.size - 1))
+ return { ok: true, html: 'draft
more
' }
+ },
+ }
+ const exec = await executeTool(
+ editor,
+ { id: 't', name: 'write_document', input: { plan: 'p' } },
+ NUM_IDS,
+ undefined,
+ undefined,
+ null,
+ undefined,
+ undefined,
+ writer,
+ )
+ expect(exec.isError).toBeFalsy()
+ expect(texts(editor)).toEqual(['draft', 'more', 'mine'])
+ })
+
+ it('a failed or discarded write leaves the document unchanged', async () => {
+ const editor = await createBlankEditor()
+ const writer: AiDocWriter = {
+ write: async (_spec, onProgress) => {
+ onProgress('draft
')
+ await tick()
+ return { ok: false, error: 'the user discarded the partial content' }
+ },
+ }
+ const exec = await executeTool(
+ editor,
+ { id: 't', name: 'write_document', input: { plan: 'p' } },
+ NUM_IDS,
+ undefined,
+ undefined,
+ null,
+ undefined,
+ undefined,
+ writer,
+ )
+ expect(exec.isError).toBe(true)
+ expect(texts(editor)).toEqual([''])
+ })
+})
diff --git a/apps/docs/tests/anchor-line-spec.test.ts b/apps/docs/tests/anchor-line-spec.test.ts
index 79694e3..37d744e 100644
--- a/apps/docs/tests/anchor-line-spec.test.ts
+++ b/apps/docs/tests/anchor-line-spec.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
-import { anchorLineSpec } from '../src/renderer/editor/extensions'
+import { DocProtected, anchorLineSpec } from '../src/renderer/editor/extensions'
describe('anchorLineSpec', () => {
it('lays the line out with the paragraph format but leaves the page break on the picture', () => {
@@ -17,3 +17,38 @@ describe('anchorLineSpec', () => {
expect(attrs.style).toContain('margin-top')
})
})
+
+describe('floating textbox anchor line', () => {
+ const spec = (anchorLine: Record | null) =>
+ DocProtected.config.renderHTML!.call(
+ DocProtected as never,
+ {
+ node: {
+ attrs: {
+ blockType: 'passthrough',
+ docxIndex: 3,
+ label: 'Text box',
+ textboxes: [{ paras: [], floating: true, widthPx: 83, heightPx: 62 }],
+ anchorLine,
+ },
+ },
+ HTMLAttributes: {},
+ } as never,
+ ) as unknown as [string, Record, ...unknown[]]
+ const childTags = (out: unknown[]) =>
+ out.slice(2).map((c) => (Array.isArray(c) ? [c[0], (c[1] as Record).class] : c))
+
+ it('lays the anchor paragraph out with its own spacing when the format is known', () => {
+ const out = spec({ styleId: null, spaceAfter: 200, lineSpacing: 276, lineRule: 'auto' })
+ expect(out[1].class).toContain('doc-protected-floating-stray')
+ const line = out.slice(2).find((c) => Array.isArray(c) && c[0] === 'p') as
+ [string, Record] | undefined
+ expect(line?.[1].class).toContain('doc-anchor-line')
+ expect(line?.[1].class).toContain('doc-anchor-strut')
+ expect(line?.[1].style).toContain('margin-bottom')
+ })
+
+ it('falls back to the bare strut without a format', () => {
+ expect(childTags(spec(null))).toContainEqual(['div', 'doc-anchor-strut'])
+ })
+})
diff --git a/apps/docs/tests/autospace-doc-off.test.ts b/apps/docs/tests/autospace-doc-off.test.ts
index 418813f..bc4fcee 100644
--- a/apps/docs/tests/autospace-doc-off.test.ts
+++ b/apps/docs/tests/autospace-doc-off.test.ts
@@ -25,6 +25,20 @@ const KILL_RULE =
'.page-wrap, .doc-page, .pv-page { text-autospace:no-autospace; --doc-autospace-pad:0 }'
describe('docAutospaceOff', () => {
+ it('suppresses when docDefaults w:lang w:val is an East Asian language (Word probe 2026-09-11)', () => {
+ // a Yu Gothic docDefaults with w:lang w:val="ja-JP": Word lays "\u7b2c3\u90e8" with no gap;
+ // en-US in the same package restores the ~1/4em gap
+ const doc = parsedDoc({ docDefaults: { eastAsiaFont: 'Yu Gothic', lang: 'ja-JP' } })
+ expect(docAutospaceOff(doc)).toBe(true)
+ expect(docStyleCss(doc)).toContain(KILL_RULE)
+ expect(
+ docAutospaceOff(parsedDoc({ docDefaults: { eastAsiaFont: 'Yu Gothic', lang: 'en-US' } })),
+ ).toBe(false)
+ expect(
+ docAutospaceOff(parsedDoc({ docDefaults: { eastAsiaFont: 'Yu Gothic', lang: 'jam' } })),
+ ).toBe(false)
+ })
+
it('suppresses when docDefaults declares an unavailable EA face', () => {
const doc = parsedDoc({ docDefaults: { eastAsiaFont: 'Noto Sans CJK KR' } })
expect(docAutospaceOff(doc)).toBe(true)
diff --git a/apps/docs/tests/cell-anchored-boxes-render.test.ts b/apps/docs/tests/cell-anchored-boxes-render.test.ts
new file mode 100644
index 0000000..097f1fd
--- /dev/null
+++ b/apps/docs/tests/cell-anchored-boxes-render.test.ts
@@ -0,0 +1,57 @@
+/** anchored shapes inside read-only / nested table cells are drawn, not dropped */
+import { DOMSerializer } from '@tiptap/pm/model'
+import type { TableModel, TextboxDisplay } from '@genoffice/docx-engine'
+import { describe, expect, it } from 'vitest'
+import { renderTableSpec } from '../src/renderer/editor/protected-render'
+
+const render = (spec: unknown): HTMLElement =>
+ DOMSerializer.renderSpec(document, spec as never).dom as HTMLElement
+
+// a 24x24 white square with a black outline, anchored 11px below its paragraph
+const checkbox: TextboxDisplay = {
+ paras: [],
+ fill: 'FFFFFF',
+ borderColor: '000000',
+ borderWidthPx: 1,
+ widthPx: 24,
+ heightPx: 24,
+ readOnly: true,
+ offsetXEmu: 155575,
+ offsetYEmu: 106045,
+ floating: true,
+}
+
+describe('renderTableSpec anchored cell boxes', () => {
+ it('draws the boxes of a nested table cell before their anchor paragraph', () => {
+ const nested: TableModel = {
+ rows: [
+ [
+ {
+ paras: ['', 'RELEASED', 'REJECTED'],
+ anchoredBoxes: [checkbox, { ...checkbox, offsetYEmu: 400000 }],
+ anchoredBoxAnchors: [1, 2],
+ },
+ ],
+ ],
+ }
+ const model: TableModel = {
+ rows: [[{ paras: ['outer'], nestedTables: [nested], nestedTableAnchors: [1] }]],
+ }
+ const dom = render(renderTableSpec(model))
+ const struts = dom.querySelectorAll(
+ '.doc-nested-table .doc-cell-boxes, .doc-table .doc-table .doc-cell-boxes',
+ )
+ const all = dom.querySelectorAll('.doc-cell-boxes')
+ expect(all.length).toBe(2)
+ expect(struts.length + all.length).toBeGreaterThan(0)
+ expect(all[0].querySelectorAll('.doc-textbox').length).toBe(1)
+ expect(all[0].nextElementSibling?.textContent).toBe('RELEASED')
+ expect(all[1].nextElementSibling?.textContent).toBe('REJECTED')
+ expect((all[0] as HTMLElement).style.height).toBe('35.1px')
+ })
+
+ it('a cell without anchored boxes renders no strut', () => {
+ const dom = render(renderTableSpec({ rows: [[{ paras: ['plain'] }]] }))
+ expect(dom.querySelectorAll('.doc-cell-boxes').length).toBe(0)
+ })
+})
diff --git a/apps/docs/tests/century-gothic-alias-metrics.test.ts b/apps/docs/tests/century-gothic-alias-metrics.test.ts
new file mode 100644
index 0000000..bf6ff5e
--- /dev/null
+++ b/apps/docs/tests/century-gothic-alias-metrics.test.ts
@@ -0,0 +1,105 @@
+/**
+ * Width contract of the Century Gothic alias (fonts.css): Word renders the
+ * Office-bundled font, the per-case size-adjusted Liberation Sans faces must
+ * reproduce its advances so line breaks match. Truth = hmtx sums of Word's
+ * Century Gothic / Century Gothic Bold (2026-09-12), in em.
+ */
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import * as opentype from 'opentype.js'
+import { describe, expect, it } from 'vitest'
+
+const css = readFileSync(join(__dirname, '../src/renderer/fonts/fonts.css'), 'utf8')
+const FONT_DIR = join(__dirname, '../src/renderer/fonts')
+
+interface Face {
+ adjust: number
+ ranges: Array<[number, number]> | null
+ file: string
+}
+
+function facesOf(weight: string, style: string): Face[] {
+ return [...css.matchAll(/@font-face\s*\{[^}]*\}/g)]
+ .map((m) => m[0])
+ .filter((f) => f.includes("font-family: 'Century Gothic GO'"))
+ .filter((f) => f.includes(`font-weight: ${weight}`) && f.includes(`font-style: ${style}`))
+ .map((f) => {
+ const range = /unicode-range:\s*([^;]+);/.exec(f)?.[1]
+ return {
+ adjust: Number(/size-adjust:\s*([\d.]+)%/.exec(f)?.[1] ?? 100) / 100,
+ ranges: range
+ ? range.split(',').map((r) => {
+ const [a, b] = r.trim().replace('U+', '').split('-')
+ return [parseInt(a, 16), parseInt(b ?? a, 16)] as [number, number]
+ })
+ : null,
+ file: /LiberationSans-(\w+)\.ttf/.exec(f)![1],
+ }
+ })
+}
+
+const fonts = new Map()
+function font(file: string): opentype.Font {
+ let f = fonts.get(file)
+ if (!f) {
+ const buf = readFileSync(join(FONT_DIR, `LiberationSans-${file}.ttf`))
+ f = opentype.parse(buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength))
+ fonts.set(file, f)
+ }
+ return f
+}
+
+/** later faces win inside their unicode-range (CSS Fonts 4) */
+function widthEm(text: string, faces: Face[]): number {
+ let em = 0
+ for (const ch of text) {
+ const cp = ch.codePointAt(0)!
+ const face = [...faces]
+ .reverse()
+ .find((f) => !f.ranges || f.ranges.some(([a, b]) => cp >= a && cp <= b))!
+ const f = font(face.file)
+ em += (f.charToGlyph(ch).advanceWidth! / f.unitsPerEm) * face.adjust
+ }
+ return em
+}
+
+const PANGRAM = 'The quick brown fox jumps over the lazy dog 0123456789'
+const BODY =
+ 'On the Insert tab, the galleries include items that are designed to coordinate with the overall look of your document.'
+
+describe('Century Gothic GO reproduces Century Gothic advances', () => {
+ const regular = facesOf('normal', 'normal')
+ const bold = facesOf('bold', 'normal')
+
+ it('declares general, lowercase and capital faces for every weight and style', () => {
+ for (const weight of ['normal', 'bold']) {
+ for (const style of ['normal', 'italic']) {
+ const faces = facesOf(weight, style)
+ expect(faces.map((f) => f.ranges?.[0]?.[0] ?? null)).toEqual([null, 0x61, 0x41])
+ }
+ }
+ })
+
+ it('pangram within 1% (27.3203em regular, 27.4995em bold)', () => {
+ expect(Math.abs(widthEm(PANGRAM, regular) / 27.3203 - 1)).toBeLessThan(0.01)
+ expect(Math.abs(widthEm(PANGRAM, bold) / 27.4995 - 1)).toBeLessThan(0.01)
+ })
+
+ it('body sentence within 2% (56.3652em regular, 56.1152em bold)', () => {
+ expect(Math.abs(widthEm(BODY, regular) / 56.3652 - 1)).toBeLessThan(0.02)
+ expect(Math.abs(widthEm(BODY, bold) / 56.1152 - 1)).toBeLessThan(0.02)
+ })
+
+ it('Latin-1 accented letters share the per-case faces (23.9644em regular)', () => {
+ const accented =
+ "\u00c9l\u00e8ve \u00e0 c\u00f4t\u00e9 de la fen\u00eatre, o\u00f9 l'\u00e9t\u00e9 s'ach\u00e8ve d\u00e9j\u00e0"
+ const asciiOnly = regular.map((f) => ({ ...f, ranges: f.ranges && [f.ranges[0]] }))
+ expect(Math.abs(widthEm(accented, regular) / 23.9644 - 1)).toBeLessThan(0.035)
+ expect(Math.abs(widthEm(accented, asciiOnly) / 23.9644 - 1)).toBeGreaterThan(0.035)
+ })
+
+ it('unscaled Liberation Sans would miss the regular body line by more than 5%', () => {
+ const plain = [{ adjust: 1, ranges: null, file: 'Regular' }]
+ expect(widthEm(BODY, plain) / 56.3652).toBeLessThan(0.95)
+ })
+})
diff --git a/apps/docs/tests/chart-caption-render.test.ts b/apps/docs/tests/chart-caption-render.test.ts
new file mode 100644
index 0000000..59de611
--- /dev/null
+++ b/apps/docs/tests/chart-caption-render.test.ts
@@ -0,0 +1,51 @@
+/** chart + caption in one paragraph: plot on top, caption text under it, caption not field-editable */
+import { Editor } from '@tiptap/core'
+import { parseDocx } from '@genoffice/docx-engine'
+import { describe, expect, it } from 'vitest'
+import {
+ buildDocx,
+ CHART_PARAGRAPH_XML,
+ CHART_PART_XML,
+ CHART_RELS,
+} from '../../../packages/docx-engine/tests/helpers/build-docx'
+import { blocksToPmDoc } from '../src/renderer/editor/convert'
+import { editorExtensions } from '../src/renderer/editor/extensions'
+
+const CAPTION =
+ 'Figure ' +
+ '1 ' +
+ ': Filler comparison '
+
+describe('chart caption rendering', () => {
+ it('renders the SVG chart with the caption below and keeps the caption read-only', async () => {
+ const parsed = await parseDocx(
+ await buildDocx({
+ bodyXml: CHART_PARAGRAPH_XML.replace('', `${CAPTION}`),
+ extraRels: CHART_RELS,
+ extraParts: [
+ {
+ path: 'word/charts/chart1.xml',
+ xml: CHART_PART_XML,
+ contentType: 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml',
+ },
+ ],
+ }),
+ )
+ const editor = new Editor({
+ element: document.createElement('div'),
+ extensions: editorExtensions,
+ content: blocksToPmDoc(parsed.blocks) as never,
+ })
+ const chart = editor.view.dom.querySelector('.doc-protected-chart')
+ expect(chart).toBeTruthy()
+ expect(chart!.querySelector('.doc-chart-svg')).toBeTruthy()
+ const caption = chart!.querySelector('.doc-chart-caption .doc-field-text')
+ expect(caption?.textContent).toBe('Figure 1: Filler comparison')
+ expect(chart!.querySelector('.doc-chart')!.compareDocumentPosition(caption!) & 4).toBeTruthy()
+
+ caption!.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, button: 0 }))
+ caption!.dispatchEvent(new MouseEvent('dblclick', { bubbles: true, button: 0 }))
+ expect(caption!.getAttribute('contenteditable')).toBe('false')
+ editor.destroy()
+ })
+})
diff --git a/apps/docs/tests/chart-edit.test.ts b/apps/docs/tests/chart-edit.test.ts
index 1fe1d7f..0a7bb77 100644
--- a/apps/docs/tests/chart-edit.test.ts
+++ b/apps/docs/tests/chart-edit.test.ts
@@ -22,7 +22,8 @@ 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(7) // 6 slots - 1 gap + 2 legend swatches
+ // 6 slots - 1 gap; the part has no c:legend, so no legend swatches
+ expect(chart.querySelectorAll('.doc-chart-svg rect').length).toBe(5)
expect(chart.querySelectorAll('.doc-chart-cat').length).toBe(3)
expect(chart.querySelectorAll('.doc-chart-val').length).toBe(5)
expect(chart.querySelectorAll('.doc-chart-gap').length).toBe(1)
diff --git a/apps/docs/tests/chart-svg-draw.test.ts b/apps/docs/tests/chart-svg-draw.test.ts
index 0be5bdf..c71adab 100644
--- a/apps/docs/tests/chart-svg-draw.test.ts
+++ b/apps/docs/tests/chart-svg-draw.test.ts
@@ -20,8 +20,9 @@ describe('chart svg drawing', () => {
categories: ['Alpha', 'Beta', 'Gamma'],
series: [{ name: 'S1', values: [10, 20, 30], xValues: [1, null, 3] }],
})
- // the Beta point (null x) is dropped, not plotted at index 2
- expect(dom.querySelectorAll('circle').length).toBe(2)
+ // the Beta point (null x) is dropped, not plotted at index 2 (series 0 marks points with diamonds)
+ const markers = [...dom.querySelectorAll('polygon')]
+ expect(markers.length).toBe(2)
const labels = [...dom.querySelectorAll('.doc-chart-axis-label')].map((t) => t.textContent)
expect(labels).toContain('Alpha')
expect(labels).toContain('Gamma')
@@ -33,9 +34,9 @@ describe('chart svg drawing', () => {
const alpha = [...dom.querySelectorAll('.doc-chart-axis-label')].find(
(t) => t.textContent === 'Alpha',
)!
- const circles = [...dom.querySelectorAll('circle')]
- expect(Number(gamma.getAttribute('x'))).toBeCloseTo(Number(circles[1].getAttribute('cx')), 3)
- expect(Number(alpha.getAttribute('x'))).toBeCloseTo(Number(circles[0].getAttribute('cx')), 3)
+ const markerX = (p: Element) => Number(p.getAttribute('points')!.split(' ')[0].split(',')[0])
+ expect(Number(gamma.getAttribute('x'))).toBeCloseTo(markerX(markers[1]), 3)
+ expect(Number(alpha.getAttribute('x'))).toBeCloseTo(markerX(markers[0]), 3)
})
it('stacks percentStacked area charts and normalizes the axis to 0-100%', () => {
@@ -133,4 +134,204 @@ describe('chart svg drawing', () => {
expect(new Set(legendTexts.map((t) => t.getAttribute('y'))).size).toBe(1)
expect(new Set(legendTexts.map((t) => t.getAttribute('x'))).size).toBe(2)
})
+
+ it('draws radar charts as rings, spokes and closed series outlines', () => {
+ const dom = draw({
+ partPath: 'word/charts/chart1.xml',
+ kind: 'radar',
+ radarStyle: 'standard',
+ categories: ['A', 'B', 'C', 'D', 'E'],
+ series: [
+ { name: 'S1', values: [1, 2, 3, 4, 5] },
+ { name: 'S2', values: [5, 4, 3, 2, 1] },
+ ],
+ })
+ expect(dom.querySelectorAll('polyline').length).toBe(0)
+ const polygons = [...dom.querySelectorAll('polygon')]
+ const series = polygons.filter(
+ (p) => p.getAttribute('fill') === 'none' && !p.classList.contains('doc-chart-grid'),
+ )
+ expect(series.length).toBe(2)
+ for (const p of series) expect(p.getAttribute('points')!.split(' ').length).toBe(5)
+ // value rings are polygons, one spoke per category
+ expect(polygons.filter((p) => p.classList.contains('doc-chart-grid')).length).toBeGreaterThan(1)
+ expect(dom.querySelectorAll('line.doc-chart-grid').length).toBe(5)
+ const labels = [...dom.querySelectorAll('.doc-chart-axis-label')].map((t) => t.textContent)
+ for (const c of ['A', 'B', 'C', 'D', 'E']) expect(labels).toContain(c)
+ })
+
+ it('fills filled-style radar series opaquely', () => {
+ const dom = draw({
+ partPath: 'word/charts/chart1.xml',
+ kind: 'radar',
+ radarStyle: 'filled',
+ categories: ['A', 'B', 'C'],
+ series: [{ name: 'S1', values: [1, 2, 3], color: 'C0504D' }],
+ })
+ const filled = [...dom.querySelectorAll('polygon')].filter(
+ (p) => p.getAttribute('fill') === '#C0504D',
+ )
+ expect(filled.length).toBe(1)
+ expect(filled[0].getAttribute('fill-opacity')).toBeNull()
+ })
+
+ it('explodes pie slices away from the center and labels them with percentages', () => {
+ const base = {
+ partPath: 'word/charts/chart1.xml',
+ kind: 'pie' as const,
+ categories: ['A', 'B', 'C'],
+ series: [{ values: [1, 1, 2] }],
+ }
+ const solid = draw(base)
+ const exploded = draw({ ...base, explosionPct: 25, dataLabels: { pct: true } })
+ const apex = (dom: HTMLElement) =>
+ [...dom.querySelectorAll('path')].map((p) =>
+ p.getAttribute('d')!.split(' ').slice(1, 3).join(','),
+ )
+ // every slice starts from its own shifted center
+ expect(new Set(apex(solid)).size).toBe(1)
+ expect(new Set(apex(exploded)).size).toBe(3)
+ const texts = [...exploded.querySelectorAll('text')].map((t) => t.textContent)
+ expect(texts).toContain('25%')
+ expect(texts).toContain('50%')
+ expect([...solid.querySelectorAll('text')].map((t) => t.textContent)).not.toContain('50%')
+ })
+
+ it('stacks stacked line series on the running total', () => {
+ const dom = draw({
+ partPath: 'word/charts/chart1.xml',
+ kind: 'line',
+ grouping: 'stacked',
+ categories: ['A', 'B'],
+ series: [
+ { name: 'S1', values: [2, 2] },
+ { name: 'S2', values: [2, 2] },
+ ],
+ })
+ const ys = [...dom.querySelectorAll('polyline')].map((l) =>
+ l
+ .getAttribute('points')!
+ .split(' ')
+ .map((p) => Number(p.split(',')[1])),
+ )
+ expect(ys.length).toBe(2)
+ // the second series sits above the first by the same value step
+ expect(ys[1][0]).toBeLessThan(ys[0][0])
+ const labels = [...dom.querySelectorAll('.doc-chart-axis-label')].map((t) => t.textContent)
+ expect(labels).toContain('4')
+ })
+
+ it('draws the data table under the plot and drops the axis category labels', () => {
+ const dom = draw({
+ partPath: 'word/charts/chart1.xml',
+ kind: 'bar',
+ noLegend: true,
+ categories: ['apple', 'pear'],
+ series: [
+ { name: 'S1', values: [4.6, 3.9] },
+ { name: 'S2', values: [2.4, 2.2] },
+ ],
+ dataTable: { keys: true, horz: true, vert: true, outline: true, line: '404040' },
+ })
+ const texts = [...dom.querySelectorAll('text')].map((t) => t.textContent)
+ expect(texts.filter((t) => t === 'apple').length).toBe(1)
+ expect(texts).toContain('4.6')
+ expect(texts).toContain('2.2')
+ const borders = [...dom.querySelectorAll('line')].filter(
+ (l) => l.getAttribute('stroke') === '#404040',
+ )
+ expect(borders.length).toBeGreaterThan(4)
+ // two key swatches, no legend row
+ expect(dom.querySelectorAll('rect[width="8"]').length).toBe(2)
+ })
+
+ it('draws axis lines, titles and a top legend with line keys', () => {
+ const dom = draw({
+ partPath: 'word/charts/chart1.xml',
+ kind: 'line',
+ markers: true,
+ legendPos: 't',
+ xAxis: { line: '404040' },
+ yAxis: { line: '404040', title: 'Axis Title' },
+ categories: ['A', 'B'],
+ series: [
+ { name: 'S1', values: [1, 2] },
+ { name: 'S2', values: [2, 1] },
+ ],
+ })
+ const axisLines = [...dom.querySelectorAll('line')].filter(
+ (l) => l.getAttribute('stroke') === '#404040',
+ )
+ expect(axisLines.length).toBe(2)
+ const title = dom.querySelector('.doc-chart-axis-title')!
+ expect(title.textContent).toBe('Axis Title')
+ expect(title.getAttribute('transform')).toMatch(/^rotate\(-90/)
+ const legend = [...dom.querySelectorAll('text')].filter(
+ (t) => t.textContent === 'S1' || t.textContent === 'S2',
+ )
+ expect(legend.map((t) => t.getAttribute('y'))).toEqual(['12', '12'])
+ // line series keys are line segments, not swatches; markers use the shape cycle
+ expect(dom.querySelectorAll('rect[width="8"]').length).toBe(0)
+ expect(dom.querySelectorAll('polygon').length).toBeGreaterThan(0)
+ })
+
+ it('lists stacked series top-first in a side legend and hides absent legends', () => {
+ const base = {
+ partPath: 'word/charts/chart1.xml',
+ kind: 'bar' as const,
+ grouping: 'stacked' as const,
+ categories: ['A'],
+ series: [
+ { name: 'S1', values: [1] },
+ { name: 'S2', values: [1] },
+ ],
+ }
+ const side = draw({ ...base, legendPos: 'r' })
+ const names = [...side.querySelectorAll('text')]
+ .filter((t) => t.textContent === 'S1' || t.textContent === 'S2')
+ .sort((a, b) => Number(a.getAttribute('y')) - Number(b.getAttribute('y')))
+ .map((t) => t.textContent)
+ expect(names).toEqual(['S2', 'S1'])
+ const none = draw({ ...base, noLegend: true })
+ expect([...none.querySelectorAll('text')].map((t) => t.textContent)).not.toContain('S1')
+ })
+
+ it('breaks radar outlines at gaps and pulls filled outlines to the center', () => {
+ const base = {
+ partPath: 'word/charts/chart1.xml',
+ kind: 'radar' as const,
+ categories: ['A', 'B', 'C', 'D'],
+ series: [{ name: 'S1', values: [1, null, 3, 4] }],
+ }
+ const open = draw({ ...base, radarStyle: 'standard' })
+ expect(open.querySelectorAll('polygon:not(.doc-chart-grid)').length).toBe(0)
+ const run = open.querySelector('polyline')!
+ expect(run.getAttribute('points')!.split(' ').length).toBe(3)
+ const filled = draw({ ...base, radarStyle: 'filled' })
+ const poly = filled.querySelector('polygon:not(.doc-chart-grid)')!
+ expect(poly.getAttribute('points')!.split(' ').length).toBe(4)
+ })
+
+ it('uses the marker shape cycle on scatter points and skips tables on horizontal bars', () => {
+ const scatter = draw({
+ partPath: 'word/charts/chart1.xml',
+ kind: 'scatter',
+ markers: true,
+ categories: [],
+ series: [{ name: 'S1', values: [1, 2], xValues: [1, 2], line: true }],
+ })
+ expect(scatter.querySelectorAll('circle').length).toBe(0)
+ expect(scatter.querySelectorAll('polygon').length).toBe(3) // 2 points + legend key
+ const bars = draw({
+ partPath: 'word/charts/chart1.xml',
+ kind: 'bar',
+ horizontal: true,
+ categories: ['A', 'B'],
+ series: [{ name: 'S1', values: [1, 2] }],
+ dataTable: { keys: true, horz: true, vert: true, outline: true, line: '404040' },
+ })
+ expect(
+ [...bars.querySelectorAll('line')].some((l) => l.getAttribute('stroke') === '#404040'),
+ ).toBe(false)
+ })
})
diff --git a/apps/docs/tests/checkbox-toggle.test.ts b/apps/docs/tests/checkbox-toggle.test.ts
new file mode 100644
index 0000000..726b5c5
--- /dev/null
+++ b/apps/docs/tests/checkbox-toggle.test.ts
@@ -0,0 +1,79 @@
+/**
+ * Clicking a checkbox glyph flips it (genoffice#248): legacy FORMCHECKBOX
+ * fields and w14:checkbox content controls toggle, plain box characters do not.
+ */
+import { Editor } from '@tiptap/core'
+import { afterEach, describe, expect, it } from 'vitest'
+import { toggleCheckboxAt } from '../src/renderer/editor/checkbox-toggle'
+import { editorExtensions } from '../src/renderer/editor/extensions'
+
+const SDT_PR =
+ ' ' +
+ ' ' +
+ ' '
+
+// destroyed after each test: ProseMirror's DOM observer flushes on a timer
+// and would touch `document` after the jsdom environment is torn down
+const editors: Editor[] = []
+afterEach(() => {
+ for (const e of editors.splice(0)) e.destroy()
+})
+
+const editorWith = (content: Array>) => {
+ const editor = new Editor({
+ element: document.createElement('div'),
+ extensions: editorExtensions,
+ content: {
+ type: 'doc',
+ content: [{ type: 'docParagraph', content }],
+ } as never,
+ })
+ editors.push(editor)
+ return editor
+}
+
+const text = (editor: Editor) => editor.state.doc.textContent
+
+describe('toggleCheckboxAt', () => {
+ it('flips a FORMCHECKBOX glyph on either side of the caret slot', () => {
+ const editor = editorWith([
+ { type: 'text', text: 'item: ' },
+ {
+ type: 'text',
+ text: '☐',
+ marks: [{ type: 'instrField', attrs: { instr: 'FORMCHECKBOX', beginXml: ' ' } }],
+ },
+ ])
+ // glyph sits at doc position 7 (paragraph open + 6 characters)
+ let tr = toggleCheckboxAt(editor.state, 7, 'after')
+ expect(tr).not.toBeNull()
+ editor.view.dispatch(tr!)
+ expect(text(editor)).toBe('item: ☒')
+ tr = toggleCheckboxAt(editor.state, 8, 'before')
+ editor.view.dispatch(tr!)
+ expect(text(editor)).toBe('item: ☐')
+ const glyph = editor.state.doc.nodeAt(7)!
+ expect(glyph.marks.map((m) => m.type.name)).toEqual(['instrField'])
+ })
+
+ it('flips a content control between the glyphs its properties declare', () => {
+ const editor = editorWith([
+ { type: 'text', text: '☐', marks: [{ type: 'ctrlCheckbox', attrs: { sdtPr: SDT_PR } }] },
+ ])
+ editor.view.dispatch(toggleCheckboxAt(editor.state, 1, 'after')!)
+ expect(text(editor)).toBe('☑')
+ expect(editor.state.doc.nodeAt(1)!.marks[0].attrs.sdtPr).toBe(SDT_PR)
+ editor.view.dispatch(toggleCheckboxAt(editor.state, 2, 'before')!)
+ expect(text(editor)).toBe('☐')
+ })
+
+ it('leaves a plain box character and other fields alone', () => {
+ const editor = editorWith([
+ { type: 'text', text: '☐ ' },
+ { type: 'text', text: '3', marks: [{ type: 'instrField', attrs: { instr: 'PAGE' } }] },
+ ])
+ expect(toggleCheckboxAt(editor.state, 1, 'after')).toBeNull()
+ expect(toggleCheckboxAt(editor.state, 3, 'after')).toBeNull()
+ expect(toggleCheckboxAt(editor.state, 0, 'before')).toBeNull()
+ })
+})
diff --git a/apps/docs/tests/convert-regressions.test.ts b/apps/docs/tests/convert-regressions.test.ts
index 70bd1ae..25c6cea 100644
--- a/apps/docs/tests/convert-regressions.test.ts
+++ b/apps/docs/tests/convert-regressions.test.ts
@@ -88,6 +88,7 @@ describe('runsToInline image runs', () => {
wrap: null,
offsetXEmu: null,
offsetYEmu: null,
+ relV: null,
wrapDistTopEmu: null,
wrapDistBottomEmu: null,
wrapDistLeftEmu: null,
@@ -133,6 +134,7 @@ describe('runsToInline image runs', () => {
wrap: null,
offsetXEmu: null,
offsetYEmu: null,
+ relV: null,
wrapDistTopEmu: null,
wrapDistBottomEmu: null,
wrapDistLeftEmu: null,
diff --git a/apps/docs/tests/dark-page.test.ts b/apps/docs/tests/dark-page.test.ts
index 7d3df36..626bee0 100644
--- a/apps/docs/tests/dark-page.test.ts
+++ b/apps/docs/tests/dark-page.test.ts
@@ -176,7 +176,7 @@ describe('docStyleCss dark twins', () => {
`tr:nth-child(even) td${island} { background:${darkPageColor('d9d9d9')} }`,
)
expect(dark).toContain(
- `tr:first-child th${island} { background:${darkPageColor('4472c4')};color:${DARK_PAPER_HEX} }`,
+ `tr[data-repeat-header="1"]:not(tr:not([data-repeat-header="1"]) ~ tr) th${island} { background:${darkPageColor('4472c4')};color:${DARK_PAPER_HEX} }`,
)
// a filled box would inherit the remapped document default from .doc-page:
// the island re-sets the authored one
diff --git a/apps/docs/tests/doc-style-css-borders.test.ts b/apps/docs/tests/doc-style-css-borders.test.ts
index 4fbe148..85d6e7c 100644
--- a/apps/docs/tests/doc-style-css-borders.test.ts
+++ b/apps/docs/tests/doc-style-css-borders.test.ts
@@ -16,13 +16,26 @@ describe('docStyleCss paragraph borders', () => {
parsedWith('HDR', { borderSides: { b: { color: '1F4E79', szPt: 6 }, t: {} } }),
)
expect(css).toContain(
- '[data-style="HDR"] { border-top:1px solid #444;border-bottom:8px solid #1F4E79;padding:1px 4px }',
+ '[data-style="HDR"] { border-top:1px solid #444;border-bottom:8px solid #1F4E79;padding-top:0;padding-bottom:0 }',
)
})
+ it('pads only the drawn sides, by w:space, as longhands (a direct side on another edge layers per side)', () => {
+ const css = docStyleCss(
+ parsedWith('Title', { borderSides: { b: { color: '4F81BD', szPt: 1, spacePt: 4 } } }),
+ )
+ expect(css).toContain(
+ '[data-style="Title"] { border-bottom:1px solid #4F81BD;padding-bottom:4pt }',
+ )
+ const boxed = docStyleCss(
+ parsedWith('Box', { borderSides: { t: { spacePt: 1 }, l: { spacePt: 4 }, b: {}, r: {} } }),
+ )
+ expect(boxed).toContain('padding-top:1pt;padding-right:4px;padding-bottom:0;padding-left:4px }')
+ })
+
it('emits nothing for a side reset to none', () => {
const css = docStyleCss(parsedWith('Off', { borderSides: { b: null } }))
expect(css).not.toContain('border-')
- expect(css).not.toContain('padding:1px 4px')
+ expect(css).not.toContain('padding:')
})
})
diff --git a/apps/docs/tests/doc-style-css-char-format.test.ts b/apps/docs/tests/doc-style-css-char-format.test.ts
new file mode 100644
index 0000000..679982b
--- /dev/null
+++ b/apps/docs/tests/doc-style-css-char-format.test.ts
@@ -0,0 +1,96 @@
+import { describe, expect, it } from 'vitest'
+import type {
+ ParsedDocFull,
+ StyleDisplay,
+ StyleInfo,
+ TableStyleDisplay,
+} from '@genoffice/docx-engine'
+import { docStyleCss } from '../src/renderer/doc-style-css'
+
+;(globalThis as { CSS?: unknown }).CSS ??= { escape: (s: string) => s }
+
+function parsedWith(info: Partial & { styleId: string }): ParsedDocFull {
+ const styles = new Map()
+ styles.set(info.styleId, { name: info.styleId, type: 'paragraph', ...info } as StyleInfo)
+ return { styles, docDefaults: {}, blocks: [] } as unknown as ParsedDocFull
+}
+
+describe('docStyleCss character formatting from styles.xml', () => {
+ it('strokes text with the style w14:textOutline, alpha as rgba', () => {
+ const display: StyleDisplay = { textOutline: { color: 'FF0000', widthPt: 0.75, alpha: 0.4 } }
+ const css = docStyleCss(parsedWith({ styleId: 'IntenseEmphasis', type: 'character', display }))
+ expect(css).toContain(
+ '[data-style="IntenseEmphasis"] { -webkit-text-stroke:0.75pt rgba(255,0,0,0.4) }',
+ )
+ })
+
+ it('paints character-style shading and flips auto ink on a dark fill', () => {
+ const css = docStyleCss(
+ parsedWith({ styleId: 'ChangeType', type: 'character', display: { shading: '000000' } }),
+ )
+ expect(css).toMatch(
+ /\[data-style="ChangeType"\] \{[^}]*background-color:#000000;--docs-paper-ink:#fff;color:var\(--docs-paper-ink\)/,
+ )
+ // the dark page remaps the fill light, so the auto ink goes paper-dark like run-level data-ink
+ expect(css).toMatch(
+ /\.page-dark \.doc-page \[data-style="ChangeType"\][^{]*\{ background:#[0-9a-f]{6};--docs-paper-ink:#1e1e1e \}/,
+ )
+ })
+
+ it('keeps an explicit style colour over the auto ink and skips paragraph styles', () => {
+ const explicit = docStyleCss(
+ parsedWith({
+ styleId: 'Tag',
+ type: 'character',
+ display: { shading: '000000', color: 'FFFF00' },
+ }),
+ )
+ expect(explicit).not.toContain('color:#FFFFFF')
+ const para = docStyleCss(
+ parsedWith({ styleId: 'Boxed', type: 'paragraph', display: { shading: '000000' } }),
+ )
+ expect(para).not.toContain('background-color:#000000')
+ })
+
+ // TOC \h entries carry the (localized id) Hyperlink style;
+ // Word's print layout keeps them in the TOC paragraph's ink, face and size intact
+ it('hides the Hyperlink style colour and underline inside TOC entries only', () => {
+ const styles = new Map()
+ styles.set('a3', {
+ styleId: 'a3',
+ name: 'Hyperlink',
+ type: 'character',
+ display: { color: '0000FF', underline: true, fontAscii: 'Verdana' },
+ } as StyleInfo)
+ styles.set('20', { styleId: '20', name: 'toc 2', type: 'paragraph', display: {} } as StyleInfo)
+ styles.set('Body', {
+ styleId: 'Body',
+ name: 'Body',
+ type: 'paragraph',
+ display: {},
+ } as StyleInfo)
+ const css = docStyleCss({ styles, docDefaults: {}, blocks: [] } as unknown as ParsedDocFull)
+ expect(css).toMatch(/\[data-style="a3"\] \{[^}]*color:#0000FF;[^}]*text-decoration:underline/)
+ expect(css).toContain(
+ '.doc-page :is(.doc-toc-line,[data-style="20"]) [data-style="a3"] { color:inherit;text-decoration:none }',
+ )
+ expect(css).toContain(
+ '.page-dark .doc-page :is(.doc-toc-line,[data-style="20"]) [data-style="a3"] { color:inherit }',
+ )
+ expect(css).toContain('.doc-link:has([data-style="a3"]) { color:inherit;text-decoration:none }')
+ expect(css).not.toContain('[data-style="Body"]) [data-style="a3"]')
+ })
+
+ it('applies header-row caps and font to the first row and the leading tblHeader rows', () => {
+ const tableDisplay: TableStyleDisplay = {
+ firstRow: { caps: 'all', color: '4F81BD', fontAscii: 'Cambria', charSpacingTwips: 20 },
+ }
+ const css = docStyleCss(parsedWith({ styleId: 'Calendar2', type: 'table', tableDisplay }))
+ const headerTr = 'tr[data-repeat-header="1"]:not(tr:not([data-repeat-header="1"]) ~ tr)'
+ const rule = css.split('\n').find((line) => line.includes('tr:first-child td'))
+ expect(rule).toContain(`table[data-tbl-style="Calendar2"] ${headerTr} td`)
+ expect(rule).toContain('text-transform:uppercase')
+ expect(rule).toContain('letter-spacing:1pt')
+ expect(rule).toMatch(/font-family:[^;]*Cambria/)
+ })
+})
diff --git a/apps/docs/tests/doc-style-css-indent.test.ts b/apps/docs/tests/doc-style-css-indent.test.ts
index 5cceb01..74c45ab 100644
--- a/apps/docs/tests/doc-style-css-indent.test.ts
+++ b/apps/docs/tests/doc-style-css-indent.test.ts
@@ -43,3 +43,22 @@ describe('docStyleCss first-line indent', () => {
expect(css).not.toContain('--style-li-hang')
})
})
+
+describe('docStyleCss paragraph-style Latin line factor', () => {
+ it('a style with its own Latin face re-anchors --doc-line-factor-latin', () => {
+ const css = docStyleCss(parsedWith('Heading1', { fontAscii: 'Cambria', font: 'Cambria' }))
+ expect(css).toMatch(/\[data-style="Heading1"\] \{[^}]*--doc-line-factor-latin:1\.172/)
+ })
+
+ it('a character style leaves the paragraph factor alone', () => {
+ const styles = new Map()
+ styles.set('Strong', {
+ styleId: 'Strong',
+ name: 'Strong',
+ type: 'character',
+ display: { fontAscii: 'Cambria', font: 'Cambria' },
+ } as StyleInfo)
+ const css = docStyleCss({ styles, docDefaults: {}, blocks: [] } as unknown as ParsedDocFull)
+ expect(css).not.toContain('--doc-line-factor-latin:1.172')
+ })
+})
diff --git a/apps/docs/tests/doc-style-css-spacing.test.ts b/apps/docs/tests/doc-style-css-spacing.test.ts
index af710cc..5964f08 100644
--- a/apps/docs/tests/doc-style-css-spacing.test.ts
+++ b/apps/docs/tests/doc-style-css-spacing.test.ts
@@ -99,6 +99,11 @@ describe('docStyleCss spacing', () => {
parsedWith('Body', { lineRule: 'auto', lineRawTwips: 480, spaceAfterTwips: 100 }),
)
expect(auto).not.toContain('--doc-line-fixed')
+ // line="0" atLeast is a natural-height fixed line: its spans must not
+ // re-snap to the grid either (Word probe 2026-09-11)
+ const zero = docStyleCss(parsedWith('Loose', { lineRule: 'atLeast', lineRawTwips: 0 }))
+ expect(zero).toMatch(/\[data-style="Loose"\] \{[^}]*--doc-line-fixed:1/)
+ expect(zero).toContain('[data-style="Loose"]:not(.doc-lh-fixed) span { line-height:inherit }')
})
it('lets a direct ctxSp off (.ctx-sp-off) escape the style-level suppression', () => {
diff --git a/apps/docs/tests/enter-overtype-para-format.test.ts b/apps/docs/tests/enter-overtype-para-format.test.ts
new file mode 100644
index 0000000..ddd93ec
--- /dev/null
+++ b/apps/docs/tests/enter-overtype-para-format.test.ts
@@ -0,0 +1,162 @@
+/**
+ * Replacing whole paragraphs must keep their paragraph FORMATTING (r176
+ * follow-up): a selection that consumes complete blocks makes ProseMirror
+ * fill the hole with a default paragraph, so a document whose Calibri comes
+ * from the paragraph style or the paragraph mark (not explicit run marks)
+ * fell back to the theme font — and alignment, indents and spacing were
+ * silently lost even in run-formatted documents. Word keeps the formatting
+ * of the START of the replaced range, the same rule the run-mark carry
+ * (r133) already applies.
+ */
+import { Editor } from '@tiptap/core'
+import { AllSelection, TextSelection } from '@tiptap/pm/state'
+import { describe, expect, it } from 'vitest'
+import { editorExtensions } from '../src/renderer/editor/extensions'
+
+const calibri = { type: 'docTextStyle', attrs: { font: 'Calibri', fontAscii: 'Calibri' } }
+
+const STYLED = {
+ styleId: 'BodyCalibri',
+ emptyRunFont: 'Calibri',
+ align: 'center',
+ indentLeft: 48,
+ docxIndex: 7,
+ bookmarks: ['keep-out'],
+}
+
+const makeEditor = (opts?: { runMarks?: boolean; paras?: number }) => {
+ const paras = opts?.paras ?? 2
+ return new Editor({
+ element: document.createElement('div'),
+ extensions: editorExtensions,
+ content: {
+ type: 'doc',
+ content: Array.from({ length: paras }, (_v, i) => ({
+ type: 'docParagraph',
+ attrs: STYLED,
+ content: [
+ {
+ type: 'text',
+ text: `ligne ${i + 1} de texte`,
+ ...(opts?.runMarks === false ? {} : { marks: [calibri] }),
+ },
+ ],
+ })),
+ } as never,
+ })
+}
+
+const pressEnter = (editor: Editor): boolean => {
+ const event = new KeyboardEvent('keydown', {
+ key: 'Enter',
+ code: 'Enter',
+ bubbles: true,
+ cancelable: true,
+ })
+ editor.view.dom.dispatchEvent(event)
+ return event.defaultPrevented
+}
+
+const selectAllContent = (editor: Editor) => {
+ const end = editor.state.doc.content.size - 1
+ editor.view.dispatch(editor.state.tr.setSelection(TextSelection.create(editor.state.doc, 1, end)))
+}
+
+const expectFormatKept = (editor: Editor) => {
+ expect(editor.state.doc.childCount).toBe(2)
+ editor.state.doc.forEach((node) => {
+ expect(node.content.size).toBe(0)
+ expect(node.attrs.styleId).toBe('BodyCalibri')
+ expect(node.attrs.emptyRunFont).toBe('Calibri')
+ expect(node.attrs.align).toBe('center')
+ expect(node.attrs.indentLeft).toBe(48)
+ })
+}
+
+describe('Enter over whole paragraphs keeps paragraph formatting (r176 follow-up)', () => {
+ it('cross-block full selection: both empty halves keep style, mark font and alignment', () => {
+ const editor = makeEditor()
+ selectAllContent(editor)
+ expect(pressEnter(editor)).toBe(true)
+ expectFormatKept(editor)
+ // the run-mark carry (r133) still rides along
+ const stored = editor.state.storedMarks ?? []
+ expect(stored.some((m) => m.type.name === 'docTextStyle' && m.attrs.font === 'Calibri')).toBe(
+ true,
+ )
+ editor.destroy()
+ })
+
+ it('Ctrl+A AllSelection: both empty halves keep the paragraph formatting', () => {
+ const editor = makeEditor({ paras: 3 })
+ editor.view.dispatch(editor.state.tr.setSelection(new AllSelection(editor.state.doc)))
+ expect(pressEnter(editor)).toBe(true)
+ expectFormatKept(editor)
+ // the AllSelection replace built a FRESH paragraph: the format restore
+ // must not clone identity/annotation attrs onto it
+ editor.state.doc.forEach((node) => {
+ expect(node.attrs.docxIndex).toBeNull()
+ expect(node.attrs.bookmarks).toBeNull()
+ })
+ editor.destroy()
+ })
+
+ it('style-derived font only (no run marks): paragraph attrs still come back', () => {
+ const editor = makeEditor({ runMarks: false })
+ selectAllContent(editor)
+ pressEnter(editor)
+ expectFormatKept(editor)
+ editor.destroy()
+ })
+
+ it('mid-paragraph selection: surviving halves keep their own attrs untouched', () => {
+ const editor = makeEditor()
+ // from inside para 1 to inside para 2 — both halves keep text
+ editor.view.dispatch(
+ editor.state.tr.setSelection(TextSelection.create(editor.state.doc, 7, 30)),
+ )
+ pressEnter(editor)
+ expect(editor.state.doc.childCount).toBe(2)
+ editor.state.doc.forEach((node) => {
+ expect(node.content.size).toBeGreaterThan(0)
+ expect(node.attrs.styleId).toBe('BodyCalibri')
+ expect(node.attrs.align).toBe('center')
+ })
+ editor.destroy()
+ })
+
+ it('plain Delete over whole paragraphs restores the filler paragraph format', () => {
+ const editor = makeEditor()
+ selectAllContent(editor)
+ editor.commands.deleteSelection()
+ expect(editor.state.doc.childCount).toBe(1)
+ const para = editor.state.doc.child(0)
+ expect(para.content.size).toBe(0)
+ expect(para.attrs.styleId).toBe('BodyCalibri')
+ expect(para.attrs.emptyRunFont).toBe('Calibri')
+ expect(para.attrs.align).toBe('center')
+ // the r172 mark carry still seeds the pilcrow memory
+ expect(String(para.attrs.caretMarks)).toContain('Calibri')
+ editor.destroy()
+ })
+
+ it('Delete over unformatted-default paragraphs stays a no-op', () => {
+ const editor = new Editor({
+ element: document.createElement('div'),
+ extensions: editorExtensions,
+ content: {
+ type: 'doc',
+ content: [
+ { type: 'docParagraph', content: [{ type: 'text', text: 'plain one' }] },
+ { type: 'docParagraph', content: [{ type: 'text', text: 'plain two' }] },
+ ],
+ } as never,
+ })
+ selectAllContent(editor)
+ editor.commands.deleteSelection()
+ const para = editor.state.doc.child(0)
+ expect(para.attrs.styleId).toBeNull()
+ expect(para.attrs.caretMarks).toBeNull()
+ editor.destroy()
+ })
+})
diff --git a/apps/docs/tests/field-eq-render.test.ts b/apps/docs/tests/field-eq-render.test.ts
new file mode 100644
index 0000000..794f5c5
--- /dev/null
+++ b/apps/docs/tests/field-eq-render.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it } from 'vitest'
+import type { FieldDisplay } from '@genoffice/docx-engine'
+import { renderFieldSpec } from '../src/renderer/editor/protected-render'
+
+describe('EQ field result rendering', () => {
+ it('the math host carries the run marks and the OMML for buildProtectedDom', () => {
+ const field: FieldDisplay = {
+ kind: 'text',
+ left: 'x = 1/2',
+ runs: [
+ { text: 'x = ' },
+ {
+ text: '1/2',
+ bold: true,
+ color: 'FF0000',
+ sizeHalfPoints: 28,
+ math: { omml: ' ' },
+ },
+ ],
+ }
+ const spec = renderFieldSpec(field) as unknown[]
+ const host = spec[3] as [string, Record, string]
+ expect(host[0]).toBe('span')
+ expect(host[1].class).toBe('doc-inline-math doc-field-math')
+ expect(host[1]['data-omml']).toBe(' ')
+ expect(host[1].style).toContain('font-weight:700')
+ expect(host[1].style).toContain('font-size:14pt')
+ expect(host[1].style).toContain('#FF0000')
+ expect(host[2]).toBe('1/2')
+ })
+})
diff --git a/apps/docs/tests/float-spill.test.ts b/apps/docs/tests/float-spill.test.ts
index c0466e2..c5b9c6c 100644
--- a/apps/docs/tests/float-spill.test.ts
+++ b/apps/docs/tests/float-spill.test.ts
@@ -28,6 +28,16 @@ describe('appendFloatSpillBlock', () => {
expect(blocks).toHaveLength(1)
})
+ it('wrapNone/front/behind boxes never open a page (Word clips them at the anchor page)', () => {
+ const blocks: BlockBox[] = [{ top: 0, height: 100 }]
+ const floats: FloatBox[] = [
+ { el, ...base, top: 950, height: 400, noSpill: true },
+ { el, ...base, top: 0, height: 50 },
+ ]
+ expect(appendFloatSpillBlock(blocks, 100, floats)).toBeNull()
+ expect(blocks).toHaveLength(1)
+ })
+
it('materializes trailing pages for overflowing floats', () => {
const blocks: BlockBox[] = [{ top: 0, height: 100 }]
const floats: FloatBox[] = [{ el, ...base, top: 1500, height: 400 }]
diff --git a/apps/docs/tests/float-table-keyword-anchor.test.ts b/apps/docs/tests/float-table-keyword-anchor.test.ts
new file mode 100644
index 0000000..163e541
--- /dev/null
+++ b/apps/docs/tests/float-table-keyword-anchor.test.ts
@@ -0,0 +1,156 @@
+import { Editor } from '@tiptap/core'
+import { describe, expect, it } from 'vitest'
+import { editorExtensions } from '../src/renderer/editor/extensions'
+import {
+ computeSectionedSlicesF2,
+ type BlockBox,
+ type SectionGeom,
+ type SliceOutputs,
+} from '../src/renderer/pagination'
+
+const cell = { type: 'docTableCell', content: [{ type: 'docParagraph' }] }
+const row = { type: 'docTableRow', content: [cell] }
+const editor = new Editor({ element: document.createElement('div'), extensions: editorExtensions })
+
+function tableAttrs(attrs: Record): Record {
+ const table = editor.schema.nodeFromJSON({ type: 'docTable', attrs, content: [row] })
+ return (editor.schema.nodes.docTable.spec.toDOM!(table) as [string, Record])[1]
+}
+
+const block = (top: number, height: number, extra?: Partial): BlockBox => ({
+ top,
+ height,
+ ...extra,
+})
+
+describe('w:tblpXSpec / w:tblpYSpec keyword anchors', () => {
+ it('a keyword Y on a margin anchor emits the spec instead of a fixed target', () => {
+ const attrs = tableAttrs({
+ tblFloat: 'left',
+ tblFloatSource: 'left',
+ tblFloatHorzAnchor: 'margin',
+ tblFloatVertAnchor: 'margin',
+ tblFloatXSpec: 'center',
+ tblFloatYSpec: 'bottom',
+ })
+ expect(attrs['data-tblp-vy']).toBe('0.0')
+ expect(attrs['data-tblp-vanchor']).toBe('margin')
+ expect(attrs['data-tblp-vspec']).toBe('bottom')
+ expect(attrs.style).toContain('margin-top:var(--tblp-dy,0px)')
+ })
+
+ it('a page-anchored X of zero reaches into the left margin', () => {
+ const attrs = tableAttrs({
+ tblFloat: 'left',
+ tblFloatSource: 'left',
+ tblFloatHorzAnchor: 'page',
+ tblFloatVertAnchor: 'page',
+ tblFloatXTwips: 0,
+ tblFloatYSpec: 'top',
+ tblFloatWidthPx: 264,
+ })
+ expect(attrs.style).toContain(
+ 'margin-left:max(calc(0px - var(--doc-margin-left,0px)),min(calc(0.0px - var(--doc-margin-left,0px)),max(0px,calc(var(--doc-content-w,100%) - 264.0px))))',
+ )
+ // a page-anchored X inside the content box with a table wider than the
+ // content stays at the content edge (the cap must not pull it into the margin)
+ const wide = tableAttrs({
+ tblFloat: 'left',
+ tblFloatSource: 'left',
+ tblFloatHorzAnchor: 'page',
+ tblFloatVertAnchor: 'text',
+ tblFloatXTwips: 4000,
+ tblFloatWidthPx: 700,
+ })
+ expect(wide.style).toContain(
+ 'margin-left:max(calc(0px - var(--doc-margin-left,0px)),min(calc(266.7px - var(--doc-margin-left,0px)),max(0px,calc(var(--doc-content-w,100%) - 700.0px))))',
+ )
+ const marginAnchored = tableAttrs({
+ tblFloat: 'left',
+ tblFloatSource: 'left',
+ tblFloatHorzAnchor: 'margin',
+ tblFloatVertAnchor: 'text',
+ tblFloatXTwips: 0,
+ })
+ expect(marginAnchored.style ?? '').not.toContain('margin-left')
+ })
+
+ it('centers a fixed-width float in the content box', () => {
+ const attrs = tableAttrs({
+ tblFloat: 'left',
+ tblFloatSource: 'left',
+ tblFloatHorzAnchor: 'margin',
+ tblFloatVertAnchor: 'text',
+ tblFloatXSpec: 'center',
+ tblFloatWidthPx: 200,
+ })
+ expect(attrs.style).toContain(
+ 'margin-left:max(0px,calc((var(--doc-content-w,100%) - 200.0px) / 2))',
+ )
+ })
+})
+
+describe('keyword-anchored float shifts in the slice engine', () => {
+ const geoms: SectionGeom[] = [
+ { contentHeight: 600, forceBreak: false, topPx: 60, pageHeightPx: 720, contentWidth: 400 },
+ ]
+
+ it('bottom aligns the table bottom with the content bottom', () => {
+ const out: SliceOutputs = { floatVShifts: [] }
+ const blocks = [
+ block(0, 40),
+ block(40, 60, {
+ floated: true,
+ pageRelVyPx: 0,
+ pageRelVAnchor: 'margin',
+ pageRelVSpec: 'bottom',
+ }),
+ ]
+ computeSectionedSlicesF2(blocks, geoms, 600, out)
+ expect(out.floatVShifts).toEqual([{ blockTop: 40, dyPx: 500 }])
+ })
+
+ it('a page-anchored top keyword on a blank page hangs the table into the top margin', () => {
+ const out: SliceOutputs = { floatVShifts: [] }
+ const blocks = [
+ block(0, 100, { floated: true, pageRelVyPx: 0, pageRelVAnchor: 'page', pageRelVSpec: 'top' }),
+ block(0, 40),
+ ]
+ computeSectionedSlicesF2(blocks, geoms, 600, out)
+ expect(out.floatVShifts).toEqual([{ blockTop: 0, dyPx: -60 }])
+ })
+
+ it('a float stacked under an earlier float measures its shift from where CSS put it', () => {
+ const out: SliceOutputs = { floatVShifts: [] }
+ const blocks = [
+ block(0, 100, { floated: true, pageRelVyPx: 0, pageRelVAnchor: 'page', pageRelVSpec: 'top' }),
+ block(0, 40),
+ block(100, 60, {
+ floated: true,
+ pageRelVyPx: 0,
+ pageRelVAnchor: 'margin',
+ pageRelVSpec: 'bottom',
+ }),
+ ]
+ computeSectionedSlicesF2(blocks, geoms, 600, out)
+ expect(out.floatVShifts).toEqual([
+ { blockTop: 0, dyPx: -60 },
+ { blockTop: 100, dyPx: 440 },
+ ])
+ })
+
+ it('never lifts a float above content already on the page', () => {
+ const out: SliceOutputs = { floatVShifts: [] }
+ const blocks = [
+ block(0, 200),
+ block(200, 100, {
+ floated: true,
+ pageRelVyPx: 0,
+ pageRelVAnchor: 'page',
+ pageRelVSpec: 'top',
+ }),
+ ]
+ computeSectionedSlicesF2(blocks, geoms, 600, out)
+ expect(out.floatVShifts).toEqual([{ blockTop: 200, dyPx: 0 }])
+ })
+})
diff --git a/apps/docs/tests/footnote-beneath-text.test.ts b/apps/docs/tests/footnote-beneath-text.test.ts
new file mode 100644
index 0000000..3f13642
--- /dev/null
+++ b/apps/docs/tests/footnote-beneath-text.test.ts
@@ -0,0 +1,95 @@
+import { describe, expect, it } from 'vitest'
+import { appendEndnotesBlock, noteAreaPlacement, pageTextEnds } from '../src/renderer/pagination'
+import type { BlockBox, PageNoteItem, PageSlice } from '../src/renderer/pagination-types'
+
+const el = (marginBottomPx = 0): HTMLElement => {
+ const d = document.createElement('div')
+ d.style.marginBottom = `${marginBottomPx}px`
+ document.body.appendChild(d)
+ return d
+}
+
+const slice = (start: number, end: number): PageSlice => ({ start, end, section: 0 })
+
+describe('footnotes beneath text (w:footnotePr w:pos="beneathText")', () => {
+ it('page text end excludes the footnote reservation and clips a split block at the page end', () => {
+ const blocks: BlockBox[] = [
+ // referencing paragraph: 100px of text + 40px reserved for its note
+ { top: 0, height: 140, footnoteExtraPx: 40, el: el(), docxIndex: 0 },
+ { top: 100, height: 300, el: el(), docxIndex: 1 },
+ { top: 400, height: 50, el: el(), docxIndex: 2 },
+ ]
+ const slices = [slice(0, 250), slice(250, 450)]
+ // page 1 ends inside the second block; page 2 ends at the last block's bottom
+ expect(pageTextEnds(blocks, slices)).toEqual([250, 450])
+ })
+
+ it('the flow-final block contributes its space after (Word lays the separator below it)', () => {
+ const blocks: BlockBox[] = [
+ { top: 0, height: 100, footnoteExtraPx: 20, el: el(), docxIndex: 0 },
+ { top: 80, height: 40, el: el(13), docxIndex: 1 },
+ ]
+ expect(pageTextEnds(blocks, [slice(0, 500)])).toEqual([133])
+ })
+
+ it('virtual blocks (endnote area, float spill) are not text', () => {
+ const blocks: BlockBox[] = [
+ { top: 0, height: 60, el: el(), docxIndex: 0 },
+ { top: 60, height: 200, isEndnotes: true },
+ { top: 260, height: 300 },
+ ]
+ expect(pageTextEnds(blocks, [slice(0, 700)])).toEqual([60])
+ })
+})
+
+describe('page note area placement', () => {
+ const geom = { pageH: 1000, mTop: 100, mBottom: 100, headerH: 0, vOffset: 0 }
+
+ it('bottom-anchored by default; beneath the text end when the section asks for it', () => {
+ expect(noteAreaPlacement(60, undefined, slice(0, 800), geom)).toEqual({
+ top: null,
+ endnoteShift: 0,
+ })
+ expect(noteAreaPlacement(60, 300, slice(0, 800), geom)).toEqual({ top: 400, endnoteShift: 60 })
+ // an over-tall area clamps to the content bottom; endnotes follow its real bottom
+ expect(noteAreaPlacement(60, 790, slice(0, 800), geom)).toEqual({ top: 840, endnoteShift: 10 })
+ })
+
+ it('moves with the page vAlign shift like the body text', () => {
+ expect(noteAreaPlacement(60, 300, slice(0, 800), { ...geom, vOffset: 50 })).toEqual({
+ top: 450,
+ endnoteShift: 60,
+ })
+ })
+
+ it('endnotes on a beneath-text page stack below the footnote area, not over it', () => {
+ const { top, endnoteShift } = noteAreaPlacement(60, 300, slice(0, 800), geom)
+ // endnote rows start at the flow end (300) like the footnote area; the shift keeps them apart
+ const endnoteTop = geom.mTop + (300 - 0) + endnoteShift
+ expect(endnoteTop).toBe(top! + 60)
+ })
+
+ it('no footnotes or regioned pages leave the endnotes at their flow position', () => {
+ expect(noteAreaPlacement(0, 300, slice(0, 800), geom)).toEqual({ top: null, endnoteShift: 0 })
+ expect(noteAreaPlacement(60, 300, { ...slice(0, 800), regions: [] }, geom)).toEqual({
+ top: null,
+ endnoteShift: 0,
+ })
+ })
+})
+
+describe('endnote area anchor', () => {
+ it('starts below the last body paragraph including its space after', () => {
+ const blocks: BlockBox[] = [{ top: 0, height: 100, el: el(13), docxIndex: 0 }]
+ const items: PageNoteItem[] = [{ no: 1, id: '1', text: 'n', height: 20 }]
+ const out = appendEndnotesBlock(blocks, 100, items, 16)
+ expect(out).toEqual({ top: 113, totalHeight: 149 })
+ expect(blocks[1]).toMatchObject({ top: 113, height: 36, isEndnotes: true })
+ })
+
+ it('a folded inter-block margin is not counted twice', () => {
+ const blocks: BlockBox[] = [{ top: 0, height: 113, spaceAfterPx: 13, el: el(13), docxIndex: 0 }]
+ const out = appendEndnotesBlock(blocks, 113, [{ no: 1, id: '1', text: 'n', height: 20 }], 16)
+ expect(out?.top).toBe(113)
+ })
+})
diff --git a/apps/docs/tests/headless-export.test.ts b/apps/docs/tests/headless-export.test.ts
new file mode 100644
index 0000000..e8bd46c
--- /dev/null
+++ b/apps/docs/tests/headless-export.test.ts
@@ -0,0 +1,109 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { runHeadlessDocumentExport, waitForDocumentSettled } from '../src/renderer/headless-export'
+import type { DocumentReadiness } from '../src/renderer/headless-export'
+
+/**
+ * Headless export readiness (src/renderer/headless-export.ts): the hidden
+ * window must not print before a document is open and pagination has
+ * settled, and it must fail loudly instead of hanging when it never does.
+ */
+
+type PageDebugWindow = typeof globalThis & { __pageDebug?: { slices?: unknown[] } }
+
+function setSlices(count: number | null): void {
+ const w = globalThis as PageDebugWindow
+ if (count === null) delete w.__pageDebug
+ else w.__pageDebug = { slices: Array.from({ length: count }, (_, i) => i) }
+}
+
+afterEach(() => {
+ setSlices(null)
+ vi.restoreAllMocks()
+})
+
+const fast = { pollMs: 1, timeoutMs: 400 }
+
+/** default readiness: a real file is open and the open did not fail */
+const ready = (over: Partial = {}): DocumentReadiness => ({
+ opened: true,
+ failed: false,
+ ...over,
+})
+
+describe('waitForDocumentSettled', () => {
+ it('waits for a document and a page count that repeats', async () => {
+ setSlices(null)
+ let hasDoc = false
+ setTimeout(() => {
+ hasDoc = true
+ setSlices(2)
+ }, 5)
+ await waitForDocumentSettled(() => ready({ opened: hasDoc }), fast)
+ expect(hasDoc).toBe(true)
+ })
+
+ it('keeps waiting while the page count is still moving', async () => {
+ setSlices(1)
+ const growth = [2, 3, 4, 4, 4]
+ let i = 0
+ const timer = setInterval(() => {
+ if (i < growth.length) setSlices(growth[i++]!)
+ }, 2)
+ await waitForDocumentSettled(ready, fast)
+ clearInterval(timer)
+ expect(i).toBeGreaterThan(2)
+ })
+
+ it('fails when no document ever opens', async () => {
+ await expect(waitForDocumentSettled(() => ready({ opened: false }), fast)).rejects.toThrow(
+ 'did not open',
+ )
+ })
+
+ it('fails when pagination produced no pages at all', async () => {
+ setSlices(0)
+ await expect(waitForDocumentSettled(ready, fast)).rejects.toThrow(
+ 'pagination produced no pages',
+ )
+ })
+
+ it('accepts a page count that never stabilized rather than losing the export', async () => {
+ let n = 1
+ const timer = setInterval(() => setSlices(++n), 1)
+ await expect(waitForDocumentSettled(ready, fast)).resolves.toBeUndefined()
+ clearInterval(timer)
+ })
+})
+
+describe('waitForDocumentSettled (unreadable input)', () => {
+ it('fails immediately on the blank fallback instead of waiting out the budget', async () => {
+ const t0 = Date.now()
+ await expect(
+ waitForDocumentSettled(() => ready({ opened: false, failed: true }), {
+ pollMs: 1,
+ timeoutMs: 5000,
+ }),
+ ).rejects.toThrow('did not open')
+ expect(Date.now() - t0).toBeLessThan(1000)
+ })
+})
+
+describe('runHeadlessDocumentExport', () => {
+ it('runs the export once the document has settled', async () => {
+ setSlices(3)
+ const exportPdf = vi.fn(() => Promise.resolve(true))
+ await expect(runHeadlessDocumentExport('/o.pdf', ready, exportPdf, fast)).resolves.toEqual({
+ ok: true,
+ })
+ expect(exportPdf).toHaveBeenCalledWith('/o.pdf')
+ })
+
+ it('reports the stall instead of exporting a document that never opened', async () => {
+ const exportPdf = vi.fn(() => Promise.resolve(true))
+ await expect(
+ runHeadlessDocumentExport('/o.pdf', () => ready({ opened: false }), exportPdf, fast),
+ ).resolves.toMatchObject({ ok: false, error: expect.stringContaining('did not open') })
+ expect(exportPdf).not.toHaveBeenCalled()
+ })
+})
diff --git a/apps/docs/tests/hf-page-mark.test.ts b/apps/docs/tests/hf-page-mark.test.ts
index 9937e79..b95b2a1 100644
--- a/apps/docs/tests/hf-page-mark.test.ts
+++ b/apps/docs/tests/hf-page-mark.test.ts
@@ -3,6 +3,9 @@ import { PAGE_MARK, TOTAL_PAGES_MARK, type HeaderFooter } from '@genoffice/docx-
import {
hfHasPageField,
hfSegLeftCss,
+ hfStripGeom,
+ hfTabLines,
+ hfTabOverflowPx,
hfTabSegments,
hfWithoutPageMarks,
makeGapHfEl,
@@ -111,6 +114,130 @@ describe('page-number substitution (PAGE_MARK)', () => {
])
})
+ it('a tab line with nothing before its first tab keeps an in-flow strut', () => {
+ // footer "\t\tPAGE(NUMPAGES)": only positioned segments would leave the
+ // line box empty (zero height once the preview drops the chrome min-height)
+ // and the strip's overflow would clip the page number away
+ const value: HeaderFooter = {
+ text: '()',
+ pageNumber: true,
+ paras: [
+ {
+ runs: [
+ { text: '\t\t' },
+ { text: PAGE_MARK },
+ { text: '(' },
+ { text: TOTAL_PAGES_MARK },
+ { text: ')' },
+ ],
+ ptabAligns: ['center', 'right'],
+ },
+ ],
+ }
+ const el = makeGapHfEl({ kind: 'footer', value, pageNo: 2, pageTotal: 3 })
+ const para = el.querySelector('.page-hf-para')!
+ expect(para.childNodes[0].nodeType).toBe(Node.TEXT_NODE)
+ expect(para.childNodes[0].textContent).toBe('\u200b')
+ const segs = [...para.querySelectorAll('.page-hf-tabseg')]
+ expect(segs.map((s) => s.textContent)).toEqual(['', '2(3)'])
+ expect(segs[1].style.left).toBe('100%')
+ // a lead with visible text needs no strut
+ const withLead = makeGapHfEl({
+ kind: 'footer',
+ value: { text: 'L', pageNumber: false, paras: [{ runs: [{ text: 'L\tR' }] }] },
+ pageNo: 1,
+ pageTotal: 1,
+ })
+ expect(withLead.querySelector('.page-hf-para')!.childNodes[0].nodeName).toBe('SPAN')
+ })
+
+ it('w:br inside a tabbed paragraph starts a new tab line', () => {
+ // header "Title\tApproved: Edition: 2\tPublished: 2012": each line lays
+ // its tab out from the column edge again; ptab order continues across lines
+ const value: HeaderFooter = {
+ text: 'Title Approved: Edition: 2 Published: 2012',
+ pageNumber: false,
+ paras: [
+ {
+ runs: [{ text: 'Title\tApproved: \nEdition: 2\tPublished: 2012' }],
+ tabStops: [{ pos: 9000, val: 'right' }],
+ spaceAfter: 0,
+ },
+ ],
+ }
+ const w = (chars: number) => chars * 10.5 * 0.5 * (4 / 3)
+ const el = makeGapHfEl({ kind: 'header', value, pageNo: 1, pageTotal: 1 })
+ const para = el.querySelector('.page-hf-para')!
+ expect(para.classList.contains('page-hf-tabbed')).toBe(false)
+ const lines = [...para.querySelectorAll(':scope > .page-hf-tabbed')]
+ expect(lines.map((l) => l.textContent)).toEqual([
+ 'TitleApproved: ',
+ 'Edition: 2Published: 2012',
+ ])
+ for (const line of lines) {
+ const seg = line.querySelector('.page-hf-tabseg')!
+ // right stop at 9000 twips: both segments end on the same stop
+ expect(parseFloat(seg.style.left) + w(seg.textContent!.length)).toBeCloseTo(9000 / 15, 0)
+ }
+ const ptab = hfTabLines({
+ runs: [{ text: 'A\tB\nC\tD' }],
+ ptabAligns: ['center', 'right'],
+ })!
+ expect(ptab.map((l) => l.segments[0].anchor)).toEqual(['center', 'right'])
+ expect(hfTabLines({ runs: [{ text: 'A\nC\tD' }] })![0]).toEqual({
+ lead: [{ text: 'A' }],
+ segments: [],
+ })
+ })
+
+ it('a stop past the right margin widens the strip clip box into the margin (Word keeps the stop)', () => {
+ // A4 column 9070 twips, Footer style right stop at 9360: "Page 3 of 3" ends
+ // 290 twips into the right margin instead of being cut at the column edge
+ const geom = hfStripGeom({
+ pageWidth: 11906,
+ pageHeight: 16838,
+ marginLeft: 1418,
+ marginRight: 1418,
+ marginTop: 1418,
+ marginBottom: 1134,
+ } as Parameters[0])
+ const para = {
+ runs: [{ text: '\t\tPage 3 of 3' }],
+ tabStops: [
+ { pos: 4680, val: 'center' as const },
+ { pos: 9360, val: 'right' as const },
+ ],
+ }
+ const lines = hfTabLines(para)!
+ const seg = lines[0].segments[0]
+ expect(seg.endPx).toBeCloseTo(9360 / 15, 1)
+ expect(hfTabOverflowPx(lines, geom)).toBeCloseTo((9360 - 9070) / 15, 1)
+ expect(hfTabOverflowPx(lines, undefined)).toBe(0)
+ const el = makeGapHfEl({
+ kind: 'footer',
+ value: { text: 'Page 3 of 3', pageNumber: false, paras: [para] },
+ pageNo: 3,
+ pageTotal: 3,
+ geom,
+ })
+ expect(el.style.getPropertyValue('--hf-tab-over')).toBe('19.3px')
+ // stops inside the column leave the strip alone
+ const inside = makeGapHfEl({
+ kind: 'footer',
+ value: {
+ text: 'x',
+ pageNumber: false,
+ paras: [
+ { runs: [{ text: '\tPage 3 of 3' }], tabStops: [{ pos: 9000, val: 'right' as const }] },
+ ],
+ },
+ pageNo: 3,
+ pageTotal: 3,
+ geom,
+ })
+ expect(inside.style.getPropertyValue('--hf-tab-over')).toBe('')
+ })
+
it('tab advances to the next stop past the current position, not by tab index', () => {
// lead is wide enough to pass the first (center) stop: the single tab must
// land on the right stop (Word), not on stops[0]
diff --git a/apps/docs/tests/hf-table-cell-paras.test.ts b/apps/docs/tests/hf-table-cell-paras.test.ts
index 11e3bc6..7ee7590 100644
--- a/apps/docs/tests/hf-table-cell-paras.test.ts
+++ b/apps/docs/tests/hf-table-cell-paras.test.ts
@@ -1,14 +1,17 @@
import { describe, expect, it } from 'vitest'
import type { HeaderFooter, HfImage, HfTextBox, SectionSettings } from '@genoffice/docx-engine'
import {
- HF_WASHOUT_FILTER,
+ hfCellParaStyle,
hfFloatPagePos,
hfHasVisibleContent,
hfStripGeom,
hfTextBoxStyle,
+ hfWashoutFilter,
makeGapHfEl,
makeHfFloatImgEl,
} from '../src/renderer/editor/hf-dom'
+
+const WASHOUT_PRESET = { gain: 0.3, blackLevel: 0.35 }
import { estimateHfHeight, hfHeaderGeom } from '../src/renderer/line-metrics'
import { effectiveTopPx } from '../src/renderer/pagination'
@@ -60,6 +63,34 @@ describe('header table cells keep per-paragraph lines', () => {
expect(oneLine).toBeGreaterThan(0)
expect(twoLines).toBeGreaterThan(oneLine * 1.5)
})
+
+ it('cell paragraph line spacing (style chain or direct) sizes the row and the cell line box', () => {
+ const rowOf = (lineSpacing: number) =>
+ estimateHfHeight(
+ {
+ text: '',
+ paras: [
+ {
+ runs: [],
+ cells: [
+ {
+ paras: [[{ text: 'Faculty name' }]],
+ paraProps: [{ lineRule: 'auto', lineRawTwips: lineSpacing * 240, lineSpacing }],
+ },
+ ],
+ },
+ ],
+ },
+ 600,
+ )
+ const single = rowOf(1)
+ const double = rowOf(2)
+ expect(double).toBeGreaterThan(single * 1.8)
+ expect(
+ hfCellParaStyle({ lineRule: 'auto', lineRawTwips: 240, lineSpacing: 1 }).lineHeight,
+ ).toBe('calc(var(--doc-line-factor,1.2) * 1)')
+ expect(hfCellParaStyle({ align: 'right' }).lineHeight).toBeUndefined()
+ })
})
describe('floating header image positioning', () => {
@@ -127,6 +158,20 @@ describe('floating header image positioning', () => {
expect(hfFloatPagePos(img, box)).toEqual({ x: 106, y: 34, translateX: 0, translateY: 0 })
})
+ it('footer paragraph-relative offsets measure from the footer strip top', () => {
+ const img: HfImage = {
+ dataUrl: 'data:,',
+ posXPx: 570,
+ posYPx: 52,
+ posHRel: 'margin',
+ posVRel: 'paragraph',
+ wrap: 'none',
+ }
+ // strip top = pageH - footerDist - reserved strip height
+ const pos = hfFloatPagePos(img, { ...box, paraOriginY: 1056 - 48 - 88 })
+ expect(pos).toEqual({ x: 666, y: 972, translateX: 0, translateY: 0 })
+ })
+
it('alignment fields reproduce the legacy margin-box anchors', () => {
expect(hfFloatPagePos({ dataUrl: 'data:,' }, box)).toEqual({
x: 96,
@@ -152,27 +197,50 @@ describe('floating header image positioning', () => {
widthPx: 816,
heightPx: 1056,
behind: true,
- washout: true,
+ washout: WASHOUT_PRESET,
}
const el = makeHfFloatImgEl(img, box, 'gap')
expect(el.className).toBe('page-hf-float-img')
expect(el.style.left).toBe('0px')
expect(el.style.top).toBe('calc(100% - 96px)')
expect(el.style.width).toBe('816px')
- expect(el.style.filter).toBe(HF_WASHOUT_FILTER)
+ expect(el.style.filter).toBe(hfWashoutFilter(WASHOUT_PRESET))
})
- it('washout filter fades toward white and keeps white pixels white (Word preset out = 0.3*in + 0.7)', () => {
- const steps = [...HF_WASHOUT_FILTER.matchAll(/(invert|brightness)\(([\d.]+)\)/g)]
- expect(steps).toHaveLength(3)
+ it('washout filter matches Word: black to 0.805, white from 1 - blacklevel up (preset out = 0.805 + 0.3*in)', () => {
+ const steps = [...hfWashoutFilter(WASHOUT_PRESET).matchAll(/(invert|brightness)\(([\d.]+)\)/g)]
+ expect(steps).toHaveLength(4)
const apply = (v: number) =>
steps.reduce((c, [, fn, amt]) => {
const a = Number(amt)
return fn === 'invert' ? c * (1 - a) + (1 - c) * a : Math.min(1, c * a)
}, v)
- expect(apply(1)).toBeCloseTo(1, 5)
- expect(apply(0)).toBeCloseTo(0.7, 5)
- expect(apply(0.5)).toBeCloseTo(0.85, 5)
+ expect(apply(1)).toBeCloseTo(1, 3)
+ expect(apply(0.65)).toBeCloseTo(1, 3)
+ expect(apply(0)).toBeCloseTo(0.805, 3)
+ expect(apply(0.3)).toBeCloseTo(0.895, 3)
+ })
+
+ it('rotated WordArt float renders inline SVG text stretched to the box, rotated about its center', () => {
+ const img: HfImage = {
+ dataUrl: '',
+ widthPx: 400,
+ heightPx: 200,
+ floating: true,
+ behind: true,
+ posH: 'center',
+ posV: 'center',
+ posHRel: 'margin',
+ posVRel: 'margin',
+ rotationDeg: 315,
+ wordArt: { text: 'DRAFT', colorHex: 'C0C0C0', opacity: 0.5, fontFamily: 'Calibri' },
+ }
+ const el = makeHfFloatImgEl(img, box, 'lead')
+ expect(el.style.transform).toBe('translate(-50%, -50%) rotate(315deg)')
+ expect(el.style.width).toBe('400px')
+ expect(el.style.zIndex).toBe('')
+ // jsdom has no canvas text metrics: the SVG stays empty instead of guessing glyph bounds
+ expect(el.querySelector('img')).toBeNull()
})
it('lead-hosted element positions from the first page content origin', () => {
diff --git a/apps/docs/tests/html-export.test.ts b/apps/docs/tests/html-export.test.ts
index b8ccb84..b4d0e2a 100644
--- a/apps/docs/tests/html-export.test.ts
+++ b/apps/docs/tests/html-export.test.ts
@@ -45,6 +45,16 @@ describe('buildStandaloneHtml', () => {
expect(out).toMatch(/^/)
})
+ it('exports tab leaders as a border, not the on-screen glyph run', () => {
+ const root = mount(
+ 'Intro\t 5
',
+ )
+ const out = buildStandaloneHtml(root, { title: 'T' })
+ expect(out).toMatch(/\t<\/span>5/)
+ expect(out).not.toMatch(/\.{3}/)
+ })
+
it('escapes text and restores lifted screen-only classes', () => {
const wrap = document.createElement('div')
wrap.className = 'workspace page-dark'
diff --git a/apps/docs/tests/image-drop.test.ts b/apps/docs/tests/image-drop.test.ts
new file mode 100644
index 0000000..5d93aaf
--- /dev/null
+++ b/apps/docs/tests/image-drop.test.ts
@@ -0,0 +1,138 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { Editor } from '@tiptap/core'
+import { editorExtensions } from '../src/renderer/editor/extensions'
+import {
+ droppedImageMime,
+ imageFilesFromDataTransfer,
+ insertImageFilesAt,
+ isImageFileDrag,
+ nearestTextSelection,
+} from '../src/renderer/editor/image-drop'
+
+const PNG_BYTES = Uint8Array.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0])
+
+function fakeTransfer(files: File[]): DataTransfer {
+ return {
+ files,
+ items: files.map((f) => ({ kind: 'file', type: f.type })),
+ } as unknown as DataTransfer
+}
+
+/** paragraph, TOC-like atom, paragraph */
+function openDoc(): Editor {
+ return new Editor({
+ element: document.createElement('div'),
+ extensions: editorExtensions,
+ content: {
+ type: 'doc',
+ content: [
+ { type: 'docParagraph', content: [{ type: 'text', text: 'Hello' }] },
+ { type: 'docProtected', attrs: { blockType: 'toc', label: 'TOC' } },
+ { type: 'docParagraph', content: [{ type: 'text', text: 'World' }] },
+ ],
+ },
+ })
+}
+
+describe('image file drops', () => {
+ it('accepts only the picture formats the insert dialog accepts', () => {
+ const png = new File([PNG_BYTES], 'a.png', { type: 'image/png' })
+ const jpg = new File([PNG_BYTES], 'b.jpg', { type: 'image/jpeg' })
+ const webp = new File([PNG_BYTES], 'c.webp', { type: 'image/webp' })
+ const pdf = new File([PNG_BYTES], 'd.pdf', { type: 'application/pdf' })
+ const untyped = new File([PNG_BYTES], 'e.GIF', { type: '' })
+ const untypedText = new File([PNG_BYTES], 'f.txt', { type: '' })
+ expect(
+ imageFilesFromDataTransfer(fakeTransfer([png, jpg, webp, pdf, untyped, untypedText])),
+ ).toEqual([png, jpg, untyped])
+ expect(droppedImageMime(untyped)).toBe('image/gif')
+ expect(imageFilesFromDataTransfer(null)).toEqual([])
+ })
+
+ it('recognises an image file drag from the item types alone', () => {
+ const dt = {
+ items: [{ kind: 'file', type: 'image/png' }],
+ files: [],
+ } as unknown as DataTransfer
+ expect(isImageFileDrag(dt)).toBe(true)
+ expect(
+ isImageFileDrag(fakeTransfer([new File([], 'x.pdf', { type: 'application/pdf' })])),
+ ).toBe(false)
+ expect(
+ isImageFileDrag({
+ items: [{ kind: 'string', type: 'image/png' }],
+ } as unknown as DataTransfer),
+ ).toBe(false)
+ })
+
+ it('resolves a drop inside a read-only block to the nearest text position', () => {
+ const editor = openDoc()
+ const doc = editor.state.doc
+ const tocPos = doc.child(0).nodeSize
+ const sel = nearestTextSelection(doc, tocPos + 1)
+ expect(sel).not.toBeNull()
+ expect(sel!.$from.parent.type.name).toBe('docParagraph')
+ expect(nearestTextSelection(doc, 99999)?.$from.parent.textContent).toBe('World')
+ editor.destroy()
+ })
+
+ describe('insertion', () => {
+ class FakeImage {
+ onload: (() => void) | null = null
+ onerror: (() => void) | null = null
+ naturalWidth = 120
+ naturalHeight = 60
+ set src(_v: string) {
+ queueMicrotask(() => this.onload?.())
+ }
+ }
+ let savedImage: typeof Image
+ beforeEach(() => {
+ savedImage = globalThis.Image
+ globalThis.Image = FakeImage as unknown as typeof Image
+ })
+ afterEach(() => {
+ globalThis.Image = savedImage
+ })
+
+ it('inserts pictures at the drop point and leaves the caret after them', async () => {
+ const editor = openDoc()
+ const files = [
+ new File([PNG_BYTES], 'one.png', { type: 'image/png' }),
+ new File([PNG_BYTES], 'two.png', { type: 'image/png' }),
+ ]
+ const inserted = await insertImageFilesAt(editor, files, 3)
+ expect(inserted).toBe(2)
+ const names = editor.state.doc.content.content.map((n) =>
+ n.type.name === 'docProtected' ? `${n.type.name}:${n.attrs.blockType}` : n.type.name,
+ )
+ expect(names).toEqual([
+ 'docParagraph',
+ 'docProtected:image',
+ 'docProtected:image',
+ 'docParagraph',
+ 'docProtected:toc',
+ 'docParagraph',
+ ])
+ const image = editor.state.doc.child(1)
+ expect(image.attrs.imageDataUrl).toMatch(/^data:image\/png;base64,/)
+ expect(image.attrs.imageWidthPx).toBe(120)
+ expect(image.attrs.label).toContain('one.png')
+ expect(editor.state.doc.child(0).textContent).toBe('He')
+ expect(editor.state.selection.$from.parent.textContent).toBe('llo')
+ editor.destroy()
+ })
+
+ it('skips files whose type is not a supported picture', async () => {
+ const editor = openDoc()
+ const inserted = await insertImageFilesAt(
+ editor,
+ [new File([PNG_BYTES], 'x.webp', { type: 'image/webp' })],
+ 1,
+ )
+ expect(inserted).toBe(0)
+ expect(editor.state.doc.childCount).toBe(3)
+ editor.destroy()
+ })
+ })
+})
diff --git a/apps/docs/tests/image-page-relative.test.ts b/apps/docs/tests/image-page-relative.test.ts
new file mode 100644
index 0000000..89c3636
--- /dev/null
+++ b/apps/docs/tests/image-page-relative.test.ts
@@ -0,0 +1,109 @@
+/**
+ * Anchored pictures whose wp:positionV is page/margin-relative: the posOffset
+ * is a position on the landing page (Word), not a distance below the anchor
+ * paragraph. Overlays (wrapNone/behind) render in content-area coordinates
+ * and hand the page re-pin to the pagination; CSS-floated side wraps start at
+ * their anchor line and let the engine shift them down.
+ */
+import { Editor } from '@tiptap/core'
+import { parseDocx } from '@genoffice/docx-engine'
+import { describe, expect, it } from 'vitest'
+import { buildDocx } from '../../../packages/docx-engine/tests/helpers/build-docx'
+import { blocksToPmDoc } from '../src/renderer/editor/convert'
+import { editorExtensions } from '../src/renderer/editor/extensions'
+
+const PIC =
+ '' +
+ ' ' +
+ ' '
+
+const anchor = (relV: string, wrap: string, behind: string) =>
+ '' +
+ `` +
+ ' ' +
+ '0 ' +
+ `1417320 ` +
+ ' ' +
+ wrap +
+ ' ' +
+ PIC +
+ ' '
+
+const SQUARE = ' '
+const TEXT = 'Purpose: the picture floats beside this paragraph. '
+
+async function open(bodyXml: string) {
+ const parsed = await parseDocx(await buildDocx({ bodyXml, withImage: true }))
+ return new Editor({
+ element: document.createElement('div'),
+ extensions: editorExtensions,
+ content: blocksToPmDoc(parsed.blocks) as never,
+ })
+}
+
+describe('run-level anchors (paragraph with text)', () => {
+ it('renders a page-relative behind-text logo in content-area coordinates and marks it for re-pin', async () => {
+ const editor = await open(`${anchor('page', ' ', '1')}${TEXT} `)
+ const img = editor.view.dom.querySelector('img.doc-inline-img--behind')!
+ const style = img.getAttribute('style')!
+ // 1417320 EMU = 148.8px from the page top; the page margin comes off in CSS
+ expect(style).toContain('translate(0.0px, calc(148.8px - var(--doc-margin-top,0px)))')
+ expect(img.dataset.pageRelV).toBe('1')
+ expect(img.dataset.pageRelFrom).toBe('page')
+ editor.destroy()
+ })
+
+ it('margin-relative offsets already are content-area coordinates', async () => {
+ const editor = await open(`${anchor('margin', ' ', '0')}${TEXT} `)
+ const img = editor.view.dom.querySelector('img.doc-inline-img')!
+ expect(img.getAttribute('style')).toContain('translate(0.0px, 148.8px)')
+ expect(img.dataset.pageRelV).toBe('1')
+ expect(img.dataset.pageRelFrom).toBeUndefined()
+ editor.destroy()
+ })
+
+ it('paragraph-relative overlays keep the plain offset and no re-pin marker', async () => {
+ const editor = await open(`${anchor('paragraph', ' ', '0')}${TEXT} `)
+ const img = editor.view.dom.querySelector('img.doc-inline-img')!
+ expect(img.getAttribute('style')).toContain('translate(0.0px, 148.8px)')
+ expect(img.dataset.pageRelV).toBeUndefined()
+ editor.destroy()
+ })
+
+ it('a page-relative side wrap starts at its anchor line instead of a page offset below it', async () => {
+ const editor = await open(`${anchor('page', SQUARE, '0')}${TEXT} `)
+ const img = editor.view.dom.querySelector('img.doc-inline-img--wrap-square-left')!
+ expect(parseFloat(img.style.marginTop || '0')).toBe(0)
+ expect(img.getAttribute('style')).not.toContain('shape-outside')
+ editor.destroy()
+ })
+})
+
+describe('block-level anchors (picture-only paragraph)', () => {
+ it('page-relative overlay: content-area top plus the re-pin markers on the wrap', async () => {
+ const editor = await open(`${anchor('page', ' ', '1')} `)
+ const wrap = editor.view.dom.querySelector('.img-wrap-behind .doc-img-wrap')!
+ expect(wrap.style.top).toBe('calc(148.8px - var(--doc-margin-top,0px))')
+ expect(wrap.dataset.pageRelV).toBe('1')
+ expect(wrap.dataset.pageRelFrom).toBe('page')
+ editor.destroy()
+ })
+
+ it('page-relative side wrap hands the vertical target to the pagination engine', async () => {
+ const editor = await open(`${anchor('page', SQUARE, '0')} `)
+ const block = editor.view.dom.querySelector('.doc-protected.img-wrap-square-left')!
+ expect(block.dataset.tblpVy).toBe('148.8')
+ expect(block.dataset.tblpVanchor).toBe('page')
+ expect(block.getAttribute('style')).toMatch(/margin: var\(--tblp-dy,0px\)/)
+ expect(block.getAttribute('style')).toContain('shape-outside: inset(var(--tblp-dy,0px) 0 0 0)')
+ editor.destroy()
+ })
+
+ it('paragraph-relative side wrap keeps the offset as a flow margin', async () => {
+ const editor = await open(`${anchor('paragraph', SQUARE, '0')} `)
+ const block = editor.view.dom.querySelector('.doc-protected.img-wrap-square-left')!
+ expect(block.dataset.tblpVy).toBeUndefined()
+ expect(block.style.marginTop).toBe('148.8px')
+ editor.destroy()
+ })
+})
diff --git a/apps/docs/tests/image-rotation.test.ts b/apps/docs/tests/image-rotation.test.ts
index 08ffe1f..baa9e8b 100644
--- a/apps/docs/tests/image-rotation.test.ts
+++ b/apps/docs/tests/image-rotation.test.ts
@@ -86,6 +86,8 @@ describe('rotated pictures', () => {
expect(img.style.marginBottom).toBe('50px')
expect(img.style.marginLeft).toBe('-50px')
expect(img.style.marginRight).toBe('-50px')
+ // the column clamp must meet the turned bounding box, not the extent
+ expect(img.style.maxWidth).toBe('none')
editor.destroy()
})
@@ -191,6 +193,7 @@ describe('rotated pictures', () => {
)!
expect(img.style.transform).toBe('rotate(90deg)')
expect(img.style.margin).toBe('50px -50px')
+ expect(img.style.maxWidth).toBe('none')
editor.destroy()
})
})
diff --git a/apps/docs/tests/invisible-chars-save.test.ts b/apps/docs/tests/invisible-chars-save.test.ts
index 3605850..5118a24 100644
--- a/apps/docs/tests/invisible-chars-save.test.ts
+++ b/apps/docs/tests/invisible-chars-save.test.ts
@@ -68,7 +68,7 @@ describe('invisible characters survive saving', () => {
const plan = pmDocToSavePlan(editor.getJSON() as PmNode, parsed.blocks)
expect(plan.changedCount).toBe(1)
const xml = await documentXml(await saveDocx(parsed, plan.saveBlocks))
- expect(xml).toContain(`${FIELD_TEXT}!`)
+ expect(xml).toMatch(new RegExp(`${FIELD_TEXT}! `))
expect(xml).toContain('ZOTERO_ITEM')
editor.destroy()
host.remove()
diff --git a/apps/docs/tests/justify-shrink.test.ts b/apps/docs/tests/justify-shrink.test.ts
index d02c2d2..08e4555 100644
--- a/apps/docs/tests/justify-shrink.test.ts
+++ b/apps/docs/tests/justify-shrink.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest'
import {
decideLineShrinks,
+ sameLine,
type ShrinkGap,
type ShrinkLine,
} from '../src/renderer/editor/justify-shrink'
@@ -83,6 +84,24 @@ describe('decideLineShrinks — Word compat15 pull rule', () => {
expect(decideLineShrinks([l])[0]).toBeNull()
})
+ it('pulls a word that overflows by a single LayoutUnit (Word fits it by twip rounding)', () => {
+ // Cyrillic Times 14pt line whose natural width equals the column to the twip:
+ // Chromium wraps the last word by ~1/64px, Word keeps it
+ const [pull] = decideLineShrinks([line(10, 1 / 64, 40)])
+ expect(pull).not.toBeNull()
+ expect(pull!.perChar).toBeCloseTo((1 / 64 + 0.5) / 10, 4)
+ })
+
+ it('keeps the pull when the joined line overflows by a single LayoutUnit', () => {
+ const l = line(10, 1 / 64, 40)
+ l.wordWidths = [...l.wordWidths, 40]
+ l.gaps = [...l.gaps, l.boundary!]
+ l.boundary = null
+ l.nextWordWidth = null
+ const [keep] = decideLineShrinks([l])
+ expect(keep).not.toBeNull()
+ })
+
it('leaves naturally fitting lines alone', () => {
const l = line(10, -2, 13.21)
expect(decideLineShrinks([l])[0]).toBeNull()
@@ -99,3 +118,35 @@ describe('decideLineShrinks — Word compat15 pull rule', () => {
expect(decideLineShrinks([l])[0]).toBeNull()
})
})
+
+describe('sameLine — rendered-line grouping of word boxes', () => {
+ // glyph boxes are ascent+descent tall regardless of line-height, so under
+ // tight leading consecutive lines overlap by a few px; chaining them into one
+ // "line" makes decideLineShrinks compress the whole paragraph (word-spacing
+ // of minus hundreds of px, words overprinting in a narrow column)
+ const box = (top: number, height: number) => ({ top, bottom: top + height, left: 0, right: 10 })
+
+ it('keeps consecutive lines apart under w:line=204 auto (Arial 9pt: 14px box, 11.7px pitch)', () => {
+ const l1 = box(100, 14)
+ const l2 = box(100 + 11.73, 14)
+ expect(sameLine(l1, l2)).toBe(false)
+ })
+
+ it('keeps consecutive lines apart at a 1.0 face factor (Helvetica 11pt: 16px box, 14.67px pitch)', () => {
+ expect(sameLine(box(50, 16), box(50 + 14.67, 16))).toBe(false)
+ })
+
+ it('joins words on one baseline with different font sizes and a superscript', () => {
+ const big = { top: 100, bottom: 100 + 29, left: 0, right: 10 } // 22pt
+ const small = { top: 100 + 29 - 4 - 13, bottom: 100 + 29 - 4, left: 0, right: 10 } // 9pt, shared baseline
+ const sup = { top: 100 + 29 - 4 - 13 - 5, bottom: 100 + 29 - 4 - 5, left: 0, right: 10 } // raised 5px
+ expect(sameLine(big, small)).toBe(true)
+ expect(sameLine(small, big)).toBe(true)
+ expect(sameLine(small, sup)).toBe(true)
+ })
+
+ it('still separates lines that merely touch', () => {
+ expect(sameLine(box(0, 14), box(14, 14))).toBe(false)
+ expect(sameLine(box(0, 14), box(13.5, 14))).toBe(false)
+ })
+})
diff --git a/apps/docs/tests/line-metrics.test.ts b/apps/docs/tests/line-metrics.test.ts
index 8db9b79..0732a89 100644
--- a/apps/docs/tests/line-metrics.test.ts
+++ b/apps/docs/tests/line-metrics.test.ts
@@ -119,6 +119,21 @@ describe('HeuristicMetrics', () => {
// ─── computeLineHeight ─────────────────────────────────────────────────────
+describe('lineHeightFactor', () => {
+ it('Comic Sans MS uses its own hhea total (Word renders the macOS face)', () => {
+ expect(lineHeightFactor('Comic Sans MS')).toBe(1.3936)
+ expect(lineHeightFactor('comic sans ms bold')).toBe(1.3936)
+ })
+ it('symbol faces take the metrics of the copies Word ships, not the unknown fallback', () => {
+ expect(lineHeightFactor('Symbol')).toBe(1.2251)
+ expect(lineHeightFactor('Wingdings')).toBe(1.1099)
+ expect(lineHeightFactor('Wingdings 2')).toBe(1.0542)
+ expect(lineHeightFactor('Wingdings 3')).toBe(1.1387)
+ expect(lineHeightFactor('Webdings')).toBe(1.0)
+ expect(lineHeightFactor('Segoe UI Symbol')).toBe(1.15)
+ })
+})
+
describe('computeLineHeight', () => {
const naturalH = 20 // px, assume the font's natural line height is 20px
@@ -194,8 +209,9 @@ describe('computeLineHeight', () => {
it('docGrid lines mode: exact keeps its value; atLeast floors at the snapped single', () => {
const docGrid = { type: 'lines' as const, linePitch: 312 }
expect(computeLineHeight(20, 'exact', 260, docGrid)).toBeCloseTo(260 * (96 / 1440), 2)
- // atLeast 0 degrades to single spacing on the grid
- expect(computeLineHeight(20, 'atLeast', 0, docGrid)).toBeCloseTo(20.8, 2)
+ // atLeast 0 is natural height off the grid (Word probe 2026-09-11: Meiryo UI
+ // 10pt on a 350-twip grid lays 16.56pt, not the 17.5pt cell)
+ expect(computeLineHeight(20, 'atLeast', 0, docGrid)).toBeCloseTo(20, 2)
// face value above the snapped single stays un-snapped (probe atleast500-sz21: 25pt)
expect(computeLineHeight(20, 'atLeast', 480, docGrid)).toBeCloseTo(480 * (96 / 1440), 2)
// snapped single floor applies when the font outgrows the cell (probe atleast500-sz28)
@@ -544,6 +560,10 @@ describe('cssLineHeight', () => {
)
})
+ it('atLeast line="0" → natural height, never the grid single', () => {
+ expect(cssLineHeight('atLeast', 0, undefined)).toBe('calc(var(--doc-line-factor,1.2) * 1em)')
+ })
+
it('no line spacing settings at all → null (inherit)', () => {
expect(cssLineHeight(undefined, undefined, undefined)).toBeNull()
})
@@ -617,9 +637,8 @@ describe('cssFontFamily', () => {
})
it('monospace families map to a mono chain (Menlo first on macOS)', () => {
- expect(cssFontFamily('Consolas')).toBe(
- "'Consolas','Menlo','Courier New','Liberation Mono','Noto Sans CJK SC',monospace",
- )
+ // Consolas is Office-only: the size-adjusted alias stands in behind a real local copy
+ expect(cssFontFamily('Consolas')).toBe("'Consolas','Consolas GO','Noto Sans CJK SC',monospace")
expect(cssFontFamily('Courier New')).toBe(
"'Courier New','Menlo','Liberation Mono','Noto Sans CJK SC',monospace",
)
@@ -866,6 +885,26 @@ describe('document fontTable substitution hints', () => {
expect(cjkDeclaredLineFactor('다솜글꼴')).toBe(1.3029)
})
+ it('missing Noto Sans KR with a sans PANOSE takes the Malgun class (Word probe 2026-09-11)', () => {
+ setDocFontTable([{ name: 'Noto Sans KR', panose: '020B0200000000000000' }])
+ const css = cssFontFamily('Noto Sans KR')
+ expect(css).toContain("'GenOffice Sans KR'")
+ expect(css).not.toContain("'GenOffice Batang'")
+ expect(css).not.toContain("'KR Theme Latin GO'")
+ expect(css.endsWith('sans-serif')).toBe(true)
+ expect(lineHeightFactor('Noto Sans KR')).toBe(1.7371)
+ expect(cjkDeclaredLineFactor('Noto Sans KR')).toBe(1.7371)
+ expect(krLineFactor('Noto Sans KR')).toBe(1.7371)
+ })
+
+ it('Noto Sans KR without a fontTable sans hint stays Batang-ward (Word probe 2026-08-13)', () => {
+ setDocFontTable([{ name: 'Noto Sans KR', panose: '00000000000000000000' }])
+ expect(cssFontFamily('Noto Sans KR')).toContain("'GenOffice Batang'")
+ expect(lineHeightFactor('Noto Sans KR')).toBe(1.3029)
+ setDocFontTable(null)
+ expect(cjkDeclaredLineFactor('Noto Sans KR')).toBe(1.3029)
+ })
+
it('Noto Sans CJK KR keeps its probed Batang-class behavior despite an altName', () => {
setDocFontTable([
{ name: 'Noto Sans CJK KR', altName: 'Cambria', panose: '00000000000000000000' },
@@ -897,6 +936,23 @@ describe('document fontTable substitution hints', () => {
})
})
+describe('Segoe UI (M365 cloud face)', () => {
+ it('text cuts take the cloud hhea factor and the size-adjusted Helvetica alias', () => {
+ for (const name of ['Segoe UI', 'Segoe UI Semibold', 'Segoe UI Light']) {
+ expect(lineHeightFactor(name)).toBe(1.3301)
+ expect(cssFontFamily(name)).toBe(
+ `'${name}','Segoe UI GO','Noto Sans CJK GO','GenOffice PUA Blank',sans-serif`,
+ )
+ }
+ })
+ it('symbol/emoji/script cuts keep the old branch', () => {
+ for (const name of ['Segoe UI Emoji', 'Segoe UI Symbol', 'Segoe Print', 'Segoe Script']) {
+ expect(lineHeightFactor(name)).toBe(1.15)
+ expect(cssFontFamily(name)).not.toContain("'Segoe UI GO'")
+ }
+ })
+})
+
describe('Aptos (M365 cloud face)', () => {
afterEach(() => setDocFontTable(null))
@@ -1079,7 +1135,7 @@ describe('Korean line metrics', () => {
it('mono ascii face keeps its mono faces, CJK falls through to the eastAsia font', () => {
expect(cssDualFontFamily('Consolas', 'SimSun')).toBe(
- "'Consolas','Menlo','Courier New','Liberation Mono','SimSun','GenOffice Songti SC','STSong','Noto Serif CJK SC',serif",
+ "'Consolas','Consolas GO','SimSun','GenOffice Songti SC','STSong','Noto Serif CJK SC',serif",
)
})
@@ -1256,7 +1312,6 @@ describe('cssFontFamily Arabic', () => {
)
expect(cssFontFamily('Traditional Arabic')).not.toContain("'Naskh Digits GO'")
expect(cssFontFamily('Noto Naskh Arabic')).not.toContain("'Naskh Digits GO'")
- expect(cssFontFamily('Noto Kufi Arabic')).not.toContain("'Naskh Digits GO'")
})
it('Traditional/Simplified Arabic map to the size-adjusted alias (no Times head)', () => {
@@ -1264,20 +1319,40 @@ describe('cssFontFamily Arabic', () => {
"'Traditional Arabic','Noto Naskh Arabic TA','Geeza Pro','Al Bayan',serif",
)
expect(cssFontFamily('Traditional Arabic')).not.toContain("'Times New Roman'")
- expect(cssFontFamily('Simplified Arabic')).toContain("'Noto Naskh Arabic TA'")
- // other missing naskh-class names take the TNR calibration, not TA
- expect(cssFontFamily('Amiri')).not.toContain("'Noto Naskh Arabic TA'")
- expect(cssFontFamily('Arabic Typesetting')).not.toContain("'Noto Naskh Arabic TA'")
+ // Simplified Arabic is a different cut (0.924 vs 0.800 of the Noto subset,
+ // shaped over the cloud files 2026-09-11) and gets its own alias
+ expect(cssFontFamily('Simplified Arabic')).toBe(
+ "'Simplified Arabic','Noto Naskh Arabic SA','Geeza Pro','Al Bayan',serif",
+ )
+ // other missing naskh-class names take the TNR calibration, not TA/SA
+ expect(cssFontFamily('Amiri')).not.toMatch(/Noto Naskh Arabic (TA|SA)/)
+ expect(cssFontFamily('Arabic Typesetting')).not.toMatch(/Noto Naskh Arabic (TA|SA)/)
// M365 cloud fonts Word downloads and renders with real metrics (probe 2026-08-22)
expect(lineHeightFactor('Simplified Arabic')).toBe(1.66)
expect(lineHeightFactor('Traditional Arabic')).toBe(1.5)
})
- it('kufi/sans-class names get the Sans Arabic chain (no Times head)', () => {
- expect(cssFontFamily('Noto Sans Arabic')).toBe("'Noto Sans Arabic W','Geeza Pro',sans-serif")
+ it('missing kufi/sans-class names substitute to Times like every missing Arabic name', () => {
+ // Word probe 2026-09-11: a report whose list items declare Noto Kufi Arabic
+ // rendered them in TimesNewRomanPSMT, same as its Noto Naskh body
expect(cssFontFamily('Noto Kufi Arabic')).toBe(
- "'Noto Kufi Arabic','Noto Sans Arabic','Geeza Pro',sans-serif",
+ "'Noto Kufi Arabic','Times New Roman','Liberation Serif','Naskh Digits GO','Noto Naskh Arabic TNR','Geeza Pro','Al Bayan',serif",
)
+ expect(cssFontFamily('Noto Sans Arabic')).toBe(
+ "'Noto Naskh Arabic W','Geeza Pro','Al Bayan',serif",
+ )
+ })
+
+ it('an installed kufi/sans face keeps the Sans Arabic chain (no Times head)', () => {
+ // a name no earlier case probed (availability is memoized per name)
+ stubCanvas(['Noto Sans Arabic UI'])
+ try {
+ expect(cssFontFamily('Noto Sans Arabic UI')).toBe(
+ "'Noto Sans Arabic UI','Noto Sans Arabic','Geeza Pro',sans-serif",
+ )
+ } finally {
+ vi.restoreAllMocks()
+ }
})
it('unknown Arabic names (by script in the name) default to the naskh chain', () => {
diff --git a/apps/docs/tests/line-numbers.test.ts b/apps/docs/tests/line-numbers.test.ts
new file mode 100644
index 0000000..4304def
--- /dev/null
+++ b/apps/docs/tests/line-numbers.test.ts
@@ -0,0 +1,95 @@
+// @vitest-environment jsdom
+import { describe, expect, it } from 'vitest'
+import type { LineNumbering, SectionInfo } from '@genoffice/docx-engine'
+import {
+ columnAt,
+ columnLefts,
+ groupLineRects,
+ numberLines,
+} from '../src/renderer/editor/line-numbers'
+
+const line = (page: number, top: number, section = 0, col = 0) => ({ page, col, top, section })
+
+describe('numberLines', () => {
+ it('counts every line in reading order and labels multiples of countBy', () => {
+ const ln: LineNumbering = { countBy: 2, start: 1, restart: 'continuous' }
+ const out = numberLines(
+ [line(0, 40), line(0, 20), line(1, 0), line(0, 0, 0, 1), line(0, 60)],
+ () => ln,
+ )
+ expect(out.map((o) => [o.line.page, o.line.col, o.line.top, o.label])).toEqual([
+ [0, 0, 40, '2'],
+ [0, 1, 0, '4'],
+ ])
+ })
+
+ it('restarts per page or per section from w:start; continuous never restarts', () => {
+ const lines = [line(0, 0, 0), line(0, 10, 0), line(1, 0, 0), line(1, 10, 1), line(2, 0, 1)]
+ const labels = (restart: LineNumbering['restart']) =>
+ numberLines(lines, () => ({ countBy: 1, start: 5, restart })).map((o) => o.label)
+ expect(labels('continuous')).toEqual(['5', '6', '7', '8', '9'])
+ expect(labels('newPage')).toEqual(['5', '6', '5', '6', '5'])
+ expect(labels('newSection')).toEqual(['5', '6', '7', '5', '6'])
+ })
+
+ it('skips lines of sections without numbering without breaking the count', () => {
+ const lines = [line(0, 0, 0), line(0, 10, 1), line(0, 20, 0)]
+ const out = numberLines(lines, (s) =>
+ s === 0 ? { countBy: 1, start: 1, restart: 'continuous' } : undefined,
+ )
+ expect(out.map((o) => [o.line.top, o.label])).toEqual([
+ [0, '1'],
+ [20, '2'],
+ ])
+ })
+})
+
+describe('groupLineRects', () => {
+ it('merges fragments sharing a line box and keeps distinct lines apart', () => {
+ const lines = groupLineRects([
+ { top: 20, bottom: 40, left: 100, right: 160 },
+ { top: 0, bottom: 20, left: 10, right: 50 },
+ { top: 1, bottom: 19, left: 50, right: 90 },
+ { top: 0, bottom: 0, left: 0, right: 0 },
+ ])
+ expect(lines).toEqual([
+ { top: 0, bottom: 20, left: 10, right: 90 },
+ { top: 20, bottom: 40, left: 100, right: 160 },
+ ])
+ })
+})
+
+describe('columnLefts', () => {
+ const section = (sectPrXml: string): SectionInfo =>
+ ({
+ settings: {
+ pageWidth: 12240,
+ marginLeft: 1440,
+ marginRight: 1440,
+ columns: 2,
+ colSpace: 720,
+ },
+ sectPrXml,
+ }) as unknown as SectionInfo
+
+ it('lists reading-order column lefts; a w:bidi section fills from the right', () => {
+ expect(columnLefts(section(' '))).toEqual([0, 336])
+ expect(columnLefts(section(' '))).toEqual([336, 0])
+ const unequal =
+ ' '
+ expect(columnLefts(section(`${unequal} `))).toEqual([0, 248])
+ expect(columnLefts(section(`${unequal} `))).toEqual([424, 0])
+ })
+})
+
+describe('columnAt', () => {
+ it('picks the column under x for plain and mirrored (w:bidi) lefts', () => {
+ expect([columnAt([0, 336], -5), columnAt([0, 336], 10), columnAt([0, 336], 340)]).toEqual([
+ 0, 0, 1,
+ ])
+ expect([columnAt([336, 0], -5), columnAt([336, 0], 10), columnAt([336, 0], 340)]).toEqual([
+ 1, 1, 0,
+ ])
+ expect(columnAt([0], 500)).toBe(0)
+ })
+})
diff --git a/apps/docs/tests/native-table.test.ts b/apps/docs/tests/native-table.test.ts
index 1d67540..87a15a5 100644
--- a/apps/docs/tests/native-table.test.ts
+++ b/apps/docs/tests/native-table.test.ts
@@ -22,6 +22,7 @@ import {
} from '../src/renderer/editor/convert'
import { editorExtensions, rowHeightCss, tableRowEatCss } from '../src/renderer/editor/extensions'
import { renderTableSpec } from '../src/renderer/editor/protected-render'
+import { collectRevisions, type TrackChangesStorage } from '../src/renderer/editor/revisions'
import {
constrainSelectedTableWidth,
constrainTableWidthAtCell,
@@ -63,43 +64,6 @@ async function openTable(): Promise<{
return { editor, parsed, source }
}
-function openEmptyTable(): Editor {
- return new Editor({
- element: document.createElement('div'),
- extensions: editorExtensions,
- content: {
- type: 'doc',
- content: [
- {
- type: 'docTable',
- content: [
- {
- type: 'docTableRow',
- content: [{ type: 'docTableCell', content: [{ type: 'docParagraph' }] }],
- },
- ],
- },
- ],
- } as never,
- })
-}
-
-function selectFirstCellStart(editor: Editor): void {
- const firstCell = cellPositions(editor)[0]
- editor.view.dispatch(
- editor.state.tr.setSelection(TextSelection.create(editor.state.doc, firstCell + 2)),
- )
-}
-
-function tableHasLeafContent(editor: Editor): boolean {
- let hasLeaf = false
- editor.state.doc.firstChild?.descendants((node) => {
- if (node.isLeaf) hasLeaf = true
- return !hasLeaf
- })
- return hasLeaf
-}
-
function selectLastCellTextEnd(editor: Editor): void {
let lastCellTextEnd = 0
editor.state.doc.descendants((node, pos) => {
@@ -128,63 +92,6 @@ function clickBelowTrailingTable(editor: Editor): void {
}
describe('native editable tables', () => {
- it('deletes a completely empty table with Backspace and Delete', () => {
- for (const key of ['Backspace', 'Delete']) {
- const editor = openEmptyTable()
- selectFirstCellStart(editor)
-
- expect(tableHasLeafContent(editor)).toBe(false)
- pressKey(editor, key)
-
- expect(editor.state.doc.firstChild?.type.name).not.toBe('docTable')
- editor.destroy()
- }
- })
-
- it('keeps a non-empty table when the current cell is empty', async () => {
- const { editor } = await openTable()
- const firstCell = cellPositions(editor)[0]
- const transaction = editor.state.tr.delete(firstCell + 2, firstCell + 3)
- editor.view.dispatch(
- transaction.setSelection(TextSelection.create(transaction.doc, firstCell + 2)),
- )
-
- pressKey(editor, 'Backspace')
-
- expect(editor.state.doc.firstChild?.type.name).toBe('docTable')
- expect(editor.state.doc.textContent).toContain('B')
- editor.destroy()
- })
-
- it('keeps a table with a non-text leaf even when its text is empty', () => {
- const editor = openEmptyTable()
- selectFirstCellStart(editor)
- editor.view.dispatch(
- editor.state.tr.replaceSelectionWith(editor.schema.nodes.hardBreak.create()),
- )
-
- expect(editor.state.doc.textContent).toBe('')
- expect(tableHasLeafContent(editor)).toBe(true)
- pressKey(editor, 'Backspace')
-
- expect(editor.state.doc.firstChild?.type.name).toBe('docTable')
- editor.destroy()
- })
-
- it('restores an empty table when undoing its deletion', () => {
- const editor = openEmptyTable()
- selectFirstCellStart(editor)
-
- pressKey(editor, 'Backspace')
- expect(editor.state.doc.firstChild?.type.name).not.toBe('docTable')
-
- expect(editor.commands.undo()).toBe(true)
-
- expect(editor.state.doc.firstChild?.type.name).toBe('docTable')
- expect(tableHasLeafContent(editor)).toBe(false)
- editor.destroy()
- })
-
it('allows typing after an imported trailing table', async () => {
const { editor } = await openTable()
selectLastCellTextEnd(editor)
@@ -236,6 +143,19 @@ describe('native editable tables', () => {
editor.destroy()
})
+ it('exiting a trailing table under track changes records no revision', async () => {
+ const { editor } = await openTable()
+ const storage = editor.storage.trackChanges as TrackChangesStorage
+ storage.enabled = true
+ storage.author = 'Tester'
+
+ clickBelowTrailingTable(editor)
+
+ expect(editor.state.doc.lastChild?.type.name).toBe('docParagraph')
+ expect(collectRevisions(editor.state.doc)).toHaveLength(0)
+ editor.destroy()
+ })
+
it('undoing a trailing-table exit does not recreate its paragraph', async () => {
const { editor } = await openTable()
selectLastCellTextEnd(editor)
@@ -281,8 +201,16 @@ describe('native editable tables', () => {
csFont: null,
charSpacingTwips: null,
charScaleEm: null,
+ charScaleX: null,
highlight: null,
shading: null,
+ shadingDisplay: null,
+ textOutline: null,
+ textEffect: null,
+ dstrike: null,
+ glow: null,
+ positionHalfPoints: null,
+ bdr: null,
vertAlign: null,
em: null,
boldOff: null,
diff --git a/apps/docs/tests/note-format.test.ts b/apps/docs/tests/note-format.test.ts
index 527643d..1642a60 100644
--- a/apps/docs/tests/note-format.test.ts
+++ b/apps/docs/tests/note-format.test.ts
@@ -1,6 +1,11 @@
import { describe, expect, it } from 'vitest'
import { Editor } from '@tiptap/core'
-import { noteMarkText, toRoman } from '../src/renderer/note-format'
+import {
+ formatNoteNumber,
+ noteMarkText,
+ setNoteNumFmts,
+ toRoman,
+} from '../src/renderer/note-format'
import { editorExtensions } from '../src/renderer/editor/extensions'
describe('note numbering', () => {
@@ -37,4 +42,36 @@ describe('note numbering', () => {
expect(sups.map((s) => s.textContent)).toEqual(['2', 'ii'])
editor.destroy()
})
+
+ it('w:numFmt overrides the per-kind default (decimal endnotes, roman footnotes, chicago marks)', () => {
+ expect(formatNoteNumber(undefined, 4)).toBe('4')
+ expect(formatNoteNumber('upperRoman', 4)).toBe('IV')
+ expect(formatNoteNumber('lowerLetter', 27)).toBe('aa')
+ expect(formatNoteNumber('upperLetter', 2)).toBe('B')
+ expect(formatNoteNumber('chicago', 5)).toBe('**')
+ expect(formatNoteNumber('decimalEnclosedCircle', 3)).toBe('3')
+ setNoteNumFmts({ endnote: { numFmt: 'decimal' }, footnote: { numFmt: 'lowerRoman' } })
+ try {
+ expect(noteMarkText('endnote', 1)).toBe('1')
+ expect(noteMarkText('footnote', 2)).toBe('ii')
+ const editor = new Editor({
+ element: document.createElement('div'),
+ extensions: editorExtensions,
+ content: {
+ type: 'doc',
+ content: [
+ {
+ type: 'docParagraph',
+ content: [{ type: 'docNoteRef', attrs: { kind: 'endnote', id: 'e1', num: 3 } }],
+ },
+ ],
+ } as never,
+ })
+ expect(editor.view.dom.querySelector('sup[data-note-ref]')?.textContent).toBe('3')
+ editor.destroy()
+ } finally {
+ setNoteNumFmts({})
+ }
+ expect(noteMarkText('endnote', 1)).toBe('i')
+ })
})
diff --git a/apps/docs/tests/numbering.test.ts b/apps/docs/tests/numbering.test.ts
index 6f9fdfb..1d4a29a 100644
--- a/apps/docs/tests/numbering.test.ts
+++ b/apps/docs/tests/numbering.test.ts
@@ -187,6 +187,56 @@ describe('computeListMarkers', () => {
editor.destroy()
})
+ it('decorates picture-bullet items with the image instead of the placeholder glyph', async () => {
+ const numberingXml =
+ '\r\n' +
+ '' +
+ ' ' +
+ '' +
+ ' ' +
+ ' ' +
+ ' ' +
+ ' ' +
+ ' ' +
+ ' '
+ const li = (ilvl: number, text: string) =>
+ `${text} `
+ const source = await buildDocx({
+ bodyXml: li(0, 'picture') + li(1, 'unresolved') + li(2, 'spaced'),
+ numberingXml,
+ extraParts: [
+ {
+ path: 'word/_rels/numbering.xml.rels',
+ xml:
+ '' +
+ ' ' +
+ ' ',
+ contentType: 'application/vnd.openxmlformats-package.relationships+xml',
+ },
+ ],
+ withImage: true,
+ })
+ const parsed = await parseDocx(source)
+ const editor = new Editor({
+ element: document.createElement('div'),
+ extensions: editorExtensions,
+ })
+ editor.storage.listNumbering.defs = parsed.numbering
+ editor.commands.setContent(blocksToPmDoc(parsed.blocks) as never)
+ const items = Array.from(editor.view.dom.querySelectorAll('.doc-li'))
+ expect(items.map((el) => el.getAttribute('data-marker'))).toEqual(['', '\u2022', ''])
+ expect(items[0].hasAttribute('data-marker-pic')).toBe(true)
+ expect(items[0].style.getPropertyValue('--li-marker-pic')).toMatch(
+ /^url\("data:image\/png;base64,/,
+ )
+ expect(items[1].hasAttribute('data-marker-pic')).toBe(false)
+ // w:suff space on a picture level: the flags the margin-gap CSS rule keys on
+ expect(items[2].hasAttribute('data-marker-pic')).toBe(true)
+ expect(items[2].getAttribute('data-suff')).toBe('space')
+ editor.destroy()
+ })
+
it('counts a numbered textbox anchor paragraph in the sequence and marks its stray line', async () => {
const numberingXml =
'\r\n' +
@@ -234,6 +284,7 @@ describe('computeListMarkers', () => {
)
const marker = /\[data-stray-marker\] \.doc-li-stray::before \{([^}]*)\}/.exec(css)!
expect(marker[1]).toContain('line-height: var(--li-marker-lh, inherit)')
+ expect(marker[1]).toContain('color: var(--li-marker-color, inherit)')
expect(css).toMatch(
/\[data-stray-marker\]\[data-marker-clip\] \.doc-li-stray::before \{\s*visibility: hidden;/,
)
@@ -241,7 +292,28 @@ describe('computeListMarkers', () => {
/\[data-stray-marker\]\[data-suff\] \.doc-li-stray::before \{\s*min-width: 0;/,
)
expect(css).toMatch(
- /\[data-stray-marker\]\[data-suff='space'\] \.doc-li-stray::before \{\s*content: var\(--li-marker\) '\\00a0';/,
+ /\[data-stray-marker\]\[data-suff='space'\]:not\(\[data-marker-pic\]\) \.doc-li-stray::before \{\s*content: var\(--li-marker\) '\\00a0';/,
+ )
+ })
+
+ it('picture bullets keep logical geometry and beat the space-suffix text rule', () => {
+ const css = readFileSync(
+ join(dirname(fileURLToPath(import.meta.url)), '../src/renderer/styles.css'),
+ 'utf8',
+ )
+ const picRules = [
+ /\.doc-page \.doc-li\[data-marker-pic\]::before,\n[^{]*\{([^}]*)\}/,
+ /\.doc-page \.doc-li\[data-marker-pic\]::before \{([^}]*)\}/,
+ /\.doc-textbox-para\[data-marker-pic\]::before \{([^}]*)\}/,
+ ].map((re) => re.exec(css)![1])
+ // RTL lists mirror through margin-inline-end; no physical side anywhere
+ expect(picRules[1]).toContain('margin-inline-end: max(')
+ expect(picRules[2]).toContain('margin-inline-end: max(')
+ for (const body of picRules) expect(body).not.toMatch(/\bleft\b|\bright\b/)
+ // the nbsp content rules step aside for picture levels, whose gap is a margin
+ expect(css).toMatch(/\[data-suff='space'\]\[data-marker\]:not\(\[data-marker-pic\]\)::before/)
+ expect(css).toMatch(
+ /\.doc-li\[data-suff='space'\]\[data-marker-pic\]::before,\n[^{]*\{\s*margin-inline-end: 0\.25em;/,
)
})
@@ -304,19 +376,19 @@ describe('computeListMarkers', () => {
[
{ numId: '1', ilvl: 0 }, // Wingdings 'l' = ●
{ numId: '2', ilvl: 0 }, // Wingdings PUA F0A7 = ▪
- { numId: '3', ilvl: 0 }, // Webdings has no mapping table → default
- { numId: '4', ilvl: 0 }, // glyph not in the Wingdings table → default
+ { numId: '3', ilvl: 0 }, // Webdings decodes by its own table
+ { numId: '4', ilvl: 0 }, // 0x7F is a hole in every Wingdings table → default
{ numId: '5', ilvl: 0 }, // PUA without a font → legacy font-agnostic mapping
],
defs(
mk('1', 'l', 'Wingdings'),
mk('2', '', 'Wingdings'),
mk('3', '', 'Webdings'),
- mk('4', 'e', 'Wingdings'),
+ mk('4', '\uF07F', 'Wingdings'),
mk('5', ''),
),
)
- expect(markers).toEqual(['●', '▪', '•', '•', '•'])
+ expect(markers).toEqual(['●', '▪', '🚍', '•', '•'])
})
it('bullet infos carry the original glyph (U+F0xx form) and the declared symbol font', () => {
@@ -336,14 +408,14 @@ describe('computeListMarkers', () => {
defs(
mk('1', '\uF0B7', 'Symbol'),
mk('2', 'l', 'Wingdings'), // raw byte normalized to U+F0xx
- mk('3', '\uF0C1', 'Symbol'), // undecodable → default text, glyph still kept
+ mk('3', '\uF07F', 'Symbol'), // undecodable → default text, glyph still kept
mk('4', '\uF0B7'), // no symbol font → plain substitute
def({ numId: '5', levels: DECIMAL_3LVL.levels }),
),
)
expect(infos[0]).toEqual({ text: '•', symbolChar: '\uF0B7', symbolFont: 'Symbol' })
expect(infos[1]).toEqual({ text: '●', symbolChar: '\uF06C', symbolFont: 'Wingdings' })
- expect(infos[2]).toEqual({ text: '•', symbolChar: '\uF0C1', symbolFont: 'Symbol' })
+ expect(infos[2]).toEqual({ text: '•', symbolChar: '\uF07F', symbolFont: 'Symbol' })
expect(infos[3]).toEqual({ text: '•' })
expect(infos[4]).toEqual({ text: '1.' })
})
@@ -621,4 +693,117 @@ describe('list marker decorations', () => {
expect(measuredFonts[0]).toBe('16px "Times New Roman", Calibri, sans-serif')
destroy()
})
+
+ it('a level with left="0" firstLine="0" puts the marker at the margin and tabs to the next default stop', async () => {
+ const { el, destroy } = await renderLi(
+ ' ' +
+ ' ',
+ )
+ expect(el.getAttribute('data-marker')).toBe('Article I.')
+ const style = el.getAttribute('style') ?? ''
+ // 10 chars * 8px = 1200 twips from 0 -> stop 1440
+ expect(style).toContain('--li-left: 0pt')
+ expect(style).toContain('--li-hang: 0pt')
+ expect(style).toContain('--li-tab: 72pt')
+ destroy()
+ })
+
+ it('the marker tab lands on the paragraph custom tab stop, not the default grid', async () => {
+ const lvl =
+ ' ' +
+ ' '
+ const item = (pPr: string) =>
+ ` ${pPr} ` +
+ 'item '
+ const parsed = await parseDocx(
+ await buildDocx({
+ bodyXml:
+ item(
+ ' ',
+ ) +
+ item(
+ ' ',
+ ) +
+ item(' '),
+ numberingXml: numberingXml(lvl),
+ }),
+ )
+ const editor = new Editor({
+ element: document.createElement('div'),
+ extensions: editorExtensions,
+ })
+ editor.storage.listNumbering.defs = parsed.numbering
+ editor.commands.setContent(blocksToPmDoc(parsed.blocks) as never)
+ const styles = Array.from(editor.view.dom.querySelectorAll('.doc-li')).map(
+ (el) => el.getAttribute('style') ?? '',
+ )
+ // marker at 720 ends 960: the 4320 stop, not 1440
+ expect(styles[0]).toContain('--li-tab: 180pt')
+ // marker at 360 ends 600: the 1080 stop replaces the cleared 720 default
+ expect(styles[1]).toContain('--li-tab: 36pt')
+ // level hanging fits the marker: text at the hanging edge, no tab box
+ expect(styles[2]).not.toContain('--li-tab')
+ editor.destroy()
+ })
+
+ it('a level with only left="0" has no hanging area: marker at the margin, tab to the next stop', async () => {
+ const { el, destroy } = await renderLi(
+ ' ' +
+ ' ',
+ )
+ const style = el.getAttribute('style') ?? ''
+ expect(style).toContain('--li-left: 0pt')
+ expect(style).toContain('--li-hang: 0pt')
+ // 2 chars * 8px = 240 twips -> stop 720
+ expect(style).toContain('--li-tab: 36pt')
+ destroy()
+ })
+
+ it('a right-aligned marker without a hanging area still tabs to the next stop', async () => {
+ const { el, destroy } = await renderLi(
+ ' ' +
+ ' ',
+ )
+ const style = el.getAttribute('style') ?? ''
+ // marker ends at 720 (box 480..720), text at the 1440 stop: box 960 twips
+ expect(style).toContain('--li-hang: 12pt')
+ expect(style).toContain('--li-tab: 48pt')
+ destroy()
+ })
+
+ it('lvlJc right hangs the marker so its end sits at the marker position', async () => {
+ const { el, destroy } = await renderLi(
+ ' ' +
+ ' ',
+ )
+ expect(el.getAttribute('data-marker')).toBe('1.1.1')
+ const style = el.getAttribute('style') ?? ''
+ // 5 chars * 8px = 600 twips: hang 180 + 600
+ expect(style).toContain('--li-hang: 39pt')
+ expect(style).not.toContain('--li-tab')
+ destroy()
+ })
+
+ it('the level rPr color and a text-font bullet reach the marker as custom properties', async () => {
+ const colored = await renderLi(
+ ' ' +
+ ' ',
+ )
+ expect(colored.el.getAttribute('data-marker')).toBe('First.')
+ const style = colored.el.getAttribute('style') ?? ''
+ expect(style).toContain('--li-marker-color: #FFC000')
+ expect(style).toContain('--dk-li-mc:')
+ expect(style).toContain('--li-marker-size: 26pt')
+ expect(style).toContain('--li-marker-lh: calc(')
+ colored.destroy()
+
+ const bullet = await renderLi(
+ ' ' +
+ ' ',
+ )
+ expect(bullet.el.getAttribute('data-marker')).toBe('o')
+ expect(bullet.el.getAttribute('style')).toContain('--li-marker-font: "Courier New"')
+ expect(bullet.el.getAttribute('style')).toContain('--li-marker-lh: 0')
+ bullet.destroy()
+ })
})
diff --git a/apps/docs/tests/page-note-areas.test.ts b/apps/docs/tests/page-note-areas.test.ts
index ba82216..7f0e151 100644
--- a/apps/docs/tests/page-note-areas.test.ts
+++ b/apps/docs/tests/page-note-areas.test.ts
@@ -165,6 +165,23 @@ describe('endnotesAnchorY — flow-end anchor for the endnote area', () => {
})
})
+describe('note areas: engine numbering', () => {
+ it('markers follow the supplied numbers (body order / numStart) instead of list position', () => {
+ const { container, unmount } = render(
+ createElement(PageFootnotes, {
+ notes: [note('a', 'first'), note('b', 'second')],
+ skipIds: new Set(),
+ numberOf: (n) => (n.id === 'a' ? 6 : 5),
+ onEdit: () => {},
+ onDelete: () => {},
+ }),
+ )
+ const sups = Array.from(container.querySelectorAll('.page-note sup'), (s) => s.textContent)
+ expect(sups).toEqual(['6', '5'])
+ unmount()
+ })
+})
+
describe('note-area CSS contract (document data, not chrome)', () => {
const css = readFileSync(join(__dirname, '../src/renderer/styles.css'), 'utf8')
const ruleOf = (selector: string): string => {
diff --git a/apps/docs/tests/pagepinned-preview.test.ts b/apps/docs/tests/pagepinned-preview.test.ts
index bc46f8c..518241e 100644
--- a/apps/docs/tests/pagepinned-preview.test.ts
+++ b/apps/docs/tests/pagepinned-preview.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import { pinnedFloatPage, type PageSlice } from '../src/renderer/pagination'
-import { pinnedCloneCss } from '../src/renderer/components/PaginationPreview'
+import { hoistSlotOf, pinnedCloneCss } from '../src/renderer/components/PaginationPreview'
const slice = (start: number, end: number): PageSlice => ({ start, end, section: 0 })
@@ -83,3 +83,24 @@ describe('pinnedCloneCss', () => {
expect(hidden(p0, '.doc-anchor-strut')).toEqual([false, false])
})
})
+
+describe('hoistSlotOf', () => {
+ const box = (style: string) => {
+ const el = document.createElement('span')
+ el.setAttribute('style', style)
+ return { el }
+ }
+
+ it('classifies the inline horizontal slot of a floating box', () => {
+ expect(hoistSlotOf(box('position:absolute;left:12.5px;top:3px'))).toBe('left')
+ expect(hoistSlotOf(box('position:absolute;left:-4px;top:0px'))).toBe('left')
+ // a centred cover logo (left:50% + translateX(-50%)) used to be skipped and
+ // spilled past the page window, repainting on the next page's top
+ expect(
+ hoistSlotOf(box('position: absolute; left: 50%; top: 5.8px; transform: translateX(-50%);')),
+ ).toBe('center')
+ expect(hoistSlotOf(box('position:absolute;right:0;top:2px'))).toBe('right')
+ expect(hoistSlotOf(box('position:absolute;right:0px;top:2px'))).toBe('right')
+ expect(hoistSlotOf(box('position:absolute;right:20px;top:2px'))).toBeNull()
+ })
+})
diff --git a/apps/docs/tests/pagination-gaps.test.ts b/apps/docs/tests/pagination-gaps.test.ts
index 8756325..35c4fd1 100644
--- a/apps/docs/tests/pagination-gaps.test.ts
+++ b/apps/docs/tests/pagination-gaps.test.ts
@@ -4,10 +4,15 @@ import {
alignGapHfStrips,
alignTableGapFills,
makeGapEl,
+ pageFramesFromGaps,
syncCutOverlays,
+ syncPageSheets,
syncPhantomRowspans,
clampCellBoxTops,
+ pageBorderArtStripStyle,
pageBorderStyleOf,
+ rowFillAttrs,
+ syncPageBorders,
} from '../src/renderer/editor/pagination-gaps'
import { createLineRectsCache, singleCutCell } from '../src/renderer/pagination'
@@ -286,6 +291,87 @@ describe('alignTableGapFills', () => {
expect(fill.style.left).toBe('-32px')
expect(fill.style.width).toBe('816px')
})
+
+ it('differing-width documents: the fill covers the table’s own centered page, not the paper', () => {
+ // portrait page (816) centered on a landscape paper (1056): gap carries the page box
+ const pm = document.createElement('div')
+ pm.getBoundingClientRect = () => ({ left: 0, width: 1056 }) as DOMRect
+ const gap = makeGapEl({ ...m, pageLeft: 120, pageWidth: 816 }, 'table', 2)
+ const cell = gap.firstElementChild as HTMLElement
+ cell.getBoundingClientRect = () => ({ left: 120 + 96, width: 624 }) as DOMRect
+ pm.appendChild(gap)
+ const fill = cell.firstElementChild as HTMLElement
+ alignTableGapFills(pm, 1)
+ expect(fill.style.left).toBe('-96px')
+ expect(fill.style.width).toBe('816px')
+ })
+})
+
+describe('page frames and sheets (differing-width documents, genoffice#246)', () => {
+ const rect = (top: number, height: number, left = 0, width = 1056) =>
+ ({ top, height, left, width, bottom: top + height, right: left + width }) as DOMRect
+ /** wrap holding a paper and two gaps: page 0 (portrait) → page 1 (landscape) → page 2 (portrait) */
+ const wrapEl = () => {
+ const wrap = document.createElement('div')
+ wrap.getBoundingClientRect = () => rect(0, 3000)
+ const paper = document.createElement('div')
+ paper.className = 'doc-page'
+ paper.getBoundingClientRect = () => rect(0, 3000, 0, 1056)
+ wrap.appendChild(paper)
+ const g1 = makeGapEl({ ...m, pageLeft: 0, pageWidth: 1056 }, 'block')
+ g1.getBoundingClientRect = () => rect(1000, 96 + GAP_BAND + 96)
+ const g2 = makeGapEl({ ...m, pageLeft: 120, pageWidth: 816 }, 'block')
+ g2.getBoundingClientRect = () => rect(2000, 96 + GAP_BAND + 96)
+ paper.append(g1, g2)
+ return wrap
+ }
+
+ it('derives each page’s box from the first page and the gaps’ next-page geometry', () => {
+ const frames = pageFramesFromGaps(wrapEl(), 1, { left: 120, width: 816 })
+ expect(frames).toHaveLength(3)
+ expect(frames[0]).toEqual({ top: 0, bottom: 1096, left: 120, width: 816 })
+ expect(frames[1]).toEqual({
+ top: 1000 + 96 + GAP_BAND + 96 - 96,
+ bottom: 2096,
+ left: 0,
+ width: 1056,
+ })
+ expect(frames[2]).toEqual({ top: 2000 + 96 + GAP_BAND, bottom: 3000, left: 120, width: 816 })
+ })
+
+ it('a boundary without page geometry (cut marker) keeps the page above it', () => {
+ const wrap = wrapEl()
+ const cut = makeGapEl(m, 'cut')
+ cut.getBoundingClientRect = () => rect(1500, 0)
+ wrap.firstElementChild!.appendChild(cut)
+ const frames = pageFramesFromGaps(wrap, 1, { left: 120, width: 816 })
+ expect(frames.map((f) => f.left)).toEqual([120, 0, 0, 120])
+ })
+
+ it('without a first frame the whole paper is the page', () => {
+ const wrap = document.createElement('div')
+ wrap.getBoundingClientRect = () => rect(0, 1056)
+ const paper = document.createElement('div')
+ paper.className = 'doc-page'
+ paper.getBoundingClientRect = () => rect(0, 1056, 0, 816)
+ wrap.appendChild(paper)
+ expect(pageFramesFromGaps(wrap, 1)).toEqual([{ top: 0, bottom: 1056, left: 0, width: 816 }])
+ })
+
+ it('paints one sheet per page and clears the layer when the paper is uniform again', () => {
+ const wrap = wrapEl()
+ syncPageSheets(wrap, 1, { left: 120, width: 816 })
+ const sheets = Array.from(wrap.querySelectorAll('.page-sheets > .page-sheet'))
+ expect(sheets.map((s) => [s.style.left, s.style.width])).toEqual([
+ ['120px', '816px'],
+ ['0px', '1056px'],
+ ['120px', '816px'],
+ ])
+ expect(sheets[0].style.top).toBe('0px')
+ expect(sheets[0].style.height).toBe('1096px')
+ syncPageSheets(wrap, 1, null)
+ expect(wrap.querySelector('.page-sheets')).toBeNull()
+ })
})
describe('alignGapHfStrips', () => {
@@ -327,6 +413,27 @@ describe('alignGapHfStrips', () => {
expect(strip.getBoundingClientRect().left).toBeCloseTo(96, 1)
})
+ it('re-anchors footnote areas and floating images from their gap’s origin (data-paper-x)', () => {
+ // block gap starting 20px right of the paper edge (next section's narrower margin)
+ const pm = pmEl()
+ const gap = makeGapEl(
+ { marginTop: 96, marginBottom: 96, marginLeft: 76, marginRight: 96 },
+ 'block',
+ )
+ gap.getBoundingClientRect = () => ({ left: 20, width: 796 }) as DOMRect
+ pm.appendChild(gap)
+ const notes = document.createElement('div')
+ notes.className = 'page-gap-notes'
+ notes.dataset.paperX = '216.0'
+ notes.style.left = '216px'
+ Object.defineProperty(notes, 'offsetParent', { get: () => gap })
+ gap.appendChild(notes)
+ alignGapHfStrips(pm, 96, 1)
+ expect(notes.style.left).toBe('196px')
+ alignGapHfStrips(pm, 96, 1)
+ expect(notes.style.left).toBe('196px')
+ })
+
// A full-bleed cover section (w:pgMar left="0") ahead of body sections with real
// margins: the canvas pads by the cover, so the body pages' strips must follow
// their own section inset (--gap-ml), not the canvas target
@@ -487,7 +594,7 @@ describe('pageBorderStyleOf', () => {
expect(style!.sides.bottom).toBeUndefined()
})
- it('maps compound thin/thick lines to CSS double and art lines to solid', () => {
+ it('maps compound thin/thick lines to CSS double; an unflagged art val stays a solid line', () => {
const style = pageBorderStyleOf({
...margins,
pageBorder: true,
@@ -505,6 +612,129 @@ describe('pageBorderStyleOf', () => {
expect(style!.sides.bottom!.css).toBe('3px solid #000000')
})
+ describe('art borders', () => {
+ const artSide = (val: string, color?: string) => ({
+ val,
+ widthPt: 16,
+ spacePt: 24,
+ art: true as const,
+ ...(color ? { color } : {}),
+ })
+ const styleOf = (
+ sides: NonNullable[0]['pageBorderProps']>['sides'],
+ ) =>
+ pageBorderStyleOf({
+ ...margins,
+ pageBorder: true,
+ pageBorderProps: { offsetFrom: 'page', spacePt: 24, widthPt: 16, sides },
+ })!
+
+ it('stitch family: a 16pt-tall zigzag strip in the bitmap grey, tiled along the side', () => {
+ const side = styleOf({ bottom: artSide('zigZagStitch') }).sides.bottom!
+ expect(side.css).toBeUndefined()
+ expect(side.insetPx).toBe(32)
+ expect(side.art!.sizePx).toBe(21)
+ expect(side.art!.backgroundRepeat).toBe('repeat-x')
+ expect(side.art!.backgroundSize).toBe('21px 21px')
+ const svg = decodeURIComponent(side.art!.backgroundImage)
+ expect(svg).toContain(' {
+ const gems = styleOf({ left: artSide('gems') }).sides.left!
+ expect(gems.art!.backgroundRepeat).toBe('repeat-y')
+ const svg = decodeURIComponent(gems.art!.backgroundImage)
+ expect(svg).toContain(' {
+ const sides = styleOf({
+ top: artSide('handmade2'),
+ right: artSide('whiteFlowers'),
+ bottom: artSide('basicBlackDashes'),
+ left: artSide('weavingAngles'),
+ }).sides
+ expect(sides.top).toEqual({ css: '11px double #000000', insetPx: 32 })
+ expect(sides.right).toEqual({ css: '3px solid #000000', insetPx: 32 })
+ expect(sides.bottom).toEqual({ css: '21px dashed #000000', insetPx: 32 })
+ expect(sides.left).toEqual({ css: '11px double #000000', insetPx: 32 })
+ })
+
+ it('an explicit w:color recolours the pattern and drops the bitmap ink', () => {
+ const side = styleOf({ top: artSide('gems', 'FF0000') }).sides.top!
+ const svg = decodeURIComponent(side.art!.backgroundImage)
+ expect(svg).toContain('fill="#FF0000"')
+ expect(svg).not.toContain('stroke=')
+ expect(styleOf({ top: artSide('handmade1', '1F497D') }).sides.top!.css).toBe(
+ '11px double #1F497D',
+ )
+ })
+
+ it('syncPageBorders draws the strip inside the box and keeps back borders out of the editor root', () => {
+ const wrap = document.createElement('div')
+ wrap.className = 'page-wrap'
+ const paper = document.createElement('div')
+ paper.className = 'doc-page'
+ wrap.appendChild(paper)
+ const rect = { top: 0, left: 0, width: 816, height: 1056, right: 816, bottom: 1056 }
+ wrap.getBoundingClientRect = () => ({ ...rect, x: 0, y: 0, toJSON: () => rect })
+ paper.getBoundingClientRect = wrap.getBoundingClientRect
+ const style = styleOf({
+ top: artSide('gems'),
+ left: { val: 'single', widthPt: 1, spacePt: 24 },
+ })
+ syncPageBorders(wrap, style, 1)
+ const box = wrap.querySelector('.page-border-overlays > .page-border-overlay') as HTMLElement
+ expect(box.style.borderLeft).toBe('1px solid rgb(0, 0, 0)')
+ expect(box.style.borderTop).toBe('')
+ const strip = box.querySelector('.page-border-art') as HTMLElement
+ expect(strip.style.height).toBe('21px')
+ expect(strip.style.backgroundRepeat).toBe('repeat-x')
+ syncPageBorders(wrap, { ...style, zOrder: 'back' }, 1)
+ const layer = wrap.querySelector('.page-border-overlays') as HTMLElement
+ expect(layer.parentElement).toBe(wrap)
+ expect(paper.querySelector('.page-border-overlays')).toBeNull()
+ expect(layer.classList.contains('page-border-overlays-back')).toBe(true)
+ syncPageBorders(wrap, style, 1)
+ expect(layer.classList.contains('page-border-overlays-back')).toBe(false)
+ expect(wrap.querySelectorAll('.page-border-overlays').length).toBe(1)
+ syncPageBorders(wrap, null, 1)
+ expect(wrap.querySelector('.page-border-overlays')).toBeNull()
+ })
+
+ it('zOrder=back carries through to the style', () => {
+ const style = pageBorderStyleOf({
+ ...margins,
+ pageBorder: true,
+ pageBorderProps: {
+ zOrder: 'back',
+ spacePt: 24,
+ widthPt: 16,
+ sides: { top: artSide('stars') },
+ },
+ })
+ expect(style!.zOrder).toBe('back')
+ expect(styleOf({ top: artSide('stars') }).zOrder).toBeUndefined()
+ })
+ })
+
it('offsetFrom=text measures the inset back from the margin edge', () => {
const style = pageBorderStyleOf({
...margins,
@@ -560,3 +790,11 @@ describe('pageBorderStyleOf', () => {
expect(style!.sides.bottom!.css).toBe('1px solid #000000')
})
})
+
+describe('rowFillAttrs', () => {
+ it('measures the stored split extra against the rounded CSS height', () => {
+ expect(rowFillAttrs(310.4, 10.4)).toEqual({ style: 'height:310px', 'data-split-extra': '10.0' })
+ expect(rowFillAttrs(309.6, 9.6)).toEqual({ style: 'height:310px', 'data-split-extra': '10.0' })
+ expect(rowFillAttrs(310.4)).toEqual({ style: 'height:310px' })
+ })
+})
diff --git a/apps/docs/tests/pagination.test.ts b/apps/docs/tests/pagination.test.ts
index 6d3204b..f0c8bc0 100644
--- a/apps/docs/tests/pagination.test.ts
+++ b/apps/docs/tests/pagination.test.ts
@@ -6,9 +6,19 @@ import {
assignSections,
cellCutYs,
columnLayoutSpecs,
+ columnLineSplits,
+ fillColWraps,
+ splitFloatStyle,
+ widthPassGate,
+ newWidthPassState,
+ resetWidthPassHistory,
vAlignShiftSpecs,
+ verticalTextSpecs,
sectionWidthSpecs,
+ paperWidthPx,
+ pageLeftPx,
sectionGridPitchSpecs,
+ sectionTopMarginSpecs,
docGridPitchPt,
sectionCharSpaceSpecs,
docCharSpacePt,
@@ -16,8 +26,12 @@ import {
computePageSlices,
computeSectionedSlices,
computeSectionedSlicesF2,
+ planRowSplit,
+ cellLinesOf,
+ rowSplitCss,
effectiveHfRefs,
hasPrintableHeaderFooter,
+ hfVariantOf,
insertParityBlanks,
lineBreakBoundaries,
lineStartAnchor,
@@ -38,10 +52,13 @@ import {
tableHeaderFlags,
tableRowFlags,
type BlockBox,
+ type ColWrapTable,
type PageSlice,
type SectionGeom,
type TableRowBox,
} from '../src/renderer/pagination'
+import { rowFillAttrs } from '../src/renderer/editor/pagination-gaps'
+import { verticalPageCss } from '../src/renderer/components/PaginationPreview'
const block = (top: number, height: number, extra?: Partial): BlockBox => ({
top,
@@ -662,6 +679,45 @@ describe('sectionWidthSpecs — differing-width sections wrap at their own conte
expect(specs[1].widthPx).toBeCloseTo(((11906 - 1701 - 1417) / 1440) * 96, 1)
})
+ it('pages narrower than the widest section are centered on the shared paper (genoffice#246)', () => {
+ // portrait pages in a document with a landscape section: the canvas paper is
+ // the landscape width, so every portrait block carries the centering offset
+ const landscape = sec({ pageWidth: 16838, pageHeight: 11906, orientation: 'landscape' })
+ const secsList = [sec({}), landscape, sec({})]
+ const paperW = (16838 / 1440) * 96
+ expect(paperWidthPx(secsList)).toBeCloseTo(paperW, 5)
+ const offset = ((16838 - 11906) / 1440 / 2) * 96
+ expect(pageLeftPx(secsList[0].settings, paperW)).toBeCloseTo(offset, 5)
+ expect(pageLeftPx(landscape.settings, paperW)).toBe(0)
+ const blocks = [
+ block(0, 100, { section: 0, el: el() }),
+ block(100, 100, { section: 1, el: el() }),
+ block(200, 100, { section: 2, el: el() }),
+ ]
+ const specs = sectionWidthSpecs(blocks, secsList, sectionGeoms(secsList))
+ expect(specs).toHaveLength(3)
+ expect(specs[0].pageDx).toBeCloseTo(offset, 1)
+ expect(specs[1].pageDx).toBe(0)
+ expect(specs[2].pageDx).toBeCloseTo(offset, 1)
+ // the column shift (dx) stays the margin difference: page-relative anchors undo it alone
+ expect(specs[0].dx).toBe(0)
+ expect(specs[1].dx).toBe(0)
+ })
+
+ it('a page-width-only difference (same margins and content width) still emits specs', () => {
+ // A4 vs. a 1in wider page whose extra width sits in the right margin only
+ const wide = sec({ pageWidth: 11906 + 1440, marginRight: 2880 })
+ const secsList = [sec({}), wide]
+ const blocks = [
+ block(0, 100, { section: 0, el: el() }),
+ block(100, 100, { section: 1, el: el() }),
+ ]
+ const specs = sectionWidthSpecs(blocks, secsList, sectionGeoms(secsList))
+ expect(specs).toHaveLength(2)
+ expect(specs[0].pageDx).toBeCloseTo(48, 1)
+ expect(specs[1].pageDx).toBe(0)
+ })
+
it('side-margin-only differences still get placement specs', () => {
// Mirrored margins keep the content width identical: nothing would be emitted
// on the width comparison alone, but the text column must move right.
@@ -680,6 +736,30 @@ describe('sectionWidthSpecs — differing-width sections wrap at their own conte
})
})
+describe('sectionTopMarginSpecs — per-section top margin for page-relative anchors', () => {
+ const el = () => document.createElement('p')
+
+ it('uniform top margins produce no specs (single .doc-page injection)', () => {
+ const secsList = [sec({ marginTop: 860 }), sec({ marginTop: 860 })]
+ expect(sectionTopMarginSpecs([block(0, 100, { section: 0, el: el() })], secsList)).toEqual([])
+ })
+
+ it('a final section with a different top margin: each block carries its own section top', () => {
+ // a letterhead section (pgMar top 860) closed by a continuous 1in section:
+ // the header logo pinned to the page top must subtract 860, not 1440
+ const secsList = [sec({ marginTop: 860 }), sec({ marginTop: 1440 })]
+ const blocks = [
+ block(0, 100, { section: 0, el: el() }),
+ block(100, 100, { section: 1, el: el() }),
+ ]
+ const specs = sectionTopMarginSpecs(blocks, secsList)
+ expect(specs).toHaveLength(2)
+ expect(specs[0].marginTopPx).toBeCloseTo((860 / 1440) * 96, 3)
+ expect(specs[1].marginTopPx).toBe(96)
+ expect(specs.every((sp) => sp.dx === 0 && sp.dy === 0)).toBe(true)
+ })
+})
+
describe('sectionGridPitchSpecs — per-section typed docGrid pitch', () => {
const gridSec = (linePitch?: number, type: 'lines' | 'linesAndChars' = 'lines') =>
sec(linePitch ? { docGrid: { type, linePitch } } : {})
@@ -905,6 +985,97 @@ describe('computeSectionedSlicesF2 — line-level pagination', () => {
780,
)
expect(kept.map((s) => [s.start, s.end, s.section])).toEqual([[0, 780, 0]])
+ // a later block of a section that already began on the host page opens a
+ // non-first page: the 600 default capacity takes the 480 block
+ const later = computeSectionedSlicesF2(
+ [
+ block(0, 300, { section: 0 }),
+ block(300, 60, { section: 1 }),
+ block(360, 480, { section: 1 }),
+ ],
+ geoms,
+ 840,
+ )
+ expect(later.map((s) => [s.start, s.end, s.section, s.continuedSection ?? false])).toEqual([
+ [0, 360, 0, false],
+ [360, 840, 1, true],
+ ])
+ })
+
+ describe('titlePg first page: the page a section starts on, only when it owns that page', () => {
+ const geoms: SectionGeom[] = [
+ { contentHeight: 400, forceBreak: false, startType: 'nextPage' },
+ { contentHeight: 400, firstContentHeight: 300, forceBreak: false, startType: 'continuous' },
+ ]
+ const shape = (slices: PageSlice[]) =>
+ slices.map((s) => [s.start, s.end, s.section, s.continuedSection ?? false])
+
+ it('nextPage section: its first page takes the first-page variant and capacity', () => {
+ const next: SectionGeom[] = [
+ geoms[0],
+ { ...geoms[1], forceBreak: true, startType: 'nextPage' },
+ ]
+ const blocks = [
+ block(0, 300, { section: 0 }),
+ block(300, 200, { section: 1 }),
+ block(500, 150, { section: 1 }), // 500..650 overflows the 300 first-page capacity
+ ]
+ const slices = computeSectionedSlicesF2(blocks, next, 650)
+ expect(shape(slices)).toEqual([
+ [0, 300, 0, false],
+ [300, 500, 1, false],
+ [500, 650, 1, false],
+ ])
+ expect(sectionFirstPages(slices)).toEqual([true, true, false])
+ expect(hfVariantOf(true, true, false, 2)).toBe('first')
+ })
+
+ it('continuous section starting mid-page: the host page keeps its section, later pages are not first pages', () => {
+ const blocks = [
+ block(0, 300, { section: 0 }),
+ block(300, 60, { section: 1 }),
+ block(360, 60, { section: 1 }), // crosses the host's 400 capacity
+ block(420, 280, { section: 1 }), // 360..700 fits the 400 default capacity, not the 300 first-page one
+ ]
+ const slices = computeSectionedSlicesF2(blocks, geoms, 700)
+ expect(shape(slices)).toEqual([
+ [0, 360, 0, false],
+ [360, 700, 1, true],
+ ])
+ const firsts = sectionFirstPages(slices)
+ expect(firsts).toEqual([true, false])
+ expect(hfVariantOf(true, firsts[1], false, 2)).toBe('default')
+ expect(hfVariantOf(true, firsts[1], true, 2)).toBe('even')
+ })
+
+ it('continuous section starting exactly at a page top: that page is its first page', () => {
+ const blocks = [
+ block(0, 400, { section: 0 }),
+ block(400, 200, { section: 1 }),
+ block(600, 150, { section: 1 }), // 600..750 overflows the 300 first-page capacity
+ ]
+ const slices = computeSectionedSlicesF2(blocks, geoms, 750)
+ expect(shape(slices)).toEqual([
+ [0, 400, 0, false],
+ [400, 600, 1, false],
+ [600, 750, 1, false],
+ ])
+ expect(sectionFirstPages(slices)).toEqual([true, true, false])
+ expect(hfVariantOf(true, true, true, 2)).toBe('first')
+ })
+
+ it('a page break right after a mid-page continuous break opens the section at a page top', () => {
+ const blocks = [
+ block(0, 300, { section: 0 }),
+ block(300, 200, { section: 1, breakBefore: true }),
+ ]
+ const slices = computeSectionedSlicesF2(blocks, geoms, 500)
+ expect(shape(slices)).toEqual([
+ [0, 300, 0, false],
+ [300, 500, 1, false],
+ ])
+ expect(sectionFirstPages(slices)).toEqual([true, true])
+ })
})
it("a page that begins with the previous section's float keeps that section", () => {
@@ -1083,6 +1254,63 @@ describe('computeSectionedSlicesF2 — line-level pagination', () => {
])
})
+ it('two leading w:br on one paragraph leave a blank sheet before it', () => {
+ const blocks = [
+ block(0, 100),
+ { ...block(100, 100), breakBefore: true, breakBeforeBr: true, extraBreaksBefore: 1 },
+ ]
+ const slices = computeSectionedSlicesF2(blocks, geoms1, 200)
+ expect(slices).toEqual([
+ { start: 0, end: 100, section: 0 },
+ { start: 100, end: 100, section: 0 },
+ { start: 100, end: 200, section: 0 },
+ ])
+ })
+
+ it('a trailing w:br on a keepNext block ends the chain: the next block starts the new page', () => {
+ const marker = block(0, 20, { keepNext: true, breakAfter: true })
+ const heading = block(20, 30, { keepNext: true })
+ const body = block(50, 100)
+ const slices = computeSectionedSlicesF2([marker, heading, body], geoms1, 150)
+ expect(slices).toEqual([
+ { start: 0, end: 20, section: 0 },
+ { start: 20, end: 150, section: 0 },
+ ])
+ })
+
+ it('a leading-break cut that snaps into the first line box turns the page before the block', () => {
+ const blocks = [
+ block(0, 100),
+ block(100, 60, {
+ innerBreaks: [10],
+ lineBoxes: [
+ { offsetInBlock: 0, height: 40 },
+ { offsetInBlock: 40, height: 20 },
+ ],
+ }),
+ ]
+ const slices = computeSectionedSlicesF2(blocks, geoms1, 160)
+ expect(slices).toEqual([
+ { start: 0, end: 100, section: 0 },
+ { start: 100, end: 160, section: 0 },
+ ])
+ })
+
+ it('two trailing w:br leave a blank sheet before the next block and two blank last pages', () => {
+ const blocks = [
+ { ...block(0, 100), breakAfter: true, extraBreaksAfter: 1 },
+ { ...block(100, 100), breakAfter: true, extraBreaksAfter: 1 },
+ ]
+ const slices = computeSectionedSlicesF2(blocks, geoms1, 200)
+ expect(slices).toEqual([
+ { start: 0, end: 100, section: 0 },
+ { start: 100, end: 100, section: 0 },
+ { start: 100, end: 200, section: 0 },
+ { start: 200, end: 200, section: 0 },
+ { start: 200, end: 200, section: 0 },
+ ])
+ })
+
it('a trailing w:br keeps its deliberate blank last page (tdf#99090)', () => {
const blocks = [{ ...block(0, 100), breakAfter: true }]
const slices = computeSectionedSlicesF2(blocks, geoms1, 100)
@@ -1134,6 +1362,32 @@ describe('computeSectionedSlicesF2 — line-level pagination', () => {
expect(slices[1].start).toBe(250) // 2+2 split; a whole push would start at 150
})
+ it('widowControl: an over-page paragraph whose first cut would orphan one line starts on the next page', () => {
+ // 150px used of 300; the paragraph (100 + 300 = 400px) exceeds a page, and
+ // only its first line fits here -> Word moves the start down, then cuts
+ const beforeBlock = lineBlock(0, [50, 50, 50])
+ const mainBlock = lineBlock(150, [100, 300], { widowControl: true })
+ const geoms = [{ contentHeight: 300, forceBreak: false }]
+ const slices = computeSectionedSlicesF2([beforeBlock, mainBlock], geoms, 550)
+ expect(slices.map((s) => s.start)).toEqual([0, 150, 250])
+ })
+
+ it('widowControl: an over-page paragraph keeps its start when two lines fit before the cut', () => {
+ const beforeBlock = lineBlock(0, [50, 50, 50])
+ const mainBlock = lineBlock(150, [50, 50, 300], { widowControl: true })
+ const geoms = [{ contentHeight: 300, forceBreak: false }]
+ const slices = computeSectionedSlicesF2([beforeBlock, mainBlock], geoms, 550)
+ expect(slices.map((s) => s.start)).toEqual([0, 250])
+ })
+
+ it('widowControl=false: an over-page paragraph cuts after its first line', () => {
+ const beforeBlock = lineBlock(0, [50, 50, 50])
+ const mainBlock = lineBlock(150, [100, 300], { widowControl: false })
+ const geoms = [{ contentHeight: 300, forceBreak: false }]
+ const slices = computeSectionedSlicesF2([beforeBlock, mainBlock], geoms, 550)
+ expect(slices.map((s) => s.start)).toEqual([0, 250])
+ })
+
it('widowControl=false: a single line may remain at the page bottom', () => {
const beforeBlock = lineBlock(0, [50, 50, 50]) // 150px
const mainBlock = lineBlock(150, [50, 50, 50, 50], { widowControl: false }) // 200px
@@ -1410,6 +1664,24 @@ describe('computeSectionedSlicesF2 — mid-paragraph page breaks (innerBreaks)',
])
})
+ it('truncates a keepNext chain at a forced section start: the next section is not pulled back', () => {
+ // a keep-on title closing section 0, then two keep-on headings opening a
+ // nextPage section 1 (the chain must not hold the section break's page open)
+ const geoms = [
+ { contentHeight: 800, forceBreak: false, startType: 'nextPage' as const },
+ { contentHeight: 800, forceBreak: true, startType: 'nextPage' as const },
+ ]
+ const title = lineBlock(0, [60], { keepNext: true, section: 0 })
+ const h1 = lineBlock(60, [50], { keepNext: true, section: 1 })
+ const h2 = lineBlock(110, [40], { keepNext: true, section: 1 })
+ const body = lineBlock(150, [20, 20, 20, 20, 20], { section: 1 })
+ const slices = computeSectionedSlicesF2([title, h1, h2, body], geoms, 250)
+ expect(slices.map((s) => [s.start, s.end, s.section])).toEqual([
+ [0, 60, 0],
+ [60, 250, 1],
+ ])
+ })
+
it('a break with no text after it still pushes the next block (breakAfter unchanged)', () => {
const para = lineBlock(0, [20, 20], { breakAfter: true })
const slices = computeSectionedSlicesF2([para, block(40, 30)], geoms1, 70)
@@ -1628,6 +1900,162 @@ describe('computeSectionedSlicesF2 — table row-level page breaks', () => {
expect(legacy[1].start).toBe(150)
})
+ it('tblHeader on every row: no repetition and every row reaches a page (LO tdf104492)', () => {
+ // 12 header rows x 150 = 1800px on 680px pages: Word lays the rows out
+ // normally (a header set that is the whole table cannot repeat)
+ const rows: TableRowBox[] = Array.from({ length: 12 }, () => ({
+ height: 150,
+ isHeader: true,
+ cutYs: [50, 100],
+ }))
+ const b = makeTableBlock(0, rows)
+ b.modernTableHeaders = true
+ const slices = computeSectionedSlicesF2([b], [{ contentHeight: 680, forceBreak: false }], 1800)
+ expect(slices.map((s) => [s.start, s.end])).toEqual([
+ [0, 600],
+ [600, 1200],
+ [1200, 1800],
+ ])
+ for (const s of slices) expect(s.repeatHeader).toBeUndefined()
+ })
+
+ it('tblHeader: header block taller than a page drops repetition but keeps every body row', () => {
+ const rows: TableRowBox[] = [
+ { height: 150, isHeader: true },
+ { height: 150, isHeader: true },
+ ...Array.from({ length: 4 }, () => ({ height: 50 })),
+ ]
+ const b = makeTableBlock(0, rows)
+ const slices = computeSectionedSlicesF2([b], [{ contentHeight: 200, forceBreak: false }], 500)
+ for (const s of slices) expect(s.repeatHeader).toBeUndefined()
+ expect(slices[0].start).toBe(0)
+ expect(slices[slices.length - 1].end).toBe(500)
+ for (let i = 1; i < slices.length; i++) expect(slices[i].start).toBe(slices[i - 1].end)
+ })
+
+ it('floating table flows only when one of its rows is taller than the page', () => {
+ const oneRow: BlockBox = {
+ top: 0,
+ height: 300,
+ floated: true,
+ floatTable: true,
+ tableRows: [{ height: 300 }],
+ pageRelVyPx: 40,
+ pageRelVAnchor: 'margin',
+ }
+ const out: SliceOutputs = { floatFlows: [], floatVShifts: [], floatSplits: [] }
+ computeSectionedSlicesF2([oneRow, { top: 0, height: 320 }], geoms1, 320, out)
+ expect(out.floatFlows).toEqual([{ blockTop: 0 }])
+ // a table about to flow takes no --tblp-dy shift and is not split
+ expect(out.floatVShifts).toEqual([])
+ expect(out.floatSplits).toEqual([])
+ // rows not sampled yet: the float is placed whole, never flowed
+ const unsampled: BlockBox = { top: 0, height: 300, floated: true, floatTable: true }
+ const out2: SliceOutputs = { floatFlows: [], floatSplits: [] }
+ computeSectionedSlicesF2([unsampled, { top: 0, height: 320 }], geoms1, 320, out2)
+ expect(out2.floatFlows).toEqual([])
+ expect(out2.floatSplits).toEqual([])
+ // a flowed table whose rows all fit a page goes back to floating
+ const flowed = makeTableBlock(
+ 0,
+ Array.from({ length: 6 }, () => ({ height: 50 })),
+ )
+ flowed.floatTable = true
+ flowed.floatFlowed = true
+ const out3: SliceOutputs = { floatFlows: [] }
+ computeSectionedSlicesF2([flowed], geoms1, 300, out3)
+ expect(out3.floatFlows).toEqual([])
+ })
+
+ it('floating table taller than the page splits at row boundaries, the last portion floating', () => {
+ const rows: TableRowBox[] = Array.from({ length: 6 }, () => ({ height: 50 }))
+ const b = makeTableBlock(0, rows)
+ b.floated = true
+ b.floatTable = true
+ // converged state: the anchor paragraph already sits beside the last portion
+ const anchor: BlockBox = { top: 200, height: 60 }
+ const out: SliceOutputs = { floatFlows: [], floatSplits: [] }
+ const slices = computeSectionedSlicesF2([b, anchor], geoms1, 300, out)
+ expect(out.floatFlows).toEqual([])
+ expect(out.floatSplits).toEqual([{ blockTop: 0, dyPx: 0, cutYs: [200], carryPx: 200 }])
+ // rows 0-3 fill page 1 alone; rows 4-5 float on page 2 with the anchor beside
+ expect(slices.map((s) => [s.start, s.end])).toEqual([
+ [0, 200],
+ [200, 300],
+ ])
+ })
+
+ it('floating table not fitting the remainder splits; the text after it starts beside the continuation', () => {
+ const lead: BlockBox = { top: 0, height: 120 }
+ const b = makeTableBlock(
+ 120,
+ Array.from({ length: 3 }, () => ({ height: 50 })),
+ )
+ b.floated = true
+ b.floatTable = true
+ const anchor: BlockBox = { top: 170, height: 50 }
+ const out: SliceOutputs = { floatSplits: [] }
+ const slices = computeSectionedSlicesF2([lead, b, anchor], geoms1, 270, out)
+ expect(out.floatSplits).toEqual([{ blockTop: 120, dyPx: 0, cutYs: [170], carryPx: 50 }])
+ expect(slices.map((s) => [s.start, s.end])).toEqual([
+ [0, 170],
+ [170, 270],
+ ])
+ // the whole anchor paragraph fits page 2 next to the float: no further turn
+ expect(slices).toHaveLength(2)
+ })
+
+ it('floating table whose first row does not fit the remainder moves whole to the next page', () => {
+ const lead: BlockBox = { top: 0, height: 180 }
+ const b = makeTableBlock(
+ 180,
+ Array.from({ length: 3 }, () => ({ height: 50 })),
+ )
+ b.floated = true
+ b.floatTable = true
+ const out: SliceOutputs = { floatSplits: [] }
+ const slices = computeSectionedSlicesF2([lead, b, { top: 180, height: 100 }], geoms1, 330, out)
+ expect(out.floatSplits).toEqual([])
+ expect(slices.map((s) => [s.start, s.end])).toEqual([
+ [0, 180],
+ [180, 330],
+ ])
+ })
+
+ it('cantSplit rows of a split floating table stay whole', () => {
+ const rows: TableRowBox[] = [
+ { height: 50 },
+ { height: 50 },
+ { height: 50 },
+ { height: 80, cantSplit: true },
+ { height: 50 },
+ ]
+ const b = makeTableBlock(0, rows)
+ b.floated = true
+ b.floatTable = true
+ const out: SliceOutputs = { floatSplits: [] }
+ computeSectionedSlicesF2([b, { top: 150, height: 130 }], geoms1, 280, out)
+ // 150 + 80 > 200: the cantSplit row opens page 2
+ expect(out.floatSplits).toEqual([{ blockTop: 0, dyPx: 0, cutYs: [150], carryPx: 150 }])
+ })
+
+ it('page-anchored split floating table: cuts are measured from the shifted top', () => {
+ const b = makeTableBlock(
+ 0,
+ Array.from({ length: 6 }, () => ({ height: 50 })),
+ )
+ b.floated = true
+ b.floatTable = true
+ b.pageRelVyPx = 40
+ b.pageRelVAnchor = 'margin'
+ const out: SliceOutputs = { floatSplits: [], floatVShifts: [] }
+ const slices = computeSectionedSlicesF2([b, { top: 190, height: 100 }], geoms1, 340, out)
+ expect(out.floatVShifts).toEqual([{ blockTop: 0, dyPx: 40 }])
+ // 40 + 3 rows = 190 fit; the fourth row would end at 240
+ expect(out.floatSplits).toEqual([{ blockTop: 0, dyPx: 40, cutYs: [190], carryPx: 190 }])
+ expect(slices[0]).toMatchObject({ start: 0, end: 190 })
+ })
+
it('split table without tblHeader carries no repeatHeader', () => {
const rows: TableRowBox[] = Array.from({ length: 5 }, () => ({ height: 50 }))
const b = makeTableBlock(0, rows)
@@ -1995,6 +2423,71 @@ describe('measureBlocks — page-anchored floated tables', () => {
})
})
+describe('measureBlocks — adjacent page breaks in one paragraph', () => {
+ const para = (html: string) => {
+ const pm = document.createElement('div')
+ const el = document.createElement('p')
+ el.innerHTML = html
+ el.getBoundingClientRect = () =>
+ ({ top: 0, height: 60, bottom: 60, left: 0, right: 100, width: 100 }) as DOMRect
+ pm.appendChild(el)
+ return measureBlocks(pm, 0, 1).blocks[0]
+ }
+
+ it('two leading breaks before the text: breakBefore plus one extra turn', () => {
+ const b = para(' Another Look')
+ expect(b).toMatchObject({ breakBefore: true, breakBeforeBr: true, extraBreaksBefore: 1 })
+ expect(b.breakAfter).toBeUndefined()
+ expect(b.innerBreaks).toBeUndefined()
+ })
+
+ it('a leading break cuts at the measured text line: the break line stays on the page before', () => {
+ const proto = Range.prototype as unknown as { getClientRects?: () => DOMRect[] }
+ const orig = proto.getClientRects
+ proto.getClientRects = () =>
+ [{ top: 20, height: 20, width: 80, left: 0, right: 80, bottom: 40 }] as DOMRect[]
+ try {
+ const b = para(' Business Plan')
+ expect(b.innerBreaks).toEqual([20])
+ expect(b.breakBefore).toBeUndefined()
+ expect(b.breakBeforeBr).toBeUndefined()
+ const two = para(' Another Look')
+ expect(two).toMatchObject({ innerBreaks: [20], extraBreaksBefore: 1 })
+ expect(two.breakBefore).toBeUndefined()
+ } finally {
+ proto.getClientRects = orig
+ }
+ })
+
+ it('two trailing breaks after the text: breakAfter plus one extra turn', () => {
+ const b = para('Closing line ')
+ expect(b).toMatchObject({ breakAfter: true, extraBreaksAfter: 1 })
+ expect(b.breakBefore).toBeUndefined()
+ })
+
+ it('a break-only paragraph with two breaks queues one extra turn', () => {
+ const b = para(
+ ' ',
+ )
+ expect(b).toMatchObject({ breakAfter: true, extraBreaksAfter: 1 })
+ expect(b.breakBefore).toBeUndefined()
+ })
+
+ it('a field page break with only its own label is a break-only paragraph (one turn)', () => {
+ const b = para('Page Break
')
+ expect(b).toMatchObject({ breakAfter: true })
+ expect(b.breakBefore).toBeUndefined()
+ expect(b.extraBreaksAfter).toBeUndefined()
+ })
+
+ it('a single leading and a single trailing break keep both turns', () => {
+ const b = para(' Middle ')
+ expect(b).toMatchObject({ breakBefore: true, breakBeforeBr: true, breakAfter: true })
+ expect(b.extraBreaksBefore).toBeUndefined()
+ expect(b.extraBreaksAfter).toBeUndefined()
+ })
+})
+
describe('measureBlocks — break-only paragraphs', () => {
const rectOf = (top: number, height: number) =>
({
@@ -2946,6 +3439,315 @@ describe('computeSectionedSlicesF2 — multi-column flow', () => {
expect(slices[0].regions![1].top).toBe(20)
})
+ it('a continuous section keeping the column count still balances the closed region (Word balance-columns idiom)', () => {
+ // five 2-line paragraphs in a 2-col section closed by a continuous 2-col section
+ const blocks: BlockBox[] = [
+ ...Array.from({ length: 5 }, (_, i) => ({
+ ...lineBlock(i * 40, [20, 20]),
+ section: 0,
+ })),
+ { ...lineBlock(200, [20]), section: 1, emptyPara: true },
+ ]
+ const geoms = [
+ { contentHeight: 400, forceBreak: false, cols: 2 },
+ { contentHeight: 400, forceBreak: false, cols: 2 },
+ ]
+ const slices = computeSectionedSlicesF2(blocks, geoms, 220)
+ expect(slices).toHaveLength(1)
+ const regions = slices[0].regions!
+ expect(regions).toHaveLength(2)
+ expect(regions[0].columns.map((c) => [c.start, c.end])).toEqual([
+ [0, 120],
+ [120, 200],
+ ])
+ expect(regions[0].height).toBe(120)
+ expect(regions[1].top).toBe(120)
+ expect(regions[1].section).toBe(1)
+ // a nextColumn boundary keeps flowing in the region (no balance)
+ const flow = computeSectionedSlicesF2(
+ blocks,
+ [geoms[0], { ...geoms[1], colBreakStart: true }],
+ 220,
+ )
+ expect(flow[0].regions).toHaveLength(1)
+ })
+
+ it('unequal column widths balance at block tops with extents scaled by the column width', () => {
+ // cols [400, 200]: measured in the wide column, the overflowing paragraph
+ // (140px) would wrap to ~280px in the narrow one. The balance weighs each
+ // block by measured width / column width and cuts on block tops only (a
+ // block keeps one wrap width), so the last paragraph moves whole to column 2
+ // instead of the line-quota cut inside the third paragraph
+ const wide = { widthPx: 400 }
+ const blocks: BlockBox[] = [
+ { ...lineBlock(0, [20], wide), section: 0 },
+ { ...lineBlock(20, [20, 20, 20, 20, 20, 20], wide), section: 0 },
+ { ...lineBlock(140, [20, 20, 20, 20, 20, 20], wide), section: 0 },
+ { ...lineBlock(260, [20, 20, 20, 20, 20, 20, 20], wide), section: 0 },
+ { ...lineBlock(400, [20]), section: 1, emptyPara: true },
+ ]
+ const geoms = [
+ { contentHeight: 800, forceBreak: false, cols: 2, colWidths: [400, 200] },
+ { contentHeight: 800, forceBreak: false, cols: 2, colWidths: [400, 200] },
+ ]
+ const slices = computeSectionedSlicesF2(blocks, geoms, 420)
+ const regions = slices[0].regions!
+ expect(regions[0].columns.map((c) => [c.start, c.end])).toEqual([
+ [0, 260],
+ [260, 400],
+ ])
+ // after the remeasure with the paragraph wrapped at the narrow width, the
+ // same cut holds and the region grows to the narrow column's extent
+ const narrow = blocks.map((b, i) =>
+ i === 3
+ ? {
+ ...lineBlock(
+ 260,
+ Array.from({ length: 14 }, () => 20),
+ { widthPx: 200 },
+ ),
+ section: 0,
+ }
+ : i === 4
+ ? { ...b, top: 540 }
+ : b,
+ )
+ const again = computeSectionedSlicesF2(narrow, geoms, 560)
+ const r2 = again[0].regions!
+ expect(r2[0].columns.map((c) => [c.start, c.end])).toEqual([
+ [0, 260],
+ [260, 540],
+ ])
+ expect(r2[0].height).toBe(280)
+ expect(r2[1].top).toBe(280)
+ })
+
+ // 171 shape: cols [400, 200] (wide / narrow), heading + two 6-line paragraphs +
+ // a 6-line paragraph (wide). Rewrapped narrow the last paragraph runs 14 lines;
+ // after k wide head lines its tail runs [14, 13, 10, 8, 6, 3, 0] narrow lines.
+ const wrap171 = (): ColWrapTable => {
+ const tailLines = [14, 13, 10, 8, 6, 3, 0]
+ const headH = Array.from({ length: 7 }, (_, k) => 20 * k)
+ const tailH = tailLines.map((n) => 20 * n)
+ return {
+ headWidthPx: 400,
+ tailWidthPx: 200,
+ n: 6,
+ headH,
+ tailH,
+ tailBottom: headH.map((h, k) => h + tailH[k]),
+ // ink edges 2px inside the 20px line boxes
+ shapeY: headH.map((h, k) => (k === 0 || k === 6 ? h : h + 2)),
+ }
+ }
+ const blocks171 = (extra?: Partial): BlockBox[] => {
+ const wide = { widthPx: 400 }
+ return [
+ { ...lineBlock(0, [20], wide), section: 0 },
+ { ...lineBlock(20, [20, 20, 20, 20, 20, 20], wide), section: 0 },
+ { ...lineBlock(140, [20, 20, 20, 20, 20, 20], wide), section: 0 },
+ {
+ ...lineBlock(260, [20, 20, 20, 20, 20, 20], wide),
+ section: 0,
+ el: document.createElement('p'),
+ ...extra,
+ },
+ { ...lineBlock(380, [20]), section: 1, emptyPara: true },
+ ]
+ }
+ const geoms171 = [
+ { contentHeight: 800, forceBreak: false, cols: 2, colWidths: [400, 200] },
+ { contentHeight: 800, forceBreak: false, cols: 2, colWidths: [400, 200] },
+ ]
+
+ it('unequal columns: with a wrap table the balance cuts inside the paragraph at the line minimizing the taller column, left column first on ties', () => {
+ // block-top cut: 13 wide lines / 14 narrow lines; one head line: 14 / 13
+ // (same maximum, fuller left column, Word); two head lines: 15 / 12
+ const blocks = blocks171({ widowControl: false, colWraps: [wrap171()] })
+ const out: SliceOutputs = { colWrapRequests: [] }
+ const slices = computeSectionedSlicesF2(blocks, geoms171, 400, out)
+ const region = slices[0].regions![0]
+ expect(region.columns.map((c) => [c.start, c.end])).toEqual([
+ [0, 280],
+ [280, 380],
+ ])
+ expect(out.colWrapRequests).toEqual([])
+ // widow control on: a single head line is not allowed, the block-top cut
+ // (13 / 14) beats two head lines (15 / 12)
+ const widow = blocks171({ colWraps: [wrap171()] })
+ const again = computeSectionedSlicesF2(widow, geoms171, 400)
+ expect(again[0].regions![0].columns.map((c) => [c.start, c.end])).toEqual([
+ [0, 260],
+ [260, 380],
+ ])
+ // keepLines: never cut inside
+ const keep = blocks171({ widowControl: false, keepLines: true, colWraps: [wrap171()] })
+ expect(computeSectionedSlicesF2(keep, geoms171, 400)[0].regions![0].columns[1].start).toBe(260)
+ })
+
+ it('unequal columns: a paragraph near the quota without a wrap table is requested and the pass cuts on block tops', () => {
+ const blocks = blocks171()
+ const out: SliceOutputs = { colWrapRequests: [] }
+ const slices = computeSectionedSlicesF2(blocks, geoms171, 400, out)
+ expect(slices[0].regions![0].columns[1].start).toBe(260)
+ expect(out.colWrapRequests).toEqual([{ blockTop: 260, headWidthPx: 400, tailWidthPx: 200 }])
+ })
+
+ it('columnLineSplits: a cut on a line boundary between windows of different widths (in a region, across a page turn) yields one split per block', () => {
+ const els = Array.from({ length: 3 }, () => document.createElement('p'))
+ const blocks: BlockBox[] = [
+ { ...lineBlock(0, [20]), section: 0, el: els[0] },
+ { ...lineBlock(20, [20, 20, 20, 20]), section: 0, el: els[1], colWraps: [wrap171()] },
+ { ...lineBlock(100, [20, 20]), section: 0, el: els[2] },
+ ]
+ const ws = () => [400, 200]
+ const region = (start: number, end: number, cut: number) => ({
+ top: 0,
+ height: end - start,
+ section: 0,
+ columns: [
+ { start, end: cut },
+ { start: cut, end },
+ ],
+ })
+ // balance cut after the second line of block 1 (table match), narrow tail
+ const inRegion = columnLineSplits(
+ blocks,
+ [{ start: 0, end: 140, section: 0, regions: [region(0, 140, 60)] }],
+ ws,
+ )
+ expect(inRegion).toEqual([
+ {
+ bi: 1,
+ line: 2,
+ headWidthPx: 400,
+ tailWidthPx: 200,
+ cutY: 40,
+ tailBottom: 240,
+ shapeY: 42,
+ },
+ ])
+ // page turn from a narrow last column into a wide first column: the block
+ // has no table for that pair, the line boxes locate the cut
+ const turn = columnLineSplits(
+ blocks,
+ [
+ { start: 0, end: 80, section: 0, regions: [region(0, 80, 10)] },
+ { start: 80, end: 140, section: 0, regions: [region(80, 140, 120)] },
+ ],
+ ws,
+ )
+ expect(turn).toEqual([
+ { bi: 1, line: 3, headWidthPx: 200, tailWidthPx: 400, cutY: 60 },
+ { bi: 2, line: 1, headWidthPx: 400, tailWidthPx: 200, cutY: 20 },
+ ])
+ // an overflow cut that is not one of the table's boundaries (the DOM wraps
+ // at another width right now) falls back to the measured line boxes
+ const shifted: BlockBox[] = [
+ blocks[0],
+ {
+ ...blocks[1],
+ lineBoxes: [16, 32, 48, 64].map((h, m) => ({ offsetInBlock: m * 16, height: 16 })),
+ },
+ blocks[2],
+ ]
+ expect(
+ columnLineSplits(
+ shifted,
+ [{ start: 0, end: 140, section: 0, regions: [region(0, 140, 52)] }],
+ ws,
+ ),
+ ).toEqual([{ bi: 1, line: 2, headWidthPx: 400, tailWidthPx: 200, cutY: 32 }])
+ // block-top cuts and equal widths never split
+ expect(
+ columnLineSplits(
+ blocks,
+ [{ start: 0, end: 140, section: 0, regions: [region(0, 140, 20)] }],
+ ws,
+ ),
+ ).toEqual([])
+ expect(
+ columnLineSplits(
+ blocks,
+ [{ start: 0, end: 140, section: 0, regions: [region(0, 140, 60)] }],
+ () => [300, 300],
+ ),
+ ).toEqual([])
+ })
+
+ it('fillColWraps: probes once per element and text, reuses the table for fresh block records', () => {
+ const el = document.createElement('p')
+ el.textContent = 'straddling paragraph'
+ let probes = 0
+ const probe = () => {
+ probes++
+ return wrap171()
+ }
+ const req = [{ blockTop: 100, headWidthPx: 400, tailWidthPx: 200 }]
+ const a: BlockBox[] = [{ top: 100, height: 60, el }]
+ expect(fillColWraps(a, req, 1, probe)).toBe(true)
+ expect(a[0].colWraps).toHaveLength(1)
+ expect(fillColWraps(a, req, 1, probe)).toBe(false)
+ const b: BlockBox[] = [{ top: 100, height: 60, el }]
+ expect(fillColWraps(b, req, 1, probe)).toBe(true)
+ expect(probes).toBe(1)
+ el.textContent = 'edited paragraph'
+ const c: BlockBox[] = [{ top: 100, height: 60, el }]
+ expect(fillColWraps(c, req, 1, probe)).toBe(true)
+ expect(probes).toBe(2)
+ // a failed probe attaches nothing
+ expect(
+ fillColWraps([{ top: 100, height: 60, el: document.createElement('p') }], req, 1, () => null),
+ ).toBe(false)
+ })
+
+ it('splitFloatStyle: right float (left in RTL) with the shape inset', () => {
+ expect(splitFloatStyle(224, 80, 20.4, undefined)).toBe(
+ 'float:right;width:224px;height:80px;shape-outside:inset(20.4px 0 0 0)',
+ )
+ expect(splitFloatStyle(224, 80, 0, true)).toContain('float:left')
+ })
+
+ it('widthPassGate: a changed split shape asks for another pass at unchanged widths; split blocks are never pinned', () => {
+ const el = document.createElement('p')
+ const state = newWidthPassState()
+ const at = (h: number) => [
+ { el, widthPx: 400, dx: 0, dy: 0, split: { floatPx: 224, heightPx: h, insetPx: 20 } },
+ ]
+ expect(widthPassGate(state, at(80))).toBe(true)
+ expect(widthPassGate(state, at(80))).toBe(false)
+ expect(widthPassGate(state, at(120))).toBe(true)
+ state.forced.set(el, 200)
+ const specs = at(120)
+ widthPassGate(state, specs)
+ expect(specs[0].widthPx).toBe(400)
+ })
+
+ it('unequal columns: an empty paragraph mid-region does not force the cut', () => {
+ // cols [400, 200], every block measured wide: the balance target is 2/3 of
+ // the content (a block doubles in the narrow column). The blank line after
+ // the first paragraph has zero extent and must not be a cut point; the cut
+ // lands where the accumulated extent is nearest the quota (top of p4)
+ const wide = { widthPx: 400 }
+ const blocks: BlockBox[] = [
+ { ...lineBlock(0, [20], wide), section: 0 },
+ { ...lineBlock(20, [20], wide), section: 0, emptyPara: true },
+ { ...lineBlock(40, [20, 20, 20], wide), section: 0 },
+ { ...lineBlock(100, [20, 20, 20], wide), section: 0 },
+ { ...lineBlock(160, [20, 20, 20], wide), section: 0 },
+ { ...lineBlock(220, [20]), section: 1, emptyPara: true },
+ ]
+ const geoms = [
+ { contentHeight: 800, forceBreak: false, cols: 2, colWidths: [400, 200] },
+ { contentHeight: 800, forceBreak: false, cols: 2, colWidths: [400, 200] },
+ ]
+ const slices = computeSectionedSlicesF2(blocks, geoms, 240)
+ expect(slices[0].regions![0].columns.map((c) => [c.start, c.end])).toEqual([
+ [0, 160],
+ [160, 220],
+ ])
+ })
+
it('columnLayoutSpecs: width + per-column constant translate, later regions pull up', () => {
const els = Array.from({ length: 4 }, () => document.createElement('p'))
const blocks: BlockBox[] = [
@@ -3099,6 +3901,131 @@ describe('computeSectionedSlicesF2 — multi-column flow', () => {
expect(specs[1].dy).toBe(-20)
})
+ it('columnLayoutSpecs: a block cut at a line boundary from a wide column into a narrower one is split: wide width plus a float shape that narrows the tail', () => {
+ const els = Array.from({ length: 3 }, () => document.createElement('p'))
+ const blocks: BlockBox[] = [
+ { ...lineBlock(0, [20]), section: 0, el: els[0] },
+ // starts in the wide first column of page 1, continues on page 2's narrow first column
+ { ...lineBlock(20, [20, 20, 20, 20]), section: 0, el: els[1] },
+ { ...lineBlock(100, [20]), section: 0, el: els[2] },
+ ]
+ const sectPrXml =
+ ' '
+ const secs = [sec({ columns: 2, colSpace: 720 }, { sectPrXml })]
+ const g = sectionColGeom(secs[0])
+ const page = (start: number, end: number, cut: number): PageSlice => ({
+ start,
+ end,
+ section: 0,
+ physHeight: end - start,
+ regions: [
+ {
+ top: 0,
+ height: end - start,
+ section: 0,
+ columns: [
+ { start, end: cut },
+ { start: cut, end },
+ ],
+ },
+ ],
+ })
+ // page 1: wide column [0,40) holds block 0 and the first line of block 1; the
+ // narrow column [40,60) shows its next line; page 2's wide column the rest
+ const specs = columnLayoutSpecs(blocks, [page(0, 60, 40), page(60, 120, 100)], secs)
+ expect(specs.map((s) => s.el)).toEqual(els)
+ expect(specs[0].widthPx).toBeCloseTo(g.widths[0], 3)
+ // one element at the wide width; the float covers the tail lines (from the
+ // cut, in-block Y 20, to the text bottom) on the right by the width difference
+ expect(specs[1].widthPx).toBeCloseTo(g.widths[0], 3)
+ expect(specs[1].dx).toBe(0)
+ expect(specs[1].split).toEqual({
+ floatPx: g.widths[0] - g.widths[1],
+ heightPx: 80,
+ insetPx: 21,
+ })
+ expect(specs[2].split).toBeUndefined()
+ // a block whole inside the narrow column keeps that column's width; one whole
+ // inside a wide column is not narrowed by columns it never reaches
+ expect(specs[2].widthPx).toBeCloseTo(g.widths[1], 3)
+ const whole = columnLayoutSpecs(blocks, [page(0, 200, 150)], secs)
+ expect(whole[1].widthPx).toBeCloseTo(g.widths[0], 3)
+ // only the trailing space after crosses into the narrow column: the lines
+ // themselves are whole in the wide one, which keeps its width
+ const spaced: BlockBox[] = [
+ blocks[0],
+ { ...blocks[1], height: 80 + 30, spaceAfterPx: 30 },
+ { ...blocks[2], top: 130 },
+ ]
+ const tail = columnLayoutSpecs(spaced, [page(0, 200, 110)], secs)
+ expect(tail[1].widthPx).toBeCloseTo(g.widths[0], 3)
+ })
+
+ it('widthPassGate: unequal-column widths re-pass until the landing columns settle, bounded', () => {
+ const el = document.createElement('p')
+ const at = (w: number) => [{ el, widthPx: w, dx: 0, dy: 0 }]
+ const state = newWidthPassState()
+ // first decorated pass: blocks got their column widths, line breaks moved
+ expect(widthPassGate(state, at(166))).toBe(true)
+ // a block moved from the narrow to the wide column: once more
+ expect(widthPassGate(state, at(360))).toBe(true)
+ // fixed point: same widths, no further pass, run counter cleared
+ expect(widthPassGate(state, at(360))).toBe(false)
+ expect(state.runs).toBe(0)
+ expect(state.forced.size).toBe(0)
+ // a run of moving widths stops after maxRuns re-passes
+ const drift = newWidthPassState()
+ let granted = 0
+ for (let i = 0; i < 10; i++) if (widthPassGate(drift, at(100 + i), 3)) granted++
+ expect(granted).toBe(3)
+ // and recovers once a pass repeats its predecessor
+ widthPassGate(drift, at(360), 3)
+ expect(widthPassGate(drift, at(360), 3)).toBe(false)
+ expect(widthPassGate(drift, at(166), 3)).toBe(true)
+ // no regioned pages at all: nothing to converge
+ expect(widthPassGate(newWidthPassState(), [])).toBe(false)
+ })
+
+ it('widthPassGate: a block ping-ponging between columns is pinned to the narrower width', () => {
+ const straddler = document.createElement('p')
+ const steady = document.createElement('p')
+ const pass = (w: number) => [
+ { el: steady, widthPx: 360, dx: 0, dy: 0 },
+ { el: straddler, widthPx: w, dx: 0, dy: 0 },
+ ]
+ const state = newWidthPassState()
+ expect(widthPassGate(state, pass(360))).toBe(true)
+ expect(widthPassGate(state, pass(166))).toBe(true)
+ // wide again = the pass before last: the cycle is caught and the applied
+ // specs already carry the narrow width
+ const cyc = pass(360)
+ expect(widthPassGate(state, cyc)).toBe(true)
+ expect(cyc[1].widthPx).toBe(166)
+ expect(cyc[0].widthPx).toBe(360)
+ expect(state.forced.get(straddler)).toBe(166)
+ // the pin holds while the engine keeps wanting the wide column: settled
+ const next = pass(360)
+ expect(widthPassGate(state, next)).toBe(false)
+ expect(next[1].widthPx).toBe(166)
+ // a narrower column than the pin still wins (never widen past the landing column)
+ const narrower = pass(120)
+ widthPassGate(state, narrower)
+ expect(narrower[1].widthPx).toBe(120)
+ // a document edit releases the pins and forgets the cycle history: the
+ // widths of the edited flow are not compared with the old flow's
+ resetWidthPassHistory(state)
+ const free = pass(360)
+ expect(widthPassGate(state, free)).toBe(true)
+ expect(free[1].widthPx).toBe(360)
+ expect(state.forced.size).toBe(0)
+ // a gate exhausted by a long drift is re-armed by an edit
+ const drift = newWidthPassState()
+ for (let i = 0; i < 10; i++) widthPassGate(drift, pass(100 + i), 3)
+ expect(widthPassGate(drift, pass(200), 3)).toBe(false)
+ resetWidthPassHistory(drift)
+ expect(widthPassGate(drift, pass(300), 3)).toBe(true)
+ })
+
it('columnLayoutSpecs: an indented paragraph gets the column width minus its margins', () => {
const indented = document.createElement('p')
indented.style.marginLeft = '11.33px'
@@ -3434,3 +4361,493 @@ describe('fillLineBoxes — empty paragraphs above a cell heading are row cut po
expect(block.tableRows![0].contentBottom).toBe(80)
})
})
+
+describe('computeSectionedSlicesF2 — multi-cell rows split per cell (Word row break)', () => {
+ const makeTableBlock = (top: number, rows: TableRowBox[]): BlockBox => ({
+ top,
+ height: rows.reduce((s, r) => s + r.height, 0),
+ tableRows: rows,
+ })
+ /** n lines of `pitch` px starting at `top`, all in child `child`, grouped into paragraphs of `perPara` lines */
+ const linesOf = (n: number, pitch: number, perPara: number, child = 0, top = 0) => ({
+ lines: Array.from({ length: n }, (_, i): [number, number] => [
+ top + i * pitch,
+ top + (i + 1) * pitch,
+ ]),
+ childOf: Array.from({ length: n }, () => child),
+ paraOf: Array.from({ length: n }, (_, i) => Math.floor(i / perPara)),
+ })
+ const page = [{ contentHeight: 200, forceBreak: false }]
+
+ it('the first fragment fills the page and each cell breaks at its own line boundary', () => {
+ // page 200; a 40px row leaves 160. Cell 0: 15 lines x 20px in 3 paragraphs
+ // (8 lines fit, the cut leaves 3+2 lines of paragraph 2). Cell 1: 4 lines x
+ // 60px, centered (canvas offset 30): 2 lines fit; on page 2 its remaining lines
+ // start flush at the top (shift 40 - 30) with the first two clipped away
+ const rows: TableRowBox[] = [
+ { height: 40 },
+ {
+ height: 300,
+ contentBottom: 300,
+ cells: [
+ { ...linesOf(15, 20, 5), alignDy: 0, alignFrac: 0 },
+ { ...linesOf(4, 60, 4), alignDy: 30, alignFrac: 0.5 },
+ ],
+ },
+ ]
+ const out: SliceOutputs = { rowFills: [], rowSplits: [] }
+ const slices = computeSectionedSlicesF2([makeTableBlock(0, rows)], page, 340, out)
+ expect(slices.map((s) => [s.start, s.end])).toEqual([
+ [0, 200],
+ [200, 340],
+ ])
+ expect(out.rowFills).toEqual([])
+ expect(out.rowSplits).toEqual([
+ {
+ blockTop: 0,
+ row: 1,
+ rules: [
+ { from: 40, cell: 0, child: 0, clipBottom: 140 },
+ { from: 40, cell: 0, child: 1, tail: true, hide: true },
+ { from: 40, cell: 1, child: 0, tail: true, dy: -30 },
+ { from: 40, cell: 1, child: 0, clipBottom: 120 },
+ { from: 40, cell: 1, child: 1, tail: true, hide: true },
+ { from: 200, cell: 0, child: 0, clipTop: 160 },
+ { from: 200, cell: 1, child: 0, tail: true, dy: -30 },
+ { from: 200, cell: 1, child: 0, tail: true, dy: 10 },
+ { from: 200, cell: 1, child: 0, clipTop: 120 },
+ ],
+ },
+ ])
+ })
+
+ it('a centered cell that fits the first fragment whole is centered within the fragment', () => {
+ // cell 1 holds one 20px line the canvas centered in the 300px row (offset 140);
+ // Word centers it in the 160px fragment instead: (160 - 20) / 2 - 140
+ const rows: TableRowBox[] = [
+ { height: 40 },
+ {
+ height: 300,
+ contentBottom: 300,
+ cells: [
+ { ...linesOf(15, 20, 5), alignDy: 0, alignFrac: 0 },
+ { ...linesOf(1, 20, 1), alignDy: 140, alignFrac: 0.5 },
+ ],
+ },
+ ]
+ const out: SliceOutputs = { rowSplits: [] }
+ computeSectionedSlicesF2([makeTableBlock(0, rows)], page, 340, out)
+ expect(out.rowSplits![0].rules.filter((r) => r.cell === 1)).toEqual([
+ { from: 40, cell: 1, child: 0, tail: true, dy: -70 },
+ { from: 200, cell: 1, child: 0, tail: true, hide: true },
+ ])
+ })
+
+ it('a widow/orphan cut moves the paragraph whole; a continuation shift past the row bottom patches the row height idempotently', () => {
+ // cell 1: 4 lines x 75px, one paragraph in child 2: 2 fit (150), the cut leaves
+ // 2+2 -> legal; the continuation starts at 160 so the last line ends at 310 > 300
+ const cells = [
+ { ...linesOf(15, 20, 5), alignDy: 0, alignFrac: 0 },
+ { ...linesOf(4, 75, 4, 2), alignDy: 0, alignFrac: 0 },
+ ]
+ const out: SliceOutputs = { rowFills: [], rowSplits: [] }
+ const slices = computeSectionedSlicesF2(
+ [makeTableBlock(0, [{ height: 40 }, { height: 300, contentBottom: 300, cells }])],
+ page,
+ 340,
+ out,
+ )
+ // the flow total (340) clamps the last slice; the row itself grows to 310
+ expect(slices.map((s) => [s.start, s.end])).toEqual([
+ [0, 200],
+ [200, 340],
+ ])
+ expect(out.rowFills).toEqual([{ blockTop: 0, row: 1, targetPx: 310, extraPx: 10 }])
+ expect(out.rowSplits![0].rules.filter((r) => r.cell === 1)).toEqual([
+ { from: 40, cell: 1, child: 2, clipBottom: 150 },
+ { from: 40, cell: 1, child: 3, tail: true, hide: true },
+ { from: 200, cell: 1, child: 2, tail: true, dy: 10 },
+ { from: 200, cell: 1, child: 2, clipTop: 150 },
+ ])
+ // the patched DOM row (310px, data-split-extra 10) yields the same plan
+ const again: SliceOutputs = { rowFills: [], rowSplits: [] }
+ computeSectionedSlicesF2(
+ [
+ makeTableBlock(0, [
+ { height: 40 },
+ { height: 310, contentBottom: 300, cells, splitExtra: 10 },
+ ]),
+ ],
+ page,
+ 350,
+ again,
+ )
+ expect(again.rowFills).toEqual([{ blockTop: 0, row: 1, targetPx: 310, extraPx: 10 }])
+ expect(again.rowSplits).toEqual(out.rowSplits)
+ })
+
+ it('a fractional row target round-trips through the integer CSS height without drifting', () => {
+ // 4 x 75.1px lines: the continuation ends at 310.2 over a 300.4 natural row.
+ // The DOM renders height 310 and stores extra 9.6 (310 - 300.4), so the
+ // remeasure recovers the same natural height and plan (extra 9.8 again)
+ const cells = [
+ { ...linesOf(15, 20, 5), alignDy: 0, alignFrac: 0 },
+ { ...linesOf(4, 75.1, 4, 2), alignDy: 0, alignFrac: 0 },
+ ]
+ const plan = (row: TableRowBox) => {
+ const out: SliceOutputs = { rowFills: [], rowSplits: [] }
+ computeSectionedSlicesF2([makeTableBlock(0, [{ height: 40 }, row])], page, 360, out)
+ return out
+ }
+ const first = plan({ height: 300.4, contentBottom: 300.4, cells })
+ expect(first.rowFills![0].targetPx).toBeCloseTo(310.2)
+ expect(first.rowFills![0].extraPx).toBeCloseTo(9.8)
+ const attrs = rowFillAttrs(first.rowFills![0].targetPx, first.rowFills![0].extraPx)
+ expect(attrs).toEqual({ style: 'height:310px', 'data-split-extra': '9.6' })
+ const again = plan({ height: 310, contentBottom: 300.4, cells, splitExtra: 9.6 })
+ expect(again.rowFills![0].targetPx).toBeCloseTo(310.2)
+ expect(again.rowFills![0].extraPx).toBeCloseTo(9.8)
+ expect(again.rowSplits).toEqual(first.rowSplits)
+ })
+
+ it('a continuation that fits only one more line of a running paragraph holds it back (widow)', () => {
+ // one paragraph of 5 x 20px lines; 3 fit the first page (3+2 legal). The next
+ // page holds a single line: Word carries the last two lines over together
+ // instead of leaving the final line alone on a third page
+ const row: TableRowBox = {
+ height: 100,
+ contentBottom: 100,
+ cells: [{ ...linesOf(5, 20, 5), alignDy: 0, alignFrac: 0 }],
+ }
+ const pages = [20, 200]
+ let n = -1
+ const plan = planRowSplit(row, 60, 200, () => pages[++n])
+ expect(plan).toEqual({
+ lastFragment: 40,
+ target: 120,
+ rules: [
+ { from: 0, cell: 0, child: 0, clipBottom: 40 },
+ { from: 0, cell: 0, child: 1, tail: true, hide: true },
+ { from: 60, cell: 0, child: 0, clipTop: 60, clipBottom: 40 },
+ { from: 60, cell: 0, child: 1, tail: true, hide: true },
+ { from: 80, cell: 0, child: 0, tail: true, dy: 20 },
+ { from: 80, cell: 0, child: 0, clipTop: 60 },
+ ],
+ })
+ // pages that never hold two lines: the rule yields after one held page (no stall)
+ const tiny = planRowSplit(row, 60, 200, () => 20)
+ expect(tiny).toMatchObject({ lastFragment: 20, target: 120 })
+ })
+
+ it('a paragraph opening in the fragment carries two lines over instead of moving whole', () => {
+ // 5 x 20px lines, 4 fit: Word cuts after 3 lines (widow), not before the paragraph
+ const row: TableRowBox = {
+ height: 100,
+ contentBottom: 100,
+ cells: [{ ...linesOf(5, 20, 5), alignDy: 0, alignFrac: 0 }],
+ }
+ const plan = planRowSplit(row, 80, 200, () => 200)
+ expect(plan).toMatchObject({ lastFragment: 40, target: 120 })
+ expect(plan !== 'nofit' && plan?.rules[0]).toEqual({
+ from: 0,
+ cell: 0,
+ child: 0,
+ clipBottom: 40,
+ })
+ })
+
+ it('a 2-line paragraph cannot split: with nothing else fitting the row pushes whole', () => {
+ const rows: TableRowBox[] = [
+ { height: 150 },
+ {
+ height: 100,
+ contentBottom: 100,
+ cells: [
+ { ...linesOf(2, 50, 2), alignDy: 0, alignFrac: 0 },
+ { ...linesOf(2, 50, 2), alignDy: 0, alignFrac: 0 },
+ ],
+ },
+ ]
+ const out: SliceOutputs = { rowSplits: [] }
+ const slices = computeSectionedSlicesF2([makeTableBlock(0, rows)], page, 250, out)
+ expect(slices.map((s) => [s.start, s.end])).toEqual([
+ [0, 150],
+ [150, 250],
+ ])
+ expect(out.rowSplits).toEqual([])
+ })
+
+ it('an over-page row keeps splitting page by page; a child cut on both sides gets one combined clip', () => {
+ // 500px row on 200px pages: cell 0 lines of 20px tile the pages; cell 1 lines
+ // of 30px in 5-line paragraphs: 6 fit but the cut would orphan one line of
+ // paragraph 1, so 5 stay (150) and the continuation restarts flush (shift 50);
+ // page 2 likewise keeps paragraph 2 whole (top 300 -> shift 100) and its child
+ // is clipped at both ends; the last line then ends at 550, growing the row by 50
+ const rows: TableRowBox[] = [
+ {
+ height: 500,
+ contentBottom: 500,
+ cells: [
+ { ...linesOf(25, 20, 5), alignDy: 0, alignFrac: 0 },
+ { ...linesOf(15, 30, 5), alignDy: 0, alignFrac: 0 },
+ ],
+ },
+ ]
+ const out: SliceOutputs = { rowFills: [], rowSplits: [] }
+ const slices = computeSectionedSlicesF2([makeTableBlock(0, rows)], page, 500, out)
+ expect(slices.map((s) => [s.start, s.end])).toEqual([
+ [0, 200],
+ [200, 400],
+ [400, 500],
+ ])
+ expect(out.rowSplits![0].rules.filter((r) => r.cell === 1)).toEqual([
+ { from: 0, cell: 1, child: 0, clipBottom: 300 },
+ { from: 0, cell: 1, child: 1, tail: true, hide: true },
+ { from: 200, cell: 1, child: 0, tail: true, dy: 50 },
+ { from: 200, cell: 1, child: 0, clipTop: 150, clipBottom: 150 },
+ { from: 200, cell: 1, child: 1, tail: true, hide: true },
+ { from: 400, cell: 1, child: 0, tail: true, dy: 100 },
+ { from: 400, cell: 1, child: 0, clipTop: 300 },
+ ])
+ expect(out.rowFills).toEqual([{ blockTop: 0, row: 0, targetPx: 550, extraPx: 50 }])
+ })
+
+ it('a row whose lines all fit but whose bottom cell margin hangs over stays on the page', () => {
+ // page 200; 40px row, then a 165px row whose last line ends at 158: only the
+ // 7px margin overflows, so no empty continuation fragment and no page turn
+ const rows: TableRowBox[] = [
+ { height: 40 },
+ {
+ height: 165,
+ contentBottom: 158,
+ cutYs: [20, 40],
+ cells: [
+ { ...linesOf(2, 20, 2, 0, 2), alignDy: 0, alignFrac: 0 },
+ { ...linesOf(2, 78, 1, 0, 2), alignDy: 0, alignFrac: 0 },
+ ],
+ },
+ { height: 50 },
+ ]
+ const out: SliceOutputs = { rowFills: [], rowSplits: [] }
+ const slices = computeSectionedSlicesF2([makeTableBlock(0, rows)], page, 255, out)
+ expect(slices.map((s) => [s.start, s.end])).toEqual([
+ [0, 205],
+ [205, 255],
+ ])
+ expect(out.rowSplits).toEqual([])
+ expect(out.rowFills).toEqual([])
+ })
+
+ it('a centered cell pushed whole onto the continuation is hidden on the cut page and centered within its fragment', () => {
+ // cell 1: one 2-line paragraph (60px) that does not fit the 40px remainder
+ // (widow rule) and lands whole on page 2, a page-filling fragment (cell 0 runs
+ // on to page 3): flush at the page top (shift 40) plus (200 - 60) / 2, minus the
+ // canvas centering offset
+ const rows: TableRowBox[] = [
+ { height: 160 },
+ {
+ height: 300,
+ contentBottom: 300,
+ cells: [
+ { ...linesOf(15, 20, 5), alignDy: 0, alignFrac: 0 },
+ { ...linesOf(2, 30, 2), alignDy: 120, alignFrac: 0.5 },
+ ],
+ },
+ ]
+ const out: SliceOutputs = { rowSplits: [] }
+ computeSectionedSlicesF2([makeTableBlock(0, rows)], page, 460, out)
+ expect(out.rowSplits![0].rules.filter((r) => r.cell === 1)).toEqual([
+ { from: 160, cell: 1, child: 0, tail: true, dy: -120 },
+ { from: 160, cell: 1, child: 0, tail: true, hide: true },
+ { from: 200, cell: 1, child: 0, tail: true, dy: 40 + 70 - 120 },
+ { from: 400, cell: 1, child: 0, tail: true, hide: true },
+ ])
+ })
+
+ it('rowSplitCss emits each rule on the page its fragment lands on', () => {
+ const tbl = document.createElement('table')
+ tbl.innerHTML = 'a
b
c
'
+ const block: BlockBox = { top: 100, height: 300, el: tbl, tableRows: [{ height: 300 }] }
+ const css = rowSplitCss(
+ [
+ {
+ blockTop: 100,
+ row: 0,
+ rules: [
+ { from: 100, cell: 0, child: 2, tail: true, hide: true },
+ { from: 200, cell: 1, child: 1, tail: true, dy: 20 },
+ { from: 400, cell: 0, child: 0, clipTop: 10, clipBottom: 5 },
+ ],
+ },
+ ],
+ [block],
+ [{ start: 0 }, { start: 200 }, { start: 400 }, { start: 600 }],
+ )
+ expect(tbl.querySelector('tr')!.dataset.pvSplit).toBe('0')
+ expect(css.split('\n')).toEqual([
+ '.pv-page[data-pv-page="0"] .pv-content tr[data-pv-split="0"] > :nth-child(1) > :nth-child(n+3){visibility:hidden}',
+ '.pv-page[data-pv-page="1"] .pv-content tr[data-pv-split="0"] > :nth-child(2) > :nth-child(n+2){transform:translateY(20.0px)}',
+ '.pv-page[data-pv-page="2"] .pv-content tr[data-pv-split="0"] > :nth-child(1) > :nth-child(1){clip-path:inset(10.0px 0 5.0px 0)}',
+ ])
+ })
+
+ it('cellLinesOf clusters same-line rects and keeps the topmost rect child/paragraph ids', () => {
+ const res = cellLinesOf([
+ { band: [20, 40], child: 1, para: 1 },
+ { band: [0, 20], child: 0, para: 0 },
+ { band: [2, 19], child: 0, para: 0 },
+ { band: [41, 60], child: 1, para: 1 },
+ ])
+ expect(res.lines).toEqual([
+ [0, 20],
+ [20, 40],
+ [41, 60],
+ ])
+ expect(res.childOf).toEqual([0, 1, 1])
+ expect(res.paraOf).toEqual([0, 1, 1])
+ })
+})
+
+describe('vertical-text sections (sectPr w:textDirection)', () => {
+ // landscape A4, 1800 twips top/bottom, 1440 left/right
+ const vert = (over: Partial = {}) =>
+ sec({
+ pageWidth: 16838,
+ pageHeight: 11906,
+ orientation: 'landscape',
+ marginTop: 1800,
+ marginBottom: 1800,
+ textDirection: 'tbRl',
+ ...over,
+ })
+ const px = (twips: number) => (twips / 1440) * 96
+
+ it('sectionGeoms swaps the axes: capacity is the side-margin width, line length the body height', () => {
+ const [g] = sectionGeoms([vert()])
+ expect(g.vertical).toBe('tbRl')
+ expect(g.contentHeight).toBeCloseTo(px(16838 - 2880), 3)
+ expect(g.contentWidth).toBeCloseTo(px(11906 - 3600), 3)
+ expect(g.firstContentHeight).toBeUndefined()
+ const [h] = sectionGeoms([vert({ textDirection: 'lrTb' })])
+ expect(h.vertical).toBeUndefined()
+ expect(h.contentHeight).toBeCloseTo(px(11906 - 3600), 3)
+ })
+
+ it('verticalTextSpecs places blocks from the right edge and trims their flow footprint', () => {
+ const els = Array.from({ length: 3 }, () => document.createElement('p'))
+ const blocks: BlockBox[] = [
+ { ...lineBlock(0, [40]), section: 0, el: els[0] },
+ { ...lineBlock(50, [100]), section: 0, el: els[1] },
+ { ...lineBlock(150, [30]), section: 0, el: els[2] },
+ ]
+ const slices: PageSlice[] = [{ start: 0, end: 180, section: 0 }]
+ const secs = [vert()]
+ const geoms = sectionGeoms(secs)
+ const specs = verticalTextSpecs(blocks, slices, secs, geoms)
+ const W = geoms[0].contentHeight
+ const L = geoms[0].contentWidth!
+ expect(specs).toHaveLength(3)
+ expect(specs[0]).toMatchObject({ el: els[0], dy: 0, widthPx: L })
+ expect(specs[0].dx).toBeCloseTo(W - 40, 3)
+ expect(specs[0].vertical).toMatchObject({ mode: 'tbRl', firstOnPage: true })
+ // next block starts 50 below: the box is L tall, so margin-bottom pulls 50 - L
+ expect(specs[0].vertical!.marginBottomPx).toBeCloseTo(50 - L, 3)
+ expect(specs[1].dx).toBeCloseTo(W - 50 - 100, 3)
+ expect(specs[1].dy).toBe(-50)
+ expect(specs[1].vertical!.marginBottomPx).toBeCloseTo(100 - L, 3)
+ expect(specs[1].vertical!.firstOnPage).toBe(false)
+ // last block: the page's flow footprint becomes min(used, L) = 180
+ expect(specs[2].vertical!.marginBottomPx).toBeCloseTo(180 - 150 - L, 3)
+ })
+
+ it('measured inline extras win over the live margins when trimming the line length', () => {
+ const el = document.createElement('p')
+ el.style.marginLeft = '30px'
+ const secs = [vert()]
+ const geoms = sectionGeoms(secs)
+ const L = geoms[0].contentWidth!
+ const slices: PageSlice[] = [{ start: 0, end: 40, section: 0 }]
+ const live = verticalTextSpecs([{ ...lineBlock(0, [40]), section: 0, el }], slices, secs, geoms)
+ expect(live[0].widthPx).toBeCloseTo(L - 30, 3)
+ const captured = verticalTextSpecs(
+ [{ ...lineBlock(0, [40]), section: 0, el, inlineExtraPx: 12 }],
+ slices,
+ secs,
+ geoms,
+ )
+ expect(captured[0].widthPx).toBeCloseTo(L - 12, 3)
+ })
+
+ it('a page filled past the body height keeps a body-height footprint; btLr fills from the left', () => {
+ const els = Array.from({ length: 2 }, () => document.createElement('p'))
+ const secs = [vert({ textDirection: 'btLr' })]
+ const geoms = sectionGeoms(secs)
+ const L = geoms[0].contentWidth!
+ const blocks: BlockBox[] = [
+ { ...lineBlock(0, [700]), section: 0, el: els[0] },
+ { ...lineBlock(700, [100]), section: 0, el: els[1] },
+ ]
+ const specs = verticalTextSpecs(blocks, [{ start: 0, end: 800, section: 0 }], secs, geoms)
+ expect(specs[0].dx).toBe(0)
+ expect(specs[1].dx).toBe(700)
+ expect(specs[1].vertical!.marginBottomPx).toBeCloseTo(L - 700 - L, 3)
+ expect(specs[0].vertical!.mode).toBe('btLr')
+ })
+
+ it('vAlign shifts skip vertical-text pages (their contentHeight is the sideways fill)', () => {
+ const el = document.createElement('p')
+ const secs = [vert({ vAlign: 'center' })]
+ const blocks: BlockBox[] = [{ ...lineBlock(0, [40]), section: 0, el }]
+ expect(
+ vAlignShiftSpecs(blocks, [{ start: 0, end: 40, section: 0 }], secs, sectionGeoms(secs)),
+ ).toEqual([])
+ })
+
+ it('horizontal sections and region pages get no vertical specs', () => {
+ const el = document.createElement('p')
+ const blocks: BlockBox[] = [{ ...lineBlock(0, [40]), section: 0, el }]
+ expect(
+ verticalTextSpecs(
+ blocks,
+ [{ start: 0, end: 40, section: 0 }],
+ [sec({})],
+ sectionGeoms([sec({})]),
+ ),
+ ).toEqual([])
+ })
+
+ it('verticalPageCss hides gap chrome siblings and reveals only the blocks on each page', () => {
+ const mk = (idx: number, vert: boolean) => {
+ const el = document.createElement('p')
+ el.dataset.idx = String(idx)
+ if (vert) el.classList.add('doc-vert-block')
+ return el
+ }
+ const blocks: BlockBox[] = [
+ { ...lineBlock(0, [40]), section: 0, el: mk(0, true) },
+ { ...lineBlock(40, [60]), section: 0, el: mk(1, false) },
+ { ...lineBlock(100, [30]), section: 0, el: mk(2, true) },
+ ]
+ const slices: PageSlice[] = [
+ { start: 0, end: 100, section: 0 },
+ { start: 100, end: 130, section: 0 },
+ ]
+ const secs = [vert()]
+ const rules = verticalPageCss(blocks, slices, secs, sectionGeoms(secs)).split('\n')
+ const hide = (i: number) =>
+ `.pv-page[data-pv-page="${i}"] .pv-content > [data-idx],` +
+ `.pv-page[data-pv-page="${i}"] .pv-content > :is([class*="page-gap"],.page-float-host){visibility:hidden;}`
+ expect(rules[0]).toBe(hide(0))
+ expect(rules[1]).toMatch(
+ /^\.pv-page\[data-pv-page="0"\] \.pv-content > \[data-idx="0"\]\{visibility:visible;--pv-vdx:/,
+ )
+ expect(rules[2]).toBe(
+ '.pv-page[data-pv-page="0"] .pv-content > [data-idx="1"]{visibility:visible;}',
+ )
+ expect(rules[3]).toBe(hide(1))
+ expect(rules[4]).toMatch(
+ /^\.pv-page\[data-pv-page="1"\] \.pv-content > \[data-idx="2"\]\{visibility:visible;--pv-vdx:/,
+ )
+ expect(rules).toHaveLength(5)
+ })
+})
diff --git a/apps/docs/tests/para-border-reset.test.ts b/apps/docs/tests/para-border-reset.test.ts
index 54c0cab..594d853 100644
--- a/apps/docs/tests/para-border-reset.test.ts
+++ b/apps/docs/tests/para-border-reset.test.ts
@@ -22,12 +22,33 @@ function paraStyle(attrs: Record): CSSStyleDeclaration {
return style
}
+function listItemStyle(attrs: Record): CSSStyleDeclaration {
+ const editor = new Editor({
+ element: document.createElement('div'),
+ extensions: editorExtensions,
+ content: {
+ type: 'doc',
+ content: [
+ {
+ type: 'docListItem',
+ attrs: { docxIndex: null, kind: 'bullet', ilvl: 0, ...attrs },
+ content: [{ type: 'text', text: 'x' }],
+ },
+ ],
+ },
+ })
+ const style = editor.view.dom.querySelector('.doc-li')!.style
+ editor.destroy()
+ return style
+}
+
describe('direct w:pBdr none over a style border', () => {
it('emits an inline border-none for the reset sides only', () => {
const style = paraStyle({ styleId: 'HDR', borderReset: 'b' })
expect(style.borderBottomStyle).toBe('none')
expect(style.borderTopStyle).toBe('')
- expect(style.padding).toBe('')
+ expect(style.paddingBottom).toBe('0px')
+ expect(style.paddingTop).toBe('')
})
it('keeps drawn sides next to reset ones', () => {
@@ -35,6 +56,34 @@ describe('direct w:pBdr none over a style border', () => {
expect(style.borderTopStyle).toBe('solid')
expect(style.borderTopWidth).toBe('1px')
expect(style.borderBottomStyle).toBe('none')
- expect(style.padding).toBe('1px 4px')
+ expect(style.paddingTop).toBe('0px')
+ // the reset side also drops the style-level w:space gap
+ expect(style.paddingBottom).toBe('0px')
+ expect(style.paddingLeft).toBe('')
+ })
+
+ it('a reset left/right side drops the style inset on a paragraph', () => {
+ const style = paraStyle({ borderReset: 'lr' })
+ expect(style.borderLeftStyle).toBe('none')
+ expect(style.paddingLeft).toBe('0px')
+ expect(style.paddingRight).toBe('0px')
+ })
+
+ it('a list item keeps its indent padding when a left/right side is reset', () => {
+ const style = listItemStyle({ borderReset: 'lr' })
+ expect(style.borderLeftStyle).toBe('none')
+ expect(style.paddingLeft).toBe('')
+ expect(style.paddingRight).toBe('')
+ })
+
+ it('pads drawn top/bottom sides by their w:space, left/right by the text inset', () => {
+ const style = paraStyle({
+ borders: 'bl',
+ borderLines: JSON.stringify({ b: { color: '4F81BD', szPt: 1, spacePt: 4 } }),
+ })
+ expect(style.paddingTop).toBe('')
+ expect(style.paddingBottom).toBe('4pt')
+ expect(style.paddingLeft).toBe('4px')
+ expect(style.paddingRight).toBe('')
})
})
diff --git a/apps/docs/tests/para-frame.test.ts b/apps/docs/tests/para-frame.test.ts
new file mode 100644
index 0000000..ee67a84
--- /dev/null
+++ b/apps/docs/tests/para-frame.test.ts
@@ -0,0 +1,101 @@
+import { describe, expect, it } from 'vitest'
+import { Editor } from '@tiptap/core'
+import { editorExtensions } from '../src/renderer/editor/extensions'
+import { paraFrameCss, textFlowCss } from '../src/renderer/editor/para-frame'
+
+function paraEl(attrs: Record): HTMLParagraphElement {
+ const editor = new Editor({
+ element: document.createElement('div'),
+ extensions: editorExtensions,
+ content: {
+ type: 'doc',
+ content: [
+ {
+ type: 'docParagraph',
+ attrs: { docxIndex: null, ...attrs },
+ content: [{ type: 'text', text: 'x' }],
+ },
+ ],
+ },
+ })
+ const p = editor.view.dom.querySelector('p')!.cloneNode(true) as HTMLParagraphElement
+ editor.destroy()
+ return p
+}
+
+describe('w:framePr paragraph frames', () => {
+ it('a page-anchored wrap-around frame floats at its x minus the section margin', () => {
+ const frame = {
+ wTwips: 2851,
+ hTwips: 3241,
+ hRule: 'atLeast',
+ xTwips: 1816,
+ yTwips: 299,
+ vAnchor: 'text',
+ wrap: 'around',
+ hSpaceTwips: 180,
+ }
+ const p = paraEl({ frame: JSON.stringify(frame), textDirection: 'tbRl' })
+ expect(p.classList.contains('doc-para-frame')).toBe(true)
+ expect(p.classList.contains('doc-para-frame-float')).toBe(true)
+ expect(p.style.width).toBe('142.55pt')
+ expect(p.style.height).toBe('162.05pt')
+ expect(p.style.minHeight).toBe('')
+ expect(p.style.cssFloat).toBe('left')
+ expect(p.style.marginLeft).toBe('calc(90.80pt - var(--doc-margin-left, 0px))')
+ expect(p.style.marginRight).toBe('9pt')
+ expect(p.style.marginTop).toBe('14.95pt')
+ expect(p.style.writingMode).toBe('vertical-rl')
+ })
+
+ it('a tight-wrap frame floats like an around-wrap one', () => {
+ const p = paraEl({
+ frame: JSON.stringify({ wTwips: 1200, xTwips: 0, yTwips: 0, wrap: 'tight', xAlign: 'right' }),
+ })
+ expect(p.classList.contains('doc-para-frame-float')).toBe(true)
+ expect(p.style.cssFloat).toBe('right')
+ })
+
+ it('exact height clips; notBeside frames stay in flow', () => {
+ const { classes, styles } = paraFrameCss(
+ {
+ wTwips: 1200,
+ hTwips: 600,
+ hRule: 'exact',
+ xTwips: 0,
+ yTwips: 0,
+ wrap: 'notBeside',
+ xAlign: 'right',
+ },
+ null,
+ )
+ expect(classes).toEqual(['doc-para-frame'])
+ expect(styles).toContain('height:30.00pt')
+ expect(styles).toContain('overflow:hidden')
+ expect(styles.some((s) => s.startsWith('float:'))).toBe(false)
+ expect(styles.some((s) => s.startsWith('margin-left'))).toBe(false)
+ })
+
+ it('a centered wrap-around frame takes its own line instead of floating', () => {
+ const { classes, styles } = paraFrameCss(
+ { wTwips: 1200, xTwips: 0, yTwips: 0, wrap: 'around', xAlign: 'center' },
+ null,
+ )
+ expect(classes).toEqual(['doc-para-frame'])
+ expect(styles).toContain('margin-left:auto')
+ expect(styles.some((s) => s.startsWith('float:'))).toBe(false)
+ })
+
+ it('maps the three sideways flows to writing modes', () => {
+ expect(textFlowCss('tbRl')).toEqual(['writing-mode:vertical-rl'])
+ expect(textFlowCss('tbRlV')).toEqual(['writing-mode:vertical-rl', 'text-orientation:sideways'])
+ expect(textFlowCss('btLr')).toEqual(['writing-mode:sideways-lr'])
+ expect(textFlowCss(null)).toEqual([])
+ })
+
+ it('a paragraph without a frame carries no frame styling even with a text direction', () => {
+ const p = paraEl({ textDirection: 'tbRl' })
+ expect(p.classList.contains('doc-para-frame')).toBe(false)
+ expect(p.style.writingMode).toBe('')
+ })
+})
diff --git a/apps/docs/tests/paragraph-strut-size.test.ts b/apps/docs/tests/paragraph-strut-size.test.ts
index b3b0529..ec54780 100644
--- a/apps/docs/tests/paragraph-strut-size.test.ts
+++ b/apps/docs/tests/paragraph-strut-size.test.ts
@@ -68,4 +68,31 @@ describe('paragraph strut font-size from run sizes', () => {
expect(pFontSize(editor)).toBe('')
editor.destroy()
})
+
+ // Word probe 2026-09-11: space runs never size a line (a 2pt, 4pt or 17pt
+ // space paragraph measures exactly like an 11pt text line)
+ it('space-only runs do not size the strut', () => {
+ const editor = editorWith([
+ { type: 'docParagraph', content: [sized('text', 20), sized(' ', 40)] },
+ { type: 'docParagraph', content: [sized(' ', 8)] },
+ ])
+ expect(pFontSize(editor, 0)).toBe('10pt')
+ expect(pFontSize(editor, 1)).toBe('')
+ editor.destroy()
+ })
+
+ it('a space-only paragraph is sized by the mark like an empty one', () => {
+ const editor = editorWith([
+ { type: 'docParagraph', attrs: { emptyRunSize: 8 }, content: [sized(' ', 8)] },
+ { type: 'docParagraph', content: [sized(' ', 8)] },
+ ])
+ const [marked, plain] = Array.from(editor.view.dom.querySelectorAll('p')) as HTMLElement[]
+ expect(marked.style.fontSize).toBe('4pt')
+ expect(plain.style.fontSize).toBe('')
+ for (const p of [marked, plain]) {
+ expect(p.style.getPropertyValue('--doc-strut')).toBe('')
+ expect(p.style.getPropertyValue('--doc-line-factor')).toBe('var(--doc-line-factor-latin,1.2)')
+ }
+ editor.destroy()
+ })
})
diff --git a/apps/docs/tests/paste-options.test.ts b/apps/docs/tests/paste-options.test.ts
new file mode 100644
index 0000000..47db449
--- /dev/null
+++ b/apps/docs/tests/paste-options.test.ts
@@ -0,0 +1,434 @@
+/**
+ * Paste options for foreign HTML: the default-mode setting, the per-paste
+ * handshake shared by the paste entry points, and the merge-formatting
+ * transform (keep emphasis and structure, format text and paragraphs like
+ * typing at the insertion point).
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { Editor } from '@tiptap/core'
+import type { Mark, Node as PmNode } from '@tiptap/pm/model'
+import { DOMParser as PmDOMParser, Fragment, Slice as PmSlice } from '@tiptap/pm/model'
+import type { EditorState, Transaction } from '@tiptap/pm/state'
+import { TextSelection } from '@tiptap/pm/state'
+import { editorExtensions } from '../src/renderer/editor/extensions'
+import {
+ beginForeignPaste,
+ capturePasteRestore,
+ caretParaFormat,
+ caretStyleMark,
+ consumeForeignPaste,
+ defaultPasteMode,
+ forceNextPasteMode,
+ lastForeignPasteMode,
+ mergeFormattingFragment,
+ revertPaste,
+ setDefaultPasteMode,
+ stashPastePayload,
+ takePastePayload,
+ takeTextReroute,
+ type PasteMode,
+ type PasteRestore,
+} from '../src/renderer/editor/paste-options'
+import { pasteTextSlice } from '../src/renderer/editor/paste-text'
+import { isForeignPasteHtml } from '../src/renderer/editor/paste-web-html'
+
+class FakeClipboardEvent extends Event {
+ clipboardData = null
+}
+;(globalThis as Record).ClipboardEvent = FakeClipboardEvent
+
+const FOREIGN = `web text
`
+const INTERNAL = ``
+
+function makeEditor() {
+ return new Editor({
+ element: document.createElement('div'),
+ extensions: editorExtensions,
+ content: {
+ type: 'doc',
+ content: [
+ {
+ type: 'docParagraph',
+ attrs: { align: 'both', lineSpacing: 2, indentLeft: 240 },
+ content: [
+ {
+ type: 'text',
+ text: 'host',
+ marks: [{ type: 'docTextStyle', attrs: { font: 'Calibri', fontAscii: 'Calibri' } }],
+ },
+ ],
+ },
+ ],
+ },
+ })
+}
+
+beforeEach(() => {
+ localStorage.clear()
+ beginForeignPaste('') // reset the handshake between tests
+})
+
+describe('default paste mode setting', () => {
+ it('defaults to keep-source and persists changes', () => {
+ expect(defaultPasteMode()).toBe('source')
+ setDefaultPasteMode('merge')
+ expect(defaultPasteMode()).toBe('merge')
+ setDefaultPasteMode('source')
+ expect(defaultPasteMode()).toBe('source')
+ })
+
+ it('ignores garbage stored values', () => {
+ localStorage.setItem('aidocs.pasteFromOtherApps', 'banana')
+ expect(defaultPasteMode()).toBe('source')
+ })
+})
+
+describe('per-paste handshake', () => {
+ it('arms only for foreign HTML', () => {
+ expect(beginForeignPaste(FOREIGN)).toBe(true)
+ expect(consumeForeignPaste()).toBe('source')
+ expect(beginForeignPaste(INTERNAL)).toBe(false)
+ expect(consumeForeignPaste()).toBeNull()
+ expect(beginForeignPaste('')).toBe(false)
+ })
+
+ it('the armed mode follows the setting and a one-shot force wins once', () => {
+ setDefaultPasteMode('merge')
+ beginForeignPaste(FOREIGN)
+ expect(consumeForeignPaste()).toBe('merge')
+ forceNextPasteMode('text')
+ beginForeignPaste(FOREIGN)
+ expect(consumeForeignPaste()).toBe('text')
+ beginForeignPaste(FOREIGN)
+ expect(consumeForeignPaste()).toBe('merge')
+ })
+
+ it('text mode raises the reroute and records the consumed mode', () => {
+ forceNextPasteMode('text')
+ beginForeignPaste(FOREIGN)
+ expect(takeTextReroute()).toBe(false)
+ consumeForeignPaste()
+ expect(lastForeignPasteMode()).toBe('text')
+ expect(takeTextReroute()).toBe(true)
+ expect(takeTextReroute()).toBe(false)
+ })
+
+ it('a new paste clears the previous paste state', () => {
+ forceNextPasteMode('text')
+ beginForeignPaste(FOREIGN)
+ consumeForeignPaste()
+ beginForeignPaste(FOREIGN)
+ expect(lastForeignPasteMode()).toBeNull()
+ expect(takeTextReroute()).toBe(false)
+ })
+})
+
+describe('chip payload stash', () => {
+ it('stores prose payloads and consumes once', () => {
+ stashPastePayload({ html: FOREIGN, text: 'web text', mode: 'source' })
+ expect(takePastePayload()?.text).toBe('web text')
+ expect(takePastePayload()).toBeNull()
+ })
+
+ it('never stores image-only payloads', () => {
+ stashPastePayload({ html: ' ', text: '', mode: 'source' })
+ expect(takePastePayload()).toBeNull()
+ })
+})
+
+describe('mergeFormattingFragment', () => {
+ it('replaces run styles with the caret style, keeps emphasis, clones paragraph format', () => {
+ const editor = makeEditor()
+ const schema = editor.state.schema
+ const $host = editor.state.doc.resolve(2)
+ const style = caretStyleMark($host.marks(), schema)
+ const paraAttrs = caretParaFormat($host, schema)
+ expect(style?.attrs.font).toBe('Calibri')
+ expect(paraAttrs).toMatchObject({ align: 'both', lineSpacing: 2, indentLeft: 240 })
+
+ const arial = schema.marks.docTextStyle!.create({
+ font: 'Arial',
+ fontAscii: 'Arial',
+ sizeHalfPoints: 24,
+ color: '222222',
+ })
+ const bold = schema.marks.bold!.create()
+ const pasted = Fragment.from([
+ schema.nodes.docParagraph!.create(null, [
+ schema.text('plain ', [arial]),
+ schema.text('strong', [arial, bold]),
+ ]),
+ schema.nodes.docParagraph!.create(null, [schema.text('second', [arial])]),
+ ])
+
+ const merged = mergeFormattingFragment(pasted, schema, style, paraAttrs)
+ const runs: Array<{ text: string; marks: readonly Mark[] }> = []
+ const paras: PmNode[] = []
+ merged.forEach((node) => {
+ paras.push(node)
+ node.descendants((child) => {
+ if (child.isText) runs.push({ text: child.text ?? '', marks: child.marks })
+ return true
+ })
+ })
+ for (const para of paras) {
+ expect(para.attrs).toMatchObject({ align: 'both', lineSpacing: 2, indentLeft: 240 })
+ }
+ for (const run of runs) {
+ const docStyle = run.marks.find((mark) => mark.type.name === 'docTextStyle')
+ expect(docStyle?.attrs).toMatchObject({ font: 'Calibri', fontAscii: 'Calibri' })
+ expect(docStyle?.attrs.color).toBeNull()
+ }
+ expect(
+ runs.find((run) => run.text === 'strong')?.marks.some((mark) => mark.type.name === 'bold'),
+ ).toBe(true)
+ editor.destroy()
+ })
+
+ it('with no caret style the pasted text follows the document default', () => {
+ const editor = makeEditor()
+ const schema = editor.state.schema
+ const arial = schema.marks.docTextStyle!.create({ font: 'Arial', fontAscii: 'Arial' })
+ const pasted = Fragment.from(
+ schema.nodes.docParagraph!.create(null, [schema.text('web', [arial])]),
+ )
+ const merged = mergeFormattingFragment(pasted, schema, null, null)
+ let styleSeen = false
+ merged.forEach((node) =>
+ node.descendants((child) => {
+ if (child.isText && child.marks.some((mark) => mark.type.name === 'docTextStyle')) {
+ styleSeen = true
+ }
+ return true
+ }),
+ )
+ expect(styleSeen).toBe(false)
+ editor.destroy()
+ })
+})
+
+// ── chip re-apply: undo the paste, restore the insertion point, paste again ─
+
+const ARIAL_P = `web text
`
+const H1 = `Title `
+
+/** An editor with the two App paste lanes a mode change depends on: the
+ * transformPasted merge branch and the empty-paragraph wholesale lane
+ * (plus the text-mode reroute), all reading the current insertion point. */
+function makePasteEditor() {
+ return new Editor({
+ element: document.createElement('div'),
+ extensions: editorExtensions,
+ content: {
+ type: 'doc',
+ content: [
+ {
+ type: 'docParagraph',
+ content: [
+ {
+ type: 'text',
+ text: 'host',
+ marks: [{ type: 'docTextStyle', attrs: { font: 'Calibri', fontAscii: 'Calibri' } }],
+ },
+ ],
+ },
+ { type: 'docParagraph' },
+ ],
+ },
+ editorProps: {
+ transformPasted: (slice, view) => {
+ const mode = consumeForeignPaste()
+ if (mode !== 'merge') return slice
+ const schema = view.state.schema
+ const marks = view.state.storedMarks ?? view.state.selection.$from.marks()
+ return new PmSlice(
+ mergeFormattingFragment(
+ slice.content,
+ schema,
+ caretStyleMark(marks, schema),
+ caretParaFormat(view.state.selection.$from, schema),
+ ),
+ slice.openStart,
+ slice.openEnd,
+ )
+ },
+ handlePaste: (view, event) => {
+ const data = event.clipboardData!
+ const html = data.getData('text/html')
+ if (takeTextReroute()) {
+ const slice = pasteTextSlice(data.getData('text/plain'), view.state.selection.$from, view)
+ view.dispatch(view.state.tr.replaceSelection(slice))
+ return true
+ }
+ const { $from, empty } = view.state.selection
+ if (!(html && empty && $from.parent.isTextblock && $from.parent.content.size === 0)) {
+ return false
+ }
+ const dom = new window.DOMParser().parseFromString(html, 'text/html')
+ let content = PmDOMParser.fromSchema(view.state.schema).parse(dom.body).content
+ if (isForeignPasteHtml(html) && lastForeignPasteMode() === 'merge') {
+ const schema = view.state.schema
+ const marks = view.state.storedMarks ?? $from.marks()
+ content = mergeFormattingFragment(
+ content,
+ schema,
+ caretStyleMark(marks, schema),
+ caretParaFormat($from, schema),
+ )
+ }
+ view.dispatch(view.state.tr.replaceWith($from.before(1), $from.after(1), content))
+ return true
+ },
+ },
+ })
+}
+
+function fakePasteEvent(html: string, text: string): ClipboardEvent {
+ return {
+ clipboardData: { getData: (type: string) => (type === 'text/html' ? html : text) },
+ } as unknown as ClipboardEvent
+}
+
+/** The chip's handshake around a paste: remember the state the paste starts
+ * from, snapshot the restore when it lands. */
+function pasteWithRestore(editor: Editor, html: string, text: string, mode: PasteMode) {
+ let before: EditorState | null = null
+ let restore: PasteRestore | null = null
+ const onBefore = ({ transaction }: { transaction: Transaction }) => {
+ if (transaction.docChanged) before = editor.state
+ }
+ const onTransaction = ({
+ transaction,
+ appendedTransactions,
+ }: {
+ transaction: Transaction
+ appendedTransactions: Transaction[]
+ }) => {
+ if (transaction.docChanged && before) {
+ restore = capturePasteRestore(before, [transaction, ...appendedTransactions])
+ }
+ }
+ editor.on('beforeTransaction', onBefore)
+ editor.on('transaction', onTransaction)
+ forceNextPasteMode(mode)
+ beginForeignPaste(html)
+ editor.view.pasteHTML(html, fakePasteEvent(html, text))
+ editor.off('beforeTransaction', onBefore)
+ editor.off('transaction', onTransaction)
+ return restore!
+}
+
+function reapply(
+ editor: Editor,
+ restore: PasteRestore,
+ html: string,
+ text: string,
+ mode: PasteMode,
+) {
+ const revert = revertPaste(editor.state, restore)
+ expect(revert).not.toBeNull()
+ editor.view.dispatch(revert!)
+ return pasteWithRestore(editor, html, text, mode)
+}
+
+function caretIntoEmptyParagraph(editor: Editor) {
+ const calibri = editor.state.schema.marks.docTextStyle!.create({
+ font: 'Calibri',
+ fontAscii: 'Calibri',
+ })
+ const pos = editor.state.doc.content.size - 1
+ editor.view.dispatch(
+ editor.state.tr
+ .setSelection(TextSelection.create(editor.state.doc, pos))
+ .setStoredMarks([calibri]),
+ )
+}
+
+function runFonts(editor: Editor): string[] {
+ const out: string[] = []
+ editor.state.doc.descendants((node) => {
+ if (node.isText) {
+ const style = node.marks.find((mark) => mark.type.name === 'docTextStyle')
+ out.push(`${node.text}:${style?.attrs.font ?? '-'}`)
+ }
+ return true
+ })
+ return out
+}
+
+const blockTypes = (editor: Editor) =>
+ editor.state.doc.content.content.map((node) => node.type.name)
+
+describe('chip re-apply restores the insertion point', () => {
+ it('merge and text after a keep-source paste into an empty paragraph adopt the caret style', () => {
+ const editor = makePasteEditor()
+ caretIntoEmptyParagraph(editor)
+ const pre = editor.state.doc
+ let restore = pasteWithRestore(editor, ARIAL_P, 'web text', 'source')
+ expect(runFonts(editor)).toEqual(['host:Calibri', 'web text:Arial'])
+
+ restore = reapply(editor, restore, ARIAL_P, 'web text', 'merge')
+ expect(runFonts(editor)).toEqual(['host:Calibri', 'web text:Calibri'])
+
+ restore = reapply(editor, restore, ARIAL_P, 'web text', 'text')
+ expect(runFonts(editor)).toEqual(['host:Calibri', 'web text:Calibri'])
+
+ restore = reapply(editor, restore, ARIAL_P, 'web text', 'source')
+ expect(runFonts(editor)).toEqual(['host:Calibri', 'web text:Arial'])
+
+ const revert = revertPaste(editor.state, restore)!
+ expect(revert.doc.eq(pre)).toBe(true)
+ expect(revert.selection.empty).toBe(true)
+ expect(revert.selection.$from.parent.content.size).toBe(0)
+ editor.destroy()
+ })
+
+ it('a heading pasted onto an empty paragraph keeps the wholesale lane on every mode change', () => {
+ const editor = makePasteEditor()
+ caretIntoEmptyParagraph(editor)
+ let restore = pasteWithRestore(editor, H1, 'Title', 'text')
+ expect(blockTypes(editor)).toEqual(['docParagraph', 'docParagraph'])
+
+ restore = reapply(editor, restore, H1, 'Title', 'source')
+ expect(blockTypes(editor)).toEqual(['docParagraph', 'docHeading'])
+ expect(runFonts(editor)).toEqual(['host:Calibri', 'Title:Arial'])
+
+ restore = reapply(editor, restore, H1, 'Title', 'text')
+ expect(blockTypes(editor)).toEqual(['docParagraph', 'docParagraph'])
+ expect(runFonts(editor)).toEqual(['host:Calibri', 'Title:Calibri'])
+
+ reapply(editor, restore, H1, 'Title', 'source')
+ expect(blockTypes(editor)).toEqual(['docParagraph', 'docHeading'])
+ editor.destroy()
+ })
+
+ it('a mode change is one undo step back to the original paste and is not tracked as a deletion', () => {
+ vi.useFakeTimers()
+ try {
+ const editor = makePasteEditor()
+ caretIntoEmptyParagraph(editor)
+ const restore = pasteWithRestore(editor, ARIAL_P, 'web text', 'source')
+ const afterPaste = editor.state.doc
+ vi.advanceTimersByTime(2000)
+ const revert = revertPaste(editor.state, restore)!
+ expect(revert.getMeta('trackIgnore')).toBe(true)
+ reapply(editor, restore, ARIAL_P, 'web text', 'merge')
+ expect(runFonts(editor)).toEqual(['host:Calibri', 'web text:Calibri'])
+ expect(editor.commands.undo()).toBe(true)
+ expect(editor.state.doc.eq(afterPaste)).toBe(true)
+ expect(runFonts(editor)).toEqual(['host:Calibri', 'web text:Arial'])
+ editor.destroy()
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it('revertPaste refuses a document the paste no longer fits', () => {
+ const editor = makePasteEditor()
+ caretIntoEmptyParagraph(editor)
+ const restore = pasteWithRestore(editor, ARIAL_P, 'web text', 'source')
+ editor.commands.setContent('replaced
')
+ expect(revertPaste(editor.state, restore)).toBeNull()
+ editor.destroy()
+ })
+})
diff --git a/apps/docs/tests/paste-single-cell.test.ts b/apps/docs/tests/paste-single-cell.test.ts
index 5e4d91a..349e742 100644
--- a/apps/docs/tests/paste-single-cell.test.ts
+++ b/apps/docs/tests/paste-single-cell.test.ts
@@ -37,8 +37,34 @@ describe('singleCellPasteText', () => {
expect(singleCellPasteText('')).toBe('a\nb')
})
- it('keeps the HTML lane for multi-cell tables', () => {
+ it('keeps the HTML lane for multi-COLUMN tables', () => {
expect(singleCellPasteText('')).toBeNull()
+ expect(
+ singleCellPasteText(''),
+ ).toBeNull()
+ })
+
+ it('turns a single COLUMN of plain cells into lines (r176 follow-up)', () => {
+ const univerColumn =
+ '' +
+ ' \n' +
+ 'Tuxedomoon, et la chanson ' +
+ 'zxczxcz<cx ' +
+ 'Richard Gotainer| ' +
+ 'Qu\'en dit Gros Naze ?
'
+ expect(singleCellPasteText(univerColumn)).toBe(
+ "Tuxedomoon, et la chanson\nzxczxcz {
+ expect(
+ singleCellPasteText(''),
+ ).toBeNull()
+ expect(
+ singleCellPasteText(''),
+ ).toBeNull()
})
it('keeps the HTML lane when prose accompanies the table', () => {
diff --git a/apps/docs/tests/paste-web-html.test.ts b/apps/docs/tests/paste-web-html.test.ts
new file mode 100644
index 0000000..f355fd9
--- /dev/null
+++ b/apps/docs/tests/paste-web-html.test.ts
@@ -0,0 +1,172 @@
+/**
+ * Web-HTML paste font handling (r181): whole-paragraph web copies carry the
+ * site's styles on BLOCK elements (the mark parser reads only spans), and
+ * generic-only family chains leave runs font-less — both pasted in the theme
+ * font instead of the surrounding text's font.
+ */
+import { Editor } from '@tiptap/core'
+import { DOMParser as PmDOMParser, Fragment } from '@tiptap/pm/model'
+import { describe, expect, it } from 'vitest'
+import { editorExtensions } from '../src/renderer/editor/extensions'
+import {
+ caretFontSlots,
+ fillMissingRunFonts,
+ isForeignPasteHtml,
+ pushDownWebInlineStyles,
+} from '../src/renderer/editor/paste-web-html'
+
+const makeEditor = () =>
+ new Editor({
+ element: document.createElement('div'),
+ extensions: editorExtensions,
+ content: { type: 'doc', content: [{ type: 'docParagraph' }] },
+ })
+
+const parseHtml = (editor: Editor, html: string) => {
+ const dom = new window.DOMParser().parseFromString(html, 'text/html')
+ return PmDOMParser.fromSchema(editor.schema).parse(dom.body)
+}
+
+const runStyles = (doc: ReturnType) => {
+ const runs: Array<{ text: string; attrs: Record | null }> = []
+ doc.descendants((node) => {
+ if (node.isText) {
+ const style = node.marks.find((m) => m.type.name === 'docTextStyle')
+ runs.push({ text: node.text ?? '', attrs: style ? style.attrs : null })
+ }
+ return true
+ })
+ return runs
+}
+
+describe('isForeignPasteHtml', () => {
+ it('treats browser fragments as foreign and our clipboard HTML as internal', () => {
+ expect(isForeignPasteHtml('x
')).toBe(true)
+ expect(isForeignPasteHtml('')).toBe(false)
+ expect(isForeignPasteHtml('x ')).toBe(false)
+ })
+})
+
+describe('pushDownWebInlineStyles', () => {
+ it('moves block-level font/size/color onto a span the mark parser reads', () => {
+ const editor = makeEditor()
+ const html = pushDownWebInlineStyles(
+ 'premier paragraphe
',
+ )
+ const runs = runStyles(parseHtml(editor, html))
+ expect(runs).toHaveLength(1)
+ expect(runs[0]!.attrs).toMatchObject({
+ font: 'Roboto',
+ fontAscii: 'Roboto',
+ sizeHalfPoints: 21,
+ color: '202122',
+ })
+ editor.destroy()
+ })
+
+ it('keeps an existing span’s own declarations and only fills the missing ones', () => {
+ const editor = makeEditor()
+ const html = pushDownWebInlineStyles(
+ 'cited
',
+ )
+ const runs = runStyles(parseHtml(editor, html))
+ expect(runs[0]!.attrs).toMatchObject({ font: 'Georgia', sizeHalfPoints: 21 })
+ editor.destroy()
+ })
+
+ it('reaches text in nested and shared spans', () => {
+ const editor = makeEditor()
+ const html = pushDownWebInlineStyles(
+ 'plainbold link
',
+ )
+ const runs = runStyles(parseHtml(editor, html))
+ expect(runs.map((r) => r.text)).toEqual(['plain', 'bold', 'link'])
+ for (const run of runs) expect(run.attrs).toMatchObject({ font: 'Roboto' })
+ expect(runs[2]!.attrs).toMatchObject({ color: '0000FF' })
+ editor.destroy()
+ })
+
+ it('leaves table subtrees alone', () => {
+ const html =
+ ''
+ expect(pushDownWebInlineStyles(html)).toBe(html)
+ })
+
+ it('returns the input unchanged when nothing declares pushdown styles', () => {
+ const html = 'bare text
'
+ expect(pushDownWebInlineStyles(html)).toBe(html)
+ })
+})
+
+describe('caretFontSlots + fillMissingRunFonts', () => {
+ it('fills font-less pasted runs with the caret font and keeps concrete fonts', () => {
+ const editor = makeEditor()
+ const schema = editor.schema
+ const markType = schema.marks.docTextStyle!
+ const caret = [markType.create({ font: 'Calibri', fontAscii: 'Calibri', color: 'FF0000' })]
+ const slots = caretFontSlots(caret, markType)
+ // only the font slots travel — the caret's color must not leak
+ expect(slots).toEqual({ font: 'Calibri', fontAscii: 'Calibri' })
+
+ const paragraph = schema.nodes.docParagraph!.create(null, [
+ schema.text('generic ', [markType.create({ color: '202122', sizeHalfPoints: 21 })]),
+ schema.text('roboto', [markType.create({ font: 'Roboto', fontAscii: 'Roboto' })]),
+ schema.text(' bare'),
+ ])
+ const filled = fillMissingRunFonts(Fragment.from(paragraph), slots!, schema)
+ const runs: Array | null> = []
+ filled.forEach((node) =>
+ node.descendants((child) => {
+ if (child.isText) {
+ const style = child.marks.find((m) => m.type === markType)
+ runs.push(style ? style.attrs : null)
+ }
+ return true
+ }),
+ )
+ // font-less run with other styling: gains the caret font, keeps its own attrs
+ expect(runs[0]).toMatchObject({
+ font: 'Calibri',
+ fontAscii: 'Calibri',
+ color: '202122',
+ sizeHalfPoints: 21,
+ })
+ // concrete source font is source formatting — untouched
+ expect(runs[1]).toMatchObject({ font: 'Roboto' })
+ expect((runs[1] as Record).color ?? null).toBeNull()
+ // completely unmarked text gains a font-only mark
+ expect(runs[2]).toMatchObject({ font: 'Calibri', fontAscii: 'Calibri' })
+ editor.destroy()
+ })
+
+ it('leaves table cell runs font-less like the pushdown does', () => {
+ const editor = makeEditor()
+ const schema = editor.schema
+ const markType = schema.marks.docTextStyle!
+ const table = parseHtml(
+ editor,
+ 'after
',
+ ).content
+ const filled = fillMissingRunFonts(table, { font: 'Calibri', fontAscii: 'Calibri' }, schema)
+ const fonts: Array = []
+ filled.forEach((node) =>
+ node.descendants((child) => {
+ if (child.isText) {
+ const style = child.marks.find((m) => m.type === markType)
+ fonts.push((style?.attrs.font as string | undefined) ?? null)
+ }
+ return true
+ }),
+ )
+ expect(fonts).toEqual([null, 'Calibri'])
+ editor.destroy()
+ })
+
+ it('returns null slots when the caret text has no explicit font', () => {
+ const editor = makeEditor()
+ const markType = editor.schema.marks.docTextStyle!
+ expect(caretFontSlots([], markType)).toBeNull()
+ expect(caretFontSlots([markType.create({ color: '202122' })], markType)).toBeNull()
+ editor.destroy()
+ })
+})
diff --git a/apps/docs/tests/picture-filter-frame-box.test.ts b/apps/docs/tests/picture-filter-frame-box.test.ts
new file mode 100644
index 0000000..9928399
--- /dev/null
+++ b/apps/docs/tests/picture-filter-frame-box.test.ts
@@ -0,0 +1,108 @@
+/**
+ * @vitest-environment jsdom
+ */
+import { Editor } from '@tiptap/core'
+import { parseDocx } from '@genoffice/docx-engine'
+import { describe, expect, it } from 'vitest'
+import {
+ buildDocx,
+ IMAGE_PARAGRAPH_XML,
+} from '../../../packages/docx-engine/tests/helpers/build-docx'
+import { blocksToPmDoc } from '../src/renderer/editor/convert'
+import { editorExtensions, pictureFilterCss } from '../src/renderer/editor/extensions'
+
+/** replay a CSS filter list the way the compositor does (clamped per function) */
+function applyFilters(css: string, x: number): number {
+ let v = x
+ for (const [, fn, arg] of css.matchAll(/(\w+)\(([\d.]+)\)/g)) {
+ const a = Number(arg)
+ if (fn === 'contrast') v = (v - 0.5) * a + 0.5
+ else if (fn === 'brightness') v = v * a
+ else if (fn !== 'grayscale') throw new Error(`unexpected filter ${fn}`)
+ v = Math.max(0, Math.min(1, v))
+ }
+ return v
+}
+
+/** Word's recolor: contrast (1 + c) about mid-grey, then the brightness offset */
+const word = (x: number, bright: number, contrastPct: number): number =>
+ Math.max(0, Math.min(1, (x - 0.5) * (1 + contrastPct / 100) + 0.5 + bright))
+
+async function openDoc(bodyXml: string) {
+ const parsed = await parseDocx(await buildDocx({ bodyXml, withImage: true }))
+ return new Editor({
+ element: document.createElement('div'),
+ extensions: editorExtensions,
+ content: blocksToPmDoc(parsed.blocks) as never,
+ })
+}
+
+describe('pictureFilterCss', () => {
+ it('reproduces the brightness/contrast line for positive and negative offsets', () => {
+ for (const [bright, contrast] of [
+ [0.4, 40],
+ [-0.3, 40],
+ [0.2, -50],
+ [-0.6, -20],
+ [0, 100],
+ [0.3, -100],
+ ]) {
+ const css = pictureFilterCss({ bright, contrast: contrast / 100 })
+ for (const x of [0, 0.1, 0.25, 0.5, 0.75, 0.9, 1]) {
+ expect(applyFilters(css, x), `b=${bright} c=${contrast} x=${x}`).toBeCloseTo(
+ word(x, bright, contrast),
+ 2,
+ )
+ }
+ }
+ })
+
+ it('maps grayscale and bi-level to a grayscale step around the threshold', () => {
+ expect(pictureFilterCss({ grayscale: true })).toBe('filter:grayscale(1)')
+ const css = pictureFilterCss({ biLevelThresh: 0.25 })
+ expect(css.startsWith('filter:grayscale(1)')).toBe(true)
+ expect(applyFilters(css, 0.2)).toBe(0)
+ expect(applyFilters(css, 0.3)).toBe(1)
+ expect(pictureFilterCss(null)).toBe('')
+ })
+
+ it('puts the filter on the rendered picture', async () => {
+ const editor = await openDoc(
+ IMAGE_PARAGRAPH_XML.replace(
+ ' ',
+ ' ',
+ ),
+ )
+ const img = editor.view.dom.querySelector('img.doc-protected-img') as HTMLElement
+ expect(img.style.filter).toMatch(/^contrast\([\d.]+\) brightness\([\d.]+\)$/)
+ editor.destroy()
+ })
+})
+
+describe('w:framePr frame box rendering', () => {
+ it('sizes the paragraph to the frame and floats it beside the following text', async () => {
+ const editor = await openDoc(
+ ' ' +
+ ' ' +
+ 'after ',
+ )
+ const p = editor.view.dom.querySelector('p') as HTMLElement
+ expect(p.style.width).toBe('72pt')
+ expect(p.style.minHeight).toBe('72pt')
+ expect(p.style.float).toBe('left')
+ expect(p.style.marginRight).toBe('9pt')
+ editor.destroy()
+ })
+
+ it('clips an exact-height frame like Word', async () => {
+ const editor = await openDoc(
+ ' ' +
+ 'framed ',
+ )
+ const p = editor.view.dom.querySelector('p') as HTMLElement
+ expect(p.style.height).toBe('15pt')
+ expect(p.style.overflow).toBe('hidden')
+ expect(p.style.float).toBe('')
+ editor.destroy()
+ })
+})
diff --git a/apps/docs/tests/plain-paste-para-format.test.ts b/apps/docs/tests/plain-paste-para-format.test.ts
new file mode 100644
index 0000000..0a4876e
--- /dev/null
+++ b/apps/docs/tests/plain-paste-para-format.test.ts
@@ -0,0 +1,99 @@
+/**
+ * Multi-line plain-text paste keeps the insertion paragraph's PARAGRAPH
+ * formatting on every created paragraph (Word Keep Text Only formats like
+ * typing Enter there). Only the first line merges into the destination
+ * paragraph, so lines 2+ landed as DEFAULT paragraphs and dropped the
+ * surrounding indent/line-spacing/alignment (alpha field report: multi-
+ * paragraph Ctrl+Shift+V applied the document paragraph format to the
+ * first paragraph only).
+ */
+import { describe, expect, it } from 'vitest'
+import { Editor } from '@tiptap/core'
+import { TextSelection } from '@tiptap/pm/state'
+import { editorExtensions } from '../src/renderer/editor/extensions'
+import { pasteTextSlice } from '../src/renderer/editor/paste-text'
+
+class FakeClipboardEvent extends Event {
+ clipboardData = null
+}
+;(globalThis as Record).ClipboardEvent = FakeClipboardEvent
+
+const PARA_FORMAT = {
+ align: 'both',
+ lineSpacing: 2,
+ indentLeft: 240,
+ indentFirstLine: 0,
+ styleId: 'Normal',
+}
+
+function makeEditor(paraAttrs: Record = PARA_FORMAT) {
+ return new Editor({
+ element: document.createElement('div'),
+ extensions: editorExtensions,
+ editorProps: {
+ clipboardTextParser: (text, $context, _plain, view) => pasteTextSlice(text, $context, view),
+ },
+ content: {
+ type: 'doc',
+ content: [
+ {
+ type: 'docParagraph',
+ attrs: paraAttrs,
+ content: [{ type: 'text', text: 'Existing paragraph text' }],
+ },
+ ],
+ },
+ })
+}
+
+const HOST_LEN = 'Existing paragraph text'.length
+
+function caretToEnd(editor: Editor) {
+ const { state, dispatch } = editor.view
+ dispatch(state.tr.setSelection(TextSelection.create(state.doc, 1 + HOST_LEN)))
+}
+
+const paraAttrs = (editor: Editor, index: number) => editor.state.doc.child(index).attrs
+
+describe('multi-line plain paste keeps the insertion paragraph format', () => {
+ it('every created paragraph clones the host paragraph formatting', () => {
+ const editor = makeEditor()
+ caretToEnd(editor)
+ editor.view.pasteText('first line\nsecond line\nthird line')
+ expect(editor.state.doc.childCount).toBe(3)
+ for (let i = 0; i < 3; i++) expect(paraAttrs(editor, i)).toMatchObject(PARA_FORMAT)
+ editor.destroy()
+ })
+
+ it('mid-paragraph paste formats the split tail like the host too', () => {
+ const editor = makeEditor()
+ const { state, dispatch } = editor.view
+ // caret between "Existing" and " paragraph text"
+ dispatch(state.tr.setSelection(TextSelection.create(state.doc, 1 + 'Existing'.length)))
+ editor.view.pasteText('alpha\nbeta')
+ expect(editor.state.doc.childCount).toBe(2)
+ expect(editor.state.doc.child(1).textContent).toBe('beta paragraph text')
+ expect(paraAttrs(editor, 0)).toMatchObject(PARA_FORMAT)
+ expect(paraAttrs(editor, 1)).toMatchObject(PARA_FORMAT)
+ editor.destroy()
+ })
+
+ it('identity attrs are never cloned onto created paragraphs', () => {
+ const editor = makeEditor({ ...PARA_FORMAT, docxIndex: 7 })
+ caretToEnd(editor)
+ editor.view.pasteText('one\ntwo')
+ expect(paraAttrs(editor, 0).docxIndex).toBe(7)
+ expect(paraAttrs(editor, 1).docxIndex).toBeNull()
+ expect(paraAttrs(editor, 1)).toMatchObject(PARA_FORMAT)
+ editor.destroy()
+ })
+
+ it('a default host paragraph still produces default paragraphs', () => {
+ const editor = makeEditor({})
+ caretToEnd(editor)
+ editor.view.pasteText('one\ntwo')
+ expect(paraAttrs(editor, 1).align).toBeNull()
+ expect(paraAttrs(editor, 1).lineSpacing).toBeNull()
+ editor.destroy()
+ })
+})
diff --git a/apps/docs/tests/pretty-printed-ppr-save.test.ts b/apps/docs/tests/pretty-printed-ppr-save.test.ts
new file mode 100644
index 0000000..d93c363
--- /dev/null
+++ b/apps/docs/tests/pretty-printed-ppr-save.test.ts
@@ -0,0 +1,95 @@
+import { describe, expect, it } from 'vitest'
+import { Editor } from '@tiptap/core'
+import JSZip from 'jszip'
+import { parseDocx, saveDocx } from '@genoffice/docx-engine'
+import { buildDocx } from '../../../packages/docx-engine/tests/helpers/build-docx'
+import { blocksToPmDoc, pmDocToSavePlan, type PmNode } from '../src/renderer/editor/convert'
+import { executeTool } from '../src/renderer/ai/tools'
+
+/**
+ * Third-party generators (PHPWord, docx4j...) pretty-print document.xml, so
+ * whitespace text nodes sit between and and between pPr children.
+ * The raw pPr passthrough must still find the pPr, or a text edit rebuilds it
+ * from the format model and drops keepNext/keepLines/widowControl and a
+ * mid-document w:sectPr (a continuous multicolumn section break).
+ */
+
+const NUM_IDS = { bullet: null, ordered: null }
+
+const HEADING_P =
+ '\n\t\t\t\n\t\t\t\t \n\t\t\t\t \n\t\t\t\t ' +
+ '\n\t\t\t\t ' +
+ '\n\t\t\t\t \n\t\t\t\t \n\t\t\t ' +
+ '\n\t\t\t\n\t\t\t\tFormatted paragraph text \n\t\t\t \n\t\t '
+
+const SECTION_P =
+ '\n\t\t\t\n\t\t\t\t\n\t\t\t\t\t ' +
+ '\n\t\t\t\t\t ' +
+ '\n\t\t\t\t\t ' +
+ '\n\t\t\t\t\t \n\t\t\t\t \n\t\t\t ' +
+ '\n\t\t\t\n\t\t\t\t \n\t\t\t\tMulticolumn section text \n\t\t\t \n\t\t '
+
+const PLAIN_P =
+ '\n\t\t\t\n\t\t\t\tPlain trailing text \n\t\t\t \n\t\t '
+
+const BODY = `\n\t\t${HEADING_P}\n\t\t${SECTION_P}\n\t\t${PLAIN_P}\n\t\t`
+
+async function roundTrip(ops: unknown[]) {
+ const { editorExtensions } = await import('../src/renderer/editor/extensions')
+ const parsed = await parseDocx(await buildDocx({ bodyXml: BODY }))
+ const editor = new Editor({
+ element: document.createElement('div'),
+ extensions: editorExtensions,
+ })
+ editor.commands.setContent(blocksToPmDoc(parsed.blocks) as never)
+ const exec = await executeTool(editor, { id: 't', name: 'apply_ops', input: { ops } }, NUM_IDS)
+ expect(exec.isError).toBeFalsy()
+ const plan = pmDocToSavePlan(editor.getJSON() as PmNode, parsed.blocks)
+ const saved = await saveDocx(parsed, plan.saveBlocks)
+ editor.destroy()
+ const zip = await JSZip.loadAsync(saved)
+ const xml = await zip.file('word/document.xml')!.async('string')
+ return { parsed, plan, xml }
+}
+
+const retype = (text: string) => ({
+ op: 'findReplace',
+ find: text,
+ replace: `${text}!`,
+ matchCase: true,
+})
+
+describe('pretty-printed pPr survives paragraph regeneration', () => {
+ it('parses the raw pPr despite whitespace after ', async () => {
+ const parsed = await parseDocx(await buildDocx({ bodyXml: BODY }))
+ expect(parsed.blocks[0].rawPPr).toContain(' ')
+ expect(parsed.blocks[1].type).toBe('paragraph')
+ expect(parsed.blocks[1].rawPPr).toContain('')
+ })
+
+ it('a text edit keeps keepNext/keepLines/widowControl and the mid-document sectPr', async () => {
+ const { plan, xml } = await roundTrip([
+ retype('Formatted paragraph text'),
+ retype('Multicolumn section text'),
+ ])
+ expect(plan.changedCount).toBe(2)
+ expect(xml).toContain('Multicolumn section text!')
+ expect(xml.match(/]/g)).toHaveLength(2)
+ expect(xml).toContain(' ')
+ expect(xml).toContain(' ')
+ expect(xml).toContain(' ')
+ expect(xml).toContain(' ')
+ })
+
+ it('a format edit merges into the pretty-printed pPr in schema order', async () => {
+ const { xml } = await roundTrip([
+ { op: 'setParagraphFormat', target: { blockIndexes: [0] }, align: 'center' },
+ ])
+ const pPr = /[\s\S]*?<\/w:pPr>/.exec(xml)![0]
+ const names = [...pPr.matchAll(/ ]/g)]
+ .map((m) => m[1])
+ .filter((n) => n !== 'pPr')
+ expect(names).toEqual(['keepNext', 'keepLines', 'widowControl', 'spacing', 'ind', 'jc'])
+ expect(pPr).toContain(' ')
+ })
+})
diff --git a/apps/docs/tests/ruler-tab-cycle.test.ts b/apps/docs/tests/ruler-tab-cycle.test.ts
index caab056..99675d4 100644
--- a/apps/docs/tests/ruler-tab-cycle.test.ts
+++ b/apps/docs/tests/ruler-tab-cycle.test.ts
@@ -1,9 +1,10 @@
+import type { Editor } from '@tiptap/core'
import type { TabStop } from '@genoffice/docx-engine'
import { act, createElement } from 'react'
import { createRoot } from 'react-dom/client'
import { beforeAll, describe, expect, it } from 'vitest'
-import { isRenderableTabStop, Ruler } from '../src/renderer/components/Ruler'
+import { directTabStops, isRenderableTabStop, Ruler } from '../src/renderer/components/Ruler'
beforeAll(() => {
Element.prototype.scrollTo ??= () => {}
@@ -15,12 +16,23 @@ const section = {
marginRight: 1440,
} as never
-function mountRuler(): { container: HTMLElement; cleanup: () => void } {
+/** editor stub: every paragraph query reports the given tab stops */
+function editorWith(stops: TabStop[]): Editor {
+ return {
+ isActive: () => false,
+ getAttributes: () => ({ tabStops: JSON.stringify(stops) }),
+ } as unknown as Editor
+}
+
+function mountRuler(editor: Editor | null = null): {
+ container: HTMLElement
+ cleanup: () => void
+} {
const container = document.createElement('div')
document.body.appendChild(container)
const root = createRoot(container)
act(() => {
- root.render(createElement(Ruler, { section, editor: null, onTabStopsChange: () => {} }))
+ root.render(createElement(Ruler, { section, editor, onTabStopsChange: () => {} }))
})
return {
container,
@@ -52,6 +64,36 @@ describe('ruler tab type cycle', () => {
})
})
+describe('default tab guides', () => {
+ const guides = (stops: TabStop[]) => {
+ const { container, cleanup } = mountRuler(editorWith(stops))
+ try {
+ return {
+ defaults: container.querySelectorAll('.ruler-tab-default').length,
+ custom: container.querySelectorAll('.ruler-tab').length,
+ }
+ } finally {
+ cleanup()
+ }
+ }
+
+ it('a clear-only set (last inherited stop deleted) still shows the default grid', () => {
+ expect(guides([{ pos: 709, val: 'clear' }])).toEqual({ defaults: 12, custom: 0 })
+ })
+
+ it('a real stop hides the default grid', () => {
+ expect(
+ guides([
+ { pos: 709, val: 'clear' },
+ { pos: 1440, val: 'left' },
+ ]),
+ ).toEqual({
+ defaults: 0,
+ custom: 1,
+ })
+ })
+})
+
describe('isRenderableTabStop', () => {
it('hides clear stops (they cancel inheritance, mark no position)', () => {
const stop = (val: TabStop['val']): TabStop => ({ pos: 100, val })
@@ -60,3 +102,39 @@ describe('isRenderableTabStop', () => {
expect(isRenderableTabStop(stop('bar'))).toBe(true)
})
})
+
+describe('directTabStops', () => {
+ const inherited = (pos: number): TabStop => ({ pos, val: 'left', inherited: true })
+
+ it('strips inherited from stops that stay, so the set is written out as direct', () => {
+ expect(directTabStops([inherited(709), { pos: 1440, val: 'right' }], [inherited(709)])).toEqual(
+ [{ pos: 709, val: 'left' }],
+ )
+ })
+
+ it('records a clear where an inherited stop was deleted', () => {
+ expect(directTabStops([inherited(709), inherited(5752)], [inherited(5752)])).toEqual([
+ { pos: 709, val: 'clear' },
+ { pos: 5752, val: 'left' },
+ ])
+ })
+
+ it('a moved inherited stop keeps a clear at its old position beside the new direct stop', () => {
+ expect(directTabStops([inherited(709)], [{ pos: 1500, val: 'left', inherited: true }])).toEqual(
+ [
+ { pos: 709, val: 'clear' },
+ { pos: 1500, val: 'left' },
+ ],
+ )
+ })
+
+ it('a direct stop landing on the inherited position needs no clear', () => {
+ expect(directTabStops([inherited(709)], [{ pos: 709, val: 'center' }])).toEqual([
+ { pos: 709, val: 'center' },
+ ])
+ })
+
+ it('deleting a direct stop records nothing', () => {
+ expect(directTabStops([{ pos: 709, val: 'left' }], [])).toEqual([])
+ })
+})
diff --git a/apps/docs/tests/run-border-render.test.ts b/apps/docs/tests/run-border-render.test.ts
new file mode 100644
index 0000000..5a9b56c
--- /dev/null
+++ b/apps/docs/tests/run-border-render.test.ts
@@ -0,0 +1,64 @@
+/** w:bdr character borders reach the docTextStyle span; identical adjacent runs share one box */
+import { Editor } from '@tiptap/core'
+import { parseDocx } from '@genoffice/docx-engine'
+import { describe, expect, it } from 'vitest'
+import { buildDocx } from '../../../packages/docx-engine/tests/helpers/build-docx'
+import { blocksToPmDoc, inlineToRuns, runsToInline } from '../src/renderer/editor/convert'
+import { editorExtensions } from '../src/renderer/editor/extensions'
+import { runBorderDecls } from '../src/renderer/editor/run-border'
+
+const BDR = ' '
+const run = (text: string, rPr = BDR) =>
+ ` ${rPr} ` +
+ `${text} `
+
+describe('run border rendering', () => {
+ it('draws one bordered span over adjacent runs with the same border', async () => {
+ const body =
+ '' +
+ 'answer ' +
+ run(' ') +
+ run('(') +
+ run('28') +
+ run(')') +
+ run(' ') +
+ ' here ' +
+ ' '
+ const parsed = await parseDocx(await buildDocx({ bodyXml: body }))
+ const editor = new Editor({
+ element: document.createElement('div'),
+ extensions: editorExtensions,
+ content: blocksToPmDoc(parsed.blocks) as never,
+ })
+ const boxed = Array.from(
+ editor.view.dom.querySelectorAll('span[style*="border:"]'),
+ )
+ expect(boxed.length).toBe(1)
+ expect(boxed[0].textContent).toBe(' (28) ')
+ expect(boxed[0].style.border).toBe('0.75pt solid rgb(0, 0, 0)')
+ expect(boxed[0].style.padding).toBe('1pt')
+ expect(boxed[0].style.getPropertyValue('--dk-b-t')).toBe('0.75pt solid #ffffff')
+ editor.destroy()
+ })
+
+ it('round-trips run.bdr through the mark', () => {
+ const bdr = { val: 'single', sz: 6, color: '000000', space: 1 }
+ const inline = runsToInline([{ text: 'x', bdr }])
+ const mark = inline[0].marks?.find((m) => m.type === 'docTextStyle')
+ expect(mark?.attrs?.bdr).toBe(JSON.stringify(bdr))
+ expect(inlineToRuns(inline)[0].bdr).toEqual(bdr)
+ })
+
+ it('maps Word border styles and the auto color', () => {
+ expect(runBorderDecls(JSON.stringify({ val: 'dashed', sz: 12 }))).toEqual([
+ 'border:1.5pt dashed currentColor',
+ ])
+ const decls = runBorderDecls(
+ JSON.stringify({ val: 'double', sz: 1, color: 'FF0000', space: 2 }),
+ )
+ expect(decls[0]).toBe('border:0.25pt double #FF0000')
+ expect(decls[1]).toBe('padding:2pt')
+ expect(decls.filter((d) => d.startsWith('--dk-b-')).length).toBe(4)
+ expect(runBorderDecls('not json')).toEqual([])
+ })
+})
diff --git a/apps/docs/tests/run-format-effects-render.test.ts b/apps/docs/tests/run-format-effects-render.test.ts
new file mode 100644
index 0000000..7502fce
--- /dev/null
+++ b/apps/docs/tests/run-format-effects-render.test.ts
@@ -0,0 +1,138 @@
+/** Rendering of legacy text effects, glow, w:w compression, distribute and the Hyperlink style. */
+import { Editor } from '@tiptap/core'
+import { DOMSerializer } from '@tiptap/pm/model'
+import { parseDocx } from '@genoffice/docx-engine'
+import type { ParsedDocFull, StyleDisplay, StyleInfo } from '@genoffice/docx-engine'
+import { describe, expect, it } from 'vitest'
+import { buildDocx } from '../../../packages/docx-engine/tests/helpers/build-docx'
+import { docStyleCss } from '../src/renderer/doc-style-css'
+import { blocksToPmDoc } from '../src/renderer/editor/convert'
+import { editorExtensions } from '../src/renderer/editor/extensions'
+import { renderFieldSpec } from '../src/renderer/editor/protected-render'
+import {
+ charScaleXDecls,
+ glowDecl,
+ textAlignDecl,
+ textEffectDecls,
+} from '../src/renderer/editor/text-effects'
+
+;(globalThis as { CSS?: unknown }).CSS ??= { escape: (s: string) => s }
+
+function parsedWith(
+ styleId: string,
+ type: StyleInfo['type'],
+ display: StyleDisplay,
+): ParsedDocFull {
+ const styles = new Map()
+ styles.set(styleId, { styleId, name: styleId, type, display } as StyleInfo)
+ return { styles, docDefaults: {}, blocks: [] } as unknown as ParsedDocFull
+}
+
+async function renderSpans(bodyXml: string): Promise {
+ const parsed = await parseDocx(await buildDocx({ bodyXml }))
+ const editor = new Editor({
+ element: document.createElement('div'),
+ extensions: editorExtensions,
+ content: blocksToPmDoc(parsed.blocks) as never,
+ })
+ const spans = [...editor.view.dom.querySelectorAll('p span')] as HTMLElement[]
+ editor.destroy()
+ return spans
+}
+
+describe('text effect declarations', () => {
+ it('hollows outline glyphs and paints engraved glyphs in the paper colour', () => {
+ expect(textEffectDecls('outline')).toEqual([
+ '-webkit-text-stroke:0.5px currentColor',
+ '-webkit-text-fill-color:transparent',
+ ])
+ expect(textEffectDecls('imprint')[0]).toBe('color:var(--docs-paper)')
+ expect(textEffectDecls('imprint')[1]).toContain('text-shadow:-1px -1px')
+ expect(textEffectDecls('emboss')[1]).toContain('text-shadow:1px 1px')
+ })
+
+ it('maps glow to a blurred shadow with alpha', () => {
+ expect(glowDecl({ color: 'FF0000', radiusPt: 8, alpha: 0.6 })).toBe(
+ 'text-shadow:0 0 4pt rgba(255,0,0,0.6),0 0 8pt rgba(255,0,0,0.6)',
+ )
+ })
+
+ it('compresses a whitespace-free run and gives the saved width back', () => {
+ expect(charScaleXDecls('{"s":0.33,"gapEm":-0.348}')).toEqual([
+ 'display:inline-block',
+ 'transform:scaleX(0.33)',
+ 'transform-origin:0 50%',
+ 'margin-right:-0.348em',
+ ])
+ expect(charScaleXDecls('nope')).toEqual([])
+ })
+
+ it('spreads every line of a distributed paragraph', () => {
+ expect(textAlignDecl('distribute')).toBe(
+ 'text-align:justify;text-align-last:justify;text-justify:distribute',
+ )
+ expect(textAlignDecl('right')).toBe('text-align:right')
+ })
+})
+
+describe('editor run rendering', () => {
+ it('engraved white text stays visible through its shadow', async () => {
+ const spans = await renderSpans(
+ 'engraved ',
+ )
+ const span = spans.find((s) => s.textContent === 'engraved')!
+ expect(span.style.color).toBe('var(--docs-paper)')
+ expect(span.style.textShadow).toBe('-1px -1px 0 var(--docs-paper-ink-mid)')
+ expect(span.getAttribute('style')).not.toContain('--dk-c')
+ })
+
+ it('scales a single glyph with w:w instead of letter-spacing it', async () => {
+ const spans = await renderSpans(
+ 'x ' +
+ 'two words ',
+ )
+ const single = spans.find((s) => s.textContent === 'x')!
+ expect(single.style.transform).toBe('scaleX(0.33)')
+ expect(single.style.marginRight).toBe('-0.348em')
+ expect(single.style.letterSpacing).toBe('')
+ const spaced = spans.find((s) => s.textContent === 'two words')!
+ expect(spaced.style.letterSpacing).not.toBe('')
+ expect(spaced.style.transform).toBe('')
+ })
+
+ it('lowers a run by its w:position', async () => {
+ const spans = await renderSpans(
+ 'low ',
+ )
+ expect(spans.find((s) => s.textContent === 'low')!.style.verticalAlign).toBe('-4pt')
+ })
+})
+
+describe('Hyperlink style rendering', () => {
+ it('lets a defined Hyperlink style beat the default link look', () => {
+ const css = docStyleCss(
+ parsedWith('Hyperlink', 'character', { color: '008000', underline: false }),
+ )
+ expect(css).toContain('[data-style="Hyperlink"] { color:#008000 }')
+ expect(css).toContain(
+ '.doc-link:has([data-style="Hyperlink"]) { color:inherit;text-decoration:none }',
+ )
+ expect(docStyleCss(parsedWith('Body', 'paragraph', { align: 'distribute' }))).toContain(
+ 'text-align-last:justify',
+ )
+ expect(docStyleCss(parsedWith('Body', 'paragraph', {}))).not.toContain('.doc-link:has')
+ })
+
+ it('carries the entry run style onto the TOC title', () => {
+ const dom = DOMSerializer.renderSpec(
+ document,
+ renderFieldSpec({
+ kind: 'tocLine',
+ left: 'H1',
+ right: '1',
+ runStyleId: 'Hyperlink',
+ }) as never,
+ ).dom as HTMLElement
+ expect(dom.querySelector('.doc-toc-title')?.getAttribute('data-style')).toBe('Hyperlink')
+ })
+})
diff --git a/apps/docs/tests/shading-auto-ink.test.ts b/apps/docs/tests/shading-auto-ink.test.ts
index fbc4f75..57811ae 100644
--- a/apps/docs/tests/shading-auto-ink.test.ts
+++ b/apps/docs/tests/shading-auto-ink.test.ts
@@ -141,11 +141,14 @@ describe('auto ink on dark shading', () => {
const light = '--docs-paper-ink:#fff;color:var(--docs-paper-ink)'
const reset = '--docs-paper-ink:#000;color:var(--docs-paper-ink)'
const head = 'table[data-tbl-style="DarkHead"] tr:first-child'
- expect(css).toContain(`${head} td, .doc-page ${head} th { background:#1f1f1f;font-weight:600 }`)
+ // header-row formatting also reaches the leading w:tblHeader rows
+ const lead =
+ 'table[data-tbl-style="DarkHead"] tr[data-repeat-header="1"]:not(tr:not([data-repeat-header="1"]) ~ tr)'
+ const headCells = (cell: string): string =>
+ `${head} ${cell}, .doc-page ${head} ${cell.replace('td', 'th')}, .doc-page ${lead} ${cell}, .doc-page ${lead} ${cell.replace('td', 'th')}`
+ expect(css).toContain(`${headCells('td')} { background:#1f1f1f;font-weight:600 }`)
// cells with their own fill (data-ink) are left to that attribute: the nearest fill wins
- expect(css).toContain(
- `${head} td:not([data-ink]), .doc-page ${head} th:not([data-ink]) { ${light} }`,
- )
+ expect(css).toContain(`${headCells('td:not([data-ink])')} { ${light} }`)
expect(css).toContain(`.page-dark .doc-page ${head} td:not([data-ink])`)
expect(css).toContain(`--docs-paper-ink:${DARK_PAPER_HEX}`)
expect(css).toContain(`background:#d9d9d9 }`)
@@ -157,9 +160,7 @@ describe('auto ink on dark shading', () => {
`.doc-page :is([data-ink='light'] table, table[data-ink='light'])[data-tbl-style="DarkHead"] tr:nth-child(even) td:not([data-ink]) { ${reset} }`,
)
// light data-ink fills inside the style's dark cells (only those) take the paper ink back
- expect(css).toContain(
- `${head} td:not([data-ink]) [data-ink='dark'], .doc-page ${head} th:not([data-ink]) [data-ink='dark'] { ${reset} }`,
- )
+ expect(css).toContain(`${headCells("td:not([data-ink]) [data-ink='dark']")} { ${reset} }`)
expect(css).not.toContain(`table[data-tbl-style="DarkHead"] [data-ink='dark'] {`)
expect(css).toContain(`--docs-paper-ink:#ffffff`)
expect(css).toContain(`background:#1f1f1f;color:#ff0000 }`)
diff --git a/apps/docs/tests/sym-glyph-font.test.ts b/apps/docs/tests/sym-glyph-font.test.ts
new file mode 100644
index 0000000..7a4302a
--- /dev/null
+++ b/apps/docs/tests/sym-glyph-font.test.ts
@@ -0,0 +1,40 @@
+import { Editor } from '@tiptap/core'
+import { parseDocx } from '@genoffice/docx-engine'
+import { describe, expect, it } from 'vitest'
+import { buildDocx } from '../../../packages/docx-engine/tests/helpers/build-docx'
+import { blocksToPmDoc } from '../src/renderer/editor/convert'
+import { editorExtensions } from '../src/renderer/editor/extensions'
+
+async function htmlOf(bodyXml: string): Promise {
+ const parsed = await parseDocx(await buildDocx({ bodyXml }))
+ const host = document.createElement('div')
+ document.body.appendChild(host)
+ const editor = new Editor({
+ element: host,
+ extensions: editorExtensions,
+ content: blocksToPmDoc(parsed.blocks) as never,
+ })
+ const html = editor.getHTML()
+ editor.destroy()
+ host.remove()
+ return html
+}
+
+describe('w:sym glyph font', () => {
+ it('an undecoded private-use glyph renders in its symbol font, inside the run font span', async () => {
+ const html = await htmlOf(
+ ' ' +
+ 'a b ',
+ )
+ const sym = /]*data-sym-char="F0FF"[^>]*>/.exec(html)?.[0] ?? ''
+ expect(sym).toMatch(/font-family:\s*"Wingdings 2"/)
+ expect(html.indexOf('Calibri')).toBeLessThan(html.indexOf('data-sym-char'))
+ })
+
+ it('a glyph decoded to Unicode keeps the run font', async () => {
+ const html = await htmlOf(' ')
+ const sym = /]*data-sym-char="F0FC"[^>]*>/.exec(html)?.[0] ?? ''
+ expect(sym).not.toContain('style=')
+ expect(html).toContain('>\u2713<')
+ })
+})
diff --git a/apps/docs/tests/sym-run-save.test.ts b/apps/docs/tests/sym-run-save.test.ts
new file mode 100644
index 0000000..b433a65
--- /dev/null
+++ b/apps/docs/tests/sym-run-save.test.ts
@@ -0,0 +1,138 @@
+import { Editor } from '@tiptap/core'
+import { parseDocx, saveDocx } from '@genoffice/docx-engine'
+import JSZip from 'jszip'
+import { describe, expect, it } from 'vitest'
+import { buildDocx } from '../../../packages/docx-engine/tests/helpers/build-docx'
+import { executeOps } from '../src/renderer/ai/ops'
+import {
+ blocksToPmDoc,
+ inlineToRuns,
+ pmDocToSavePlan,
+ type PmNode,
+} from '../src/renderer/editor/convert'
+import { editorExtensions } from '../src/renderer/editor/extensions'
+
+// Word writes a Symbol-font glyph as its own run; regenerating the
+// paragraph from the editor used to flatten both into w:t text (the
+// private-use code point literally, the second one remapped to U+00D7).
+const MINUS = ' '
+const TIMES = ' '
+const SYM_PARA =
+ 'fee (91 ' +
+ MINUS +
+ ' 50 ' +
+ TIMES +
+ ' 0.2). '
+const OTHER_PARA = 'other '
+
+async function openDoc(bodyXml: string) {
+ const source = await buildDocx({ bodyXml })
+ const parsed = await parseDocx(source)
+ const host = document.createElement('div')
+ document.body.appendChild(host)
+ const editor = new Editor({
+ element: host,
+ extensions: editorExtensions,
+ content: blocksToPmDoc(parsed.blocks) as never,
+ })
+ return { source, parsed, editor, host }
+}
+
+async function documentXml(bytes: Uint8Array): Promise {
+ return (await JSZip.loadAsync(bytes)).file('word/document.xml')!.async('string')
+}
+
+describe('w:sym runs survive saving', () => {
+ it('parses each symbol as its own run with the display glyph', async () => {
+ const { parsed, editor, host } = await openDoc(SYM_PARA)
+ const runs = parsed.blocks[0].runs!
+ expect(runs.map((r) => r.sym ?? null)).toEqual([
+ null,
+ { font: 'Symbol', char: 'F02D' },
+ null,
+ { font: 'Symbol', char: 'F0B4' },
+ null,
+ ])
+ expect(runs[3]).toMatchObject({ text: '×', bold: true })
+ expect(editor.getText()).toBe('fee (91 − 50 × 0.2).')
+ editor.destroy()
+ host.remove()
+ })
+
+ it('keeps an untouched paragraph byte-exact', async () => {
+ const { source, parsed, editor, host } = await openDoc(SYM_PARA + OTHER_PARA)
+ const plan = pmDocToSavePlan(editor.getJSON() as PmNode, parsed.blocks)
+ expect(plan.changedCount).toBe(0)
+ expect(await saveDocx(parsed, plan.saveBlocks)).toEqual(source)
+ editor.destroy()
+ host.remove()
+ })
+
+ it('regenerates both w:sym elements after a text edit in the same paragraph', async () => {
+ const { parsed, editor, host } = await openDoc(SYM_PARA + OTHER_PARA)
+ const outcome = executeOps(editor, [
+ { op: 'findReplace', find: '0.2).', replace: '0.2).[EE12]' },
+ ])
+ expect(outcome.ok).toBe(true)
+ const plan = pmDocToSavePlan(editor.getJSON() as PmNode, parsed.blocks)
+ expect(plan.changedCount).toBe(1)
+ const xml = await documentXml(await saveDocx(parsed, plan.saveBlocks))
+ expect(xml).toContain(MINUS)
+ expect(xml).toContain(TIMES)
+ expect(xml.match(/<\/w:r> <\/w:rPr>')
+ expect(xml).not.toMatch(/[-×]/)
+ editor.destroy()
+ host.remove()
+ })
+
+ it('splits text appended under the symbol mark into one w:sym plus plain w:t', async () => {
+ const { parsed, editor, host } = await openDoc(SYM_PARA)
+ const outcome = executeOps(editor, [
+ { op: 'findReplace', find: '\u00d7', replace: '\u00d7\u00d7yz' },
+ ])
+ expect(outcome.ok).toBe(true)
+ const plan = pmDocToSavePlan(editor.getJSON() as PmNode, parsed.blocks)
+ const xml = await documentXml(await saveDocx(parsed, plan.saveBlocks))
+ expect(xml.match(/