Sync snapshot (2026-09-17) (#463)

- MCP over HTTP: `genoffice mcp --http` serves the tool set as a Streamable HTTP server for clients on other machines, with file upload, URL inputs and result files handed back; MCP agents can also read PDF text, edit the open document and drive the visible Sheets grid
- Docs: picture-heavy documents open lazily with media served from disk (gigabyte files in seconds), files over 512 MB are refused with a message instead of a crash, long documents open and type faster, and many Word-fidelity fixes for tables (autofit width, split rows, header-row keep, page-edge borders), anchored pictures and text boxes, header/footer spacing, chart labels and EMF+ clipping, Japanese font substitution, italic and bidi runs
- Markdown: saving keeps unchanged blocks byte-for-byte and re-serializes edited blocks in the document's own conventions (plus an opt-in unchanged-source round trip); ```wavedrom fences render as timing diagrams
- Sheets: smooth scrolling, duplicate and large-range copy on big streamed workbooks; context-menu submenus reopen reliably; AI bulk-job economy rules
- App: Help → Check for Updates and an About-dialog button; the in-editor Files pane and floating Files / Outline edge tabs are removed from all editors; AI panel can dock on either side
- AI providers: DeepSeek V4.1 Flash, gpt-6-astra and Opper added, retired ids dropped, clearer error when a tool call's arguments are too large
- PPTX: chart categories honor the 1904 date system, slide text extracts in presentation order, single-quoted attributes and case-insensitive preset colors parse; backports of public PRs #432–#461

Co-authored-by: GenOffice <merrick-2002@users.noreply.github.com>
This commit is contained in:
merrick-2002
2026-09-17 21:30:17 +08:00
committed by GitHub
co-authored by GenOffice
parent 2289469bdc
commit 80d2a4651e
259 changed files with 10538 additions and 3555 deletions
+19
View File
@@ -321,6 +321,7 @@ give one. There are two ways in, both shown with copy-ready snippets in
| ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **A · `genoffice mcp`** (recommended) | A stdio server the assistant starts itself; GenOffice does not need to be open. One tool per command (`info`, `convert`, `create_docx`, `create_xlsx`, `create_pptx`, `create_pdf`, `docs_read` / `docs_apply` / `docs_check`, `sheet_*`, `slides_*`, `render`, `guide`, `search`, `image`, `media`, `open`) plus the staged deck flow `deck_start` → `deck_page` → `deck_build` → `deck_replace`. Ops, specs and Markdown are passed inline, so a client without a file system still works. |
| **B · Local HTTP server** | Runs inside the GenOffice app on `http://127.0.0.1:3093/mcp` (Streamable HTTP, with legacy SSE). Its tools drive a visible Word editor tab: `create_session`, `insert_content`, `replace_blocks`, `apply_ops`, `read_document`, `save_session`, and you watch the document take shape. Off by default; switch it on in the same settings pane. |
| **C · `genoffice mcp --http`** | The stdio tool set as a Streamable HTTP server for clients on other machines: a container, a sandbox, a shared box on your network. Files travel with the calls: `PUT /files/<name>` uploads one and returns a URL, every `file` parameter takes an http(s) URL, and a tool that writes a file hands it back as a download URL plus, when small, the bytes as an MCP resource. `--host 0.0.0.0` opens it to the network, `--token` protects it. |
```bash
# Claude Code
@@ -332,6 +333,24 @@ claude mcp add --transport stdio genoffice -- genoffice mcp
{ "mcpServers": { "genoffice": { "command": "genoffice", "args": ["mcp"] } } }
```
```bash
# On the machine that has GenOffice (private network; add --token for a shared box)
genoffice mcp --http 3093 --host 0.0.0.0 --token "$GENOFFICE_MCP_TOKEN"
# From the client: upload, then use the URL wherever a tool takes a file
curl -T report.docx -H "Authorization: Bearer $GENOFFICE_MCP_TOKEN" http://server:3093/files/
# → { "url": "http://server:3093/files/<id>/report.docx", ... }
# docs_read({ "file": "http://server:3093/files/<id>/report.docx" })
# docs_apply(...) → output_url, downloadable with curl -o
```
Over HTTP every session gets a private scratch folder, relative paths and deck
folders resolve inside it, `open` is not offered, and with
`GENOFFICE_ALLOWED_ROOTS` unset the tools cannot leave the server's own file
store. `render`, `convert` to PDF and `create_pdf` still start a hidden
GenOffice process, so a headless host needs the app installed and a virtual
display (`xvfb-run`).
`genoffice` here is the CLI shipped inside the app (on macOS
`/Applications/GenOffice.app/Contents/Resources/cli/genoffice`; the settings
pane prints the exact path for your install). The server carries its own
+11 -1
View File
@@ -6,6 +6,14 @@ import { defineConfig, externalizeDepsPlugin } from 'electron-vite'
// node_modules is a symlink into the main checkout, so bare specifiers would
// silently bundle the other checkout's (possibly stale) code.
const localAlias = {
'@genoffice/docx-engine/lazy-media': resolve(
__dirname,
'../../packages/docx-engine/src/lazy-media.ts',
),
'@genoffice/docx-engine/zip-splice': resolve(
__dirname,
'../../packages/docx-engine/src/zip-splice.ts',
),
'@genoffice/docx-engine': resolve(__dirname, '../../packages/docx-engine/src/index.ts'),
}
@@ -17,7 +25,9 @@ export default defineConfig({
// (same setup as apps/slides).
main: {
plugins: [
externalizeDepsPlugin({ exclude: ['@genoffice/electron-utils', '@genoffice/font-metrics'] }),
externalizeDepsPlugin({
exclude: ['@genoffice/docx-engine', '@genoffice/electron-utils', '@genoffice/font-metrics'],
}),
],
resolve: { alias: localAlias },
},
+133 -33
View File
@@ -34,6 +34,7 @@ import {
nativeImage,
net,
shell,
webContents,
} from 'electron'
import {
appMenuLabels,
@@ -51,6 +52,7 @@ import {
showOpenDialogWithMemory,
showSaveDialogWithMemory,
aboutMenuItem,
checkUpdatesMenuItem,
toggleDevToolsItem,
windowMenuTemplate,
type HeadlessExportFormat,
@@ -123,6 +125,15 @@ import type {
import { ATTACHMENT_IMAGE_EXTS } from '../shared/ipc'
import { findDocxPath } from '../shared/open-file'
import { atomicWriteFile, looksLikeZip } from './atomic-write'
import {
adoptLazyMediaHashes,
forgetLazyMediaOwner,
materializeLazyDocx,
openLazyDocx,
pointLazyMediaAt,
readLazyMedia,
registerLazyMediaProtocol,
} from './lazy-media'
import {
commitDocPasswordSave,
currentDocPasswordIntentRevision,
@@ -2385,14 +2396,14 @@ export function removeStarredFiles(filePaths: string[]): void {
// ---- original archive (pass-through base: original file archived by content hash) ----
async function archiveOriginal(filePath: string, bytes: Buffer): Promise<string> {
const hash = sha256Hex(bytes)
async function archiveOriginal(filePath: string, hash: string, size: number): Promise<void> {
// a copy larger than the whole cap would only evict every other original
if (size > ORIGINALS_MAX_BYTES) return
const dir = userDataPath('originals')
await mkdir(dir, { recursive: true })
const target = join(dir, `${hash}.docx`)
if (!existsSync(target)) await copyFile(filePath, target)
void pruneOriginals(dir)
return hash
}
const ORIGINALS_MAX_BYTES = 500 * 1024 * 1024
@@ -2484,6 +2495,7 @@ function dropDocWriter(wcId: number): void {
imageExportTemps.delete(wcId)
imageExportDirs.delete(wcId)
docDiskStates.delete(wcId)
forgetLazyMediaOwner(wcId)
// Destroyed renderers count as torn down too: window-close paths never run
// teardownDocsRenderer, but an in-flight save handler resuming after the
// destruction must still fail its re-check (wcIds are never reused, so the
@@ -2497,11 +2509,11 @@ const docDiskStates = new Map<number, Map<string, DiskFileState>>()
const sha256Hex = (bytes: Buffer) => createHash('sha256').update(bytes).digest('hex')
async function rememberDiskState(wcId: number, filePath: string, bytes: Buffer): Promise<void> {
async function rememberDiskState(wcId: number, filePath: string, hash: string): Promise<void> {
try {
const s = await stat(filePath)
const states = docDiskStates.get(wcId) ?? new Map<string, DiskFileState>()
states.set(filePath, { mtimeMs: s.mtimeMs, size: s.size, hash: sha256Hex(bytes) })
states.set(filePath, { mtimeMs: s.mtimeMs, size: s.size, hash })
docDiskStates.set(wcId, states)
} catch {
/* unstatable target: skip tracking; the next save simply won't flag a conflict */
@@ -2530,6 +2542,7 @@ async function diskChangedExternally(wcId: number, filePath: string): Promise<bo
export function teardownDocsRenderer(contents: WebContents): void {
teardownZoteroIpc(contents)
tornDownWcIds.add(contents.id)
forgetLazyMediaOwner(contents.id)
// Sweep recovery copies for this renderer's documents: every non-crash close
// either saved (docs:save already cleared it) or explicitly discarded, so a
// copy still on disk here is a leftover from an in-flight recovery write.
@@ -2611,6 +2624,17 @@ async function maybeRecoverDocBytes(
return { bytes: original, recovered: false }
}
// Word's own .docx ceiling; past ~1 GB the IPC reply serializer doubles its buffer beyond the allocator's map limit and crashes the main process
const MAX_OPEN_BYTES = 512 * 1024 * 1024
async function showOpenError(wcId: number, detail: string): Promise<void> {
const wc = webContents.fromId(wcId)
const parent = docsShellWindow ?? (wc && BrowserWindow.fromWebContents(wc)) ?? mainWindow
const options = { type: 'error' as const, message: tm('dlgOpenDoc'), detail }
if (parent && !parent.isDestroyed()) await dialog.showMessageBox(parent, options)
else await dialog.showMessageBox(options)
}
async function loadDocx(
filePath: string,
wcId: number,
@@ -2618,7 +2642,14 @@ async function loadDocx(
): Promise<OpenDocxResult> {
if (typeof filePath !== 'string' || !/\.docx$/i.test(filePath)) return null
if (!existsSync(filePath)) return null
const original = await readFile(filePath)
const size = (await stat(filePath)).size
const lazy = await openLazyDocx(filePath, wcId)
if ((lazy?.bytes.length ?? size) > MAX_OPEN_BYTES) {
const mb = MAX_OPEN_BYTES / 1024 / 1024
await showOpenError(wcId, `${basename(filePath)}: ${tm('errTooLarge', { mb })}`)
return null
}
const original = lazy?.bytes ?? (await readFile(filePath))
// Password-protected docx (ECMA-376 CFB container): without a password, hand
// back a marker — the renderer prompts and retries via docs:open-decrypt.
// No side effects (recents/write grant) until the password checks out.
@@ -2634,7 +2665,8 @@ async function loadDocx(
}
// the archive keeps the on-disk original as-is (encrypted ones included: they
// reopen with the user's password), so a bad save never loses the source file
const hash = await archiveOriginal(filePath, original)
const hash = lazy?.hash ?? sha256Hex(original)
await archiveOriginal(filePath, hash, size)
const recovery = await maybeRecoverDocBytes(filePath, plainBytes)
let bytes = recovery.bytes
let recovered = recovery.recovered
@@ -2648,12 +2680,13 @@ async function loadDocx(
recovered = false
}
}
if (recovered) await adoptLazyMediaHashes(bytes, filePath, wcId)
pushRecent(filePath)
allowDocWrite(wcId, filePath)
if (fileOpenedHook) fileOpenedHook(wcId, filePath)
markDiskEncrypted(wcId, filePath, encrypted)
// record the on-disk file, not the recovery copy: what matters is what save would overwrite
await rememberDiskState(wcId, filePath, original)
await rememberDiskState(wcId, filePath, hash)
return {
path: filePath,
name: basename(filePath),
@@ -3240,9 +3273,26 @@ export function registerProjectIpc(): void {
const ALT_CHUNK_VIEWPORT = { width: 794, height: 1123, deviceScaleFactor: 2 }
const ALT_CHUNK_HTML_MAX_CHARS = 64 * 1024 * 1024
/** an encrypted save leaves no plain file to serve lazy pictures from: the
* renderer takes the materialized document back and leaves lazy mode */
const reissuedDoc = (
encrypted: boolean,
hashes: Set<string>,
plain: Buffer,
): { data?: ArrayBuffer } =>
encrypted && hashes.size > 0
? {
data: plain.buffer.slice(
plain.byteOffset,
plain.byteOffset + plain.byteLength,
) as ArrayBuffer,
}
: {}
/** document/attachment/window IPC (everything except the AI proxy above) */
export function registerDocsIpc(): void {
registerZoteroIpc()
void app.whenReady().then(registerLazyMediaProtocol)
// Node fetch (undici) direct connections get reset under VPN/tun setups; retry over Chromium's stack
setRescueFetch((url, init) => net.fetch(url, init))
setAiUserAgent(`GenOffice/${app.getVersion()}`)
@@ -3440,19 +3490,24 @@ export function registerDocsIpc(): void {
// Snapshot desired state: the disk password remains unchanged until the
// atomic write succeeds, and a newer ribbon intent survives this save.
const passwordState = snapshotDocPassword(event.sender.id, filePath)
const bytes = passwordState.password
? encryptDocx(Buffer.from(data), passwordState.password)
: Buffer.from(data)
const { bytes: plain, hashes } = await materializeLazyDocx(Buffer.from(data))
const bytes = passwordState.password ? encryptDocx(plain, passwordState.password) : plain
await atomicWriteFile(filePath, bytes)
// Teardown may have cleared all in-memory secrets while the atomic
// write was pending. Never resurrect state for an orphaned renderer.
if (tornDownWcIds.has(event.sender.id)) {
return { ok: false, error: 'save target is not an opened document' }
}
await rememberDiskState(event.sender.id, filePath, bytes)
await rememberDiskState(event.sender.id, filePath, sha256Hex(bytes))
if (tornDownWcIds.has(event.sender.id)) {
return { ok: false, error: 'save target is not an opened document' }
}
pointLazyMediaAt(
hashes,
filePath,
event.sender.id,
passwordState.password ? plain : undefined,
)
// Commit immediately after the final await: intents received during
// post-write bookkeeping are included, with no later async race.
const passwordIntentPending = commitDocPasswordSave(
@@ -3462,7 +3517,11 @@ export function registerDocsIpc(): void {
)
clearRecoveryCopy(filePath)
pushRecent(filePath)
return { ok: true, passwordIntentPending }
return {
ok: true,
passwordIntentPending,
...reissuedDoc(!!passwordState.password, hashes, plain),
}
} catch (err) {
return { ok: false, error: String(err) }
}
@@ -3561,13 +3620,18 @@ export function registerDocsIpc(): void {
event.sender.id,
typeof sourcePath === 'string' && sourcePath ? sourcePath : null,
)
const bytes = passwordState.password
? encryptDocx(Buffer.from(data), passwordState.password)
: Buffer.from(data)
const { bytes: plain, hashes } = await materializeLazyDocx(Buffer.from(data))
const bytes = passwordState.password ? encryptDocx(plain, passwordState.password) : plain
await atomicWriteFile(result.filePath, bytes)
if (tornDownWcIds.has(event.sender.id)) return { ok: false }
allowDocWrite(event.sender.id, result.filePath)
await rememberDiskState(event.sender.id, result.filePath, bytes)
await rememberDiskState(event.sender.id, result.filePath, sha256Hex(bytes))
pointLazyMediaAt(
hashes,
result.filePath,
event.sender.id,
passwordState.password ? plain : undefined,
)
if (tornDownWcIds.has(event.sender.id)) return { ok: false }
const passwordIntentPending = commitDocPasswordSave(
event.sender.id,
@@ -3576,7 +3640,12 @@ export function registerDocsIpc(): void {
)
pushRecent(result.filePath)
notifyFileSaved(event.sender, result.filePath)
return { ok: true, path: result.filePath, passwordIntentPending }
return {
ok: true,
path: result.filePath,
passwordIntentPending,
...reissuedDoc(!!passwordState.password, hashes, plain),
}
} catch (err) {
return { ok: false, error: String(err) }
}
@@ -3590,9 +3659,8 @@ export function registerDocsIpc(): void {
if (tornDownWcIds.has(event.sender.id)) return { ok: false }
const filePath = uniquePathIn(defaultSaveDir(), defaultName)
const passwordState = snapshotDocPassword(event.sender.id, null)
const bytes = passwordState.password
? encryptDocx(Buffer.from(data), passwordState.password)
: Buffer.from(data)
const { bytes: plain, hashes } = await materializeLazyDocx(Buffer.from(data))
const bytes = passwordState.password ? encryptDocx(plain, passwordState.password) : plain
await atomicWriteFile(filePath, bytes)
// teardown may have happened while the write was in flight — the path is
// freshly created, so rolling it back is safe (mirrors docs:write-recovery)
@@ -3601,7 +3669,13 @@ export function registerDocsIpc(): void {
return { ok: false }
}
allowDocWrite(event.sender.id, filePath)
await rememberDiskState(event.sender.id, filePath, bytes)
await rememberDiskState(event.sender.id, filePath, sha256Hex(bytes))
pointLazyMediaAt(
hashes,
filePath,
event.sender.id,
passwordState.password ? plain : undefined,
)
if (tornDownWcIds.has(event.sender.id)) {
await unlink(filePath).catch(() => {})
return { ok: false }
@@ -3609,7 +3683,12 @@ export function registerDocsIpc(): void {
const passwordIntentPending = commitDocPasswordSave(event.sender.id, passwordState, filePath)
pushRecent(filePath)
notifyFileSaved(event.sender, filePath)
return { ok: true, path: filePath, passwordIntentPending }
return {
ok: true,
path: filePath,
passwordIntentPending,
...reissuedDoc(!!passwordState.password, hashes, plain),
}
} catch (err) {
return { ok: false, error: String(err) }
}
@@ -3649,9 +3728,8 @@ export function registerDocsIpc(): void {
}
await mkdir(dirname(filePath), { recursive: true })
const passwordState = snapshotDocPassword(event.sender.id, null)
const bytes = passwordState.password
? encryptDocx(Buffer.from(data), passwordState.password)
: Buffer.from(data)
const { bytes: plain, hashes } = await materializeLazyDocx(Buffer.from(data))
const bytes = passwordState.password ? encryptDocx(plain, passwordState.password) : plain
await atomicWriteFile(filePath, bytes)
// teardown may have happened while the write was in flight — only a file
// this handler created is safe to roll back; an overwritten one stays
@@ -3660,7 +3738,13 @@ export function registerDocsIpc(): void {
return { ok: false }
}
if (tornDownWcIds.has(event.sender.id)) return rollback()
await rememberDiskState(event.sender.id, filePath, bytes)
await rememberDiskState(event.sender.id, filePath, sha256Hex(bytes))
pointLazyMediaAt(
hashes,
filePath,
event.sender.id,
passwordState.password ? plain : undefined,
)
if (tornDownWcIds.has(event.sender.id)) return rollback()
const passwordIntentPending = commitDocPasswordSave(
event.sender.id,
@@ -3669,7 +3753,12 @@ export function registerDocsIpc(): void {
)
pushRecent(filePath)
notifyFileSaved(event.sender, filePath)
return { ok: true, path: filePath, passwordIntentPending }
return {
ok: true,
path: filePath,
passwordIntentPending,
...reissuedDoc(!!passwordState.password, hashes, plain),
}
} catch (err) {
return { ok: false, error: String(err) }
}
@@ -3777,12 +3866,22 @@ export function registerDocsIpc(): void {
// (the protected wrapper round-tripped as a "protected content" shell).
ipcMain.handle(
'docs:copy-image-to-clipboard',
(_event, dataUrl: unknown, meta: unknown): boolean => {
if (typeof dataUrl !== 'string' || !dataUrl.startsWith('data:image/')) return false
const base64 = dataUrl.slice(dataUrl.indexOf(',') + 1)
async (_event, dataUrl: unknown, meta: unknown): Promise<boolean> => {
if (typeof dataUrl !== 'string') return false
let bytes: Buffer
let htmlSrc = dataUrl
if (dataUrl.startsWith('data:image/')) {
bytes = Buffer.from(dataUrl.slice(dataUrl.indexOf(',') + 1), 'base64')
} else {
const media = await readLazyMedia(dataUrl)
if (!media) return false
bytes = media.body
// another document cannot resolve this document's lazy URL; inline the bytes
htmlSrc = `data:${media.mime};base64,${bytes.toString('base64')}`
}
// createFromBuffer, not createFromDataURL — the latter returns an empty
// image for valid PNGs in this Electron
const image = nativeImage.createFromBuffer(Buffer.from(base64, 'base64'))
const image = nativeImage.createFromBuffer(bytes)
if (image.isEmpty()) return false
// the html flavor carries the DISPLAY size + layout meta so an in-app
// paste keeps size/align/wrap instead of falling back to bitmap pixels
@@ -3804,7 +3903,7 @@ export function registerDocsIpc(): void {
}
clipboard.write({
image,
html: `<img src="${dataUrl}" width="${width}" height="${height}"${metaAttr}>`,
html: `<img src="${htmlSrc}" width="${width}" height="${height}"${metaAttr}>`,
})
return true
},
@@ -4416,6 +4515,7 @@ export function buildDocsMenu(): void {
{ type: 'separator' },
{ label: tm('menuDocsHelp'), enabled: false },
{ type: 'separator' },
checkUpdatesMenuItem(appMenuLabels(getUiLang())),
aboutMenuItem(appMenuLabels(getUiLang())),
],
},
+240
View File
@@ -0,0 +1,240 @@
import { createHash } from 'node:crypto'
import { createReadStream } from 'node:fs'
import { open, stat } from 'node:fs/promises'
import { inflateRawSync } from 'node:zlib'
import { protocol } from 'electron'
import { DOCX_MEDIA_SCHEME_PRIVILEGE } from '@genoffice/electron-utils'
import {
LAZY_MEDIA_SCHEME,
isLazyMediaPart,
parseLazyMediaUrl,
} from '@genoffice/docx-engine/lazy-media'
import {
bufferSource,
lazyMediaHashesIn,
materializeDocx,
openZipFile,
readZipEntries,
slimDocx,
type ZipEntry,
type ZipFile,
} from '@genoffice/docx-engine/zip-splice'
/** documents carrying at least this much browser-decodable media open lazily */
const LAZY_MEDIA_MIN_BYTES = 16 * 1024 * 1024
interface Source {
path: string
owners: Set<number>
table?: { size: number; mtimeMs: number; entries: Map<string, ZipEntry> }
/** the plain document once the file on disk is encrypted and cannot be served */
bytes?: Buffer
/** entry table parsed from exactly `bytes` (identity-checked, never the file's) */
memTable?: { bytes: Buffer; entries: Map<string, ZipEntry> }
}
/** original-file sha256 → where its media lives */
const sources = new Map<string, Source>()
const MIME: Record<string, string> = {
png: 'image/png',
jpg: 'image/jpeg',
jpeg: 'image/jpeg',
gif: 'image/gif',
bmp: 'image/bmp',
webp: 'image/webp',
svg: 'image/svg+xml',
}
function sha256File(path: string): Promise<string> {
return new Promise((resolve, reject) => {
const hash = createHash('sha256')
createReadStream(path)
.on('error', reject)
.on('data', (chunk) => hash.update(chunk))
.on('end', () => resolve(hash.digest('hex')))
})
}
function registerSource(hash: string, path: string, wcId: number): void {
const source = sources.get(hash)
if (source) {
if (source.path !== path) source.table = undefined
source.path = path
source.owners.add(wcId)
} else {
sources.set(hash, { path, owners: new Set([wcId]) })
}
}
/**
* The document with its pictures replaced by placeholders, or null when the
* file should be read whole (small media, encrypted container, odd zip).
*/
export async function openLazyDocx(
filePath: string,
wcId: number,
): Promise<{ bytes: Buffer; hash: string } | null> {
let zip: ZipFile
try {
zip = await openZipFile(filePath)
} catch {
return null
}
try {
let media = 0
for (const e of zip.entries.values()) if (isLazyMediaPart(e.name)) media += e.usize
if (media < LAZY_MEDIA_MIN_BYTES) return null
const hash = await sha256File(filePath)
const slim = await slimDocx(zip, hash, LAZY_MEDIA_MIN_BYTES)
if (!slim) return null
registerSource(hash, filePath, wcId)
return { bytes: slim.bytes, hash }
} catch {
return null
} finally {
await zip.close()
}
}
/** a recovery copy names the hash its placeholders were cut under; the
* on-disk file still holds those parts by name */
export async function adoptLazyMediaHashes(
bytes: Buffer,
filePath: string,
wcId: number,
): Promise<void> {
try {
for (const hash of await lazyMediaHashesIn(bytes)) registerSource(hash, filePath, wcId)
} catch {
/* not a plain zip: nothing lazy in it */
}
}
export function forgetLazyMediaOwner(wcId: number): void {
for (const [hash, source] of sources) {
source.owners.delete(wcId)
if (source.owners.size === 0) sources.delete(hash)
}
}
async function entriesOf(source: Source): Promise<Map<string, ZipEntry> | null> {
const st = await stat(source.path).catch(() => null)
if (!st) return null
if (source.table && source.table.size === st.size && source.table.mtimeMs === st.mtimeMs) {
return source.table.entries
}
const zip = await openZipFile(source.path)
try {
// an encrypted save may have switched the source to memory meanwhile
if (!source.bytes) source.table = { size: st.size, mtimeMs: st.mtimeMs, entries: zip.entries }
return zip.entries
} finally {
await zip.close()
}
}
async function readRange(path: string, offset: number, length: number): Promise<Buffer> {
const fh = await open(path, 'r')
try {
const buf = Buffer.alloc(length)
let done = 0
while (done < length) {
const { bytesRead } = await fh.read(buf, done, length - done, offset + done)
if (bytesRead === 0) throw new Error('lazy media: source file truncated')
done += bytesRead
}
return buf
} finally {
await fh.close()
}
}
async function sourceZip(hash: string): Promise<ZipFile | null> {
const source = sources.get(hash)
if (source?.bytes) {
const bytes = source.bytes
const src = bufferSource(bytes)
let mem = source.memTable
if (!mem || mem.bytes !== bytes) {
const entries = new Map<string, ZipEntry>()
for (const e of await readZipEntries(src)) entries.set(e.name, e)
source.memTable = mem = { bytes, entries }
}
return { ...src, entries: mem.entries, close: async () => {} }
}
const entries = source ? await entriesOf(source) : null
if (!source || !entries) return null
return {
size: (await stat(source.path)).size,
entries,
read: (offset, length) => {
// the file's offsets mean nothing once the source moved to memory
if (source.bytes) throw new Error('lazy media source replaced during read')
return readRange(source.path, offset, length)
},
close: async () => {},
}
}
/** saved bytes with lazy placeholders swapped back for the original media,
* plus the hashes those placeholders named */
export async function materializeLazyDocx(
bytes: Buffer,
): Promise<{ bytes: Buffer; hashes: Set<string> }> {
const hashes = await lazyMediaHashesIn(bytes).catch(() => new Set<string>())
if (hashes.size === 0) return { bytes, hashes }
const opened = new Map<string, Promise<ZipFile | null>>()
const full = await materializeDocx(bytes, (hash) => {
let zip = opened.get(hash)
if (!zip) opened.set(hash, (zip = sourceZip(hash)))
return zip
})
return { bytes: full, hashes }
}
/** after a save landed a full copy at `filePath`, serve those hashes from it;
* an encrypted save passes the plain bytes instead, since the file cannot be read by range */
export function pointLazyMediaAt(
hashes: Set<string>,
filePath: string,
wcId: number,
plain?: Buffer,
): void {
for (const hash of hashes) {
registerSource(hash, filePath, wcId)
const source = sources.get(hash)
if (source) {
source.bytes = plain
source.table = undefined
source.memTable = undefined
}
}
}
/** the picture behind a lazy URL, or null when it is not served (any more) */
export async function readLazyMedia(url: string): Promise<{ body: Buffer; mime: string } | null> {
const ref = parseLazyMediaUrl(url)
if (!ref || !isLazyMediaPart(ref.partPath)) return null
const zip = await sourceZip(ref.hash)
const entry = zip?.entries.get(ref.partPath)
if (!zip || !entry || (entry.method !== 0 && entry.method !== 8)) return null
const raw = await zip.read(entry.dataOffset, entry.csize)
const ext = ref.partPath.split('.').pop()?.toLowerCase() ?? ''
return {
body: entry.method === 0 ? raw : inflateRawSync(raw),
mime: MIME[ext] ?? 'application/octet-stream',
}
}
export function registerLazyMediaProtocol(): void {
if (DOCX_MEDIA_SCHEME_PRIVILEGE.scheme !== LAZY_MEDIA_SCHEME) {
throw new Error('lazy media scheme privilege registered under another name')
}
if (protocol.isProtocolHandled(LAZY_MEDIA_SCHEME)) return
protocol.handle(LAZY_MEDIA_SCHEME, async (request) => {
const media = await readLazyMedia(request.url)
if (!media) return new Response(null, { status: 404 })
return new Response(new Uint8Array(media.body), { headers: { 'Content-Type': media.mime } })
})
}
-3
View File
@@ -15,7 +15,6 @@ import type {
} from '../shared/ipc'
import type { ProjectApi } from '@genoffice/project-store'
import { installDropOpenBridge } from '@genoffice/electron-utils/drop-open'
import { installFilesPaneBridge } from '@genoffice/electron-utils/files-pane-bridge'
const api: DesktopApi = {
getLanguage: () => ipcRenderer.invoke('app:get-language'),
@@ -226,5 +225,3 @@ contextBridge.exposeInMainWorld('projectApi', projectApi)
// open documents dragged from the OS onto this tab as a new shell tab
installDropOpenBridge()
// folder tree over the default save folder (Files pane)
installFilesPaneBridge()
+150 -61
View File
@@ -15,7 +15,7 @@ import type { Editor } from '@tiptap/core'
import { handleDocsControl, type ControlRequest } from './control'
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, FilesEdgeTab, FilesPane, ImageViewer, useAutoSavePref } from '@genoffice/ui'
import { Dropdown, ImageViewer, useAutoSavePref } from '@genoffice/ui'
import { wordRangeAtCaret } from './editor/comments'
import { markdownPasteHtml } from './editor/markdown-paste'
import { pasteTextSlice, singleCellPasteText } from './editor/paste-text'
@@ -168,8 +168,10 @@ import {
syncPageBorders,
syncPageSheets,
clampCellBoxTops,
clampCellImageTops,
pageBorderStyleOf,
type PageGapSpec,
LayoutBatch,
} from './editor/pagination-gaps'
import { setColumnLayout } from './editor/column-layout'
import { syncLineNumbers } from './editor/line-numbers'
@@ -205,7 +207,7 @@ import { useShallowStable, useStableCallbacks } from './use-stable'
import { FindPanel } from './components/FindPanel'
import { Ribbon } from './components/Ribbon'
import { computeFormatState } from './components/ribbon-format-state'
import { IconNavPane, IconRedo, IconSave, IconUndo } from './components/icons'
import { IconRedo, IconSave, IconUndo } from './components/icons'
import { ToastHost } from './components/toast'
import {
AI_REWRITE_ACK_KEY,
@@ -242,7 +244,7 @@ import {
subscribeSubEditorState,
} from './editor/active-editor'
import type { CompareEntry } from './editor/compare'
import { collectHeadings, hasHeadings } from './editor/headings'
import { collectHeadings } from './editor/headings'
import { applyTocPageDisplays } from './editor/toc-refresh'
import { setSelectionAlign } from './editor/direction'
@@ -284,6 +286,19 @@ import {
type FileActionContext,
type PendingPdfExport,
} from './file-actions'
import { isPhasedContentPending } from './phased-content'
/** min gap between whole-document pagination passes while a phased open streams its tail */
const STREAMING_PASS_GAP_MS = 1500
/** passes wait at least this many times their own duration while streaming */
const STREAMING_PASS_DUTY = 4
const STREAMING_PASS_GAP_MAX_MS = 15_000
/** after an edit, the pass waits this many times its own last duration (300 ms floor) */
const EDIT_PASS_DUTY = 3
const EDIT_PASS_DEBOUNCE_MAX_MS = 2000
const WORD_COUNT_THROTTLE_MS = 400
/** consecutive follow-up passes a pass may schedule for itself */
const MAX_FOLLOW_UP_PASSES = 6
import { runHeadlessDocumentExport } from './headless-export'
import { installMcpBridge } from './mcp-bridge'
import {
@@ -794,7 +809,6 @@ export function App() {
const [showRuler, setShowRuler] = useState(false)
const [showNav, setShowNav] = useState(() => localStorage.getItem('aidocs.showNav') === '1')
const closeNav = useCallback(() => setShowNav(false), [])
const [showFiles, setShowFiles] = useState(() => localStorage.getItem('aidocs.showFiles') === '1')
const [viewMode, setViewMode] = useState<ViewMode>('print')
const [readMode, setReadMode] = useState(false)
const [showGrid, setShowGrid] = useState(false)
@@ -803,6 +817,7 @@ export function App() {
const [splitHtml, setSplitHtml] = useState('')
const [showFind, setShowFind] = useState(false)
const [imageDragOver, setImageDragOver] = useState(false)
const [findFocusInput, setFindFocusInput] = useState(0)
const [findFocusReplace, setFindFocusReplace] = useState(0)
const [showShortcuts, setShowShortcuts] = useState(false)
const ribbonActionsRef = useRef<{
@@ -1237,10 +1252,6 @@ export function App() {
localStorage.setItem('aidocs.showNav', showNav ? '1' : '0')
}, [showNav])
useEffect(() => {
localStorage.setItem('aidocs.showFiles', showFiles ? '1' : '0')
}, [showFiles])
const spellcheckWasOn = useRef(spellcheck)
const respellKickBusy = useRef(false)
// spell-diag trace: squiggle losses in the field are intermittent and
@@ -2835,24 +2846,31 @@ export function App() {
)
// 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 blockByDocxIndex = useMemo(() => {
const m = new Map<number, Block>()
for (const b of doc?.parsed.blocks ?? [])
if (b.docxIndex !== null && !m.has(b.docxIndex)) m.set(b.docxIndex, b)
return m
}, [doc])
const blockMetaOf = useCallback(
(docxIndex: number): BlockMeta | undefined => {
const b = doc?.parsed.blocks.find((bl) => bl.docxIndex === docxIndex)
const b = blockByDocxIndex.get(docxIndex)
if (!b) return undefined
if (b.type === 'table') {
// notes referenced inside cells reserve their page-bottom area like a
// paragraph's: the slicer charges them to the rows holding the marks
const fnBands = footnoteBandsOf(b)
const fnExtra = fnBands.reduce((s, band) => s + band.heightPx, 0)
const flagged = !!b.originalXml && /tblHeader|cantSplit|<w:trHeight\b/.test(b.originalXml)
if (!flagged && fnExtra === 0) return undefined
const styleKeepNext = (id: string) => doc?.parsed.styles.get(id)?.display?.keepNext === true
const xml = b.originalXml ?? ''
const flagged =
/tblHeader|cantSplit|keepNext|<w:trHeight\b/.test(xml) ||
[...xml.matchAll(/<w:pStyle w:val="([^"]+)"/g)].some((m) => styleKeepNext(m[1]))
const modern = (doc?.parsed.compatibilityMode ?? 0) >= 15
if (!flagged && fnExtra === 0 && !modern) return undefined
return {
...(flagged
? {
tableRowFlags: tableRowFlags(b.originalXml!),
...((doc?.parsed.compatibilityMode ?? 0) >= 15 ? { modernTableHeaders: true } : {}),
}
: {}),
...(flagged ? { tableRowFlags: tableRowFlags(xml, styleKeepNext) } : {}),
...(modern ? { modernTableHeaders: true } : {}),
...(fnExtra > 0 ? { footnoteExtraPx: fnExtra, footnoteBands: fnBands } : {}),
}
}
@@ -2876,7 +2894,7 @@ export function App() {
...(fnExtra > 0 ? { footnoteExtraPx: fnExtra, footnoteBands: fnBands } : {}),
}
},
[doc, defaultParaStyle, footnoteBandsOf],
[doc, blockByDocxIndex, defaultParaStyle, footnoteBandsOf],
)
// per-page footnote collection: the page of the referencing block → that page's footnote entries (number/text/estimated height)
@@ -2887,7 +2905,7 @@ export function App() {
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)
const pb = blockByDocxIndex.get(b.docxIndex)
if (!pb) continue
const ids = blockNoteScanRuns(pb)
.filter((r) => r.noteRef?.kind === 'footnote')
@@ -2922,7 +2940,7 @@ export function App() {
}
return out
},
[doc, footnotes, sections, section, noteRenderInfoOf, noteNo],
[doc, blockByDocxIndex, 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
@@ -3112,6 +3130,18 @@ export function App() {
let slices: PageSlice[] = []
let timer: number | null = null
let suppressSig = ''
// passes a pass schedules for itself (widths / suppression applied late);
// a document whose column widths never settle must not paginate forever
let followUps = 0
let selfScheduled = false
let retrigger: string[] = []
// several reasons in one pass debounce into one follow-up: count passes, not reasons
const followUp = (why: string) => {
retrigger.push(why)
if (followUps >= MAX_FOLLOW_UP_PASSES) return
selfScheduled = true
onUpdate()
}
let secWidthSig = ''
let charSpaceSig = ''
const colWidthPass = newWidthPassState()
@@ -3148,10 +3178,15 @@ export function App() {
prev.current === current && prev.total === total ? prev : { current, total },
)
}
let lastPassAt = 0
let lastPassMs = 0
const remeasure = () => {
timer = null
lastPassAt = performance.now()
try {
remeasurePass()
} finally {
lastPassMs = performance.now() - lastPassAt
// a pass that threw between the add and the pre-setPageGaps remove
// must not leave the gap widgets hidden
pmEl()?.classList.remove('measuring-natural')
@@ -3160,6 +3195,9 @@ export function App() {
const remeasurePass = () => {
const pm = pmEl()
if (!pm) return
followUps = selfScheduled ? followUps + 1 : 0
selfScheduled = false
retrigger = []
const tStart = performance.now()
let tMeasure = 0
let tSlice = 0
@@ -3890,6 +3928,7 @@ export function App() {
}
tGapsBuild = performance.now() - tGaps0
const tSet0 = performance.now()
const layoutBatch = new LayoutBatch(editor.view)
// split declared-height rows: resolve the engine's target heights to tr elements
const rowFillEls: Array<{ el: Element; targetPx: number; extraPx?: number }> = []
for (const f of rowFills) {
@@ -3909,7 +3948,7 @@ export function App() {
...(f.extraPx ? { extraPx: f.extraPx } : {}),
})
}
setRowFills(editor.view, rowFillEls)
setRowFills(editor.view, rowFillEls, layoutBatch)
// oversized single-line blocks: resolve the engine's page-bottom clips to their elements
const oversizeEls: Array<{ el: HTMLElement; clipPx: number }> = []
for (const c of oversizeClips) {
@@ -3926,14 +3965,35 @@ export function App() {
flow?: boolean
carryPx?: number
}> = []
// blocks by rounded top: a scan per shift was floats × blocks on picture-heavy
// documents; the first match in document order wins, as the scan did
const blockAtTop = (pred: (b: BlockBox) => boolean) => {
const byTop = new Map<number, Array<{ i: number; bb: BlockBox }>>()
blocks.forEach((bb, i) => {
if (!pred(bb)) return
const k = Math.round(bb.top)
const list = byTop.get(k)
if (list) list.push({ i, bb })
else byTop.set(k, [{ i, bb }])
})
return (top: number): BlockBox | undefined => {
const k = Math.round(top)
let hit: { i: number; bb: BlockBox } | undefined
for (const kk of [k - 1, k, k + 1]) {
const c = byTop.get(kk)?.find((e) => Math.abs(e.bb.top - top) < 0.5)
if (c && (!hit || c.i < hit.i)) hit = c
}
return hit?.bb
}
}
const pageRelBlockAt = blockAtTop((bb) => bb.pageRelVyPx !== undefined)
for (const f of floatVShifts) {
const b = blocks.find(
(bb) => bb.pageRelVyPx !== undefined && Math.abs(bb.top - f.blockTop) < 0.5,
)
const b = pageRelBlockAt(f.blockTop)
if (b?.el) floatVEls.push({ el: b.el, dyPx: f.dyPx })
}
const floatTableAt = blockAtTop((bb) => Boolean(bb.floatTable))
for (const f of floatFlows) {
const b = blocks.find((bb) => bb.floatTable && Math.abs(bb.top - f.blockTop) < 0.5)
const b = floatTableAt(f.blockTop)
if (b?.el) floatVEls.push({ el: b.el, dyPx: 0, flow: true })
}
// split floating table: its anchor paragraph (the next block) starts
@@ -3955,9 +4015,9 @@ export function App() {
metrics: { marginTop: 0, marginBottom: 0, marginLeft: 0, marginRight: 0 },
})
}
setFloatVShifts(editor.view, floatVEls)
setFloatVShifts(editor.view, floatVEls, layoutBatch)
pm.classList.remove('measuring-natural')
setPageGaps(editor.view, gaps, firstPageFloats)
setPageGaps(editor.view, gaps, firstPageFloats, layoutBatch)
// mixed-column canvas: paint the engine's regions via per-block width/translate decorations
const colSpecs =
viewMode === 'print' && !readMode && colMode === 'mixed' && secList
@@ -4013,7 +4073,8 @@ export function App() {
}
layoutSpecs = [...mergedSpecs.values()]
}
setColumnLayout(editor.view, layoutSpecs)
setColumnLayout(editor.view, layoutSpecs, layoutBatch)
layoutBatch.commit()
// in-table gap bands live in the spanning cell's coordinate space:
// re-anchor them to the paper before the strips are measured/aligned
alignTableGapFills(pm, factor)
@@ -4032,6 +4093,7 @@ export function App() {
// Word keeps anchored objects on the page: cell boxes lifted past the
// paper top by a negative anchor offset are pushed back down
clampCellBoxTops(pm, pm.getBoundingClientRect().top, factor)
clampCellImageTops(pm, factor)
syncCutOverlays((pm.closest('.page-wrap') as HTMLElement) ?? pm, overlayCutAnchors, factor)
{
// page border (w:pgBorders): per-page overlay boxes (w:display can
@@ -4064,7 +4126,7 @@ export function App() {
const sig = gaps.reduce((s, g, n) => (g.suppressLeadMt ? `${s},${n}` : s), '')
if (sig !== suppressSig) {
suppressSig = sig
onUpdate()
followUp('suppress')
}
// 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
@@ -4073,9 +4135,9 @@ export function App() {
.join(',')
if (wSig !== secWidthSig) {
secWidthSig = wSig
onUpdate()
followUp('width')
}
if (colGranted) onUpdate()
if (colGranted) followUp('columns')
// freshly applied per-block letter-spacing changes line breaks the same way
const cSig =
charSpecs.length === 0
@@ -4083,7 +4145,7 @@ export function App() {
: `${charSpecs.length}:${[...new Set(charSpecs.map((s) => s.charSpacePt))].join(',')}`
if (cSig !== charSpaceSig) {
charSpaceSig = cSig
onUpdate()
followUp('charSpace')
}
// 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
@@ -4115,6 +4177,8 @@ export function App() {
;(window as unknown as Record<string, unknown>).__pageDebug = {
slices,
colMode,
retrigger,
followUps,
colSpecs: colSpecs.map((s) => ({
w: s.widthPx === undefined ? null : Math.round(s.widthPx),
dx: Math.round(s.dx),
@@ -4170,8 +4234,29 @@ export function App() {
locate()
}
const onUpdate = () => {
// while the tail streams, chunks land every few frames: a plain debounce
// would either never fire (dense chunks) or pay a whole-document pass
// per chunk (sparse ones); keep the pass already due and pace new ones
if (isPhasedContentPending()) {
if (timer) return
// a whole-document pass grows with the streamed content; keep it to a
// fraction of the streaming time so the tail lands sooner
const gap = Math.min(
STREAMING_PASS_GAP_MAX_MS,
Math.max(STREAMING_PASS_GAP_MS, lastPassMs * STREAMING_PASS_DUTY),
)
const delay = Math.max(300, gap - (performance.now() - lastPassAt))
timer = window.setTimeout(remeasure, delay)
return
}
if (timer) window.clearTimeout(timer)
timer = window.setTimeout(remeasure, 300)
// a whole-document pass after every pause blocks typing on long
// documents: wait longer when the last pass was slow (Word paginates in
// the background too); short documents keep the 300 ms feel
timer = window.setTimeout(
remeasure,
Math.min(EDIT_PASS_DEBOUNCE_MAX_MS, Math.max(300, lastPassMs * EDIT_PASS_DUTY)),
)
}
remeasure()
// async @font-face loading triggers a full reflow (line-break points change); pagination
@@ -4272,6 +4357,28 @@ export function App() {
}
}, [editor, sections])
// status-bar word count: the whole text is re-walked per doc, so pace it
// (Word refreshes its count on idle too). A trailing throttle, not a
// debounce: the streamed tail of a phased open would keep resetting one
const [wordCount, setWordCount] = useState(0)
useEffect(() => {
if (!editor) return
let timer = 0
const refresh = () => {
timer = 0
setWordCount(wordCountOfDoc(editor.state.doc))
}
const onUpdate = () => {
if (!timer) timer = window.setTimeout(refresh, WORD_COUNT_THROTTLE_MS)
}
refresh()
editor.on('update', onUpdate)
return () => {
window.clearTimeout(timer)
editor.off('update', onUpdate)
}
}, [editor, docLoading])
/** Word word-count dialog: pages/lines estimated from the current layout */
const openStats = useCallback(() => {
if (!editor) return
@@ -4409,7 +4516,11 @@ export function App() {
}
if ((e.metaKey || e.ctrlKey) && e.key === 'f') {
e.preventDefault()
if (doc) setShowFind(true)
if (doc) {
// bump even when the panel is already open: focus returns to the find box
setShowFind(true)
setFindFocusInput((n) => n + 1)
}
}
// Word's replace: Ctrl+H everywhere (macOS Cmd+H is the system hide role,
// which never reaches the renderer, so this branch is Ctrl+H there too)
@@ -4748,7 +4859,10 @@ export function App() {
setRibbonTabRequest({ tab: 'layout', nonce: Date.now() })
break
case 'find':
if (doc) setShowFind(true)
if (doc) {
setShowFind(true)
setFindFocusInput((n) => n + 1)
}
break
case 'export-pdf':
void exportPdf()
@@ -5414,7 +5528,6 @@ export function App() {
onShowMarks: setShowMarks,
onShowRuler: setShowRuler,
onShowNav: setShowNav,
onShowFiles: setShowFiles,
onShowComments: () => setShowComments(true),
onNewComment: startNewComment,
onTrackChanges: setTrackChanges,
@@ -5500,8 +5613,6 @@ export function App() {
if (!editor) return null
const wordCount = wordCountOfDoc(editor.state.doc)
// 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
@@ -5645,7 +5756,6 @@ export function App() {
showMarks={showMarks}
showRuler={showRuler}
showNav={showNav}
showFiles={showFiles}
commentCount={comments.length}
openCommentCount={comments.filter((c) => !c.parentId && c.done !== true).length}
canComment={!editor.state.selection.empty || wordRangeAtCaret(editor) !== null}
@@ -5710,34 +5820,13 @@ export function App() {
// and land focus on the replace field
setFindFocusReplace(0)
}}
focusFindNonce={findFocusInput}
focusReplaceNonce={findFocusReplace}
/>
)}
{doc && showFiles && !readMode && (
<FilesPane
api={window.filesPaneApi}
lang={lang}
currentPath={doc.filePath ?? null}
onClose={() => setShowFiles(false)}
/>
)}
{/* the edge tab needs a free left edge: with the navigation pane open the ribbon toggle remains */}
{doc && !showFiles && !showNav && !readMode && (
<FilesEdgeTab lang={lang} onOpen={() => setShowFiles(true)} />
)}
{doc && showNav && (
<NavPane editor={editor} doc={editor.state.doc} onClose={closeNav} />
)}
{doc && !showNav && !readMode && hasHeadings(editor.state.doc) && (
<button
className="nav-edge-tab"
data-tip={t('ribbonNavPaneTip')}
onClick={() => setShowNav(true)}
>
<IconNavPane size={16} />
<span>{t('appNavOutline')}</span>
</button>
)}
{doc && (
<AiAskPopover
editor={editor}
@@ -565,6 +565,8 @@ export function FontDialog({ editor, onClose }: { editor: Editor; onClose: () =>
)
const [style, setStyle] = useState<string>(initialStyle)
const [color, setColor] = useState(`#${(textAttrs.color as string | null) ?? '000000'}`)
// the input has no "unset" state: an untouched swatch keeps the run's colour as it was
const [colorTouched, setColorTouched] = useState(false)
const [underline, setUnderline] = useState(editor.isActive('underline'))
const [strike, setStrike] = useState(editor.isActive('strike'))
const [vertAlign, setVertAlign] = useState<string>((textAttrs.vertAlign as string | null) ?? '')
@@ -574,12 +576,13 @@ export function FontDialog({ editor, onClose }: { editor: Editor; onClose: () =>
onClose()
return
}
const hex = color.replace('#', '').toUpperCase()
let chain = editor
.chain()
.focus()
.setMark('docTextStyle', {
color: hex === '000000' ? null : hex,
color: colorTouched
? color.replace('#', '').toUpperCase()
: ((textAttrs.color as string | null) ?? null),
sizeHalfPoints: Math.round(size * 2),
// picks target only their script's rFonts slot; the other slot survives
...(!font
@@ -672,7 +675,10 @@ export function FontDialog({ editor, onClose }: { editor: Editor; onClose: () =>
type="color"
className="font-color-input"
value={color}
onChange={(e) => setColor(e.target.value)}
onChange={(e) => {
setColor(e.target.value)
setColorTouched(true)
}}
/>
</label>
<label className="font-check">
@@ -64,13 +64,15 @@ export function findMatches(editor: Editor, query: string, opts: FindOptions): R
interface FindPanelProps {
editor: Editor
onClose: () => void
/** Ctrl+F / menu Find bump this to put focus back in the find field while the panel is already open */
focusFindNonce?: number
/** Ctrl+H bumps this to land focus on the replace field (falls back to find when read-only) */
focusReplaceNonce?: number
}
const SCAN_DEBOUNCE_MS = 150
export function FindPanel({ editor, onClose, focusReplaceNonce }: FindPanelProps) {
export function FindPanel({ editor, onClose, focusFindNonce, focusReplaceNonce }: FindPanelProps) {
const { t } = useI18n()
const [query, setQuery] = useState('')
const [replacement, setReplacement] = useState('')
@@ -148,6 +150,12 @@ export function FindPanel({ editor, onClose, focusReplaceNonce }: FindPanelProps
}
}, [])
useEffect(() => {
if (!focusFindNonce) return
inputRef.current?.focus()
inputRef.current?.select()
}, [focusFindNonce])
// declared after the mount effect so opening straight into replace wins the focus
useEffect(() => {
if (!focusReplaceNonce) return
@@ -29,6 +29,7 @@ import {
type HfStripGeom,
type HfTabLayout,
hfParaLineHeightCss,
hfParaIndentStyle,
hfStackedSpacingPx,
} from '../editor/hf-dom'
import { applyHfText, hfEditText, hfParasOf, PAGE_TOKEN } from '../editor/hf-text'
@@ -79,6 +80,7 @@ function paraStyle(para: HfParagraph): React.CSSProperties {
const lh = hfParaLineHeightCss(para)
if (lh) style.lineHeight = lh
if (para.bidi) style.direction = 'rtl'
Object.assign(style, hfParaIndentStyle(para))
if (para.align) {
style.textAlign =
para.align === 'left' || para.align === 'center' || para.align === 'right'
@@ -382,7 +384,13 @@ function HfContent({
<div
key={i}
className={`page-hf-para${para.frameXAlign ? ' page-hf-frame' : ''}`}
style={{ ...paraStyle(para), ...margins(i) }}
style={{
...paraStyle(para),
...margins(i),
...(para.runs.length === 0 && para.emptyRunSizeHalfPoints
? { fontSize: `${para.emptyRunSizeHalfPoints / 2}pt` }
: {}),
}}
>
{para.runs.length === 0 ? ' ' : null}
{para.runs.map((run, j) => (
@@ -31,12 +31,13 @@ import {
sectionColGeom,
sectionFirstPages,
sectionGeoms,
outerTableRows,
sectionVertical,
verticalBlockShift,
sectionPageBox,
rowSplitCss,
sliceWithLineSplit,
TABLE_SEAM_PX,
seamWindow,
type BlockBox,
type BlockMetaOf,
type FloatBox,
@@ -630,6 +631,64 @@ export function verticalPageCss(
return rules.join('\n')
}
/**
* Glyph ink may overflow its line box (CJK or bold faces whose content area
* exceeds a tight line height), so the block that opens the next page paints a
* few pixels above its own top: inside the window of the page before it, which
* ends exactly there. Word paints nothing of a page's first line on the page
* before it. Hide that lead block on the preceding page (visibility keeps the
* flow height); blocks further down cannot reach the window, straddling
* blocks must stay visible, and floated / anchored carriers are left alone
* because their boxes may own the page through the pin rules.
*/
export const EDGE_LEAK_PX = 12
export function leadLeakCss(blocks: BlockBox[], slices: PageSlice[]): string {
const rules: string[] = []
const pinCarrier = '[data-pin-page],[data-pv-hoist]'
const root = blocks[0]?.el?.parentElement
for (const el of root?.querySelectorAll('[data-pv-lead]') ?? [])
el.removeAttribute('data-pv-lead')
let leadRows = 0
slices.forEach((slice, i) => {
if (i === slices.length - 1 || slice.regions) return
for (const b of blocks) {
if (b.top < slice.end - 0.5 || b.top >= slice.end + EDGE_LEAK_PX) continue
if (b.floated || b.floatTable || b.liftPx || b.pageRelVyPx !== undefined || b.isFloatSpill)
continue
const idx = b.el?.dataset.idx
if (idx === undefined || b.el!.matches(pinCarrier) || b.el!.querySelector(pinCarrier))
continue
rules.push(
`.pv-page[data-pv-page="${i}"] .pv-content > [data-idx="${idx}"]{visibility:hidden;}`,
)
}
// a table cut at a row seam: the seam allowance keeps the collapsed border
// whole and with it the next row's glyph tops; hide that row's cell
// contents (its borders and fills stay for the seam)
for (const b of blocks) {
if (!b.tableRows || !b.el || b.top >= slice.end - 0.5 || b.top + b.height <= slice.end + 0.5)
continue
// slice.end came from these same row heights: the nearest row top matches
// exactly or the cut is mid-row
let y = b.top
let lead = -1
b.tableRows.forEach((row, k) => {
if (k > 0 && Math.abs(y - slice.end) <= 0.5) lead = k
y += row.height
})
const tr = lead > 0 ? outerTableRows(b.el)[lead] : undefined
if (!tr) continue
tr.dataset.pvLead = String(leadRows)
rules.push(
`.pv-page[data-pv-page="${i}"] .pv-content tr[data-pv-lead="${leadRows}"] > * > *{visibility:hidden;}`,
)
leadRows++
}
})
return rules.join('\n')
}
export function pinnedCloneCss(pageCount: number): string {
const rules: string[] = []
for (let i = 0; i < pageCount; i++) {
@@ -806,6 +865,7 @@ export function PaginationPreview({
const [slices, setSlices] = useState<PageSlice[]>([])
const [splitCss, setSplitCss] = useState('')
const [vertCss, setVertCss] = useState('')
const [leakCss, setLeakCss] = useState('')
const [pageNotes, setPageNotes] = useState<PageNoteItem[][]>([])
/** per-page flow-coordinate bottom of the body text (beneathText footnote anchor) */
const [textEnds, setTextEnds] = useState<number[]>([])
@@ -1146,6 +1206,7 @@ export function PaginationPreview({
setVertCss(
liveGeoms.some((g) => g.vertical) ? verticalPageCss(blocks, computed, live, liveGeoms) : '',
)
setLeakCss(leadLeakCss(blocks, computed))
setSlices(computed)
setPageNotes(pageFootnotesOf ? pageFootnotesOf(blocks, computed) : [])
setTextEnds(footnotesBeneathText ? pageTextEnds(blocks, computed) : [])
@@ -1334,6 +1395,7 @@ export function PaginationPreview({
<style>{pinnedCloneCss(slices.length)}</style>
{splitCss && <style>{splitCss}</style>}
{vertCss && <style>{vertCss}</style>}
{leakCss && <style>{leakCss}</style>}
{/* 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 */}
@@ -1392,9 +1454,12 @@ export function PaginationPreview({
// paragraph paints into the margin like Word), else by a lifted table's hang
const openTop = i === 0 ? mTop : Math.min(slice.liftTop ?? 0, mTop)
// a cut table's incoming edge: the first window on the page grows one pixel
// up into the top margin so the whole straddling border shows in place
const seamLift = slice.cutTable ? TABLE_SEAM_PX : 0
const bodyLift = slice.repeatHeader ? 0 : seamLift
// up into the top margin so the whole straddling border shows in place;
// a page opening on a table's bottom edge drops that pixel instead (the
// previous page's window keeps the whole bottom border)
const seam = seamWindow(slice, slices[i + 1])
const seamLift = Math.max(seam.lift, 0)
const bodyLift = slice.repeatHeader ? 0 : seam.lift
// page numbers display in the owning section's number format (w:pgNumType w:fmt)
const pageNoText = formatPageNumber(
nums[i],
@@ -1693,9 +1758,7 @@ export function PaginationPreview({
Math.min(
slice.end - slice.start,
contentH - (slice.repeatHeader?.height ?? 0),
) -
(slices[i + 1]?.leadTable ? TABLE_SEAM_PX : 0) +
(slices[i + 1]?.cutTable ? TABLE_SEAM_PX : 0),
) + seam.extend,
)),
...(vOffset > 0.5 || openTop > 0 || bodyLift
? { marginTop: (vOffset > 0.5 ? vOffset : 0) - openTop - bodyLift }
+9 -13
View File
@@ -232,8 +232,6 @@ interface RibbonProps {
onShowRuler: (v: boolean) => void
showNav: boolean
onShowNav: (v: boolean) => void
showFiles: boolean
onShowFiles: (v: boolean) => void
commentCount: number
/** unresolved root comments (drives the AI resolve-comments action) */
openCommentCount: number
@@ -685,8 +683,6 @@ function RibbonInner({
onShowRuler,
showNav,
onShowNav,
showFiles,
onShowFiles,
commentCount,
openCommentCount,
onShowComments,
@@ -725,7 +721,8 @@ function RibbonInner({
const docEmpty = !hasDoc || fs.docEmpty
const [tab, setTab] = useState<RibbonTab>('home')
const [dropdown, setDropdown] = useState<string | null>(null)
const [penColor, setPenColor] = useState('C00000')
// null = Automatic: the pen button clears the run colour instead of writing one
const [penColor, setPenColor] = useState<string | null>('C00000')
const [penHighlight, setPenHighlight] = useState('yellow')
const [painter, setPainter] = useState<PainterState | null>(null)
const fontStepRef = useRef<{
@@ -3308,13 +3305,14 @@ function RibbonInner({
className="rb-icon rb-color-btn"
disabled={!canEdit}
data-tip={t('ribbonFontColor')}
onClick={() =>
setTextStyle({ color: penColor === '000000' ? null : penColor })
}
onClick={() => setTextStyle({ color: penColor })}
>
<span className="rb-color-glyph rb-color-glyph-svg">
<IconFontColorA />
<span className="rb-color-bar" style={{ background: `#${penColor}` }} />
<span
className="rb-color-bar"
style={{ background: `#${penColor ?? '000000'}` }}
/>
</span>
</button>
<button
@@ -3330,11 +3328,11 @@ function RibbonInner({
noneLabel={t('ribbonAutomatic')}
onPick={(hex) => {
if (!hex) {
setPenColor('000000')
setPenColor(null)
setTextStyle({ color: null })
} else {
setPenColor(hex)
setTextStyle({ color: hex === '000000' ? null : hex })
setTextStyle({ color: hex })
}
}}
/>
@@ -3876,8 +3874,6 @@ function RibbonInner({
onShowRuler={onShowRuler}
showNav={showNav}
onShowNav={onShowNav}
showFiles={showFiles}
onShowFiles={onShowFiles}
viewMode={viewMode}
onViewMode={onViewMode}
readMode={readMode}
@@ -1328,15 +1328,6 @@ export function IconRuler(props: IconProps) {
)
}
export function IconFilesPane(props: IconProps) {
return (
<Svg {...props}>
<path d="M 2.5 4.2 h 4 l 1.2 1.3 h 5.8 v 6.3 h -11 z" />
<path d="M 2.5 7.2 h 11" strokeWidth="1" />
</Svg>
)
}
export function IconNavPane(props: IconProps) {
return (
<Svg {...props}>
@@ -5,7 +5,6 @@ import {
SHAPE_GALLERY_GROUPS,
useDismissablePopover,
wordArtSolidColor,
filesPaneTitle,
type WordArtPreset,
} from '@genoffice/ui'
import {
@@ -40,7 +39,6 @@ import {
IconLock,
IconMoon,
IconNavPane,
IconFilesPane,
IconOutlineView,
IconPageWidth,
IconGridlines,
@@ -1077,8 +1075,6 @@ interface ViewTabProps {
onShowRuler: (v: boolean) => void
showNav: boolean
onShowNav: (v: boolean) => void
showFiles: boolean
onShowFiles: (v: boolean) => void
viewMode: ViewMode
onViewMode: (mode: ViewMode) => void
readMode: boolean
@@ -1104,8 +1100,6 @@ export function ViewTab({
onShowRuler,
showNav,
onShowNav,
showFiles,
onShowFiles,
viewMode,
onViewMode,
readMode,
@@ -1116,7 +1110,7 @@ export function ViewTab({
onSplitView,
onPagePreview,
}: ViewTabProps) {
const { t, lang } = useI18n()
const { t } = useI18n()
const [winMenuOpen, setWinMenuOpen] = useState(false)
const [windows, setWindows] = useState<DocsTabInfo[]>([])
/** wrap holding both the switch-tabs trigger and its menu */
@@ -1327,17 +1321,6 @@ export function ViewTab({
</span>
<span>{t('ribbonNavPane')}</span>
</button>
<button
className={`rb-big ${showFiles ? 'active' : ''}`}
disabled={!hasDoc}
data-tip={filesPaneTitle(lang)}
onClick={() => onShowFiles(!showFiles)}
>
<span className="rb-big-icon">
<IconFilesPane size={BIG} />
</span>
<span>{filesPaneTitle(lang)}</span>
</button>
</div>
<div className="ribbon-group-label">{t('ribbonGroupShow')}</div>
</div>
+40 -17
View File
@@ -446,16 +446,11 @@ export function docStyleCss(parsed: ParsedDocFull): string {
// first-page header/footer strips are .doc-page siblings
rules.push(`.page-wrap, .doc-page, .pv-page { --doc-base-fs:${sizeHalf / 2}pt }`)
// Header/footer strips (.page-hf) resolve their default run size through
// this var (Word's Header/Footer styles are based on Normal, so runs
// without their own w:sz take the document default, not the static
// 10.5pt guess). Shrink-only: the strip line-height carries the
// document-wide script strut, which overshoots Word on Latin-only strip
// lines — letting the base size grow would over-reserve push-down and
// push page counts up (prod_008/091). .page-wrap too — the canvas
// strips are .doc-page siblings.
if (sizeHalf < 21) {
rules.push(`.page-wrap, .doc-page, .pv-page { --hf-default-fs:${sizeHalf / 2}pt }`)
}
// this var: Word's Header/Footer styles are based on Normal, so runs
// without their own w:sz take the document default (a 12pt default wraps
// a long header line one line earlier than the old 10.5pt guess).
// .page-wrap too — the canvas strips are .doc-page siblings.
rules.push(`.page-wrap, .doc-page, .pv-page { --hf-default-fs:${sizeHalf / 2}pt }`)
}
const color = normal?.color ?? dd?.color
// auto = the paper ink the page already uses
@@ -754,7 +749,17 @@ export function docStyleCss(parsed: ParsedDocFull): string {
darkDecls.push(AUTO_INK.light.dark)
}
}
const styleLh = cssLineHeight(d.lineRule, d.lineRawTwips, d.lineSpacing)
// a paragraph style whose w:basedOn chain never reaches the default style
// inherits docDefaults only: Normal's spacing and line (the .doc-page base)
// must not leak into it (a No Spacing letterhead packs its lines in Word)
const offNormalChain =
info.type === 'paragraph' && !info.isDefault && !chainReachesDefault(parsed.styles, info)
const dd = offNormalChain ? parsed.docDefaults : undefined
const styleLh =
cssLineHeight(d.lineRule, d.lineRawTwips, d.lineSpacing) ??
(offNormalChain
? (cssLineHeight(dd?.lineRule, dd?.lineRawTwips, dd?.lineSpacing) ?? cssGridLineBase())
: undefined)
if (styleLh) decls.push(`line-height:${styleLh}`)
// grid span snapping scales by the style's multiple (an explicit single
// still overrides an inherited document multiple); the extra rule keeps
@@ -788,12 +793,18 @@ export function docStyleCss(parsed: ParsedDocFull): string {
} }`,
)
}
if (d.spaceBeforeAuto) decls.push(`margin-top:${cssGridSpacingPt(WORD_AUTO_SPACING_PT)}`)
else if (d.spaceBeforeTwips !== undefined)
decls.push(`margin-top:${cssGridSpacingPt(d.spaceBeforeTwips / 20)}`)
if (d.spaceAfterAuto) decls.push(`margin-bottom:${cssGridSpacingPt(WORD_AUTO_SPACING_PT)}`)
else if (d.spaceAfterTwips !== undefined)
decls.push(`margin-bottom:${cssGridSpacingPt(d.spaceAfterTwips / 20)}`)
const beforeAuto = d.spaceBeforeAuto ?? dd?.spaceBeforeAuto
const beforeTwips =
d.spaceBeforeTwips ?? (offNormalChain ? (dd?.spaceBeforeTwips ?? 0) : undefined)
if (beforeAuto) decls.push(`margin-top:${cssGridSpacingPt(WORD_AUTO_SPACING_PT)}`)
else if (beforeTwips !== undefined)
decls.push(`margin-top:${cssGridSpacingPt(beforeTwips / 20)}`)
const afterAuto = d.spaceAfterAuto ?? dd?.spaceAfterAuto
const afterTwips =
d.spaceAfterTwips ?? (offNormalChain ? (dd?.spaceAfterTwips ?? 0) : undefined)
if (afterAuto) decls.push(`margin-bottom:${cssGridSpacingPt(WORD_AUTO_SPACING_PT)}`)
else if (afterTwips !== undefined)
decls.push(`margin-bottom:${cssGridSpacingPt(afterTwips / 20)}`)
// style-level auto spacing collapses to 0 between two list items (Word),
// mirroring the .sp-auto-* rules for direct autospacing (styles.css);
// un-!important so a direct explicit margin (inline, auto turned off) wins —
@@ -919,3 +930,15 @@ export function docStyleCss(parsed: ParsedDocFull): string {
if (darkRules.length > 0) rules.push(`@media screen {\n${darkRules.join('\n')}\n}`)
return rules.join('\n')
}
/** the style's w:basedOn chain ends at the default paragraph style (it inherits Normal) */
function chainReachesDefault(styles: Map<string, StyleInfo>, info: StyleInfo): boolean {
const seen = new Set<string>()
let cur: StyleInfo | undefined = info
while (cur && !seen.has(cur.styleId)) {
if (cur.isDefault) return true
seen.add(cur.styleId)
cur = cur.basedOn ? styles.get(cur.basedOn) : undefined
}
return false
}
+29 -15
View File
@@ -4,6 +4,8 @@ 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'
import { TopLevelPositions } from './top-level-pos'
import type { LayoutBatch } from './pagination-gaps'
const key = new PluginKey<DecorationSet>('columnLayout')
@@ -142,8 +144,13 @@ function specClass(spec: ColumnBlockSpec): string {
}
/** Rebuild the column-layout decorations (an empty list clears them). */
export function setColumnLayout(view: EditorView, specs: ColumnBlockSpec[]): void {
export function setColumnLayout(
view: EditorView,
specs: ColumnBlockSpec[],
batch?: LayoutBatch,
): void {
const decos: Decoration[] = []
const positions = new TopLevelPositions(view)
const styleOf = new Map<HTMLElement, { style: string; cls: string }>()
const splitOf = new Map<HTMLElement, string>()
for (const spec of specs) {
@@ -172,15 +179,9 @@ export function setColumnLayout(view: EditorView, specs: ColumnBlockSpec[]): voi
`--col-dx:${round2(spec.dx)}px;--col-dy:${round2(spec.dy)}px`
const cls = specClass(spec)
styleOf.set(spec.el, { style, cls })
let from: number
let to: number
try {
const $inside = view.state.doc.resolve(view.posAtDOM(spec.el, 0))
from = $inside.before(1)
to = $inside.after(1)
} catch {
continue
}
const range = positions.of(spec.el)
if (!range) continue
const { from, to } = range
decos.push(Decoration.node(from, to, { class: cls, style }, { key: `col-${cls}-${style}` }))
const split = splitOf.get(spec.el)
if (split)
@@ -194,11 +195,24 @@ export function setColumnLayout(view: EditorView, specs: ColumnBlockSpec[]): voi
}
const next = DecorationSet.create(view.state.doc, decos)
const prev = key.getState(view.state)
if (!prev || !sameCols(prev, next))
view.dispatch(view.state.tr.setMeta(key, next).setMeta('addToHistory', false))
// custom NodeViews (protected blocks etc.) don't apply node decorations — patch
// their DOM directly, observer paused so PM never re-parses the mutation (same
// technique as the phantom-rowspan sync). Re-applied by every remeasure pass.
if (!prev || !sameCols(prev, next)) {
if (batch) batch.set(key, next)
else view.dispatch(view.state.tr.setMeta(key, next).setMeta('addToHistory', false))
}
if (batch) batch.then(() => patchNodeViews(view, styleOf, splitOf))
else patchNodeViews(view, styleOf, splitOf)
}
/**
* custom NodeViews (protected blocks etc.) don't apply node decorations — patch
* their DOM directly, observer paused so PM never re-parses the mutation (same
* technique as the phantom-rowspan sync). Re-applied by every remeasure pass.
*/
function patchNodeViews(
view: EditorView,
styleOf: Map<HTMLElement, { style: string; cls: string }>,
splitOf: Map<HTMLElement, string>,
): void {
const obs = (view as unknown as { domObserver?: { stop(): void; start(): void } }).domObserver
obs?.stop()
try {
+59 -19
View File
@@ -1,5 +1,6 @@
import {
mergePPrFormat,
parseLazyMediaUrl,
setPPrChange,
stripPPrChange,
ommlToLatex,
@@ -347,13 +348,15 @@ const MEASURED_SLACK = 1.02
/** collapsed half-borders plus px rounding eat ~1px per side of the measured word (CI cap tables shattered "Board") */
const MEASURED_EDGE_PX = 2
/** per grid column (twips): widest unbreakable word in single-span cells, plus side padding */
/** per grid column (twips): widest unbreakable word in single-span cells, plus side
* padding; `bare` drops the slack (a grid Word laid out already holds its words) */
function minContentColTwips(
model: TableModel,
colCount: number,
metrics: FontMetricsProvider | null,
bare = false,
): number[] {
const slack = metrics ? MEASURED_SLACK : MIN_CONTENT_SLACK
const slack = bare ? 1 : metrics ? MEASURED_SLACK : MIN_CONTENT_SLACK
const mins = new Array<number>(colCount).fill(0)
for (const row of model.rows) {
let column = 0
@@ -371,7 +374,7 @@ function minContentColTwips(
}
let wordPx = cellMaxWordPx(cell, metrics)
if (wordPx <= 0) continue
if (metrics) wordPx += MEASURED_EDGE_PX
if (metrics && !bare) wordPx += MEASURED_EDGE_PX
mins[start] = Math.max(mins[start], Math.ceil(wordPx * slack * 15) + pad)
}
}
@@ -469,6 +472,7 @@ export function expandAutofitColWidths(
fitTwips: number = availTwips,
metrics: FontMetricsProvider | null = canvasMetrics(),
nested = false,
legacy = false,
): TableModel {
const indent = tableIndentTwips(model)
const budget = availTwips - indent
@@ -493,16 +497,36 @@ export function expandAutofitColWidths(
}
}
if (autofit && (resolvedPct || !model.widthPct) && widths?.length && budget > 0) {
const mins = minContentColTwips(model, widths.length, metrics).map((m) => Math.min(m, budget))
const mins = minContentColTwips(model, widths.length, metrics, !!model.layoutGrid).map((m) =>
Math.min(m, budget),
)
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 fit = Math.min(fitTwips, availTwips)
const target = fit - indent
// Over-wide tblW-auto preferred widths compress to the column less the
// signed table indent (Word probe 2026-09-17, compat 14 and 15: tblInd -108
// widens the box by 108, +558 narrows it by 558, the right edge stays on
// the margin). Compat < 15 measures the indent to the cell text, so the
// border box hangs by the side cell margins - the left one is already in
// the legacy indent shift, the right one is added here (centered tables
// shift nothing and hang on both sides). A nested table sits inside the
// cell padding, so it never hangs. An explicit dxa tblW is honoured as
// long as the table stays on the paper (measured: landscape and portrait
// forms 7-22% wider than the column, negative tblInd, drawn at full width).
const sideMar = sideMarginTwips(model)
const leftAligned = model.align !== 'center' && model.align !== 'right'
const legacyHang = !legacy
? 0
: leftAligned && !model.floatSide
? (model.cellMarTwips?.right ?? DEFAULT_CELL_MAR)
: sideMar
const box = fit - (leftAligned ? (model.indentTwips ?? 0) : 0) + legacyHang
const hang = leftAligned ? Math.min(model.indentTwips ?? 0, 0) : 0
const explicitDxa = !model.autoLayout && !nested && declared + hang <= budget
const kept =
resolvedPct || nested ? target : Math.max(target, Math.min(declared, target + sideMar))
resolvedPct || nested
? target
: Math.max(target, explicitDxa ? declared : Math.min(declared, box))
if (mins.some((m, i) => m > widths![i]) || (!resolvedPct && declared > kept)) {
const grown = widths.map((w, i) => Math.max(w, mins[i]))
const overflow = grown.reduce((a, b) => a + b, 0) - kept
@@ -558,7 +582,14 @@ function displayTable(
if (options.legacyTableIndent) t = legacyIndentTable(t)
if (rowCapTwips != null) t = capTableRowHeights(t, rowCapTwips)
if (budget != null) {
t = expandAutofitColWidths(t, budgetAvail(t, budget), budget.fit)
t = expandAutofitColWidths(
t,
budgetAvail(t, budget),
budget.fit,
undefined,
false,
options.legacyTableIndent ?? false,
)
t = clampTableColWidths(t, budget.paper)
}
return t
@@ -773,7 +804,14 @@ export function tableModelToPmNode(
if (legacyIndent) model = legacyIndentTable(model)
if (rowCapTwips != null) model = capTableRowHeights(model, rowCapTwips)
if (availTwips != null) {
model = expandAutofitColWidths(model, availTwips, fitTwips ?? availTwips)
model = expandAutofitColWidths(
model,
availTwips,
fitTwips ?? availTwips,
undefined,
false,
legacyIndent,
)
model = clampTableColWidths(model, paperTwips ?? availTwips)
}
const positions = model.rows.map((row) => {
@@ -892,8 +930,8 @@ export function tableModelToPmNode(
cellMar: cell.cellMarTwips ?? null,
textDirection: cell.textDirection ?? null,
fill: cell.fill ?? null,
color: cell.color ?? null,
bold: cell.bold ?? false,
color: cell.styleColor ?? null,
bold: cell.styleBold ?? false,
align: cell.align ?? null,
vAlign: cell.vAlign ?? null,
borders: cell.borders ?? null,
@@ -2246,13 +2284,15 @@ export function pmDocToSavePlan(inputDoc: PmNode, originalBlocks: Block[]): Save
/** rebuild a pasted image copy from its preview bytes; null when not materializable */
function imageFromProtectedAttrs(node: PmNode): NewImage | null {
if (node.attrs?.blockType !== 'image') return null
const m = /^data:(image\/(?:png|jpeg|gif));base64,(.+)$/.exec(
String(node.attrs?.imageDataUrl ?? ''),
)
const src = String(node.attrs?.imageDataUrl ?? '')
const lazy = parseLazyMediaUrl(src)
const m = lazy ? null : /^data:(image\/(?:png|jpeg|gif));base64,(.+)$/.exec(src)
const widthPx = Number(node.attrs?.imageWidthPx)
const heightPx = Number(node.attrs?.imageHeightPx)
if (!m || !widthPx || !heightPx) return null
const image: NewImage = { base64: m[2], mime: m[1] as NewImage['mime'], widthPx, heightPx }
if ((!m && !lazy) || !widthPx || !heightPx) return null
const image: NewImage = lazy
? { base64: '', mime: 'image/png', sourcePart: lazy.partPath, widthPx, heightPx }
: { base64: m![2], mime: m![1] as NewImage['mime'], widthPx, heightPx }
const align = node.attrs?.imageAlign as NewImage['align'] | null
if (align) image.align = align
const wrap = node.attrs?.imageWrap as ImageWrap | null
@@ -1,5 +1,5 @@
import { Extension } from '@tiptap/core'
import { Plugin, PluginKey, type EditorState } from '@tiptap/pm/state'
import { Plugin, PluginKey, type EditorState, type Transaction } from '@tiptap/pm/state'
import { Decoration, DecorationSet, type EditorView } from '@tiptap/pm/view'
import type { Node as ProseMirrorNode } from '@tiptap/pm/model'
import { isInTable } from '@tiptap/pm/tables'
@@ -17,6 +17,7 @@ import { revisionDisplayState } from './marks'
import { borderMergeFlags, type ParaBorderAttrs } from './para-border-merge'
import { rangeSlot } from '../dom-range'
import { PHASED_CONTENT_SETTLED_EVENT, isPhasedContentPending } from '../phased-content'
import { appendsAtEnd, touchedTopLevelBlocks } from './touched-blocks'
const alignRange = rangeSlot()
@@ -137,6 +138,54 @@ export const ResolvedCommentsExtension = Extension.create({
},
})
/**
* Plugin state for inline decorations that are a pure function of each text
* node: a full scan at init, then only the top-level blocks a transaction
* touched recompute (a `decorations` prop rescanned the whole document on
* every view update — tens of ms per keystroke on a 10k-paragraph file).
*/
function textDecorationState(
key: PluginKey<DecorationSet>,
decosOf: (node: ProseMirrorNode, pos: number, out: Decoration[]) => void,
) {
const scan = (root: ProseMirrorNode, base: number, out: Decoration[]) =>
root.descendants((node, pos) => {
if (node.isText) decosOf(node, base + pos, out)
})
const full = (doc: ProseMirrorNode) => {
const decos: Decoration[] = []
scan(doc, 0, decos)
return decos.length > 0 ? DecorationSet.create(doc, decos) : DecorationSet.empty
}
return {
key,
state: {
init: (_config: unknown, state: EditorState) => full(state.doc),
apply(tr: Transaction, old: DecorationSet) {
if (!tr.docChanged) return old
const touched = touchedTopLevelBlocks(tr)
if (!touched) return full(tr.doc)
let set = appendsAtEnd(tr) ? old : old.map(tr.mapping, tr.doc)
const decos: Decoration[] = []
for (const offset of touched) {
const node = tr.doc.nodeAt(offset)
if (!node) continue
const end = offset + node.nodeSize
const stale = set.find(offset, end).filter((d) => d.from >= offset && d.to <= end)
if (stale.length) set = set.remove(stale)
scan(node, offset + 1, decos)
}
return decos.length ? set.add(tr.doc, decos) : set
},
},
props: {
decorations(state: EditorState) {
return key.getState(state)
},
},
}
}
// ---- tab stop rendering extension ----
const tabStopPluginKey = new PluginKey<DecorationSet>('tabStops')
@@ -190,6 +239,9 @@ export interface TabTargetInput {
/** 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
/** the segment can wrap on its own (spaces / CJK): Word keeps the stop and
* wraps a segment overflowing the edge by more than a space (probe 2026-09-17) */
segBreakable?: boolean
}
export interface TabTarget {
@@ -253,9 +305,12 @@ export function resolveTabTarget(input: TabTargetInput): TabTarget {
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
const overflow = target + segWidth - (paraW - 1)
if (
target + segWidth > paraW - 1 &&
(val !== 'left' || target > paraW - 1 || (!inHang && paraW - segWidth - 1 > x))
overflow > 0 &&
(val !== 'left' ||
target > paraW - 1 ||
(!inHang && paraW - segWidth - 1 > x && !(input.segBreakable && overflow > minAdv)))
)
target = paraW - 1 - restWidth
let collapsed = false
@@ -311,11 +366,25 @@ export function tabSegmentWidth(
paraW: number,
zoom: number,
): number {
const sameLine = end.top < start.bottom && end.bottom > start.top
if (!sameLine) return paraW
if (!sameVisualLine(start, end)) return paraW
return Math.max(0, (end.left - start.left) / zoom)
}
/**
* Two caret rects sit on one line when either's vertical middle falls inside
* the other: a plain overlap test also matched consecutive lines whose boxes
* overlap under a tight line rule (line=177 auto: 20px boxes 15px apart), which
* read the next line's tab as a same-line continuation.
*/
export function sameVisualLine(
a: { top: number; bottom: number },
b: { top: number; bottom: number },
): boolean {
const midA = (a.top + a.bottom) / 2
const midB = (b.top + b.bottom) / 2
return (midA > b.top && midA < b.bottom) || (midB > a.top && midB < a.bottom)
}
function spaceWidthPx(cs: CSSStyleDeclaration): number {
if (spaceMeasureCtx === undefined)
spaceMeasureCtx = document.createElement('canvas').getContext('2d')
@@ -336,6 +405,9 @@ function tabGlyphLeft(view: EditorView, pos: number): number | null {
return rect ? rect.left : null
}
/** inner whitespace or CJK text: a wrap opportunity inside the tab segment */
const SEG_BREAKABLE_RE = /\s|[\u2E80-\u9FFF\uAC00-\uD7AF\uF900-\uFAFF\uFF00-\uFFEF]/
const MEASURE_RETRY_MAX = 10
/**
* Distinct decoration signatures tolerated between external invalidations
@@ -623,6 +695,7 @@ class TabLayoutView {
// otherwise the computed target depends on the layout being measured and
// re-measure never reaches a fixed point.
const endsAtBreak: boolean[] = []
const segBreakable: boolean[] = []
const segWidths = tabPositions.map((tabPos, i) => {
const segStart = tabPos + 1
const nextTab = i + 1 < tabPositions.length ? tabPositions[i + 1] : paraEnd
@@ -631,6 +704,9 @@ class TabLayoutView {
endsAtBreak[i] = nextBreak !== undefined
const segEnd = nextBreak ?? nextTab
if (segEnd <= segStart) return 0
segBreakable[i] = SEG_BREAKABLE_RE.test(
node.textBetween(segStart - pos - 1, segEnd - pos - 1).trim(),
)
try {
return tabSegmentWidth(
view.coordsAtPos(segStart, 1),
@@ -670,8 +746,7 @@ class TabLayoutView {
continue
}
const measuredX = (coords.left - alignShiftAt(coords) - originX) / zoom
const sameLine =
prevLine != null && coords.top < prevLine.bottom && coords.bottom > prevLine.top
const sameLine = prevLine != null && sameVisualLine(coords, prevLine)
const x = sameLine ? prevEnd : measuredX
prevLine = { top: coords.top, bottom: coords.bottom }
@@ -688,6 +763,7 @@ class TabLayoutView {
stops: stopsPx,
gridPx: gridTwips > 0 ? gridTwips / TWIPS_PER_PX : 0,
hangingX: inHang ? contentEdge : undefined,
segBreakable: segBreakable[i],
})
// 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
@@ -836,26 +912,17 @@ export const WsRunLineHeightExtension = Extension.create({
name: 'wsRunLineHeight',
addProseMirrorPlugins() {
return [
new Plugin({
key: wsRunPluginKey,
props: {
decorations(state) {
const decos: Decoration[] = []
state.doc.descendants((node, pos) => {
if (!node.isText || !node.text) return
if (!/^[ \t]+$/.test(node.text)) return
// only runs with a font-size source can inflate the line
const styled = node.marks.some(
(m) =>
m.type.name === 'docTextStyle' && (m.attrs.sizeHalfPoints || m.attrs.styleId),
)
if (!styled) return
decos.push(Decoration.inline(pos, pos + node.nodeSize, { class: 'doc-ws-run' }))
})
return decos.length > 0 ? DecorationSet.create(state.doc, decos) : DecorationSet.empty
},
},
}),
new Plugin(
textDecorationState(wsRunPluginKey, (node, pos, decos) => {
if (!node.text || !/^[ \t]+$/.test(node.text)) return
// only runs with a font-size source can inflate the line
const styled = node.marks.some(
(m) => m.type.name === 'docTextStyle' && (m.attrs.sizeHalfPoints || m.attrs.styleId),
)
if (!styled) return
decos.push(Decoration.inline(pos, pos + node.nodeSize, { class: 'doc-ws-run' }))
}),
),
]
},
})
@@ -895,23 +962,16 @@ export const EaHintQuotesExtension = Extension.create({
name: 'eaHintQuotes',
addProseMirrorPlugins() {
return [
new Plugin({
key: eaHintQuotesPluginKey,
props: {
decorations(state) {
const decos: Decoration[] = []
state.doc.descendants((node, pos) => {
if (!node.isText || !node.text) return
const style = node.marks.find((m) => m.type.name === 'docTextStyle')
const raw = style?.attrs.rawRPr as string | null | undefined
for (const r of eaHintQuoteRanges(raw, node.text)) {
decos.push(Decoration.inline(pos + r.from, pos + r.to, { class: 'doc-ea-quotes' }))
}
})
return decos.length > 0 ? DecorationSet.create(state.doc, decos) : DecorationSet.empty
},
},
}),
new Plugin(
textDecorationState(eaHintQuotesPluginKey, (node, pos, decos) => {
if (!node.text) return
const style = node.marks.find((m) => m.type.name === 'docTextStyle')
const raw = style?.attrs.rawRPr as string | null | undefined
for (const r of eaHintQuoteRanges(raw, node.text)) {
decos.push(Decoration.inline(pos + r.from, pos + r.to, { class: 'doc-ea-quotes' }))
}
}),
),
]
},
})
+166 -61
View File
@@ -13,6 +13,8 @@ import {
type Transaction,
} from '@tiptap/pm/state'
import { Decoration, DecorationSet } from '@tiptap/pm/view'
import { appendsAtEnd, touchedTopLevelBlocks } from './touched-blocks'
import { installProseMirrorPerf } from './prosemirror-perf'
import type { EditorView } from '@tiptap/pm/view'
import {
CellSelection,
@@ -37,6 +39,7 @@ import {
cssLineHeight,
isCjkFontName,
lineHeightFactor,
symbolBulletLinePt,
paraLineFactorCss,
SIMSUN_GAP_CHAR_RE,
simsunGapLineFactor,
@@ -54,6 +57,7 @@ import { noteMarkText } from '../note-format'
import { t } from '../i18n/locale'
import {
ommlToMathML,
parseLazyMediaUrl,
patchMathTokens,
type ChartDisplay,
type DiagramDisplay,
@@ -89,6 +93,8 @@ import { type BorderLine, borderDrawnPx, borderTruePx } from './border-metrics'
import { borderLineCss, paraBorderCss, paraBorderPadding, paraBorderPaddingDecls } from './hf-dom'
import { paraFrameCss } from './para-frame'
installProseMirrorPerf()
export { borderLineCss }
import {
INLINE_RULE_CLASS,
@@ -134,7 +140,7 @@ import { constrainTableWidthAtCell } from './table-sizing'
import {
CHART_MAX_WIDTH_PX,
CHART_TITLE_ROW_PX,
chartTitleRowPx,
cellBoxesSpec,
drawChartSvg,
renderChartSpec,
@@ -154,6 +160,7 @@ import {
DelMark,
InsMark,
CtrlCheckboxMark,
FormatOffClearExtension,
InstrFieldMark,
SymMark,
ItalicMark,
@@ -572,6 +579,25 @@ export function clipboardParaAttrs(el: HTMLElement): Record<string, unknown> | n
return Object.keys(attrs).length > 0 ? attrs : null
}
/**
* Word orders a run without w:rtl left-to-right even inside a w:bidi paragraph
* (probe 2026-09-16: "arabic (LATIN)" keeps the Latin on the right, a leading
* bullet glyph stays at the left edge). The paragraph keeps its RTL start side
* and mirrored indents; only the text is isolated as one LTR item when no run
* is an RTL run. Runs marked rtl (or inheriting it) keep the browser's RTL base.
*/
function paraContentSpec(node: PmNode): DOMOutputSpec | 0 {
if (!(node.attrs.bidi || node.attrs.bidiInferred) || !node.textContent) return 0
let rtlRun = false
node.descendants((child) => {
if (child.isText && child.marks.some((m) => m.attrs.cs === true || m.attrs.rtl === true)) {
rtlRun = true
}
return !rtlRun
})
return rtlRun ? 0 : ['span', { class: 'doc-ltr-runs' }, 0]
}
function blockAttrs(
node: {
attrs: Record<string, unknown>
@@ -1069,6 +1095,11 @@ export const DocInlineImage = Node.create({
// a float excludes its whole margin box: without a shape the lines
// above the picture (Word lays them at full width) would shorten too
if (ty - qt > 0) styles.push(`shape-outside:inset(${px(ty - qt)} 0 0 0)`)
// clampCellImageTops fills --cell-lift once the cell top is measured
if (ty < 0 && !/layoutInCell="(?:0|false)"/.test(String(node.attrs.xml ?? ''))) {
margin.top = `calc(${px(ty)} + var(--cell-lift,0px))`
attrs['data-cell-lift'] = '1'
}
}
}
// positionV line/center: lift so the picture centers on the anchor line
@@ -1391,7 +1422,7 @@ export const DocParagraph = Node.create({
return [{ tag: 'p', getAttrs: (el) => clipboardParaAttrs(el as HTMLElement) }]
},
renderHTML({ node }) {
return ['p', blockAttrs(node), 0]
return ['p', blockAttrs(node), paraContentSpec(node)]
},
})
@@ -1418,7 +1449,7 @@ export const DocHeading = Node.create({
const attrs = blockAttrs(node)
// heading by direct w:outlineLvl alone: the built-in h1-h6 font rules skip this class
if (node.attrs.outlineOnly) attrs.class = `${attrs.class ?? ''} doc-outline-only`.trim()
return [`h${level}`, attrs, 0]
return [`h${level}`, attrs, paraContentSpec(node)]
},
})
@@ -1481,7 +1512,7 @@ export const DocListItem = Node.create({
]
.filter(Boolean)
.join(' ')
return ['div', { ...base, class: cls }, 0]
return ['div', { ...base, class: cls }, paraContentSpec(node)]
},
addCommands() {
return {
@@ -1672,47 +1703,6 @@ function lineFactorDecos(doc: PmNode): DecorationSet {
return DecorationSet.create(doc, decos)
}
/**
* Top-level blocks a transaction touched, as offsets in its final document;
* null when a step replaces so much that recomputing everything is cheaper.
*/
function touchedTopLevelBlocks(tr: Transaction): Set<number> | null {
const { doc } = tr
const maps = tr.mapping.maps
const ranges: Array<[number, number]> = []
let unknown = false
tr.steps.forEach((step, i) => {
// positions after step i, carried through the later steps into the final doc
const push = (start: number, end: number) => {
let from = start
let to = end
for (let j = i + 1; j < maps.length; j++) {
from = maps[j].map(from, -1)
to = maps[j].map(to, 1)
}
ranges.push([from, to])
}
let moved = false
maps[i].forEach((_oldStart, _oldEnd, newStart, newEnd) => {
moved = true
push(newStart, newEnd)
})
if (moved) return
// mark and attribute steps leave positions alone but change the nodes
const s = step as { from?: unknown; to?: unknown; pos?: unknown }
if (typeof s.from === 'number' && typeof s.to === 'number') push(s.from, s.to)
else if (typeof s.pos === 'number') push(s.pos, s.pos + 1)
else unknown = true
})
if (unknown) return null
const touched = new Set<number>()
doc.forEach((node, offset) => {
const end = offset + node.nodeSize
if (ranges.some(([from, to]) => offset < to && end > from)) touched.add(offset)
})
return touched.size * 2 > doc.childCount ? null : touched
}
/**
* Only the touched top-level blocks recompute; every other block's
* decorations ride the mapping. Decorations are a pure function of the block
@@ -1724,7 +1714,8 @@ function updateLineFactorDecos(old: DecorationSet, tr: Transaction): DecorationS
const { doc } = tr
const touched = touchedTopLevelBlocks(tr)
if (!touched) return lineFactorDecos(doc)
let set = old.map(tr.mapping, doc)
// streamed tail chunks: mapping the whole set walked every decoration per chunk
let set = appendsAtEnd(tr) ? old : old.map(tr.mapping, doc)
const decos: Decoration[] = []
for (const offset of touched) {
const node = doc.nodeAt(offset)
@@ -1871,6 +1862,20 @@ export const LineFactorExtension = Extension.create({
},
})
function firstRunFontAscii(node: PmNode): string | null {
let font: string | null = null
node.descendants((child) => {
if (font !== null) return false
if (child.isText) {
const mark = child.marks.find((m) => m.type.name === 'docTextStyle')
font = ((mark?.attrs.fontAscii ?? mark?.attrs.font) as string | null) ?? null
return false
}
return true
})
return font
}
function firstRunSizeHalfPoints(node: PmNode): number | null {
let sz: number | null = null
node.descendants((child) => {
@@ -2019,6 +2024,17 @@ function paragraphTabStops(
}
/** the stray line's list geometry in docListItem attr shape (its w:ind is the anchor paragraph's) */
/** the paragraph's direct w:lineRule, else its style's (strays carry no direct spacing) */
function effectiveLineRule(
nodeAttrs: Record<string, unknown>,
storage: ListNumberingStorage,
): string | undefined {
if (nodeAttrs.lineRule != null || nodeAttrs.lineRawTwips != null) {
return (nodeAttrs.lineRule as string | null) ?? 'auto'
}
return storage.styles?.get(String(nodeAttrs.styleId ?? ''))?.display?.lineRule
}
function strayGeometryAttrs(node: PmNode): Record<string, unknown> {
const ind = node.attrs.strayIndent as StrayIndent | null
return {
@@ -2031,6 +2047,51 @@ function strayGeometryAttrs(node: PmNode): Record<string, unknown> {
/** the anchor paragraph's own empty line, laid out like any paragraph; the
* picture block ahead of it already carries the paragraph's page break */
/** spacing / line-rule declarations of an anchor line spec for the stray line
* (indent and alignment come from the stray's own attrs; fonts from its runs) */
const STRAY_LINE_PROPS = new Set([
'margin-top',
'margin-bottom',
'line-height',
'--doc-line-mult',
'--doc-line-factor',
'--doc-grid-pitch',
'font-size',
])
const STRAY_LINE_CLASSES = new Set(['doc-lh-fixed', 'doc-nosnap', 'sp-auto-b', 'sp-auto-a'])
function strayLineCss(spec: DomSpec, strayAttrs: Record<string, string>): string {
const attrs = spec[1] as Record<string, string>
for (const cls of (attrs.class ?? '').split(' ')) {
if (STRAY_LINE_CLASSES.has(cls)) strayAttrs.class += ` ${cls}`
}
return (attrs.style ?? '')
.split(';')
.filter((decl) => STRAY_LINE_PROPS.has(decl.slice(0, decl.indexOf(':')).trim()))
.join(';')
}
/** Chromium expands a tab to the next multiple of tab-size from the content
* edge, so the first custom stop past the indent sizes that grid: exact for the
* one-stop operator rows PDF converters emit, a plain grid beyond it */
function strayTabCss(line: Record<string, unknown>, ind: StrayIndent | null): string {
let stops: TabStop[] = []
if (typeof line.tabStops === 'string') {
try {
const parsed: unknown = JSON.parse(line.tabStops)
if (Array.isArray(parsed)) stops = parsed as TabStop[]
} catch {
/* malformed attr: default grid */
}
}
const left = ind?.leftTwips ?? (typeof line.indentLeft === 'number' ? line.indentLeft : 0)
const next = stops
.filter((s) => s.val !== 'clear' && s.val !== 'bar' && !s.rel && s.pos > left)
.map((s) => s.pos)
.sort((a, b) => a - b)[0]
return `white-space:pre-wrap;tab-size:${((next ?? left + 720) - left) / 20}pt`
}
export function anchorLineSpec(line: Record<string, unknown>): DomSpec {
const attrs = blockAttrs({
attrs: { ...line, docxIndex: null, pageBreakBefore: false },
@@ -2177,6 +2238,23 @@ export const ListNumberingExtension = Extension.create<object, ListNumberingStor
// natural height (Word); equal sizes keep the inherited line untouched
if (level.szHalfPoints && level.szHalfPoints > (runSizeHalf ?? para.sizeHalf)) {
styles.push(MARKER_NATURAL_LINE_HEIGHT)
} else if (marker.symbolFont && effectiveLineRule(nodeAttrs, storage) !== 'exact') {
// Word's line is the tallest ascent plus the tallest descent on it:
// a Symbol bullet's ascent tops every Latin text face, so the box
// (bottom-aligned, the glyph stays on the baseline) sets that height
const textPt = (runSizeHalf ?? para.sizeHalf) / 2
const linePt = symbolBulletLinePt(
marker.symbolFont,
(szHalf ?? para.sizeHalf) / 2,
(stray ? null : firstRunFontAscii(nodes[i].node)) ?? para.family,
textPt,
)
if (linePt) {
styles.push(
`--li-marker-lh:calc(${linePt}pt * var(--doc-line-mult,1))`,
'--li-marker-va:bottom',
)
}
}
if (level.color) {
styles.push(
@@ -2654,11 +2732,14 @@ export const DocTable = Node.create({
styles.push(`width:min(${widthPx}px,${paper})`)
centerMargin = `margin-left:calc((${contentW} - min(${widthPx}px,${paper}))/2)`
} else {
// a negative w:tblInd moves the box into the left margin, so the same
// amount is added back to the right-hand spill allowance
const indented =
!tblFloated && node.attrs.tblAlign !== 'right' && Number(node.attrs.indentTwips) > 0
!tblFloated && node.attrs.tblAlign !== 'right' && Number(node.attrs.indentTwips)
const indentPx = indented ? Number(node.attrs.indentTwips) / 15 : 0
const shift = indentPx < 0 ? `+ ${(-indentPx).toFixed(1)}px` : `- ${indentPx.toFixed(1)}px`
const spill = indentPx
? `calc(${contentW} + ${spillMargin} - ${indentPx.toFixed(1)}px)`
? `calc(${contentW} + ${spillMargin} ${shift})`
: `calc(${contentW} + ${spillMargin})`
widthExpr = `min(${widthPx}px,${spill})`
styles.push(`width:${widthExpr}`)
@@ -2775,16 +2856,18 @@ export const DocTable = Node.create({
// a suppressed text-anchored float with a negative w:tblpY still hangs that far
// above its anchor paragraph in Word (cover logo strips reach into the top
// margin), so the inline table keeps the lift as a negative top margin
const liftTwips =
node.attrs.tblFloatSuppressed &&
(node.attrs.tblFloatVertAnchor ?? 'text') === 'text' &&
Number(node.attrs.tblFloatYTwips) < 0
? -Number(node.attrs.tblFloatYTwips)
const suppressedTextY =
node.attrs.tblFloatSuppressed && (node.attrs.tblFloatVertAnchor ?? 'text') === 'text'
? Number(node.attrs.tblFloatYTwips) || 0
: 0
const liftTwips = suppressedTextY < 0 ? -suppressedTextY : 0
if (liftTwips > 0) {
const lift = (liftTwips / 15).toFixed(1)
styles.push(`margin-top:-${lift}px`)
attrs['data-tblp-lift'] = lift
} else if (suppressedTextY > 0) {
// ... and a positive one keeps the table that far below its anchor
styles.push(`margin-top:${(suppressedTextY / 15).toFixed(1)}px`)
}
if (styles.length > 0) attrs.style = styles.join(';')
// A colgroup with normalized percentages defines the column grid whenever the
@@ -3158,6 +3241,18 @@ export const NativeTableSupport = Extension.create({
/** formats pmDocToSavePlan can rebuild into the docx (see imageFromProtectedAttrs) */
const PERSISTABLE_IMAGE_URL = /^data:image\/(?:png|jpeg|gif);base64,/
let lazyMediaHashes = new Set<string>()
/** pictures served lazily from the open document persist by part reference */
export function setLazyMediaHashes(hashes: Iterable<string>): void {
lazyMediaHashes = new Set(hashes)
}
const isLazyImage = (src: string): boolean => {
const hash = parseLazyMediaUrl(src)?.hash
return hash !== undefined && lazyMediaHashes.has(hash)
}
const persistableImage = (src: string): boolean =>
PERSISTABLE_IMAGE_URL.test(src) || isLazyImage(src)
/** 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.
@@ -3232,12 +3327,17 @@ export const ImageCopyExtension = Extension.create({
const node = sel.node
if (node.type.name !== 'docProtected' || node.attrs.blockType !== 'image') return false
let dataUrl = node.attrs.imageDataUrl
if (typeof dataUrl !== 'string' || !dataUrl.startsWith('data:image/')) return false
if (typeof dataUrl !== 'string') return false
if (!dataUrl.startsWith('data:image/') && !isLazyImage(dataUrl)) return false
const lazyPart = parseLazyMediaUrl(dataUrl)?.partPath
const directlyCopyable = lazyPart
? /\.(?:png|jpe?g|gif)$/i.test(lazyPart)
: PERSISTABLE_IMAGE_URL.test(dataUrl)
// the save pipeline persists only png/jpeg/gif; display-only formats
// (bmp/webp/svg/tiff...) are transcoded to PNG from the already-decoded
// DOM img so the copy stays saveable — undecodable ones keep the
// default HTML copy
if (!PERSISTABLE_IMAGE_URL.test(dataUrl)) {
// default HTML copy (a lazy picture is read from the file by the main process)
if (!directlyCopyable) {
const dom = view.nodeDOM(sel.from) as HTMLElement | null
const img = dom?.querySelector?.('img.doc-protected-img') as HTMLImageElement | null
if (!img || !img.naturalWidth || !img.naturalHeight) return false
@@ -3405,7 +3505,7 @@ export const DocProtected = Node.create({
const src = img?.getAttribute('src') ?? ''
// persistable formats only: a bmp/webp/svg picture would display and
// then silently vanish on save — the placeholder shell is honest
if (!PERSISTABLE_IMAGE_URL.test(src)) return null
if (!persistableImage(src)) return null
let meta: Record<string, unknown> = {}
try {
meta = JSON.parse(el.getAttribute('data-image-meta') ?? '{}') as Record<string, unknown>
@@ -3437,7 +3537,7 @@ export const DocProtected = Node.create({
getAttrs: (el) => {
const img = el as HTMLImageElement
const src = img.getAttribute('src') ?? ''
if (!PERSISTABLE_IMAGE_URL.test(src)) return false
if (!persistableImage(src)) return false
let meta: Record<string, unknown> = {}
try {
meta = JSON.parse(img.getAttribute('data-image-meta') ?? '{}') as Record<
@@ -3861,7 +3961,11 @@ function protectedDomSpec(node: PmNode): DomSpec {
: ''
const align = node.attrs.strayAlign as string | null
const alignCss = align === 'center' || align === 'right' ? `text-align:${align}` : ''
const strayCss = [strayStyle, indCss, alignCss].filter(Boolean).join(';')
const line = node.attrs.anchorLine as Record<string, unknown> | null
const lineCss = line ? strayLineCss(anchorLineSpec(line), strayAttrs) : ''
const tabCss =
line && strayRuns.some((r) => r.text.includes('\t')) ? strayTabCss(line, ind) : ''
const strayCss = [lineCss, tabCss, strayStyle, indCss, alignCss].filter(Boolean).join(';')
if (strayCss) strayAttrs.style = strayCss
if (node.attrs.strayStyleId) strayAttrs['data-style'] = String(node.attrs.strayStyleId)
const stray: DomSpec = ['div', strayAttrs, ...strayRuns.flatMap((run) => runSpanSpecs(run))]
@@ -5118,8 +5222,7 @@ function imageResizePlugin(): Plugin {
...display,
widthPx: Math.round(w),
// the handle measures the plot SVG; heightPx spans title row + plot
heightPx:
Math.round(h) + (display.title !== undefined ? CHART_TITLE_ROW_PX : 0),
heightPx: Math.round(h) + chartTitleRowPx(display),
},
}),
)
@@ -5791,6 +5894,7 @@ const textboxSubExtensions = [
CtrlCheckboxMark,
CheckboxToggleExtension,
TextStyleMark,
FormatOffClearExtension,
CommentMark,
UndoRedo,
]
@@ -5880,6 +5984,7 @@ export const editorExtensions = [
CtrlCheckboxMark,
RprChangeMark,
TextStyleMark,
FormatOffClearExtension,
CommentMark,
InsMark,
DelMark,
@@ -17,11 +17,3 @@ export function collectHeadings(doc: PmNode): HeadingRef[] {
})
return out
}
export function hasHeadings(doc: PmNode): boolean {
for (let i = 0; i < doc.childCount; i++) {
const node = doc.child(i)
if (node.type.name === 'docHeading' && node.textContent.trim()) return true
}
return false
}
+22 -1
View File
@@ -153,6 +153,23 @@ export function hfRowStyle(row: HfTableRow | undefined): Record<string, string>
return style
}
/** w:ind of a stacked strip paragraph (twips): logical margins (RTL-aware), so a w:pBdr border
* keeps its own padding and draws at the indent edge like Word. Tabbed paragraphs
* stay full-width: their stops are laid out from the column edge (hfTabSegments). */
export function hfParaIndentStyle(para: {
indentLeft?: number
indentRight?: number
indentFirstLine?: number
runs?: Array<{ text: string }>
}): Record<string, string> {
const style: Record<string, string> = {}
if (para.runs?.some((r) => r.text.includes('\t'))) return style
if (para.indentLeft) style.marginInlineStart = px(para.indentLeft)
if (para.indentRight) style.marginInlineEnd = px(para.indentRight)
if (para.indentFirstLine) style.textIndent = px(para.indentFirstLine)
return style
}
/** cell paragraph box; a tab-wrapped paragraph spans several line boxes, so
* first-line-only (indent, space before) and last-line-only (space after)
* props land on the matching line */
@@ -1205,6 +1222,7 @@ export function makeGapHfEl(opts: {
continue
}
if (para.bidi) p.style.direction = 'rtl'
Object.assign(p.style, hfParaIndentStyle(para))
if (para.align) {
p.style.textAlign =
para.align === 'left' || para.align === 'center' || para.align === 'right'
@@ -1281,7 +1299,10 @@ export function makeGapHfEl(opts: {
host.append(p)
continue
}
if (para.runs.length === 0) p.textContent = ' '
if (para.runs.length === 0) {
p.textContent = ' '
if (para.emptyRunSizeHalfPoints) p.style.fontSize = `${para.emptyRunSizeHalfPoints / 2}pt`
}
for (const run of para.runs) {
const span = document.createElement('span')
span.textContent = display(run.text)
+76 -1
View File
@@ -1,4 +1,5 @@
import { Extension, Mark } from '@tiptap/core'
import { Extension, Mark, combineTransactionSteps, getChangedRanges } from '@tiptap/core'
import type { Mark as PmMark } from '@tiptap/pm/model'
import { Plugin, PluginKey } from '@tiptap/pm/state'
import { Decoration, DecorationSet } from '@tiptap/pm/view'
import {} from '@tiptap/pm/tables'
@@ -737,4 +738,78 @@ export const TextStyleMark = Mark.create({
},
})
/** Imported runs carry explicit Word off-switches (w:b/w:i val=0 → docTextStyle
* boldOff/italicOff, painted as font-weight/style:normal). They coexist with a
* later user toggle: the toggle only adds the bold/italic mark, and since the
* docTextStyle span renders INSIDE the strong/em, the off-switch wins the paint
* while isActive() and the saved file both say bold — the ribbon lights and the
* reopened document is bold, but the live text never changes (task#426).
* Word semantics: bolding a b=0 run replaces the off-switch. Enforce that at
* the model level — whenever an edit leaves text (or storedMarks) carrying both
* the format mark and its off-switch, retire the off-switch (true → false, not
* null: the run still knows it was explicitly off). Un-bolding such text puts
* the off-switch back (false → true), because the inherited weight — paragraph
* style, table first row, docDefaults — would otherwise paint bold while
* rawRPr keeps saving the original w:b=0. Save output is unaffected
* (runFromMarks never reads the Off attrs). */
const FORMAT_OFF_PAIRS = [
{ mark: 'bold', off: 'boldOff' },
{ mark: 'italic', off: 'italicOff' },
] as const
export const FormatOffClearExtension = Extension.create({
name: 'formatOffClear',
addProseMirrorPlugins() {
return [
new Plugin({
key: new PluginKey('formatOffClear'),
appendTransaction: (trs, oldState, state) => {
if (!trs.some((tr) => tr.docChanged || tr.storedMarksSet)) return null
const styleType = state.schema.marks.docTextStyle
if (!styleType) return null
let tr: typeof state.tr | null = null
const clearedAttrs = (marks: readonly PmMark[]): Record<string, unknown> | null => {
const style = marks.find((m) => m.type === styleType)
if (!style) return null
let attrs = style.attrs
for (const { mark, off } of FORMAT_OFF_PAIRS) {
const on = marks.some((m) => m.type.name === mark)
if (attrs[off] === true && on) attrs = { ...attrs, [off]: false }
else if (attrs[off] === false && !on) attrs = { ...attrs, [off]: true }
}
return attrs === style.attrs ? null : attrs
}
const docTrs = trs.filter((t) => t.docChanged)
if (docTrs.length) {
const transform = combineTransactionSteps(oldState.doc, [...docTrs])
for (const { newRange } of getChangedRanges(transform)) {
state.doc.nodesBetween(newRange.from, newRange.to, (node, pos) => {
if (!node.isText) return
const attrs = clearedAttrs(node.marks)
if (!attrs) return
tr ??= state.tr
tr.addMark(pos, pos + node.nodeSize, styleType.create(attrs))
})
}
}
const stored = state.storedMarks
if (stored) {
const attrs = clearedAttrs(stored)
if (attrs) {
tr ??= state.tr
tr.setStoredMarks(
stored.map((m) => (m.type === styleType ? styleType.create(attrs) : m)),
)
}
}
return tr
},
}),
]
},
})
// ---- textbox sub-editor schema ----
+161 -54
View File
@@ -4,11 +4,42 @@ import { Decoration, DecorationSet } from '@tiptap/pm/view'
import type { EditorView } from '@tiptap/pm/view'
import type { LineAnchor } from '../pagination'
import { rangeSlot } from '../dom-range'
import { TopLevelPositions } from './top-level-pos'
const anchorRange = rangeSlot()
const key = new PluginKey<DecorationSet>('paginationGaps')
/**
* The decoration metas of one pagination pass, dispatched as a single
* transaction. Each dispatch is a view update whose next DOM read forces a
* whole-document layout, so four dispatches per pass cost four layouts.
*/
export class LayoutBatch {
private readonly metas: Array<[PluginKey | string, unknown]> = []
private readonly after: Array<() => void> = []
constructor(private readonly view: EditorView) {}
set(key: PluginKey | string, value: unknown): void {
this.metas.push([key, value])
}
/** DOM-only work that must follow the dispatch */
then(fn: () => void): void {
this.after.push(fn)
}
commit(): void {
if (this.metas.length > 0) {
let tr = this.view.state.tr.setMeta('addToHistory', false)
for (const [k, v] of this.metas) tr = tr.setMeta(k, v)
this.view.dispatch(tr)
}
for (const fn of this.after) fn()
}
}
/**
* Always-on pagination in the canvas: renders a "page gap" widget before each
* page-leading block (previous page's bottom margin + gray inter-page band +
@@ -89,6 +120,7 @@ export function rowFillAttrs(
export function setRowFills(
view: EditorView,
fills: Array<{ el: Element; targetPx: number; extraPx?: number }>,
batch?: LayoutBatch,
): void {
const decos: Decoration[] = []
for (const [i, fill] of fills.entries()) {
@@ -110,8 +142,10 @@ export function setRowFills(
}
const next = DecorationSet.create(view.state.doc, decos)
const prev = rowFillKey.getState(view.state)
if (!prev || !sameGaps(prev, next))
view.dispatch(view.state.tr.setMeta(rowFillKey, next).setMeta('addToHistory', false))
if (!prev || !sameGaps(prev, next)) {
if (batch) batch.set(rowFillKey, next)
else view.dispatch(view.state.tr.setMeta(rowFillKey, next).setMeta('addToHistory', false))
}
}
/**
@@ -202,15 +236,19 @@ export function insideFloatTable(el: Element): boolean {
export function setFloatVShifts(
view: EditorView,
shifts: Array<{ el: Element; dyPx: number; flow?: boolean; carryPx?: number }>,
batch?: LayoutBatch,
): void {
const decos: Decoration[] = []
const flowKeys: string[] = []
const positions = new TopLevelPositions(view)
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)
const pos =
positions.of(shift.el)?.from ??
view.state.doc.resolve(view.posAtDOM(shift.el, 0)).before(1)
decos.push(
Decoration.widget(
pos,
@@ -232,7 +270,9 @@ export function setFloatVShifts(
const dy = Math.round(shift.dyPx * 10) / 10
if (!shift.flow && Math.abs(dy) < 0.5) continue
try {
const $inside = view.state.doc.resolve(view.posAtDOM(shift.el, 0))
// a top-level table / protected block resolves from the walk; nested ones (cell content) still scan
const top = shift.el.parentElement === view.dom ? positions.of(shift.el) : null
const $inside = view.state.doc.resolve(top ? top.from + 1 : view.posAtDOM(shift.el, 0))
for (let d = $inside.depth; d > 0; d--) {
const name = $inside.node(d).type.name
if (name !== 'docTable' && name !== 'docProtected') continue
@@ -270,12 +310,17 @@ export function setFloatVShifts(
.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),
)
if (batch) {
batch.set(floatVKey, next)
batch.set(floatFlowChangedMeta, flowChanged)
} else {
view.dispatch(
view.state.tr
.setMeta(floatVKey, next)
.setMeta(floatFlowChangedMeta, flowChanged)
.setMeta('addToHistory', false),
)
}
}
}
@@ -406,7 +451,9 @@ export function setPageGaps(
* a zero-height page-float-host widget that measurement/clones ignore
* (not page-gap: page-boundary consumers must not count it as a page) */
firstPageEls?: { els: HTMLElement[]; key: string },
batch?: LayoutBatch,
): void {
const positions = new TopLevelPositions(view)
const decos: Decoration[] = []
if (firstPageEls?.els.length) {
decos.push(
@@ -432,8 +479,14 @@ export function setPageGaps(
if ('el' in gap) {
kind = 'block'
try {
const $inside = view.state.doc.resolve(view.posAtDOM(gap.el, 0))
pos = $inside.before(1)
let after: number
const range = positions.of(gap.el)
if (range) ({ from: pos, to: after } = range)
else {
const $inside = view.state.doc.resolve(view.posAtDOM(gap.el, 0))
pos = $inside.before(1)
after = $inside.after(1)
}
if (gap.carryPx !== undefined) {
const carry = Math.round(gap.carryPx)
decos.push(
@@ -455,7 +508,7 @@ export function setPageGaps(
decos.push(
Decoration.node(
pos,
$inside.after(1),
after,
{ class: 'page-break-lead' },
{ key: `page-lead-${ordinal}` },
),
@@ -517,17 +570,23 @@ export function setPageGaps(
}
const next = DecorationSet.create(view.state.doc, decos)
const prev = key.getState(view.state)
if (!prev || !sameGaps(prev, next))
view.dispatch(view.state.tr.setMeta(key, next).setMeta('addToHistory', false))
if (!prev || !sameGaps(prev, next)) {
if (batch) batch.set(key, next)
else view.dispatch(view.state.tr.setMeta(key, next).setMeta('addToHistory', false))
}
// DOM-only rowspan bridging; observer paused so PM never re-parses the mutated
// cells (a reparse would wipe cell attrs that don't round-trip through DOM)
const obs = (view as unknown as { domObserver?: { stop(): void; start(): void } }).domObserver
obs?.stop()
try {
syncPhantomRowspans(view.dom as HTMLElement)
} finally {
obs?.start()
const bridge = () => {
const obs = (view as unknown as { domObserver?: { stop(): void; start(): void } }).domObserver
obs?.stop()
try {
syncPhantomRowspans(view.dom as HTMLElement)
} finally {
obs?.start()
}
}
if (batch) batch.then(bridge)
else bridge()
}
/** Line top of a cut anchor (screen px); falls back to the parent element's top. */
@@ -1131,7 +1190,11 @@ export function syncFloatShifts(
})
acc += r.height
}
for (const f of floats) {
// reads first: a style write between two getBoundingClientRect calls forces
// a whole-document layout per float (thousands of anchored pictures hung
// the renderer for minutes)
const curTops = floats.map((f) => f.el.getBoundingClientRect().top)
floats.forEach((f, i) => {
let above = 0
let pageStart = 0
let pagePush = firstPagePush
@@ -1153,8 +1216,7 @@ export function syncFloatShifts(
const rel = f.pageRelV ? f.top - (f.anchorTop ?? 0) - (f.pageRelFromPage ? pagePush : 0) : f.top
const desired = origin + (pageStart + rel) * factor + above
const applied = parseFloat(f.el.dataset.pageFloatDy ?? '0') || 0
const cur = f.el.getBoundingClientRect().top
const next = applied + (desired - cur) / factor
const next = applied + (desired - curTops[i]) / factor
if (Math.abs(next) < 0.5) {
f.el.style.removeProperty('--page-float-dy')
delete f.el.dataset.pageFloatDy
@@ -1162,7 +1224,7 @@ export function syncFloatShifts(
f.el.style.setProperty('--page-float-dy', `${next.toFixed(1)}px`)
f.el.dataset.pageFloatDy = String(next)
}
}
})
}
/**
@@ -1176,7 +1238,13 @@ export function syncFloatShifts(
*/
export function syncAnchorBands(pm: HTMLElement, factor: number): void {
let run: HTMLElement[] = []
// the inputs are static band data and anchor-line heights, so the writes
// can wait until the walk has read everything (no layout per anchor run)
const writes: Array<[HTMLElement, number]> = []
const apply = (el: HTMLElement, minHeight: number): void => {
writes.push([el, minHeight])
}
const commit = (el: HTMLElement, minHeight: number): void => {
const own = Math.round(parseFloat(el.dataset.band ?? '0') || 0)
if (minHeight === own) {
if (el.dataset.bandAdj === undefined) return
@@ -1303,6 +1371,7 @@ export function syncAnchorBands(pm: HTMLElement, factor: number): void {
}
flush()
settleBeside(null)
for (const [el, minHeight] of writes) commit(el, minHeight)
}
/**
@@ -1314,11 +1383,13 @@ export function syncAnchorBands(pm: HTMLElement, factor: number): void {
* --page-float-dy channel as syncFloatShifts.
*/
export function clampCellBoxTops(pm: HTMLElement, paperTop: number, factor: number): void {
for (const box of Array.from(
const boxes = Array.from(
pm.querySelectorAll<HTMLElement>('.doc-cell-boxes > .doc-textbox, .doc-cell-boxes > div'),
)) {
const r = box.getBoundingClientRect()
if (r.height <= 0) continue
)
const rects = boxes.map((box) => box.getBoundingClientRect())
boxes.forEach((box, i) => {
const r = rects[i]
if (r.height <= 0) return
const applied = parseFloat(box.dataset.pageFloatDy ?? '0') || 0
const naturalTop = r.top - applied * factor
const next = Math.max(0, (paperTop - naturalTop) / factor)
@@ -1331,7 +1402,38 @@ export function clampCellBoxTops(pm: HTMLElement, paperTop: number, factor: numb
box.style.setProperty('--page-float-dy', `${next.toFixed(1)}px`)
box.dataset.pageFloatDy = String(next)
}
}
})
}
/** Word confines a layoutInCell picture to its cell: a negative anchor offset
* lifting it past the cell top is pushed back down (--cell-lift margin term). */
export function clampCellImageTops(pm: HTMLElement, factor: number): void {
const imgs = Array.from(pm.querySelectorAll<HTMLElement>('td img[data-cell-lift]'))
const rects = imgs.map((img) => {
const cell = img.closest('td')
if (!cell) return null
const cs = getComputedStyle(cell)
const inset = (parseFloat(cs.borderTopWidth) || 0) + (parseFloat(cs.paddingTop) || 0)
return {
top: img.getBoundingClientRect().top,
cellTop: cell.getBoundingClientRect().top + inset * factor,
}
})
imgs.forEach((img, i) => {
const r = rects[i]
if (!r) return
const applied = parseFloat(img.dataset.cellLiftDy ?? '') || 0
const next = Math.max(0, (r.cellTop - (r.top - applied * factor)) / factor)
if (next < 0.5) {
if (applied) {
img.style.removeProperty('--cell-lift')
delete img.dataset.cellLiftDy
}
} else if (Math.abs(next - applied) > 0.5) {
img.style.setProperty('--cell-lift', `${next.toFixed(1)}px`)
img.dataset.cellLiftDy = String(next)
}
})
}
/**
@@ -1353,23 +1455,23 @@ 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()
for (const fill of Array.from(fills)) {
const cell = fill.parentElement
if (!cell) continue
// measure every cell before the first style write (one layout, not one per fill)
const cellLefts = Array.from(fills, (fill) => fill.parentElement?.getBoundingClientRect().left)
Array.from(fills).forEach((fill, i) => {
const cellLeft = cellLefts[i]
if (cellLeft === undefined) return
// differing-width documents: the fill covers the table's own page, not the paper
const gap = fill.closest<HTMLElement>('.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 left = px((pmRect.left - cellLeft) / 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
if (fill.style.right !== 'auto') fill.style.right = 'auto'
}
})
}
/**
@@ -1382,7 +1484,18 @@ export function alignTableGapFills(pm: HTMLElement, factor: number): void {
export function alignGapHfStrips(pm: HTMLElement, bodyLeftPx: number, factor: number): void {
const pmLeft = pm.getBoundingClientRect().left
const canvasTarget = pmLeft + bodyLeftPx * factor
for (const el of Array.from(pm.querySelectorAll<HTMLElement>('.page-gap-hf'))) {
const strips = Array.from(pm.querySelectorAll<HTMLElement>('.page-gap-hf'))
// widget DOM reused from an equal-width era still carries the stylesheet
// centering (left:50% + translateX(-50%)): pin every strip before measuring,
// or the increment is applied against the wrong base. Pins, then one round
// of measurement, then the shifts: a write between two measurements forces
// a whole-document layout per strip
for (const el of strips) {
if (el.style.transform !== 'none') el.style.transform = 'none'
if (!el.style.left) el.style.left = '0px'
}
const stripLefts = strips.map((el) => el.getBoundingClientRect().left)
strips.forEach((el, i) => {
// prefer the strip's own section inset (--hf-ml: the footer above a section
// break belongs to the PREVIOUS section, the header below it to the next one),
// then the gap's next-section inset (--gap-ml, makeGapEl): mixed-margin
@@ -1393,26 +1506,20 @@ export function alignGapHfStrips(pm: HTMLElement, bodyLeftPx: number, factor: nu
el.closest<HTMLElement>('.page-gap')?.style.getPropertyValue('--gap-ml')
const ownPx = own ? parseFloat(own) : NaN
const target = Number.isFinite(ownPx) ? pmLeft + ownPx * factor : canvasTarget
// widget DOM reused from an equal-width era still carries the stylesheet
// centering (left:50% + translateX(-50%)): pin it before measuring, or the
// increment is applied against the wrong base
if (el.style.transform !== 'none') el.style.transform = 'none'
if (!el.style.left) el.style.left = '0px'
const delta = (target - el.getBoundingClientRect().left) / factor
if (Math.abs(delta) < 0.5) continue
const delta = (target - stripLefts[i]) / factor
if (Math.abs(delta) < 0.5) return
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<HTMLElement>('.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)
const anchored = Array.from(pm.querySelectorAll<HTMLElement>('.page-gap [data-paper-x]'))
const hostLefts = anchored.map((el) => el.offsetParent?.getBoundingClientRect().left)
anchored.forEach((el, i) => {
const hostLeft = hostLefts[i]
if (hostLeft === undefined) return
const left = (parseFloat(el.dataset.paperX!) - (hostLeft - pmLeft) / factor).toFixed(1)
if (el.style.left !== `${left}px`) el.style.left = `${left}px`
}
})
}
/** remove all float display shifts (leaving print view) */
@@ -0,0 +1,140 @@
import { DecorationSet } from '@tiptap/pm/view'
import type { Decoration } from '@tiptap/pm/view'
import { Fragment } from '@tiptap/pm/model'
import type { Node as PmNode } from '@tiptap/pm/model'
/**
* prosemirror-view's DecorationSet.forChild scans every root-level decoration
* and every child entry for each child of a node. Long documents keep one
* node decoration per paragraph at the root (line factors, anchors), so each
* view update costs blocks × decorations — hundreds of ms per keystroke on a
* 10k-paragraph document. Non-inline root decorations can never apply to a
* child, and the child table is sorted, so skip the former and binary-search
* the latter. Same result as upstream; the mixed case (inline root
* decorations overlapping a child that has its own subtree) still goes
* through the original method, which builds the private DecorationGroup.
*/
interface SetInternals {
local: Decoration[]
children: Array<number | SetInternals>
inlineLocals?: Decoration[]
}
type ForChild = (this: DecorationSet, offset: number, node: PmNode) => DecorationSet
const proto = DecorationSet.prototype as unknown as { forChild: ForChild }
const original = proto.forChild
const Ctor = DecorationSet as unknown as new (
local: Decoration[],
children: Array<number | SetInternals>,
) => DecorationSet
const isInline = (d: Decoration) => (d as unknown as { inline: boolean }).inline
const byPos = (a: Decoration, b: Decoration) => a.from - b.from || a.to - b.to
export function fastForChild(this: DecorationSet, offset: number, node: PmNode): DecorationSet {
if (this === DecorationSet.empty) return this
if (node.isLeaf) return DecorationSet.empty
const self = this as unknown as SetInternals
const children = self.children
let lo = 0
let hi = children.length / 3
while (lo < hi) {
const mid = (lo + hi) >> 1
if ((children[mid * 3] as number) < offset) lo = mid + 1
else hi = mid
}
const child =
lo * 3 < children.length && children[lo * 3] === offset
? (children[lo * 3 + 2] as unknown as DecorationSet)
: undefined
const inline = self.inlineLocals ?? (self.inlineLocals = self.local.filter(isInline))
if (inline.length === 0) return child ?? DecorationSet.empty
if (child) return original.call(this, offset, node)
const start = offset + 1
const end = start + node.content.size
let local: Decoration[] | undefined
for (const dec of inline) {
if (dec.from < end && dec.to > start) {
const from = Math.max(start, dec.from) - start
const to = Math.min(end, dec.to) - start
if (from < to)
(local ??= []).push(
(dec as unknown as { copy: (f: number, t: number) => Decoration }).copy(from, to),
)
}
}
return local ? new Ctor(local.sort(byPos), []) : DecorationSet.empty
}
/**
* Fragment.findIndex walks the children from the front on every call. Node
* decorations are validated through it on every DecorationSet.map, so a
* keystroke on a 10k-paragraph document cost paragraphs² again. Fragments are
* immutable: cache the children's end positions once and binary-search.
*/
interface FragmentInternals {
content: PmNode[]
size: number
ends?: Float64Array
}
type FindIndex = (this: Fragment, pos: number) => { index: number; offset: number }
const fragmentProto = Fragment.prototype as unknown as { findIndex: FindIndex }
const originalFindIndex = fragmentProto.findIndex
/** below this the linear walk wins */
const FIND_INDEX_MIN_CHILDREN = 64
const found = { index: 0, offset: 0 }
export function fastFindIndex(this: Fragment, pos: number): { index: number; offset: number } {
const self = this as unknown as FragmentInternals
const content = self.content
if (content.length < FIND_INDEX_MIN_CHILDREN || pos <= 0 || pos >= self.size) {
return originalFindIndex.call(this, pos)
}
let ends = self.ends
if (!ends) {
ends = new Float64Array(content.length)
let acc = 0
for (let i = 0; i < content.length; i++) ends[i] = acc += content[i].nodeSize
self.ends = ends
}
let lo = 0
let hi = content.length - 1
while (lo < hi) {
const mid = (lo + hi) >> 1
if (ends[mid] < pos) lo = mid + 1
else hi = mid
}
if (ends[lo] === pos) {
found.index = lo + 1
found.offset = pos
} else {
found.index = lo
found.offset = lo === 0 ? 0 : ends[lo - 1]
}
return found
}
export function installProseMirrorPerf(): void {
if (proto.forChild !== fastForChild) proto.forChild = fastForChild
if (fragmentProto.findIndex !== fastFindIndex) fragmentProto.findIndex = fastFindIndex
}
/** test hook: run a callback against the upstream implementations */
export function withOriginalFindIndex<T>(fn: () => T): T {
fragmentProto.findIndex = originalFindIndex
try {
return fn()
} finally {
fragmentProto.findIndex = fastFindIndex
}
}
/** test hook: run a callback against the upstream implementation */
export function withOriginalForChild<T>(fn: () => T): T {
proto.forChild = original
try {
return fn()
} finally {
proto.forChild = fastForChild
}
}
+214 -34
View File
@@ -265,9 +265,17 @@ function pointColor(chart: ChartDisplay, s: number, i: number): string {
export function renderChartSpec(chart: ChartDisplay): DomSpec {
const frame: DomSpec[] = []
if (chart.title !== undefined) {
const titleStyle: Record<string, string> =
chart.titleFontPt !== undefined
? {
style:
`font-size:${chart.titleFontPt}pt;height:${chartTitleRowPx(chart)}px;` +
`line-height:${Math.round(chart.titleFontPt * PT_TO_PX * 1.2)}px`,
}
: {}
frame.push([
'div',
{ class: 'doc-chart-title', contenteditable: 'false' },
{ class: 'doc-chart-title', contenteditable: 'false', ...titleStyle },
chart.title || '\u00a0',
])
}
@@ -353,6 +361,8 @@ interface ChartGeom {
sideRight?: number
/** a data table under the plot carries the category texts */
noCatLabels?: boolean
/** axis tick-label size in px (explicit c:txPr sz, else 10) */
labelPx?: number
}
export function chartPlotWidth(chart: ChartDisplay): number {
@@ -423,6 +433,61 @@ export const CHART_MAX_WIDTH_PX = 660
/** height of the title row above the plot SVG; heightPx = title row + plot,
* so the resize write-back must add it before storing the measured SVG height */
export const CHART_TITLE_ROW_PX = 22
const PT_TO_PX = 96 / 72
/** estimated text advance at a font size: CJK glyphs ~1em, Latin ~0.7em (0.55em at title sizes) */
function chartTextPx(text: string, fontPx: number, latinEm = 0.7): number {
return [...text].reduce((w, ch) => w + fontPx * (isCjk(ch.codePointAt(0) ?? 0) ? 1 : latinEm), 0)
}
/** greedy word wrap (CJK breaks anywhere) for category labels that overflow their slot */
function wrapChartText(text: string, maxPx: number, fontPx: number): string[] {
const lines: string[] = []
let cur = ''
for (const ch of text) {
if (cur && chartTextPx(cur + ch, fontPx) > maxPx && lines.length < 2) {
const space = cur.lastIndexOf(' ')
if (space > 0 && !isCjk(ch.codePointAt(0) ?? 0)) {
lines.push(cur.slice(0, space))
cur = cur.slice(space + 1) + ch
} else {
lines.push(cur)
cur = ch
}
} else cur += ch
}
if (cur) lines.push(cur)
return lines.length ? lines : [text]
}
/** title row height; an explicit c:title size wraps inside the chart width like Word */
export function chartTitleRowPx(chart: ChartDisplay): number {
if (chart.title === undefined) return 0
if (chart.titleFontPt === undefined) return CHART_TITLE_ROW_PX
const fontPx = chart.titleFontPt * PT_TO_PX
const lines = Math.max(
1,
Math.ceil(chartTextPx(chart.title, fontPx, 0.55) / Math.max(1, chartPlotWidth(chart) - 16)),
)
return Math.round(lines * fontPx * 1.2 + 6)
}
/** inline size/color of document-authored chart text (beats the class defaults) */
function chartTextStyle(fontPt?: number, color?: string): Record<string, string> {
const decls: string[] = []
if (fontPt !== undefined) decls.push(`font-size:${Math.round(fontPt * PT_TO_PX * 10) / 10}px`)
if (color) decls.push(`fill:#${color}`)
return decls.length ? { style: decls.join(';') } : {}
}
/** c:numFmt subset for data labels: decimals from the 0s after '.', ',' switches grouping on */
function formatDataLabel(value: number, fmt?: string): string {
if (!fmt || fmt === 'General') return formatAxisValue(value)
const decimals = /\.(0+)/.exec(fmt)?.[1].length ?? 0
const [int, frac] = Math.abs(value).toFixed(decimals).split('.')
const grouped = fmt.includes(',') ? int.replace(/\B(?=(\d{3})+(?!\d))/g, ',') : int
return (value < 0 ? '-' : '') + grouped + (frac ? `.${frac}` : '')
}
/** draw the read-only SVG preview into the node's .doc-chart-canvas */
export function drawChartSvg(dom: HTMLElement, chart: ChartDisplay | null): void {
@@ -444,11 +509,13 @@ export function drawChartSvg(dom: HTMLElement, chart: ChartDisplay | null): void
// 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
const titleRowPx = chart.title !== undefined ? CHART_TITLE_ROW_PX : 0
// horizontal bars put category labels on the y axis; reserve room for the
// longest one (10px axis font: CJK glyphs are ~1em wide, Latin ~0.7em)
const catLabelPx = (s: string) =>
[...s].reduce((w, ch) => w + (isCjk(ch.codePointAt(0) ?? 0) ? 10 : 7), 0)
const titleRowPx = chartTitleRowPx(chart)
const axisPt = chart.xAxis?.fontPt ?? chart.yAxis?.fontPt
const labelPx = axisPt !== undefined ? axisPt * PT_TO_PX : 10
const legendPx = chart.legendFontPt !== undefined ? chart.legendFontPt * PT_TO_PX : 10
// horizontal bars put category labels on the y axis; reserve room for the longest one
const catLabelPx = (s: string) => chartTextPx(s, labelPx)
const legendTextPx = (s: string) => chartTextPx(s, legendPx)
const maxCatPx = Math.max(0, ...chart.categories.map(catLabelPx))
const width = chartPlotWidth(chart)
// l/r/tr legends stack vertically in a side gutter, like Word; other
@@ -457,8 +524,27 @@ export function drawChartSvg(dom: HTMLElement, chart: ChartDisplay | null): void
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)))
? Math.min(Math.round(width * 0.35), 20 + Math.max(0, ...legendNames.map(legendTextPx)))
: 0
// bottom legends wrap into centered rows when the entries overflow the width, like Word
const legendEntryW = (i: number) => 14 + legendTextPx(legendNames[i]) + 12
const legendEntryH = Math.max(18, Math.round(legendPx * 1.8))
const legendRows: number[][] = []
if (showLegend && !sideLegend && !topLegend) {
let row: number[] = []
let rowW = 0
legendNames.forEach((_, i) => {
if (row.length > 0 && rowW + legendEntryW(i) > width - 8) {
legendRows.push(row)
row = []
rowW = 0
}
row.push(i)
rowW += legendEntryW(i)
})
if (row.length > 0) legendRows.push(row)
}
const bottomLegendPx = legendRows.length * legendEntryH
const legendLeft = sideLegend && chart.legendPos === 'l'
const cartesian = !isPie && !isRadar
const xTitle = cartesian && !chart.xAxis?.deleted ? chart.xAxis?.title : undefined
@@ -479,17 +565,28 @@ export function drawChartSvg(dom: HTMLElement, chart: ChartDisplay | null): void
// also capped against the chart's own width: resize allows 120px-wide
// 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) +
(chart.kind === 'bar' && chart.horizontal
? Math.min(140, width * 0.4, 16 + maxCatPx)
: Math.round(4.6 * labelPx)) +
(legendLeft ? legendW : 0) +
(yTitle ? 14 : 0),
right: 12 + (sideLegend && !legendLeft ? legendW : 0),
top: 12 + (topLegend ? 18 : 0),
bottom:
(dataTable ? 4 + tableH : 26) +
(showLegend && !sideLegend && !topLegend ? 18 : 0) +
(xTitle ? 14 : 0),
(dataTable ? 4 + tableH : Math.round(2.6 * labelPx)) + bottomLegendPx + (xTitle ? 14 : 0),
...(sideLegend ? (legendLeft ? { sideLeft: legendW } : { sideRight: legendW }) : {}),
...(dataTable ? { noCatLabels: true } : {}),
labelPx,
}
// column charts wrap overflowing category labels inside their slot like Word
if (cartesian && !(chart.kind === 'bar' && chart.horizontal) && !geom.noCatLabels) {
const cols = Math.max(chart.categories.length, 1)
const slotW = (geom.width - geom.left - geom.right) / cols
const lines = Math.max(
1,
...chart.categories.map((c) => wrapChartText(c, slotW - 4, labelPx).length),
)
geom.bottom += (lines - 1) * Math.round(labelPx * 1.2)
}
const svg = document.createElementNS(SVG_NS, 'svg')
svg.setAttribute('viewBox', `0 0 ${geom.width} ${geom.height}`)
@@ -521,7 +618,7 @@ export function drawChartSvg(dom: HTMLElement, chart: ChartDisplay | null): void
)
}
if (xTitle) {
const legendRow = showLegend && !sideLegend && !topLegend ? 18 : 0
const legendRow = bottomLegendPx
svgEl(
svg,
'text',
@@ -581,9 +678,30 @@ export function drawChartSvg(dom: HTMLElement, chart: ChartDisplay | null): void
legendNames[i],
)
})
} else if (showLegend && !topLegend) {
legendRows.forEach((row, r) => {
const rowW = row.reduce((w, i) => w + legendEntryW(i), 0) - 12
let x = (geom.width - rowW) / 2
const y = geom.height - bottomLegendPx + r * legendEntryH + 3
for (const i of row) {
drawKey(x, y, i)
svgEl(
svg,
'text',
{
x: String(x + 14),
y: String(y + 8),
class: 'doc-chart-axis-label',
...chartTextStyle(chart.legendFontPt),
},
legendNames[i],
)
x += legendEntryW(i)
}
})
} else if (showLegend) {
const slot = geom.width / legendNames.length
const rowY = topLegend ? 4 : geom.height - 15
const rowY = 4
legendNames.forEach((name, i) => {
const cx = slot * i + slot / 2
drawKey(cx - Math.min(name.length * 3.2, slot / 2 - 14) - 12, rowY, i)
@@ -768,27 +886,36 @@ function drawAxes(svg: SVGElement, chart: ChartDisplay, geom: ChartGeom): void {
const yOf = (v: number) => geom.top + plotH - ((v - min) / span) * plotH
const slotW = plotW / cols
// horizontal gridlines with value labels
// horizontal gridlines with value labels; a parsed value axis without
// c:majorGridlines draws none, like Word
const grid = chart.yAxis?.gridLine
const labelPx = geom.labelPx ?? 10
const yStyle = chartTextStyle(chart.yAxis?.fontPt, chart.yAxis?.color)
const xStyle = chartTextStyle(chart.xAxis?.fontPt, chart.xAxis?.color)
const steps = Math.max(1, Math.round(span / step))
for (let i = 0; i <= steps; i++) {
const v = min + step * i
const y = yOf(v)
svgEl(svg, 'line', {
x1: String(geom.left),
y1: String(y),
x2: String(geom.width - geom.right),
y2: String(y),
class: 'doc-chart-grid',
})
if (!chart.yAxis || grid !== undefined) {
svgEl(svg, 'line', {
x1: String(geom.left),
y1: String(y),
x2: String(geom.width - geom.right),
y2: String(y),
class: 'doc-chart-grid',
...(grid ? { style: `stroke:#${grid}` } : {}),
})
}
if (chart.yAxis?.deleted) continue
svgEl(
svg,
'text',
{
x: String(geom.left - 6),
y: String(y + 3),
y: String(y + labelPx * 0.3),
class: 'doc-chart-axis-label',
'text-anchor': 'end',
...yStyle,
},
formatAxisValue(v) + (pct ? '%' : ''),
)
@@ -798,18 +925,42 @@ function drawAxes(svg: SVGElement, chart: ChartDisplay, geom: ChartGeom): void {
// category labels
chart.categories.forEach((cat, c) => {
if (c >= cols || geom.noCatLabels || chart.xAxis?.deleted) return
wrapChartText(cat, slotW - 4, labelPx).forEach((line, k) => {
svgEl(
svg,
'text',
{
x: String(geom.left + slotW * c + slotW / 2),
y: String(
geom.height - geom.bottom + Math.round(labelPx * 1.4) + k * Math.round(labelPx * 1.2),
),
class: 'doc-chart-axis-label',
'text-anchor': 'middle',
...xStyle,
},
line,
)
})
})
// c:showVal on bars: clustered labels sit above the bar, stacked ones in the segment
const valueLabels = chart.dataLabels?.val ? chart.dataLabels : undefined
const labelStyle = chartTextStyle(valueLabels?.fontPt, valueLabels?.color)
const valueLabelPx = valueLabels?.fontPt !== undefined ? valueLabels.fontPt * PT_TO_PX : 10
const drawValueLabel = (cx: number, y: number, value: number) => {
svgEl(
svg,
'text',
{
x: String(geom.left + slotW * c + slotW / 2),
y: String(geom.height - geom.bottom + 14),
x: String(cx),
y: String(y),
class: 'doc-chart-axis-label',
'text-anchor': 'middle',
...labelStyle,
},
cat,
formatDataLabel(value, valueLabels?.numFmt),
)
})
}
if (chart.kind === 'bar' && stacked) {
// one bar per category, series segments cumulated up (down for negatives)
@@ -831,6 +982,13 @@ function drawAxes(svg: SVGElement, chart: ChartDisplay, geom: ChartGeom): void {
height: String(Math.max(1, Math.abs(y0 - y1))),
fill: seriesColor(chart, s),
})
if (valueLabels && Math.abs(y0 - y1) >= valueLabelPx) {
drawValueLabel(
geom.left + slotW * c + slotW / 2,
(y0 + y1) / 2 + valueLabelPx * 0.35,
value,
)
}
if (v >= 0) posBase[c] = to
else negBase[c] = to
})
@@ -851,6 +1009,13 @@ function drawAxes(svg: SVGElement, chart: ChartDisplay, geom: ChartGeom): void {
height: String(Math.max(1, Math.abs(y0 - y1))),
fill: seriesColor(chart, s),
})
if (valueLabels) {
drawValueLabel(
x + barW / 2,
value >= 0 ? Math.min(y0, y1) - 3 : Math.max(y0, y1) + valueLabelPx,
value,
)
}
})
})
} else if (chart.kind === 'area' && stacked) {
@@ -1341,8 +1506,9 @@ function drawPie(svg: SVGElement, chart: ChartDisplay, geom: ChartGeom): void {
if (labels.val) parts.push(String(value))
if (labels.pct) parts.push(`${Math.round((value / total) * 100)}%`)
const text = parts.join(', ')
const labelPx = labels.fontPt !== undefined ? labels.fontPt * PT_TO_PX : 10
// 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 inside = sweep * r * 0.65 >= text.length * labelPx * 0.6 && !single
const lr = inside ? Math.max(ri, r * 0.65) : r + 10
svgEl(
svg,
@@ -1351,6 +1517,7 @@ function drawPie(svg: SVGElement, chart: ChartDisplay, geom: ChartGeom): void {
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',
...chartTextStyle(labels.fontPt, labels.color),
'text-anchor': inside
? 'middle'
: Math.cos(mid) > 0.1
@@ -1923,15 +2090,23 @@ function cellParaSpec(
if (fmt?.spaceBeforeAuto) classes.push('sp-auto-b')
if (fmt?.spaceAfterAuto) classes.push('sp-auto-a')
if (classes.length) attrs.class = classes.join(' ')
return content.length > 0 ? ['div', attrs, ...content] : ['div', attrs, ['br', {}]]
if (content.length === 0) return ['div', attrs, ['br', {}]]
// runs without w:rtl order LTR inside an RTL paragraph (same rule as the editor's paraContentSpec)
const ltrRuns =
(fmt?.bidi || inferredBidi(fmt, runs ?? undefined)) && !!runs?.length && !runs.some((r) => r.cs)
return ltrRuns
? ['div', attrs, ['span', { class: 'doc-ltr-runs' }, ...content]]
: ['div', attrs, ...content]
}
/** 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) */
* height reserves the lowest box bottom (Word grows the row to hold them);
* wrapNone boxes overlay the cell without growing it */
export function cellBoxesSpec(boxes: TextboxDisplay[]): DomSpec {
if (boxes.length === 0) return ['div', { class: 'doc-cell-boxes' }]
let bottom = 0
for (const b of boxes) {
if (b.noWrap) continue
bottom = Math.max(bottom, (b.offsetYEmu ?? 0) / 9525 + (b.heightPx ?? b.minHeightPx ?? 0))
}
return [
@@ -1987,8 +2162,8 @@ export function renderTableSpec(model: TableModel, nested = false): DomSpec {
// vertical-text cells: writing-mode rides the .cell-vert/.cell-clip wrapper below
cell.textDirection ? 'position:relative' : '',
// authored colors stay the declarations; --dk-* twins feed the dark page (dark-page.ts)
cell.color ? `color:#${cell.color};${dkColor(cell.color)}` : '',
cell.bold ? 'font-weight:600' : '',
cell.styleColor ? `color:#${cell.styleColor};${dkColor(cell.styleColor)}` : '',
cell.styleBold ? 'font-weight:600' : '',
cell.fill ? `background-color:#${cell.fill};${dkBackground(`#${cell.fill}`)}` : '',
cell.align ? `text-align:${cell.align}` : '',
cell.vAlign && cell.vAlign !== 'top'
@@ -2147,13 +2322,18 @@ export function renderTableSpec(model: TableModel, nested = false): DomSpec {
centerMargin = `margin-left:calc((${contentW} - min(${widthPx}px,${paper}))/2)`
} else {
const indented =
model.align !== 'center' && model.align !== 'right' && (model.indentTwips ?? 0) > 0
model.align !== 'center' && model.align !== 'right' && (model.indentTwips ?? 0) !== 0
const indentPx = indented ? model.indentTwips! / 15 : 0
const base = nested ? '100%' : `calc(${contentW} + ${spillMargin})`
// a negative w:tblInd moves the box into the left margin and widens the
// right-hand spill allowance by the same amount (see DocTable.renderHTML)
const shift = indentPx < 0 ? `+ ${(-indentPx).toFixed(1)}px` : `- ${indentPx.toFixed(1)}px`
const avail = indentPx
? nested
? `calc(100% - ${indentPx.toFixed(1)}px)`
: `calc(${contentW} + ${spillMargin} - ${indentPx.toFixed(1)}px)`
? indentPx > 0
? `calc(100% - ${indentPx.toFixed(1)}px)`
: base
: `calc(${contentW} + ${spillMargin} ${shift})`
: base
widthExpr = `min(${widthPx}px,${avail})`
tableStyles.push(`width:${widthExpr}`)
@@ -73,7 +73,9 @@ export function charScaleXAttr(text: string, scalePct: number, perCharEm: number
})
}
/** glyphs compress like Word; the negative margin hands the saved width back to the line */
/** glyphs compress like Word; the negative margin hands the saved width back to the line.
* text-indent:0 — the block would inherit a hanging indent and shrink-to-fit
* to zero width, piling every glyph onto one spot */
export function charScaleXDecls(json: string): string[] {
let v: Partial<CharScaleX>
try {
@@ -87,6 +89,7 @@ export function charScaleXDecls(json: string): string[] {
`transform:scaleX(${v.s})`,
'transform-origin:0 50%',
`margin-right:${v.gapEm}em`,
'text-indent:0',
]
}
@@ -0,0 +1,35 @@
import type { EditorView } from '@tiptap/pm/view'
interface ChildDesc {
dom: Node
size: number
}
/**
* Doc positions of the top-level blocks from one walk over the view's child
* descs. posAtDOM sums the sizes of every preceding sibling on each call, so
* a pass positioning thousands of blocks (column specs, float shifts, gaps)
* paid blocks² for it — tens of seconds on a long converted PDF.
*/
export class TopLevelPositions {
private map: Map<Node, { from: number; to: number }> | null = null
constructor(private readonly view: EditorView) {}
/** before/after of the top-level block holding `el`; null when the element is not mounted */
of(el: Element): { from: number; to: number } | null {
let top: Element | null = el
while (top && top.parentElement !== this.view.dom) top = top.parentElement
if (!top) return null
if (!this.map) {
this.map = new Map()
const { children } = (this.view as unknown as { docView: { children: ChildDesc[] } }).docView
let pos = 0
for (const child of children) {
if (child.size > 0) this.map.set(child.dom, { from: pos, to: pos + child.size })
pos += child.size
}
}
return this.map.get(top) ?? null
}
}
@@ -0,0 +1,51 @@
import type { Transaction } from '@tiptap/pm/state'
import { ReplaceStep } from '@tiptap/pm/transform'
/**
* Top-level blocks a transaction touched, as offsets in its final document;
* null when a step replaces so much that recomputing everything is cheaper.
*/
export function touchedTopLevelBlocks(tr: Transaction): Set<number> | null {
const { doc } = tr
const maps = tr.mapping.maps
const ranges: Array<[number, number]> = []
let unknown = false
tr.steps.forEach((step, i) => {
// positions after step i, carried through the later steps into the final doc
const push = (start: number, end: number) => {
let from = start
let to = end
for (let j = i + 1; j < maps.length; j++) {
from = maps[j].map(from, -1)
to = maps[j].map(to, 1)
}
ranges.push([from, to])
}
let moved = false
maps[i].forEach((_oldStart, _oldEnd, newStart, newEnd) => {
moved = true
push(newStart, newEnd)
})
if (moved) return
// mark and attribute steps leave positions alone but change the nodes
const s = step as { from?: unknown; to?: unknown; pos?: unknown }
if (typeof s.from === 'number' && typeof s.to === 'number') push(s.from, s.to)
else if (typeof s.pos === 'number') push(s.pos, s.pos + 1)
else unknown = true
})
if (unknown) return null
const touched = new Set<number>()
doc.forEach((node, offset) => {
const end = offset + node.nodeSize
if (ranges.some(([from, to]) => offset < to && end > from)) touched.add(offset)
})
return touched.size * 2 > doc.childCount ? null : touched
}
/** a single insertion at the document end: every existing position survives unchanged */
export function appendsAtEnd(tr: Transaction): boolean {
if (tr.steps.length !== 1) return false
const step = tr.steps[0]
if (!(step instanceof ReplaceStep)) return false
return step.from === step.to && step.from === tr.before.content.size
}
-3
View File
@@ -3,12 +3,9 @@
import type { DesktopApi } from '../shared/ipc'
import type { ProjectApi } from '@genoffice/project-store'
import type { FilesPaneApi } from '@genoffice/ui'
declare global {
interface Window {
desktop: DesktopApi
filesPaneApi: FilesPaneApi
projectApi: ProjectApi
}
}
+9 -2
View File
@@ -56,7 +56,7 @@ import { docStyleCss } from './doc-style-css'
import { setNoteNumFmts } from './note-format'
import type { CompareEntry } from './editor/compare'
import { blocksToPmDoc, pmDocOptions, pmDocToSavePlan, type PmNode } from './editor/convert'
import { TABLE_TRAILING_SKIP } from './editor/extensions'
import { TABLE_TRAILING_SKIP, setLazyMediaHashes } from './editor/extensions'
import { TRACK_IGNORE } from './editor/revisions'
import {
cancelPhasedContent,
@@ -342,6 +342,7 @@ export async function loadFile(
try {
const parsed = await parseDocx(new Uint8Array(result.data))
if (generation !== openGeneration) return 'superseded'
setLazyMediaHashes(parsed.extras.lazyMediaHashes)
// before setContent: blockAttrs/marks bake fontTable-driven factors and chains into the DOM
const adopted = await adoptEmbeddedFonts(parsed.embeddedFonts)
if (!adopted || generation !== openGeneration) return 'superseded'
@@ -466,6 +467,7 @@ export async function newFile(ctx: FileActionContext): Promise<boolean | undefin
const bytes = await buildBlankDocx({ eastAsiaFont: defaultEastAsiaFontFor(getLang()) })
const parsed = await parseDocx(bytes)
if (generation !== openGeneration) return
setLazyMediaHashes([])
const adopted = await adoptEmbeddedFonts(parsed.embeddedFonts)
if (!adopted || generation !== openGeneration) return
setDocFontTable(parsed.fontTable)
@@ -897,6 +899,7 @@ async function saveOnce(
// already landed on disk — overwrite that file instead of creating another
let savedPath = doc.filePath ?? pathlessDocSavedPath
let passwordIntentPending = false
let fullBytes: Uint8Array | undefined
if (explicitTarget) {
// MCP-driven explicit output: no dialog, no derived name — always write to
// the caller's path (overwrite policy is enforced in the main process).
@@ -913,6 +916,7 @@ async function saveOnce(
}
savedPath = result.path!
passwordIntentPending = result.passwordIntentPending === true
if (result.data) fullBytes = new Uint8Array(result.data)
if (!doc.filePath) pathlessDocSavedPath = savedPath
} else if (saveAs || !savedPath) {
// A never-saved document still called "Untitled" gets a name derived from its first heading
@@ -932,6 +936,7 @@ async function saveOnce(
}
savedPath = result.path!
passwordIntentPending = result.passwordIntentPending === true
if (result.data) fullBytes = new Uint8Array(result.data)
if (!doc.filePath) pathlessDocSavedPath = savedPath
} else {
const result = await window.desktop.saveDocx(savedPath, buffer, auto)
@@ -945,9 +950,10 @@ async function saveOnce(
return false
}
passwordIntentPending = result.passwordIntentPending === true
if (result.data) fullBytes = new Uint8Array(result.data)
}
// parse before the identity check: a document opened during this await must not be rewritten
const reparsed = await parseDocx(bytes)
const reparsed = await parseDocx(fullBytes ?? bytes)
if (editor.state.doc !== docSnapshot || passwordIntentPending) {
// The user kept editing, opened another document or chose another
// password after the main process captured this save. Keep the live state
@@ -973,6 +979,7 @@ async function saveOnce(
return true
}
// Reload from saved bytes so docxIndex anchors point at the new file.
setLazyMediaHashes(reparsed.extras.lazyMediaHashes)
setDocFontTable(reparsed.fontTable)
editor.storage.listNumbering.styles = reparsed.styles
editor.storage.listNumbering.docDefaults = reparsed.docDefaults
+54
View File
@@ -1067,6 +1067,31 @@
font-weight: bold;
font-style: normal;
}
/* Berlin Sans FB Demi (Office display face): Word renders the real bold cut;
Arial Bold rescaled to its advances (probe 2026-09-17: 0.953x at 15pt), and the
demi weight is bold at every requested weight */
@font-face {
font-family: 'Berlin Sans FB GO';
src:
local('Arial-BoldMT'),
local('Arial Bold'),
url('./LiberationSans-Bold.ttf') format('truetype');
size-adjust: 95.3%;
font-weight: normal;
font-style: normal;
font-display: block;
}
@font-face {
font-family: 'Berlin Sans FB GO';
src:
local('Arial-BoldMT'),
local('Arial Bold'),
url('./LiberationSans-Bold.ttf') format('truetype');
size-adjust: 95.3%;
font-weight: bold;
font-style: normal;
font-display: block;
}
/* MS Gothic family (Word-private on macOS, so the JA chain lands on Hiragino
* Sans whose Latin is proportional and kana fullwidth). Advances measured from
* Word's msgothic.ttc and confirmed by a Word probe (2026-09-03): MS Gothic
@@ -1110,6 +1135,35 @@
font-style: normal;
font-display: block;
}
/* MS Mincho: the same fixed-pitch half-width Latin as MS Gothic (Word probe 2026-09-17) */
@font-face {
font-family: 'MS Mincho GO';
src: url('./LiberationMono-Regular.ttf') format('truetype');
unicode-range:
U+0020-007E, U+00A0-00A6, U+00A9-00AF, U+00B2-00B3, U+00B5, U+00B7-00D6, U+00D8-00F6,
U+00F8-00FF;
size-adjust: 83.333%;
font-weight: normal;
font-style: normal;
font-display: block;
}
@font-face {
font-family: 'MS Mincho GO';
src: url('./NotoSansCJKsc-Regular-subset.woff2') format('woff2');
unicode-range: U+00A7, U+00B1, U+00B6, U+00D7, U+00F7;
font-weight: normal;
font-style: normal;
font-display: block;
}
@font-face {
font-family: 'MS Mincho GO';
src: url('./LiberationMono-Regular.ttf') format('truetype');
unicode-range: U+00A8, U+00B0, U+00B4;
size-adjust: 166.667%;
font-weight: normal;
font-style: normal;
font-display: block;
}
@font-face {
font-family: 'MS PGothic GO';
src: url('./LiberationSans-Regular.ttf') format('truetype');
+1 -1
View File
@@ -4,7 +4,7 @@
<meta charset="UTF-8" />
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data: blob:; worker-src 'self' blob:; connect-src 'self' ws://localhost:*"
content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: genoffice-docx-media:; font-src 'self' data: blob:; worker-src 'self' blob:; connect-src 'self' ws://localhost:*"
/>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>GenOffice Docs</title>
+127 -21
View File
@@ -57,7 +57,7 @@ const MONO_FONT_RE =
/** Constant Latin advance for monospace families (chain-head name decides); null when proportional */
export function monospaceAdvanceEm(fontFamily: string): number | null {
const head = fontFamily.split(',')[0]
if (/^'?(ms gothic|MS ゴシック)'?$/i.test(head.trim())) return 0.5
if (/^'?(ms (gothic|mincho)|MS (ゴシック|\u660e\u671d))'?$/i.test(head.trim())) return 0.5
if (!MONO_FONT_RE.test(head)) return null
return /consolas/i.test(head) ? 0.55 : 0.6
}
@@ -237,7 +237,9 @@ export function lineHeightFactor(fontFamily: string): number {
// BIZ UD: Word for Mac lacks the UDP cuts and substitutes Yu Gothic wholesale
// (probe 2026-09-03: 1.44 at 10.5/11/12pt); an installed face renders real
if (f.includes('biz ud')) return bizUdSubstituted(fontFamily) ? 1.44 : 1.3029
if (/mincho|明朝|ゴシック|ms (ui )?p?gothic|hiragino|osaka|kozuka|小塚/.test(f)) return 1.3029
if (hgSubstituted(fontFamily)) return 1.44
if (/mincho|明朝|ゴシック|ms (ui )?p?gothic|hiragino|osaka|kozuka|小塚/.test(f.normalize('NFKC')))
return 1.3029
// missing Noto/Source Han SC: Word substitutes SimSun at 1.3029 (probe
// 2026-08-13; bare 'Noto Sans SC' presumed same substitution)
if (/^noto sans sc$/.test(f)) return 1.3029
@@ -302,6 +304,9 @@ export function lineHeightFactor(fontFamily: string): number {
// a 4% surplus per line cascades into whole-paragraph pagination drift,
// so the big Office faces get their real values.
if (f.includes('times') || f.includes('liberation serif')) return 1.15
// Georgia Pro (M365 cloud face) renders real with its typo metrics (Word
// probe 2026-09-17: 9.72/10.8/11.76pt at 10/11/12pt)
if (f.includes('georgia pro')) return 0.98
if (f.includes('georgia')) return 1.1375
// 1.172 = Cambria's Win metrics (1172/1000), probe 2026-08-23 measured
// 1.1724 at 36pt; the unknown-name fallback below substitutes to Cambria
@@ -359,7 +364,10 @@ export function lineHeightFactor(fontFamily: string): number {
if (f.includes('lucida sans')) return 1.179
if (f.includes('bradley hand')) return 1.25
if (f.includes('open sans')) return 1.365
if (f.includes('roboto')) return 1.169
// Roboto and Montserrat are M365 cloud faces Word renders real at their hhea
// totals (probe 2026-09-17: 11.76/12.96/14.16 and 12.24/13.44/14.64pt at 10/11/12pt)
if (f.includes('roboto')) return 1.172
if (f.includes('montserrat')) return 1.219
if (f.includes('shonar bangla')) return 1.0
// IRANYekan substitutes to Arial like the Iranian B/XB faces (probe 2026-08-23)
if (f.includes('iranyekan')) return 1.15
@@ -374,6 +382,57 @@ export function lineHeightFactor(fontFamily: string): number {
return 1.172
}
/** Word DFonts win ascent (em) of the symbol bullet faces */
const SYMBOL_FACE_ASCENT: Record<string, number> = {
symbol: 1.0054,
wingdings: 0.8989,
'wingdings 2': 0.8433,
'wingdings 3': 0.9277,
webdings: 0.7998,
}
/** Descent (em) Word lays the common Latin text faces with (hhea/win, whichever its factor follows) */
const LATIN_DESCENT: Array<[RegExp, number]> = [
[/calibri|carlito/, 0.2686],
[/aptos/, 0.2817],
[/cambria|caladea/, 0.2222],
[/times|liberation serif/, 0.2163],
[/arial|helvetica|liberation sans/, 0.2119],
[/georgia/, 0.2192],
[/consolas/, 0.251],
[/courier/, 0.3003],
[/verdana/, 0.21],
[/tahoma/, 0.2065],
[/segoe ui/, 0.251],
[/roboto/, 0.25],
[/lato/, 0.213],
[/montserrat/, 0.251],
[/open sans/, 0.293],
]
/**
* Natural height (pt) of a list item's first line when a symbol-font bullet
* sits on it, or null when the text face alone is as tall. Word sizes a line
* by the max ascent plus the max descent of the faces on it, so Symbol (ascent
* 1.0054em, above every Latin text face) lifts bullet lines: probe 2026-09-17,
* Aptos 10pt text + Symbol 10.5pt bullet at 1.15 = 15.12-15.36pt against
* 14.0pt text-only lines; Cambria 11pt + Symbol 11pt = 15.36-15.6 vs 14.9.
*/
export function symbolBulletLinePt(
symbolFont: string,
markerPt: number,
textFont: string | null,
textPt: number,
): number | null {
const asc = SYMBOL_FACE_ASCENT[symbolFont.trim().toLowerCase()]
if (asc === undefined || !(markerPt > 0) || !(textPt > 0)) return null
const f = (textFont ?? '').toLowerCase()
const desc = LATIN_DESCENT.find(([re]) => re.test(f))?.[1] ?? 0.25
const line = asc * markerPt + desc * textPt
if (line <= lineHeightFactor(textFont ?? 'Calibri') * textPt + 0.01) return null
return Math.round(line * 1000) / 1000
}
/**
* Factor for run-declared Noto/Source Han regional variants missing on this
* platform, for CJK text only. JP/SC/TC are Word-probed (2026-08-13): Word
@@ -700,6 +759,25 @@ export function bizUdSubstituted(font: string): boolean {
return isBundledFont(head) || !isFontAvailable(head)
}
/**
* Ricoh HG faces of the Windows JP Office bundle that Word for Mac does not
* ship (its DFonts carry only Gothic E, Mincho E, Soei Kaku Gothic UB and Maru
* Gothic M-PRO, rendered real at the MS-class pitch): Word substitutes Yu
* Gothic wholesale, kana, kanji and Latin alike, whatever the name says (probe
* 2026-09-16: 14.4pt @10pt = 1.44 for HG(P/S) Kyokashotai, HG Mincho B, HG
* Gyoshotai, HG Sei-Kaishotai-PRO, HG Soei Kaku Pop-tai, HGS Soei Presence EB,
* HG Gothic M; the JP-named Hiragino Kaku Gothic Pro W3 the same).
*/
const HG_SUBSTITUTED_RE = new RegExp(
`^hg[ps]?(\u6559\u79d1\u66f8\u4f53|\u660e\u671db|\u884c\u66f8\u4f53|\u6b63\u6977\u66f8\u4f53|\u5275\u82f1\u89d2\u30dd\u30c3\u30d7\u4f53|\u5275\u82f1\u30d7\u30ec\u30bc\u30f3\u30b9|\u30b4\u30b7\u30c3\u30afm)|^\u30d2\u30e9\u30ae\u30ce\u89d2\u30b4`,
)
export function hgSubstituted(font: string): boolean {
const head = font.split(',')[0].replace(/['"]/g, '').trim()
if (!HG_SUBSTITUTED_RE.test(head.normalize('NFKC').toLowerCase())) return false
return isBundledFont(head) || !isFontAvailable(head)
}
export function cssFontFamily(font: string, followAltName = true): string {
const f = font.toLowerCase()
const chain = (...families: string[]) =>
@@ -736,8 +814,16 @@ export function cssFontFamily(font: string, followAltName = true): string {
// (probe 2026-08-23); macOS Palatino matches their Latin widths within 0.2%
if (f.includes('palatino') || f.includes('book antiqua'))
return `${chain(font, 'Palatino Linotype', 'Palatino', 'Book Antiqua', BOX, CJK_SERIF)},serif`
if (f === 'arial' || f.startsWith('arial '))
// a missing "Arial MT Black"-style name with a fontTable altName substitutes
// like any unknown face (Word draws its Courier New alias)
if ((f === 'arial' || f.startsWith('arial ')) && !(followAltName && fontTableAltName(font)))
return `${chain(font, 'Liberation Sans', CJK_SANS)},sans-serif`
// Berlin Sans FB Demi ships with Office and Word renders it real, a bold
// display cut 0.953x Arial Bold wide (probe 2026-09-17); the size-adjusted
// bold alias (fonts.css) stands in where the face is missing. The regular
// cut is a different (unprobed) weight and keeps the generic fallback
if (/berlin sans fb demi/.test(f))
return `${chain(font, 'Berlin Sans FB GO', 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))
@@ -909,11 +995,12 @@ export function cssFontFamily(font: string, followAltName = true): string {
return `${chain(...head, ...krLatin, ...chainFor, ...hangulTail)},${serif ? 'serif' : 'sans-serif'}`
}
if (
/[぀-ヿ]|mincho|meiryo|hiragino|osaka|yugoth|yu (gothic|mincho)|ms (ui )?p?(gothic|mincho)|明朝|biz ud|kozuka|小塚/i.test(
/[぀-ヿ]|mincho|meiryo|hiragino|osaka|yugoth|yu (gothic|mincho)|ms (ui )?p?(gothic|mincho)|明朝|biz ud|kozuka|小塚|^hg[ps]?(\u6559\u79d1\u66f8|\u884c\u66f8|\u6b63\u6977\u66f8|\u5275\u82f1)/i.test(
nfkc,
)
) {
const serif = /mincho|明朝/i.test(nfkc) && !bizUdSubstituted(font)
const serif =
/mincho|\u660e\u671d/i.test(nfkc) && !bizUdSubstituted(font) && !hgSubstituted(font)
// Meiryo (UI): Word renders the real faces; the range-limited aliases
// (fonts.css) rescale the Hiragino/Verdana fallbacks to Meiryo advances
if (/meiryo|メイリオ/i.test(nfkc)) {
@@ -921,15 +1008,20 @@ export function cssFontFamily(font: string, followAltName = true): string {
return `${chain(font, alias, ...JA_SANS)},sans-serif`
}
// MS Gothic family renders real in Word (half-width mono Latin / proportional
// kana); the range-limited aliases (fonts.css) reproduce those advances
// kana); the range-limited aliases (fonts.css) reproduce those advances.
// MS Mincho (Word probe 2026-09-17: real MS-Mincho, digits 0.5em, fullwidth
// colon 1em) shares the fixed-pitch Latin alias
const msGothic = /^ms (ui )?(p)?(gothic|ゴシック)$/i.exec(nfkc.trim())
const msAlias = !msGothic
? []
: msGothic[1]
? ['MS UI Gothic GO', 'MS UI Gothic JA GO']
: msGothic[2]
? ['MS PGothic GO', 'MS PGothic JA GO']
: ['MS Gothic GO']
const msMincho = /^ms (mincho|\u660e\u671d)$/i.test(nfkc.trim())
const msAlias = msMincho
? ['MS Mincho GO']
: !msGothic
? []
: msGothic[1]
? ['MS UI Gothic GO', 'MS UI Gothic JA GO']
: msGothic[2]
? ['MS PGothic GO', 'MS PGothic JA GO']
: ['MS Gothic GO']
return `${chain(font, ...msAlias, ...(serif ? JA_SERIF : JA_SANS))},${serif ? 'serif' : 'sans-serif'}`
}
if (
@@ -1544,19 +1636,23 @@ export function isCjkFontName(fontFamily: string): boolean {
const f = fontFamily.toLowerCase()
const nfkc = f.normalize('NFKC')
// hangul-lettered vendor names are Korean faces even when otherwise unknown
return CJK_FONT_NAME_RE.test(f) || KO_FONT_RE.test(nfkc) || /[가-힣ᄀ-ᇿ㄰-㆏]/.test(nfkc)
return (
CJK_FONT_NAME_RE.test(f) ||
CJK_FONT_NAME_RE.test(nfkc) ||
KO_FONT_RE.test(nfkc) ||
/[가-힣ᄀ-ᇿ㄰-㆏]/.test(nfkc)
)
}
const CJK_FONT_NAME_RE =
/宋|黑|楷|仿|明|雅黑|等线|simsun|simhei|simkai|simfang|kaiti|fangsong|songti|stsong|yahei|dengxian|mingliu|jhenghei|biaukai|dfkai|kaiu|mincho|ms (ui )?p?gothic|yu gothic|ゴシック|meiryo|メイリオ|hiragino|osaka|kozuka|biz ud|游|arial unicode|(noto|source han) (sans|serif)( cjk)? ?(sc|cn|jp|tc|kr)\b/i
/宋|黑|楷|仿|明|雅黑|等线|simsun|simhei|simkai|simfang|kaiti|fangsong|songti|stsong|yahei|dengxian|mingliu|jhenghei|biaukai|dfkai|kaiu|mincho|ms (ui )?p?gothic|yu gothic|ゴシック|meiryo|メイリオ|hiragino|\u30d2\u30e9\u30ae\u30ce|osaka|kozuka|biz ud|游|\u6559\u79d1\u66f8\u4f53|\u884c\u66f8\u4f53|\u5275\u82f1|arial unicode|(noto|source han) (sans|serif)( cjk)? ?(sc|cn|jp|tc|kr)\b/i
function cjkLineHFactor(fontFamily: string): number {
const f = fontFamily.toLowerCase()
if (f.includes('pmingliu') || f.includes('mingliu')) return 1.0
const declared = cjkDeclaredLineFactor(fontFamily)
if (declared !== null) return declared
if (KO_FONT_RE.test(f)) return lineHeightFactor(fontFamily)
if (CJK_FONT_NAME_RE.test(f)) return lineHeightFactor(fontFamily)
if (isCjkFontName(fontFamily)) return lineHeightFactor(fontFamily)
return 1.3
}
@@ -2042,6 +2138,11 @@ export function estimateHfHeight(
lineSpacing?: number
spaceBefore?: number
spaceAfter?: number
/** w:ind (twips): narrows the wrap width of a stacked paragraph */
indentLeft?: number
indentRight?: number
/** blank paragraph: the mark's (or style's) size sizes its line */
emptyRunSizeHalfPoints?: number
}>
}
| null
@@ -2086,7 +2187,7 @@ export function estimateHfHeight(
: part.text.trim()
? part.text.split('\n').map((t) => ({ runs: [{ text: t }] }))
: []
const lineH = (runs: HfRunLike[], rich?: HfLineSpacingLike) =>
const lineH = (runs: HfRunLike[], rich?: HfLineSpacingLike, availWidthPx = contentWidthPx) =>
computeLineMetrics({
runs: runs.map((r) => ({
text: r.text,
@@ -2095,7 +2196,7 @@ export function estimateHfHeight(
...(r.bold ? { bold: true } : {}),
...(r.italic ? { italic: true } : {}),
})),
availWidthPx: contentWidthPx,
availWidthPx,
...(rich?.lineRule ? { lineRule: rich.lineRule } : {}),
...(rich?.lineRawTwips
? { lineRawTwips: rich.lineRawTwips }
@@ -2129,7 +2230,12 @@ export function estimateHfHeight(
)
continue
}
height += lineH(p.runs, p)
const indentPx = ((p.indentLeft ?? 0) + (p.indentRight ?? 0)) / 15
const runs =
p.runs.length === 0 && p.emptyRunSizeHalfPoints
? [{ text: '', sizeHalfPoints: p.emptyRunSizeHalfPoints }]
: p.runs
height += lineH(runs, p, Math.max(1, contentWidthPx - indentPx))
}
return Math.max(height + imagesHeight, anchoredPx)
}
-1
View File
@@ -7,7 +7,6 @@ import '@genoffice/ui/tokens.css'
import '@genoffice/ui/screentip.css'
import '@genoffice/ui/color-picker.css'
import '@genoffice/ui/dropdown.css'
import '@genoffice/ui/files-pane.css'
import '@genoffice/ui/ribbon-collapse.css'
import '@genoffice/ui/markdown.css'
import '@genoffice/ui/ai-panel-prefs.css'
+14 -4
View File
@@ -423,6 +423,7 @@ export function fillLineBoxes(
// before the document is saved and reopened.
if (r.isHeader === undefined && flags[i]?.isHeader) r.isHeader = true
if (flags[i]?.cantSplit) r.cantSplit = true
if (flags[i]?.keepNext) r.keepNext = true
if (flags[i]?.minHPx) r.minHPx = flags[i].minHPx
})
const bands =
@@ -496,7 +497,7 @@ function tileBoxes(
* decoration rows (page gaps / repeated tblHeader clones) are not page-split
* units — counting them would add phantom boundaries and shift the
* tableRowFlags index alignment */
function outerTableRows(el: HTMLElement): HTMLElement[] {
export function outerTableRows(el: HTMLElement): HTMLElement[] {
return Array.from(el.querySelectorAll<HTMLElement>('tr')).filter(
(tr) =>
!tr.closest('.doc-nested-table') &&
@@ -698,7 +699,7 @@ function rowCutYs(
}
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))
if (cellsOk) cellBoxes.push(cellBoxOf(cell as HTMLElement, entries, zoomFactor, toBand))
}
const contentBottom = cellBands.reduce(
(max, bands) => bands.reduce((m, [, b]) => Math.max(m, b), max),
@@ -718,6 +719,7 @@ function cellBoxOf(
cell: HTMLElement,
entries: Array<{ band: [number, number]; child: number; para: number }>,
zoomFactor: number,
toBand: (r: DOMRect) => [number, number],
): RowCellBox {
const va = cell.style.verticalAlign
let alignDy = 0
@@ -740,7 +742,11 @@ function cellBoxOf(
band: [e.band[0] - alignDy, e.band[1] - alignDy] as [number, number],
}))
: entries
return { ...cellLinesOf(shifted), alignDy, alignFrac }
const childBox = Array.from(cell.children, (ch): [number, number] => {
const [t, b] = toBand(ch.getBoundingClientRect())
return [t - alignDy, b - alignDy]
})
return { ...cellLinesOf(shifted), childBox, alignDy, alignFrac }
}
/** Pure core of cellBoxOf: rect entries → clustered lines (same overlap rule as
@@ -903,7 +909,11 @@ function domLineRects(el: HTMLElement, zoomFactor: number): DomLineRect[] {
const lines: DomLineRect[] = []
let lineBottom = -Infinity
for (const { r, node } of rects) {
if (r.top >= lineBottom - 1) {
// glyph boxes taller than the line pitch (Batang-class KR faces: 1.45em
// content area under a 1.3029 line) overlap the next line by a few px; a
// rect the open line covers less than half of starts a new line
const overlap = lineBottom - r.top
if (overlap <= 1 || overlap < r.height / 2) {
lines.push({
offset: (r.top - elTop - gapAbove(r.top)) / zoomFactor,
bottom: (r.bottom - elTop - gapAbove(r.top)) / zoomFactor,
+23 -3
View File
@@ -459,13 +459,32 @@ export function appendFloatSpillBlock(
return top + spill
}
/** Extract each tr's tblHeader/cantSplit/atLeast-trHeight flags from table XML (header repetition across breaks / unsplittable rows / reserved row heights) */
/** Extract each tr's tblHeader/cantSplit/keepNext/atLeast-trHeight flags from table XML (header
* repetition across breaks / unsplittable rows / rows kept with the next row / reserved row heights).
* `styleKeepNext` resolves a cell paragraph's pStyle to its keepNext (Word probe 2026-09-17: one
* keepNext paragraph anywhere in the row chains it to the next row). */
export function tableRowFlags(
tableXml: string,
): Array<{ isHeader: boolean; cantSplit: boolean; minHPx?: number }> {
const flags: Array<{ isHeader: boolean; cantSplit: boolean; minHPx?: number }> = []
styleKeepNext?: (styleId: string) => boolean,
): Array<{ isHeader: boolean; cantSplit: boolean; keepNext?: boolean; minHPx?: number }> {
const flags: Array<{
isHeader: boolean
cantSplit: boolean
keepNext?: boolean
minHPx?: number
}> = []
for (const m of tableXml.matchAll(/<w:tr[\s>][\s\S]*?(?=<w:tr[\s>]|<\/w:tbl>)/g)) {
const trPr = m[0].match(/<w:trPr>[\s\S]*?<\/w:trPr>/)?.[0] ?? ''
let keepNext = false
for (const pp of m[0].matchAll(/<w:pPr>([\s\S]*?)<\/w:pPr>/g)) {
const direct = /<w:keepNext\b[^>]*>/.exec(pp[1])?.[0]
if (direct) {
if (!/w:val="(?:0|false)"/.test(direct)) keepNext = true
continue
}
const styleId = /<w:pStyle w:val="([^"]+)"/.exec(pp[1])?.[1]
if (styleId && styleKeepNext?.(styleId)) keepNext = true
}
// non-exact w:trHeight = atLeast (parse.ts semantics); exact rows keep the
// split path (deliberate clip deviation, see _placeTable). Clamp mirrors
// parse.ts (MS-OI29500 2.1.51: 31680 twips / 22in).
@@ -475,6 +494,7 @@ export function tableRowFlags(
flags.push({
isHeader: /<w:tblHeader(?!\s+w:val="(?:0|false)")/.test(trPr),
cantSplit: /<w:cantSplit(?!\s+w:val="(?:0|false)")/.test(trPr),
...(keepNext ? { keepNext } : {}),
...(atLeast ? { minHPx: Math.min(val, 31680) / 15 } : {}),
})
}
+172 -17
View File
@@ -42,9 +42,29 @@ export function anchorBoxLift(
/** one CSS pixel of preview window given or taken at a table seam: shaved when
* the next page opens with a table (its 2px margin-top keeps the shaved row in
* margin space), added when a page break cuts a table so the collapsed border
* straddling the cut shows whole on both pages */
* straddling the cut shows whole on both pages, and moved from the next page
* to the previous one when a page ends on a table's bottom edge */
export const TABLE_SEAM_PX = 1
/** preview window adjustments at table seams (px): `lift` opens this page's
* window above its start (negative: below it), `extend` grows its bottom */
export function seamWindow(
slice: PageSlice,
next: PageSlice | undefined,
): { lift: number; extend: number } {
const lift = slice.cutTable
? TABLE_SEAM_PX
: slice.tailTable && !slice.liftTop
? -TABLE_SEAM_PX
: 0
const extend = next?.leadTable
? -TABLE_SEAM_PX
: next?.cutTable || next?.tailTable
? TABLE_SEAM_PX
: 0
return { lift, extend }
}
/** open each page's clip window above its start by the part of a lifted block
* (negative text-relative w:tblpY table) that hangs above the page's first block */
export function applyLiftTops(slices: PageSlice[], blocks: BlockBox[]): void {
@@ -62,12 +82,16 @@ export function applyLiftTops(slices: PageSlice[], blocks: BlockBox[]): void {
}
/**
* Flag single-flow pages that open with a native table (leadTable) or inside one
* (cutTable). A window edge exactly on a table's top edge lets Chromium pixel-snap
* the collapsed top border onto the page before it, where Word draws nothing; a
* window edge on a row seam leaves each page half of that border, while Word
* draws the cut row's bottom border on the outgoing page and the next row's top
* border on the incoming one (probe 2026-09-05).
* Flag single-flow pages that open with a native table (leadTable), inside one
* (cutTable) or right on one's bottom edge (tailTable). A window edge exactly on
* a table's top edge lets Chromium pixel-snap the collapsed top border onto the
* page before it, where Word draws nothing; a window edge on a row seam leaves
* each page half of that border, while Word draws the cut row's bottom border
* on the outgoing page and the next row's top border on the incoming one (probe
* 2026-09-05). A window edge on the table's bottom edge (the next block has no
* top margin) puts the outer half of the collapsed bottom border, which lies
* outside the table box, on the incoming page as a hairline; Word paints the
* whole border with the table.
*/
export function markTableSeamSlices(slices: PageSlice[], blocks: BlockBox[]): void {
let bi = 0
@@ -81,7 +105,14 @@ export function markTableSeamSlices(slices: PageSlice[], blocks: BlockBox[]): vo
continue
}
const prev = blocks[bi - 1]
if (prev?.el?.tagName === 'TABLE' && prev.top + prev.height > s.start + 0.5) s.cutTable = true
if (prev?.el?.tagName !== 'TABLE') continue
if (prev.top + prev.height > s.start + 0.5) {
s.cutTable = true
continue
}
// the inter-block gap was folded into the table's height as spaceAfterPx
const boxBottom = prev.top + prev.height - (prev.spaceAfterPx ?? 0)
if (Math.abs(boxBottom - s.start) <= 0.5) s.tailTable = true
}
}
@@ -1265,16 +1296,28 @@ export function planRowSplit(
firstAvail: number,
contentH: number,
turn: (placed: number, y: number) => number,
widow = true,
): { 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)
// clip-path insets are border-box relative: without measured boxes the ink
// extents stand in (synthetic rows tile lines edge to edge)
const childTop = (c: RowCellBox, ch: number) =>
c.childBox?.[ch]?.[0] ??
Math.min(...c.lines.filter((_, i) => c.childOf[i] === ch).map((l) => l[0]))
const childBottom = (c: RowCellBox, ch: number) =>
c.childBox?.[ch]?.[1] ??
Math.max(...c.lines.filter((_, i) => c.childOf[i] === ch).map((l) => l[1]))
// Word breaks between line boxes; the ink bands leave the leading around
// them, so the boundary before line i is the middle of the gap above it (a
// paragraph's first line starts at its box top)
const lineTop = (c: RowCellBox, i: number) =>
i > 0 && c.childOf[i - 1] === c.childOf[i]
? (c.lines[i - 1][1] + c.lines[i][0]) / 2
: Math.min(c.lines[i][0], childTop(c, c.childOf[i]))
const naturalH = row.height - (row.splitExtra ?? 0)
const padB = Math.max(0, naturalH - Math.max(0, ...cells.map(lastBottom)))
let y = 0
@@ -1291,7 +1334,9 @@ export function planRowSplit(
else break
}
const raw = fit
if (fit < c.lines.length && fit > j && c.paraOf[fit - 1] === c.paraOf[fit]) {
// widow/orphan control inside cells is Word 2013+ layout only: legacy
// mode cuts a cell paragraph after any line (probe 2026-09-17: 4+1, 1+1)
if (widow && 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--
@@ -1304,6 +1349,11 @@ export function planRowSplit(
else if (raw > j) held = true
return fit
})
// a row splits only when every cell fits or breaks legally: a cell whose
// fitting lines are all held back by the widow rule makes Word move the
// row whole (probe 2026-09-17: 3-line cell with 2 lines of room), unless
// the page is already fresh
if (frag === 0 && held && firstAvail < contentH - 0.5) return 'nofit'
if (!progressed) {
if (frag === 0) return 'nofit'
// a fresh page still holds no whole line: force one line per pending cell.
@@ -1351,7 +1401,7 @@ export function planRowSplit(
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)
? lineTop(c, start) - childTop(c, first)
: undefined
if (end >= c.lines.length) {
if (clipTop !== undefined) rules.push({ from, cell: k, child: first, clipTop })
@@ -1359,7 +1409,7 @@ export function planRowSplit(
}
const last = c.childOf[end]
if (end > 0 && c.childOf[end - 1] === last) {
const clipBottom = childBottom(c, last) - c.lines[end][0]
const clipBottom = childBottom(c, last) - lineTop(c, end)
if (last === first && clipTop !== undefined)
rules.push({ from, cell: k, child: last, clipTop, clipBottom })
else {
@@ -1376,7 +1426,7 @@ export function planRowSplit(
cells.forEach((c, k) => {
const fit = cutIdx[k]
next[k] = fit
if (fit < c.lines.length) dy[k] = y + avail - c.lines[fit][0]
if (fit < c.lines.length) dy[k] = y + avail - lineTop(c, fit)
})
y += avail
avail = turn(avail, y)
@@ -1387,6 +1437,31 @@ export function planRowSplit(
/**
* Place a table (row-level page breaking).
*/
/** the shortest fragment a row can leave on a page (row-relative px): with cells
* (and a cell split path), the lowest cell cut that is legal under the widow rule
* (two lines of an opening paragraph, or that paragraph whole when it is shorter
* than four lines); else the first cut point; an unsplittable row demands its
* full height, a declared-height row at least its page-capped minimum */
function firstLegalCut(
row: TableRowBox,
widow: boolean,
contentH: number,
cellSplit: boolean,
): number {
const minH = Math.min(row.minHPx ?? 0, contentH)
if (row.cantSplit) return row.height
if (!row.cells?.length || !cellSplit) return Math.max(row.cutYs?.[0] ?? row.height, minH)
let cut = 0
for (const c of row.cells) {
if (c.lines.length === 0) continue
let n = 0
while (n < c.lines.length && c.paraOf[n] === c.paraOf[0]) n++
const keep = !widow ? 1 : n >= 4 ? 2 : n
cut = Math.max(cut, c.lines[keep - 1][1])
}
return Math.max(Math.min(cut, row.height), minH)
}
/** 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) */
@@ -1446,6 +1521,34 @@ function _placeTable(
// footnote heights charged with their referencing rows (Word lays a row's
// notes on the row's page, so a row fits only with its notes)
let chargedNotes = 0
// Word 2013+ layout: a tblHeader block is never left alone at a page bottom —
// when the first body row has to turn the page, the header goes with it
// (probe 2026-09-17; legacy mode leaves the header and repeats it). The
// header rows placed on the table's opening page are retracted and the
// table restarts on the fresh page.
let firstBodyRow = leadHeaderRows
while (firstBodyRow < rows.length && rows[firstBodyRow].vMergeContinue) firstBodyRow++
let headerPlacedPx = 0
let headerNotes = 0
let chainUntil = -1
let retractable =
block.modernTableHeaders && leadHeaderRows > 0 && headerBlockH <= contentH && !pageEmpty()
const turnBeforeRow = (ri: number, repeatH: number): boolean => {
if (retractable && ri === firstBodyRow) {
retractable = false
place(-headerPlacedPx)
chargedNotes -= headerNotes
headerPlacedPx = 0
headerNotes = 0
chainUntil = -1
placedHeader = false
rowCursor = block.top
newPage(block.top, curSection)
return true
}
newPage(rowCursor, curSection, repeatH, block.top)
return false
}
for (let ri = 0; ri < rows.length; ri++) {
const row = rows[ri]
@@ -1459,6 +1562,35 @@ function _placeTable(
const repeatH = placedHeader && ri >= headerRows ? headerHeight : 0
const notes = row.notesPx ?? 0
chargedNotes += notes
if (ri < leadHeaderRows) {
headerPlacedPx += row.height + notes
headerNotes += notes
}
// keepNext rows chain to the next row (probe 2026-09-17: one keepNext
// paragraph in any cell; the chain needs the anchor row's first segment,
// or the whole anchor when it cannot split). A chain taller than a page
// is placed normally, like a paragraph chain that cannot be honored.
if (row.keepNext && ri > chainUntil) {
let k = ri
let need = 0
for (; k < rows.length && rows[k].keepNext; k++)
need += rows[k].height + (rows[k].notesPx ?? 0)
chainUntil = k - 1
const anchor = rows[k]
if (anchor)
need +=
firstLegalCut(anchor, block.modernTableHeaders === true, contentH, !!onRowSplit) +
(anchor.notesPx ?? 0)
if (need <= contentH + 0.01 && !fits(need) && !pageEmpty()) {
chargedNotes -= notes
if (turnBeforeRow(ri, repeatH)) {
ri = -1
continue
}
chargedNotes += notes
}
}
if (!fits(row.height + notes)) {
const contentEnd =
@@ -1477,7 +1609,10 @@ function _placeTable(
// full page still split afterwards — from the fresh page.
let turnedForMinH = false
if (row.minHPx !== undefined && row.minHPx > remain() + 0.01 && !pageEmpty()) {
newPage(rowCursor, curSection, repeatH, block.top)
if (turnBeforeRow(ri, repeatH)) {
ri = -1
continue
}
turnedForMinH = true
}
const keepWhole = row.isHeader && ri < leadHeaderRows && row.height <= contentH + 0.01
@@ -1490,11 +1625,15 @@ function _placeTable(
newPage(rowCursor + y, curSection, repeatH, block.top)
return remain()
}
let plan = planRowSplit(row, remain() - notes, contentH, turn)
const widow = block.modernTableHeaders === true
let plan = planRowSplit(row, remain() - notes, contentH, turn, widow)
if (plan === 'nofit' && !pageEmpty() && !turnedForMinH) {
newPage(rowCursor, curSection, repeatH, block.top)
if (turnBeforeRow(ri, repeatH)) {
ri = -1
continue
}
turnedForMinH = true
plan = planRowSplit(row, remain() - notes, contentH, turn)
plan = planRowSplit(row, remain() - notes, contentH, turn, widow)
}
if (plan && plan !== 'nofit') {
place(plan.lastFragment + (firstFragment ? notes : 0))
@@ -1530,6 +1669,11 @@ function _placeTable(
}
return prev
}
// the first segment not fitting is a whole push of the row's head: under
// the header rule it takes the header block along
const firstSegment = (bounds: number[]) => bounds.find((c) => c > 0.5) ?? 0
const headTurns = (bounds: number[]) =>
!fits(firstSegment(bounds) + notes) && !pageEmpty() && !turnedForMinH
// Word probe 2026-08-27 (kr_fill_repro): when a declared-height (atLeast
// trHeight) row splits across pages, the continuation fragment honors the
// full declared height again as its own minimum — Word lays the row out
@@ -1576,6 +1720,10 @@ function _placeTable(
}
cuts = cuts.filter((c) => c < contentEnd - 0.01)
if (cuts.length > 0 || contentEnd < row.height - 0.5) {
if (headTurns([...cuts, contentEnd]) && turnBeforeRow(ri, repeatH)) {
ri = -1
continue
}
const prev = placeSegments([...cuts, contentEnd])
const fill = row.height - prev
if (fill > 0.5) place(Math.min(fill, remain()))
@@ -1585,6 +1733,10 @@ function _placeTable(
continue
}
} else if (cuts.length > 0) {
if (headTurns([...cuts, row.height]) && turnBeforeRow(ri, repeatH)) {
ri = -1
continue
}
placeSegments([...cuts, row.height])
continuationFill()
rowCursor += row.height
@@ -1594,7 +1746,10 @@ function _placeTable(
// cantSplit / empty / no cut points: the row is atomic; turn the page
// first if it doesn't fit. A repeated header keeps the fresh page
// non-empty, so the minH turn above must not double up here.
if (!pageEmpty() && !turnedForMinH) newPage(rowCursor, curSection, repeatH, block.top)
if (!pageEmpty() && !turnedForMinH && turnBeforeRow(ri, repeatH)) {
ri = -1
continue
}
}
place(row.height + notes)
rowCursor += row.height
+17 -2
View File
@@ -150,6 +150,8 @@ export interface TableRowBox {
cantSplit?: boolean
/** tblHeader: the row is a header row, repeated at the top of the next page after a break */
isHeader?: boolean
/** a cell paragraph carries keepNext: the row stays on the page of the next row (Word "keep with next" for rows) */
keepNext?: boolean
/** vertical merge (vMerge continue): the row continues a merged row; its height is not counted independently */
vMergeContinue?: boolean
/** in-row safe cut points (relative to row top, px, ascending): spanning all cells without splitting any text line/image.
@@ -179,6 +181,9 @@ export interface RowCellBox {
childOf: number[]
/** per line: paragraph id (lines sharing an id form one widow/orphan unit) */
paraOf: number[]
/** border-box [top, bottom] of each direct child of the cell (clip-path insets
* are box-relative; a line's ink sits half a leading inside its box) */
childBox?: Array<[number, 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 */
@@ -240,6 +245,9 @@ export interface PageSlice {
leadTable?: true
/** The page opens inside a native table that began on an earlier page (markTableSeamSlices). */
cutTable?: true
/** The previous page ends exactly on a native table's bottom edge, so the outer
* half of the collapsed bottom border lies in this page's window (markTableSeamSlices). */
tailTable?: 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
@@ -526,8 +534,15 @@ export interface BlockMeta {
/** false only when explicitly disabled (Word default on) */
widowControl?: false
/** table blocks: per-tr header/unsplittable/reserved-height flags (applied by fillLineBoxes when collecting rows) */
tableRowFlags?: Array<{ isHeader: boolean; cantSplit: boolean; minHPx?: number }>
/** Word 2013+ layout (settings compatibilityMode >= 15): a multirow tblHeader block that doesn't fit the remaining space pushes the table to a fresh page */
tableRowFlags?: Array<{
isHeader: boolean
cantSplit: boolean
keepNext?: boolean
minHPx?: number
}>
/** Word 2013+ table layout (settings compatibilityMode >= 15): a tblHeader block that doesn't fit the
* remaining space (or would stay alone at the page bottom) pushes the table to a fresh page, and
* widow/orphan control applies inside split cells */
modernTableHeaders?: boolean
/** page-bottom height reserved for footnote refs inside the block (px): merged into the block height (consumes page capacity like Word's note area) */
footnoteExtraPx?: number
+17 -31
View File
@@ -2844,32 +2844,6 @@ th.cell-rev-del {
color: var(--text);
}
/* docked handle at the page edge while the pane is closed: the View-tab
toggle alone was too easy to miss */
.nav-edge-tab {
position: absolute;
left: 0;
top: 16px;
z-index: 40;
display: flex;
align-items: center;
gap: 6px;
padding: 6px 10px 6px 8px;
border: 1px solid var(--border);
border-left: none;
border-radius: 0 8px 8px 0;
background: var(--surface);
color: var(--text);
font-size: 12px;
cursor: pointer;
box-shadow: var(--shadow-btn-hover);
}
.nav-edge-tab:hover {
background: var(--hover);
color: var(--accent);
}
.nav-pane-list {
overflow-y: auto;
padding: 6px 0;
@@ -4253,6 +4227,12 @@ th.cell-rev-del {
font-size: inherit;
}
/* text of a w:bidi paragraph whose runs carry no w:rtl: one LTR item on an RTL line (Word) */
.doc-ltr-runs {
direction: ltr;
unicode-bidi: isolate;
}
.doc-link {
color: var(--docs-paper-link);
text-decoration: underline;
@@ -4343,6 +4323,7 @@ th.cell-rev-del {
/* --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);
vertical-align: var(--li-marker-va, baseline);
/* w:lvl rPr color; the --dk-li-mc twin recolors it on the dark page */
color: var(--li-marker-color, inherit);
}
@@ -4540,9 +4521,9 @@ body.docs-crop-active .doc-protected[data-doc-protected='image'] .doc-img-wrap {
pointer-events: none;
}
/* Native ProseMirror tables */
/* Native ProseMirror tables: no vertical gap of their own (Word) */
.doc-page > .doc-table {
margin: 2px 0;
margin: 0;
}
.doc-protected[data-doc-protected='table'] {
@@ -5049,6 +5030,8 @@ body.docs-crop-active .doc-protected[data-doc-protected='image'] .doc-img-wrap {
the pagination preview clones per-page flow with no gaps, so it neutralizes it */
.doc-protected-floating > .doc-textbox {
translate: 0 var(--page-float-dy, 0px);
/* anchored shapes keep their declared extent past the column (Word) */
max-width: none;
}
.pv-clip .doc-protected-floating > .doc-textbox {
translate: none;
@@ -5125,9 +5108,12 @@ body.docs-crop-active .doc-protected[data-doc-protected='image'] .doc-img-wrap {
}
/* anchor-paragraph text next to all-floating boxes keeps its flow line:
the wrapper takes the stray line's height instead of collapsing */
the wrapper takes the stray line's height instead of collapsing. flow-root
keeps the line's space-before inside, where Word's paragraph-relative box
offsets count from */
.doc-protected.doc-protected-floating.doc-protected-floating-stray {
height: auto;
display: flow-root;
}
/* preview: an anchor-shifted box reaching above its page top rides --pv-anchor-lift
@@ -5255,6 +5241,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);
vertical-align: var(--li-marker-va, baseline);
color: var(--li-marker-color, inherit);
}
@@ -5285,6 +5272,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);
vertical-align: var(--li-marker-va, baseline);
color: var(--li-marker-color, inherit);
}
@@ -9261,7 +9249,6 @@ body.docs-crop-active
.status-bar,
.ai-dock,
.nav-pane,
.nav-edge-tab,
.ruler,
.find-panel {
display: none !important;
@@ -9484,7 +9471,6 @@ body.docs-crop-active
.read-mode .ribbon,
.read-mode .ai-dock,
.read-mode .nav-pane,
.read-mode .nav-edge-tab,
.read-mode .find-panel,
.read-mode .comments-pane,
.read-mode .split-pane {
+18 -2
View File
@@ -244,6 +244,7 @@ export interface McpSaveResult {
path?: string
error?: string
passwordIntentPending?: boolean
data?: ArrayBuffer
}
export interface DesktopApi {
@@ -315,6 +316,9 @@ export interface DesktopApi {
reason?: 'external-modified'
/** a newer password choice arrived after this save's snapshot */
passwordIntentPending?: boolean
/** the saved document in full when an encrypted save absorbed lazily served
* pictures: the renderer reparses from it and leaves lazy mode */
data?: ArrayBuffer
}>
/** crash-recovery copy of a dirty document, stored under userData */
writeRecoveryCopy(path: string, data: ArrayBuffer): Promise<{ ok: boolean }>
@@ -335,12 +339,24 @@ export interface DesktopApi {
defaultName: string,
data: ArrayBuffer,
sourcePath?: string | null,
): Promise<{ ok: boolean; path?: string; error?: string; passwordIntentPending?: boolean }>
): Promise<{
ok: boolean
path?: string
error?: string
passwordIntentPending?: boolean
data?: ArrayBuffer
}>
/** first save of a new document: silently writes into the default folder, no dialog */
saveDocxNew(
defaultName: string,
data: ArrayBuffer,
): Promise<{ ok: boolean; path?: string; error?: string; passwordIntentPending?: boolean }>
): Promise<{
ok: boolean
path?: string
error?: string
passwordIntentPending?: boolean
data?: ArrayBuffer
}>
/** MCP-driven output: write the current document to an explicit absolute path
* with no dialog; refuses to replace an existing file unless overwrite is true */
saveDocxTo(path: string, data: ArrayBuffer, overwrite: boolean): Promise<McpSaveResult>
@@ -88,12 +88,14 @@ describe('autoHyphenation CSS', () => {
styleId: 'NoHyph',
name: 'NoHyph',
type: 'paragraph',
isDefault: true,
display: { suppressAutoHyphens: true },
} as StyleInfo,
{
styleId: 'ReHyph',
name: 'ReHyph',
type: 'paragraph',
isDefault: true,
display: { suppressAutoHyphens: false },
} as StyleInfo,
],
@@ -111,6 +113,7 @@ describe('autoHyphenation CSS', () => {
styleId: 'NoHyph',
name: 'NoHyph',
type: 'paragraph',
isDefault: true,
display: { suppressAutoHyphens: true },
} as StyleInfo,
],
+67
View File
@@ -0,0 +1,67 @@
import { describe, expect, it } from 'vitest'
import { Editor } from '@tiptap/core'
import { editorExtensions } from '../src/renderer/editor/extensions'
interface JsonNode {
type: string
attrs?: Record<string, unknown>
content?: JsonNode[]
text?: string
marks?: { type: string; attrs?: Record<string, unknown> }[]
}
const ARABIC = '\u0639\u0631\u0628\u064a\u0629'
function render(node: JsonNode): HTMLElement {
const editor = new Editor({
element: document.createElement('div'),
extensions: editorExtensions,
content: { type: 'doc', content: [node] },
})
const dom = editor.view.dom.firstElementChild as HTMLElement
editor.destroy()
return dom
}
const para = (
attrs: Record<string, unknown>,
content: JsonNode[],
type = 'docParagraph',
): JsonNode => ({ type, attrs: { docxIndex: null, ...attrs }, content })
describe('w:bidi paragraphs order runs without w:rtl left-to-right (Word)', () => {
it('isolates the text as one LTR item when no run is rtl', () => {
const el = render(para({ bidi: true }, [{ type: 'text', text: `${ARABIC} (LATIN)` }]))
expect(el.style.direction).toBe('rtl')
const wrap = el.firstElementChild as HTMLElement
expect(wrap.className).toBe('doc-ltr-runs')
expect(wrap.textContent).toBe(`${ARABIC} (LATIN)`)
})
it('keeps the RTL base when a run is an rtl run', () => {
const el = render(
para({ bidi: true }, [
{ type: 'text', text: ARABIC, marks: [{ type: 'docTextStyle', attrs: { cs: true } }] },
{ type: 'text', text: ' (LATIN)' },
]),
)
expect(el.querySelector('.doc-ltr-runs')).toBeNull()
})
it('leaves LTR paragraphs and empty bidi paragraphs alone', () => {
expect(
render(para({}, [{ type: 'text', text: 'abc' }])).querySelector('.doc-ltr-runs'),
).toBeNull()
expect(render(para({ bidi: true }, [])).querySelector('.doc-ltr-runs')).toBeNull()
})
it('applies to headings and list items too', () => {
const h = render(para({ bidi: true, level: 2 }, [{ type: 'text', text: 'T' }], 'docHeading'))
expect(h.tagName).toBe('H2')
expect(h.firstElementChild?.className).toBe('doc-ltr-runs')
const li = render(
para({ bidi: true, kind: 'bullet', ilvl: 0 }, [{ type: 'text', text: 'T' }], 'docListItem'),
)
expect(li.querySelector('.doc-ltr-runs')).not.toBeNull()
})
})
@@ -50,6 +50,27 @@ describe('renderTableSpec anchored cell boxes', () => {
expect((all[0] as HTMLElement).style.height).toBe('35.1px')
})
it('a wrapNone box reserves no strut height', () => {
const model: TableModel = {
rows: [
[
{
paras: ['head'],
anchoredBoxes: [
{ ...checkbox, offsetYEmu: 217920, heightPx: 193, noWrap: true, behind: true },
// behind is z-order only: a wrapped behind-text box still grows the row
{ ...checkbox, offsetYEmu: 0, heightPx: 30, behind: true },
],
anchoredBoxAnchors: [0],
},
],
],
}
const strut = render(renderTableSpec(model)).querySelector<HTMLElement>('.doc-cell-boxes')!
expect(strut.style.height).toBe('30px')
expect(strut.querySelectorAll('.doc-textbox').length).toBe(2)
})
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)
+148 -1
View File
@@ -1,6 +1,11 @@
import type { ChartDisplay } from '@genoffice/docx-engine'
import { describe, expect, it } from 'vitest'
import { drawChartSvg } from '../src/renderer/editor/protected-render'
import {
CHART_TITLE_ROW_PX,
chartTitleRowPx,
drawChartSvg,
renderChartSpec,
} from '../src/renderer/editor/protected-render'
function draw(chart: ChartDisplay): HTMLElement {
const dom = document.createElement('div')
@@ -335,3 +340,145 @@ describe('chart svg drawing', () => {
).toBe(false)
})
})
describe('chart text sizes, value labels and legend rows', () => {
const bar: ChartDisplay = {
partPath: 'word/charts/chart2.xml',
kind: 'bar',
title: 'Revenue',
titleFontPt: 18,
noLegend: true,
widthPx: 576,
heightPx: 288,
categories: ['Base', 'A', 'B', 'C'],
series: [{ name: 'Revenue', values: [1997, 2213, 2501, 2717] }],
dataLabels: { val: true, fontPt: 12, color: '000000', numFmt: '#,##0' },
xAxis: { fontPt: 12, color: '000000', line: '888888' },
yAxis: { fontPt: 12, color: '000000', line: '888888', gridLine: '888888' },
}
it('draws c:showVal bar labels above the bars in the c:numFmt with the label size and color', () => {
const dom = draw(bar)
const texts = [...dom.querySelectorAll('text')]
const label = texts.find((t) => t.textContent === '2,717')!
expect(label).toBeDefined()
expect(label.getAttribute('style')).toBe('font-size:16px;fill:#000000')
const rects = [...dom.querySelectorAll('rect')]
const top = Math.min(...rects.map((r) => Number(r.getAttribute('y'))))
expect(Number(label.getAttribute('y'))).toBeLessThan(top)
expect(texts.every((t) => t.textContent !== '2717')).toBe(true)
})
it('sizes and colors axis labels from c:txPr and strokes gridlines with the authored color', () => {
const dom = draw(bar)
const cat = [...dom.querySelectorAll('text')].find((t) => t.textContent === 'Base')!
expect(cat.getAttribute('style')).toBe('font-size:16px;fill:#000000')
const grid = dom.querySelectorAll('.doc-chart-grid')
expect(grid.length).toBeGreaterThan(0)
expect(grid[0].getAttribute('style')).toBe('stroke:#888888')
})
it('draws no gridlines when the parsed value axis has no c:majorGridlines', () => {
const dom = draw({ ...bar, yAxis: { line: '888888' } })
expect(dom.querySelectorAll('.doc-chart-grid').length).toBe(0)
// models without a parsed axis keep the default grid
const legacy = draw({ ...bar, xAxis: undefined, yAxis: undefined })
expect(legacy.querySelectorAll('.doc-chart-grid').length).toBeGreaterThan(0)
})
it('budgets the title row from the title size, wrapping long titles', () => {
expect(chartTitleRowPx({ ...bar, title: undefined })).toBe(0)
expect(chartTitleRowPx({ ...bar, titleFontPt: undefined })).toBe(CHART_TITLE_ROW_PX)
const oneLine = chartTitleRowPx(bar)
expect(oneLine).toBeGreaterThan(CHART_TITLE_ROW_PX)
const long = {
...bar,
title: String.fromCodePoint(
0x5e74,
0x9593,
0x58f2,
0x4e0a,
0x69cb,
0x6210,
0x5185,
0x8a33,
).repeat(3),
}
expect(chartTitleRowPx(long)).toBeGreaterThan(oneLine * 1.8)
const spec = renderChartSpec(bar)
expect(JSON.stringify(spec)).toContain(`font-size:18pt;height:${oneLine}px`)
// title row + plot still fill heightPx
const svg = draw(bar).querySelector('svg')!
expect(Number(svg.style.height.replace('px', ''))).toBe(288 - oneLine)
})
it('wraps an overflowing bottom legend into centered rows', () => {
const pie: ChartDisplay = {
partPath: 'word/charts/chart1.xml',
kind: 'pie',
holePct: 50,
legendPos: 'b',
widthPx: 400,
heightPx: 240,
categories: [
'Pyrolysis oil ($972k)',
'Tipping fee ($720k)',
'Carbon ($226k)',
'Steel ($77k)',
],
series: [{ values: [972, 720, 226, 77] }],
}
const dom = draw(pie)
const entries = pie.categories.map((c) =>
[...dom.querySelectorAll('text')].find((t) => t.textContent === c)!,
)
const rows = new Set(entries.map((t) => t.getAttribute('y')))
expect(rows.size).toBe(2)
expect(entries.every((t) => t.getAttribute('text-anchor') === null)).toBe(true)
const wide = draw({ ...pie, widthPx: 660 })
const wideRows = new Set(
pie.categories.map((c) =>
[...wide.querySelectorAll('text')].find((t) => t.textContent === c)!.getAttribute('y'),
),
)
expect(wideRows.size).toBe(1)
})
})
describe('category label wrapping', () => {
it('wraps overflowing column-chart category labels into slot-width lines', () => {
const dom = draw({
partPath: 'word/charts/chart2.xml',
kind: 'bar',
noLegend: true,
widthPx: 480,
heightPx: 200,
categories: ['Base case (no credit)', 'Scenario A ($15/t)', 'B'],
series: [{ values: [1, 2, 3] }],
xAxis: { fontPt: 12 },
yAxis: { gridLine: 'D9D9D9' },
})
const texts = [...dom.querySelectorAll('text')].map((t) => t.textContent)
expect(texts).toContain('Base case')
expect(texts).toContain('(no credit)')
expect(texts).toContain('B')
expect(texts).not.toContain('Base case (no credit)')
})
it('caps a wrapped category label at three lines', () => {
const dom = draw({
partPath: 'word/charts/chart2.xml',
kind: 'bar',
noLegend: true,
widthPx: 240,
heightPx: 200,
categories: ['one two three four five six seven eight nine ten eleven twelve', 'B'],
series: [{ values: [1, 2] }],
xAxis: { fontPt: 12 },
})
const texts = [...dom.querySelectorAll('text')].map((t) => t.textContent ?? '')
const labelLines = texts.filter((t) => /[a-z]/.test(t) && t !== 'B')
expect(labelLines.length).toBeLessThanOrEqual(3)
expect(labelLines.join(' ')).toContain('twelve')
})
})
+13 -1
View File
@@ -21,7 +21,19 @@ const BODY =
function parsedWith(styleId: string, display: StyleDisplay): ParsedDocFull {
const styles = new Map<string, StyleInfo>()
styles.set(styleId, { styleId, name: styleId, type: 'paragraph', display } as StyleInfo)
styles.set('Normal', {
styleId: 'Normal',
name: 'Normal',
type: 'paragraph',
isDefault: true,
} as StyleInfo)
styles.set(styleId, {
styleId,
name: styleId,
type: 'paragraph',
basedOn: 'Normal',
display,
} as StyleInfo)
return { styles, docDefaults: {}, blocks: [] } as unknown as ParsedDocFull
}
+7
View File
@@ -139,10 +139,17 @@ describe('docStyleCss dark twins', () => {
it('pairs every color rule with a .page-dark rule inside one @media screen block', () => {
const styles = new Map<string, StyleInfo>()
styles.set('Normal', {
styleId: 'Normal',
name: 'Normal',
type: 'paragraph',
isDefault: true,
} as StyleInfo)
styles.set('Heading1', {
styleId: 'Heading1',
name: 'heading 1',
type: 'paragraph',
basedOn: 'Normal',
display: { color: '2f5496', shadingFill: 'f2f2f2' } as StyleDisplay,
} as StyleInfo)
styles.set('Grid', {
+13 -1
View File
@@ -6,7 +6,19 @@ import { docStyleCss } from '../src/renderer/doc-style-css'
function parsedWith(styleId: string, display: StyleDisplay): ParsedDocFull {
const styles = new Map<string, StyleInfo>()
styles.set(styleId, { styleId, name: styleId, type: 'paragraph', display } as StyleInfo)
styles.set('Normal', {
styleId: 'Normal',
name: 'Normal',
type: 'paragraph',
isDefault: true,
} as StyleInfo)
styles.set(styleId, {
styleId,
name: styleId,
type: 'paragraph',
basedOn: 'Normal',
display,
} as StyleInfo)
return { styles, docDefaults: {}, blocks: [] } as unknown as ParsedDocFull
}
@@ -1,10 +1,8 @@
/**
* Header/footer strip default font size: Word's Header/Footer styles are based
* on Normal, so unstyled strip runs take the document default size. The var is
* shrink-only — strips price their line boxes with the document-wide script
* strut, which overshoots Word on Latin-only strip lines, so a default above
* the static 10.5pt guess must not grow the push-down reserve
* (prod_082 8pt regression / prod_008+091 guard).
* on Normal, so unstyled strip runs take the document default size, both below
* and above the static 10.5pt guess (a 12pt-default header wraps its long line
* where Word does).
*/
import { describe, expect, it } from 'vitest'
import type { ParsedDocFull, StyleDisplay, StyleInfo } from '@genoffice/docx-engine'
@@ -44,9 +42,9 @@ describe('docStyleCss --hf-default-fs', () => {
expect(css).toContain('--hf-default-fs:9.5pt')
})
it('stays silent at or above the 10.5pt static guess', () => {
expect(docStyleCss(parsedWith({ ddSizeHalfPoints: 21 }))).not.toContain('--hf-default-fs')
expect(docStyleCss(parsedWith({ ddSizeHalfPoints: 22 }))).not.toContain('--hf-default-fs')
it('grows the strip base above the 10.5pt static guess too', () => {
expect(docStyleCss(parsedWith({ ddSizeHalfPoints: 21 }))).toContain('--hf-default-fs:10.5pt')
expect(docStyleCss(parsedWith({ ddSizeHalfPoints: 24 }))).toContain('--hf-default-fs:12pt')
})
it("no size anywhere: Word's built-in 10pt default drives body and strips", () => {
+63 -1
View File
@@ -13,7 +13,19 @@ import { docStyleCss } from '../src/renderer/doc-style-css'
function parsedWith(styleId: string, display: StyleDisplay): ParsedDocFull {
const styles = new Map<string, StyleInfo>()
styles.set(styleId, { styleId, name: styleId, type: 'paragraph', display } as StyleInfo)
styles.set('Normal', {
styleId: 'Normal',
name: 'Normal',
type: 'paragraph',
isDefault: true,
} as StyleInfo)
styles.set(styleId, {
styleId,
name: styleId,
type: 'paragraph',
basedOn: 'Normal',
display,
} as StyleInfo)
return { styles, docDefaults: {}, blocks: [] } as unknown as ParsedDocFull
}
@@ -126,3 +138,53 @@ describe('docStyleCss spacing', () => {
)
})
})
describe('docStyleCss styles off the Normal chain', () => {
const parsedOff = (display: StyleDisplay, docDefaults: object = {}): ParsedDocFull => {
const styles = new Map<string, StyleInfo>()
styles.set('Normal', {
styleId: 'Normal',
name: 'Normal',
type: 'paragraph',
isDefault: true,
display: {
spaceAfterTwips: 160,
lineRule: 'auto',
lineRawTwips: 259,
lineSpacing: 259 / 240,
},
} as StyleInfo)
styles.set('NoSpacing', {
styleId: 'NoSpacing',
name: 'No Spacing',
type: 'paragraph',
display,
} as StyleInfo)
return { styles, docDefaults, blocks: [] } as unknown as ParsedDocFull
}
it('a paragraph style without w:basedOn takes docDefaults spacing and line, not Normal', () => {
const css = docStyleCss(parsedOff({ sizeHalfPoints: 22 }))
const rule = /\[data-style="NoSpacing"\] \{ ([^}]*) \}/.exec(css)![1]
expect(rule).toContain('margin-top:0.0pt')
expect(rule).toContain('margin-bottom:0.0pt')
expect(rule).toMatch(/line-height:/)
expect(rule).not.toContain('1.079')
})
it('docDefaults spacing reaches it when declared', () => {
const css = docStyleCss(
parsedOff({ sizeHalfPoints: 22 }, { spaceAfterTwips: 200, spaceBeforeAuto: true }),
)
const rule = /\[data-style="NoSpacing"\] \{ ([^}]*) \}/.exec(css)![1]
expect(rule).toContain('margin-top:14.0pt')
expect(rule).toContain('margin-bottom:10.0pt')
})
it('own spacing still wins over docDefaults', () => {
const css = docStyleCss(parsedOff({ spaceAfterTwips: 60 }, { spaceAfterTwips: 200 }))
expect(/\[data-style="NoSpacing"\] \{ ([^}]*) \}/.exec(css)![1]).toContain(
'margin-bottom:3.0pt',
)
})
})
+10
View File
@@ -47,6 +47,16 @@ describe('suppressed text-anchored float with a negative w:tblpY', () => {
expect(attrs['data-tblp-lift']).toBe('73.1')
})
it('keeps a positive text-relative offset as a plain top margin (no lift)', () => {
const [, attrs] = tableSpec({ ...suppressedFloat, tblFloatYTwips: 312 })
expect(attrs['data-tblp-lift']).toBeUndefined()
expect(attrs.style).toContain('margin-top:20.8px')
expect(
tableSpec({ ...suppressedFloat, tblFloatVertAnchor: 'margin', tblFloatYTwips: 312 })[1]
.style ?? '',
).not.toContain('margin-top:20.8px')
})
it('does not lift a positive offset, a page anchor or a live float', () => {
expect(
tableSpec({ ...suppressedFloat, tblFloatYTwips: 72 })[1]['data-tblp-lift'],
+108
View File
@@ -0,0 +1,108 @@
/**
* Toggling bold/italic must retire the imported Word off-switch (task#426):
* runs parsed from explicit w:b/w:i val=0 carry docTextStyle boldOff/italicOff
* (painted font-weight/style:normal). The off-switch span renders inside the
* strong/em, so without clearing it a bold toggle changes the model and the
* saved file but never the pixels — the ribbon lights, the reopened document
* is bold, and the live text stays regular (classic in table cells, where
* Word writes b=0 against table-style bold).
*/
import { Editor } from '@tiptap/core'
import { afterEach, describe, expect, it } from 'vitest'
import { editorExtensions } from '../src/renderer/editor/extensions'
// an undestroyed view leaves ProseMirror's 20 ms observer flush behind, which
// then runs against the torn-down jsdom document
const editors: Editor[] = []
afterEach(() => {
for (const e of editors.splice(0)) e.destroy()
})
const offEditor = (attrs: Record<string, unknown>) =>
track(
new Editor({
element: document.createElement('div'),
extensions: editorExtensions,
content: {
type: 'doc',
content: [
{
type: 'docParagraph',
content: [{ type: 'text', text: 'label', marks: [{ type: 'docTextStyle', attrs }] }],
},
],
} as never,
}),
)
const track = (editor: Editor): Editor => {
editors.push(editor)
return editor
}
const textStyleOf = (
marks: readonly { type: { name: string }; attrs: Record<string, unknown> }[],
) => marks.find((mark) => mark.type.name === 'docTextStyle')?.attrs
describe('format off-switch clearing on toggle (task#426)', () => {
it('typing after Ctrl+B on a boldOff run produces bold text without the off-switch', () => {
const editor = offEditor({ boldOff: true, font: 'Manrope' })
editor.commands.setTextSelection(6) // caret after "label"
editor.commands.toggleMark('bold')
editor.view.dispatch(editor.state.tr.insertText('typed'))
const typed = editor.state.doc.firstChild!.lastChild!
expect(typed.text).toContain('typed')
expect(typed.marks.some((m) => m.type.name === 'bold')).toBe(true)
const style = textStyleOf(typed.marks)!
expect(style.boldOff).toBe(false)
expect(style.font).toBe('Manrope') // only the off-switch is dropped
})
it('bolding a selected boldOff run clears the off-switch in place', () => {
const editor = offEditor({ boldOff: true })
editor.commands.setTextSelection({ from: 1, to: 6 })
editor.commands.toggleMark('bold')
const node = editor.state.doc.firstChild!.firstChild!
expect(node.marks.some((m) => m.type.name === 'bold')).toBe(true)
expect(textStyleOf(node.marks)!.boldOff).toBe(false)
})
it('italic toggle clears italicOff the same way', () => {
const editor = offEditor({ italicOff: true })
editor.commands.setTextSelection({ from: 1, to: 6 })
editor.commands.toggleMark('italic')
const node = editor.state.doc.firstChild!.firstChild!
expect(node.marks.some((m) => m.type.name === 'italic')).toBe(true)
expect(textStyleOf(node.marks)!.italicOff).toBe(false)
})
it('un-bolding restores the off-switch so inherited style bold does not paint', () => {
const editor = offEditor({ boldOff: true })
editor.commands.setTextSelection({ from: 1, to: 6 })
editor.commands.toggleMark('bold')
editor.commands.toggleMark('bold')
const node = editor.state.doc.firstChild!.firstChild!
expect(node.marks.some((m) => m.type.name === 'bold')).toBe(false)
expect(textStyleOf(node.marks)!.boldOff).toBe(true)
})
it('caret toggle on then off types text with the off-switch back on', () => {
const editor = offEditor({ boldOff: true })
editor.commands.setTextSelection(6)
editor.commands.toggleMark('bold')
editor.commands.toggleMark('bold')
editor.view.dispatch(editor.state.tr.insertText('typed'))
const typed = editor.state.doc.firstChild!.lastChild!
expect(typed.text).toContain('typed')
expect(typed.marks.some((m) => m.type.name === 'bold')).toBe(false)
expect(textStyleOf(typed.marks)!.boldOff).toBe(true)
})
it('editing without a bold toggle keeps the off-switch (untouched runs stay Word-faithful)', () => {
const editor = offEditor({ boldOff: true })
editor.commands.setTextSelection(6)
editor.view.dispatch(editor.state.tr.insertText('typed'))
const node = editor.state.doc.firstChild!.firstChild!
expect(textStyleOf(node.marks)!.boldOff).toBe(true)
})
})
-2
View File
@@ -60,8 +60,6 @@ export function ribbonProps(editor: Editor, formatState: RibbonFormatState) {
onShowRuler: noop,
showNav: false,
onShowNav: noop,
showFiles: false,
onShowFiles: noop,
commentCount: 0,
openCommentCount: 0,
onShowComments: noop,
+69
View File
@@ -0,0 +1,69 @@
import { describe, expect, it } from 'vitest'
import { makeGapHfEl } from '../src/renderer/editor/hf-dom'
import { estimateHfHeight } from '../src/renderer/line-metrics'
// header text indented beside a left logo (w:ind left=1134 right=119): Word
// narrows the text block; drawn from the margin it overlapped the logo and
// wrapped one line short
const para = (extra: object) =>
({ runs: [{ text: 'PROGRAM '.repeat(12).trim(), sizeHalfPoints: 24 }], ...extra }) as never
describe('header paragraph indent', () => {
it('the strip paragraph indents by w:ind left/right (margins, clear of border padding)', () => {
const el = makeGapHfEl({
kind: 'header',
value: {
text: '',
paras: [para({ indentLeft: 1134, indentRight: 119, indentFirstLine: 300 })],
} as never,
pageNo: 1,
pageTotal: 1,
})
const p = el.querySelector<HTMLElement>('.page-hf-para')!
expect(p.style.marginInlineStart).toBe('75.6px')
expect(p.style.marginInlineEnd).toBe('7.9px')
expect(p.style.textIndent).toBe('20px')
})
it('a bordered indented paragraph keeps both the indent and the border padding', () => {
const el = makeGapHfEl({
kind: 'header',
value: {
text: '',
paras: [para({ indentLeft: 1134, borders: 'lb', borderLines: { l: { szPt: 0.5 } } })],
} as never,
pageNo: 1,
pageTotal: 1,
})
const p = el.querySelector<HTMLElement>('.page-hf-para')!
expect(p.style.marginInlineStart).toBe('75.6px')
expect(p.style.paddingLeft).toBe('4px')
})
it('a tabbed paragraph keeps its column-relative tab layout (no indent margins)', () => {
const el = makeGapHfEl({
kind: 'header',
value: {
text: '',
paras: [{ runs: [{ text: 'left\tright' }], indentLeft: 1134, indentRight: 119 }],
} as never,
pageNo: 1,
pageTotal: 1,
})
const p = el.querySelector<HTMLElement>('.page-hf-para')!
expect(p.style.marginInlineStart).toBe('')
expect(p.style.marginInlineEnd).toBe('')
})
it('the height estimate wraps the indented paragraph in the narrower width', () => {
const plain = estimateHfHeight({ text: '', paras: [para({})] }, 300)
const indented = estimateHfHeight(
{ text: '', paras: [para({ indentLeft: 1134, indentRight: 119 })] },
300,
)
expect(indented).toBeGreaterThan(plain)
expect(indented).toBe(
estimateHfHeight({ text: '', paras: [para({})] }, 300 - (1134 + 119) / 15),
)
})
})
+17
View File
@@ -101,3 +101,20 @@ describe('strip paragraph line spacing', () => {
expect(paras[1].style.lineHeight).toBe('')
})
})
describe('makeGapHfEl blank paragraph size', () => {
it('sizes a run-less paragraph line by its mark / style size', () => {
const el = makeGapHfEl({
kind: 'header',
value: {
text: '',
paras: [{ runs: [] }, { runs: [], emptyRunSizeHalfPoints: 24 }] as never,
},
pageNo: 1,
pageTotal: 1,
})
const paras = el.querySelectorAll<HTMLElement>('.page-hf-para')
expect(paras[0].style.fontSize).toBe('')
expect(paras[1].style.fontSize).toBe('12pt')
})
})
+38
View File
@@ -850,6 +850,44 @@ describe('side-wrapped pictures that leave no room for text', () => {
editor.destroy()
})
it('a cell picture lifted above its anchor paragraph leaves room for the cell clamp', async () => {
// signature anchored two empty lines above a name block inside a borderless
// table cell: Word keeps a layoutInCell picture inside the cell
const cell = (body: string) =>
'<w:tbl><w:tblPr><w:tblW w:w="5000" w:type="dxa"/></w:tblPr>' +
'<w:tblGrid><w:gridCol w:w="5000"/></w:tblGrid><w:tr><w:tc>' +
`<w:tcPr><w:tcW w:w="5000" w:type="dxa"/></w:tcPr><w:p/>${body}` +
'<w:p><w:r><w:t>(Name)</w:t></w:r></w:p></w:tc></w:tr></w:tbl>'
// jsdom drops a calc() with var() from the parsed inline style: read the
// rendered declaration off the node spec instead
const renderedImg = async (body: string) => {
const { editor } = await openImageDoc(cell(body))
let attrs: Record<string, string> | undefined
editor.state.doc.descendants((node) => {
if (node.type.name === 'docInlineImage') {
const spec = editor.schema.nodes.docInlineImage.spec.toDOM!(node) as [
string,
typeof attrs,
]
attrs = spec[1]
}
})
expect(editor.view.dom.querySelector('td img.doc-inline-img--wrap-tight-left')).toBeTruthy()
editor.destroy()
return attrs!
}
const inCell = anchoredPicture(1261745, -2315845, 1910080, 677545)
const clamped = await renderedImg(`<w:p>${inCell}</w:p>`)
expect(clamped.style).toContain('margin-top:calc(-243.1px + var(--cell-lift,0px))')
expect(clamped['data-cell-lift']).toBe('1')
const free = await renderedImg(
`<w:p>${inCell.replace('layoutInCell="1"', 'layoutInCell="0"')}</w:p>`,
)
expect(free.style).toContain('margin-top:-243.1px')
expect(free['data-cell-lift']).toBeUndefined()
})
it('composes the posOffset Y of a quarter-turned run-level float with its footprint inset', async () => {
// 157x100 turned 90deg sticks out (157-100)/2 = 28.5px above the extent box
const turned = anchoredPicture(5156200, 359410, 1498600, 952500).replace(
+82 -2
View File
@@ -36,6 +36,7 @@ import {
krLineFactor,
cjkDeclaredLineFactor,
lineHeightFactor,
symbolBulletLinePt,
simsunGapLineFactor,
paraLineFactorCss,
snapSpacingToGrid,
@@ -692,6 +693,52 @@ describe('cssFontFamily', () => {
})
})
describe('HG faces (Word for Mac ships four cuts, substitutes the rest with Yu Gothic)', () => {
afterEach(() => vi.restoreAllMocks())
const kyokasho = 'HG\u6559\u79d1\u66f8\u4f53'
const minchoB = 'HG\u660e\u671dB'
const popTai = 'HGP\u5275\u82f1\u89d2\uff8e\uff9f\uff6f\uff8c\uff9f\u4f53'
const gothicM = 'HG\uff7a\uff9e\uff7c\uff6f\uff78M'
const hiraginoKakuGo = '\u30d2\u30e9\u30ae\u30ce\u89d2\u30b4 Pro W3'
const maruGothic = 'HG\u4e38\uff7a\uff9e\uff7c\uff6f\uff78M-PRO'
const minchoE = 'HG\u660e\u671dE'
it('missing non-shipped names take the JA sans chain and the Yu Gothic factor, even the Mincho cut', () => {
for (const name of [kyokasho, minchoB, popTai, gothicM, hiraginoKakuGo]) {
expect(lineHeightFactor(name)).toBe(1.44)
expect(cssFontFamily(name)).toBe(
`'${name}','Yu Gothic','GenOffice Hiragino Sans','Meiryo','Noto Sans JP',sans-serif`,
)
expect(isCjkFontName(name)).toBe(true)
}
})
it('the shipped cuts keep the MS-class pitch and their own classification', () => {
expect(lineHeightFactor(maruGothic)).toBe(1.3029)
expect(lineHeightFactor(minchoE)).toBe(1.3029)
// half-width spelling of the shipped Gothic E cut
expect(lineHeightFactor('HG\uff7a\uff9e\uff7c\uff6f\uff78E')).toBe(1.3029)
expect(cssFontFamily(minchoE)).toMatch(/,serif$/)
})
it('an installed face renders real', () => {
const installed = 'HGS\u6559\u79d1\u66f8\u4f53'
stubCanvas([installed])
expect(lineHeightFactor(installed)).toBe(1.3029)
})
it('the line simulator applies the Yu Gothic factor to half-width spellings too', () => {
const metrics = new HeuristicMetrics()
const runs = [{ text: '\u6587\u5b57', sizeHalfPoints: 20 }]
const [halfWidth] = simulateLines(runs, 500, metrics, 10, gothicM)
const [fullWidth] = simulateLines(runs, 500, metrics, 10, kyokasho)
expect(halfWidth.naturalLineH).toBeCloseTo(fullWidth.naturalLineH, 5)
expect(halfWidth.naturalLineH).toBeGreaterThan(
simulateLines(runs, 500, metrics, 10, maruGothic)[0].naturalLineH,
)
})
})
it('Meiryo (UI) leads with the range-limited metric aliases ahead of the JP sans chain', () => {
expect(cssFontFamily('Meiryo UI')).toBe(
"'Meiryo UI','Meiryo UI GO','Yu Gothic','GenOffice Hiragino Sans','Meiryo','Noto Sans JP',sans-serif",
@@ -725,10 +772,16 @@ describe('cssFontFamily', () => {
expect(dual).not.toContain('JA GO')
expect(cssDualFontFamily('MS UI Gothic', 'Meiryo')).not.toContain('JA GO')
expect(docLatinChainCss('MS PGothic')).not.toContain('JA GO')
// Mincho and other JP names are untouched
// Berlin Sans FB Demi rides its bold alias; the regular cut is unprobed
expect(cssFontFamily('Berlin Sans FB Demi')).toContain("'Berlin Sans FB GO'")
expect(cssFontFamily('Berlin Sans FB')).not.toContain("'Berlin Sans FB GO'")
// MS Mincho shares the fixed-pitch Latin alias; other JP names are untouched
expect(cssFontFamily('MS ゴシック 太字')).not.toContain(' GO')
expect(cssFontFamily('MS Mincho')).not.toContain(' GO')
expect(cssFontFamily('MS Mincho')).toMatch(/^'MS Mincho','MS Mincho GO',/)
expect(cssFontFamily('\uFF2D\uFF33 \u660E\u671D')).toContain("'MS Mincho GO'")
expect(cssFontFamily('MS PMincho')).not.toContain(' GO')
expect(monospaceAdvanceEm("'MS ゴシック','MS Gothic GO'")).toBe(0.5)
expect(monospaceAdvanceEm("'MS Mincho','MS Mincho GO'")).toBe(0.5)
expect(monospaceAdvanceEm("'MS PGothic'")).toBeNull()
})
@@ -1524,3 +1577,30 @@ describe('justifySymbolRanges', () => {
expect(justifySymbolRanges('plain text 12%')).toEqual([])
})
})
describe('Latin faces probed 2026-09-17 (Word for Mac, 10/11/12pt single spacing)', () => {
it('renders the M365 cloud faces real at their hhea totals', () => {
expect(lineHeightFactor('Roboto')).toBe(1.172)
expect(lineHeightFactor('Montserrat')).toBe(1.219)
expect(lineHeightFactor('Georgia Pro')).toBe(0.98)
expect(lineHeightFactor('Georgia')).toBe(1.1375)
expect(lineHeightFactor('Calibri Light')).toBe(1.22)
})
})
describe('symbolBulletLinePt', () => {
it('lifts a bullet line to Symbol ascent + text descent (Word probe 2026-09-17)', () => {
// Aptos 10pt text, Symbol bullet at the 10pt run size: 10.054 + 2.817
expect(symbolBulletLinePt('Symbol', 10, 'Aptos', 10)).toBe(12.871)
// Cambria 11pt text + Symbol 11pt: 11.059 + 2.444 (Word 15.36-15.6 at 1.15)
expect(symbolBulletLinePt('Symbol', 11, 'Cambria', 11)).toBe(13.504)
expect(symbolBulletLinePt('Symbol', 12, null, 12)).toBe(15.065)
})
it('leaves lines alone when the text face is as tall as the bullet face', () => {
expect(symbolBulletLinePt('Wingdings', 11, 'Calibri', 11)).toBeNull()
expect(symbolBulletLinePt('Webdings', 12, 'Times New Roman', 12)).toBeNull()
expect(symbolBulletLinePt('Symbol', 11, 'Segoe UI', 11)).toBeNull()
expect(symbolBulletLinePt('Courier New', 11, 'Calibri', 11)).toBeNull()
expect(symbolBulletLinePt('Symbol', 0, 'Calibri', 11)).toBeNull()
})
})
+17 -1
View File
@@ -186,7 +186,7 @@ describe('native editable tables', () => {
expect(json.content?.[0].type).toBe('docTable')
expect(json.content?.[0].content?.[0].content?.[0]).toMatchObject({
type: 'docTableCell',
attrs: { fill: 'D9EAF7', bold: true, color: '1F4E78', colspan: 1, rowspan: 1 },
attrs: { fill: 'D9EAF7', bold: false, color: null, colspan: 1, rowspan: 1 },
})
expect(json.content?.[0].content?.[0].content?.[0].content?.[0].content?.[0].marks).toEqual([
{ type: 'bold' },
@@ -482,6 +482,22 @@ describe('native editable tables', () => {
'width:min(1200px,calc(var(--doc-content-w,100%) + var(--doc-margin-right,0px) - 96.7px))',
)
expect(spec[1].style).toContain('margin-left:96.7px')
// a negative indent hangs into the left margin and widens the spill by as much
editor.view.dispatch(
editor.state.tr.setNodeMarkup(0, undefined, {
...table.attrs,
widthPx: 1200,
indentTwips: -714,
}),
)
const hanging = editor.schema.nodes.docTable.spec.toDOM!(editor.state.doc.firstChild!) as [
string,
Record<string, string>,
]
expect(hanging[1].style).toContain(
'width:min(1200px,calc(var(--doc-content-w,100%) + var(--doc-margin-right,0px) + 47.6px))',
)
expect(hanging[1].style).toContain('margin-left:-47.6px')
editor.destroy()
})
+47 -1
View File
@@ -455,10 +455,56 @@ describe('computeListMarkers', () => {
const style = el.getAttribute('style') ?? ''
expect(style).toContain("--li-marker-font: Arial,'Helvetica Neue',sans-serif")
expect(style).toContain('--li-marker-scale: 1.25')
expect(style).toContain('--li-marker-lh: 0')
// Symbol's ascent tops the 12pt Calibri text: the bullet box carries Word's
// max-ascent + max-descent line (1.0054 + 0.2686 em) and sits on the bottom
expect(style).toContain('--li-marker-lh: calc(15.288pt * var(--doc-line-mult,1))')
expect(style).toContain('--li-marker-va: bottom')
expect(style).toContain('--li-marker-size: 12pt')
editor.destroy()
})
it('keeps the bullet box flat on exact lines, direct or style-level', async () => {
const numberingXml =
'<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
'<w:abstractNum w:abstractNumId="0"><w:lvl w:ilvl="0"><w:numFmt w:val="bullet"/>' +
'<w:lvlText w:val="\uF0B7"/><w:rPr><w:rFonts w:ascii="Symbol" w:hAnsi="Symbol"/></w:rPr>' +
'<w:pPr><w:ind w:left="720" w:hanging="360"/></w:pPr></w:lvl></w:abstractNum>' +
'<w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num></w:numbering>'
const item = (pPr: string) =>
`<w:p><w:pPr>${pPr}<w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr></w:pPr>` +
'<w:r><w:rPr><w:sz w:val="24"/></w:rPr><w:t>item</w:t></w:r></w:p>'
const parsed = await parseDocx(
await buildDocx({
bodyXml:
item('<w:spacing w:line="240" w:lineRule="exact"/>') +
item('<w:pStyle w:val="Tight"/>') +
item('<w:pStyle w:val="Tight"/><w:spacing w:line="276" w:lineRule="auto"/>') +
item(''),
numberingXml,
extraStylesXml:
'<w:style w:type="paragraph" w:styleId="Tight"><w:name w:val="Tight"/>' +
'<w:pPr><w:spacing w:line="240" w:lineRule="exact"/></w:pPr></w:style>',
}),
)
const editor = new Editor({
element: document.createElement('div'),
extensions: editorExtensions,
})
editor.storage.listNumbering.defs = parsed.numbering
editor.storage.listNumbering.styles = parsed.styles
editor.commands.setContent(blocksToPmDoc(parsed.blocks) as never)
const styles = [...editor.view.dom.querySelectorAll('.doc-li')].map(
(el) => el.getAttribute('style') ?? '',
)
expect(styles[0]).toContain('--li-marker-lh: 0')
expect(styles[0]).not.toContain('--li-marker-va')
expect(styles[1]).toContain('--li-marker-lh: 0')
expect(styles[1]).not.toContain('--li-marker-va')
// a direct auto rule overrides the style's exact one
expect(styles[2]).toContain('--li-marker-va: bottom')
expect(styles[3]).toContain('--li-marker-va: bottom')
editor.destroy()
})
})
describe('list marker decorations', () => {
+48
View File
@@ -9,6 +9,7 @@ import {
syncPageSheets,
syncPhantomRowspans,
clampCellBoxTops,
clampCellImageTops,
pageBorderArtStripStyle,
pageBorderStyleOf,
rowFillAttrs,
@@ -247,6 +248,53 @@ describe('clampCellBoxTops', () => {
})
})
describe('clampCellImageTops', () => {
const cellImage = (pm: HTMLElement, imgTop: number, cellTop: number): HTMLElement => {
const table = document.createElement('table')
const cell = document.createElement('td')
cell.style.border = '0'
cell.style.padding = '0'
cell.getBoundingClientRect = () => ({ top: cellTop, height: 80, width: 200 }) as DOMRect
const img = document.createElement('img')
img.dataset.cellLift = '1'
img.style.marginTop = 'calc(-243.0px + var(--cell-lift,0px))'
let lifted = 0
// the live rect follows the applied lift, like the real layout
img.getBoundingClientRect = () =>
({ top: imgTop + lifted, bottom: imgTop + lifted + 71, height: 71, width: 201 }) as DOMRect
Object.defineProperty(img, 'lift', { set: (v: number) => (lifted = v) })
cell.appendChild(img)
table.appendChild(cell)
pm.appendChild(table)
return img
}
// mounted: jsdom computes the cell insets only for elements in the document
const mounted = () => document.body.appendChild(document.createElement('div'))
it('pushes a picture lifted above its cell top back to the edge; in-cell pictures stay', () => {
const pm = mounted()
const above = cellImage(pm, 440, 660)
const inside = cellImage(pm, 700, 660)
clampCellImageTops(pm, 1)
expect(above.style.getPropertyValue('--cell-lift')).toBe('220.0px')
expect(above.dataset.cellLiftDy).toBe('220')
expect(inside.style.getPropertyValue('--cell-lift')).toBe('')
pm.remove()
})
it('is idempotent against the already-lifted rect and scales by the zoom factor', () => {
const pm = mounted()
const img = cellImage(pm, 440, 660)
clampCellImageTops(pm, 2)
expect(img.style.getPropertyValue('--cell-lift')).toBe('110.0px')
;(img as unknown as { lift: number }).lift = 220
clampCellImageTops(pm, 2)
expect(img.style.getPropertyValue('--cell-lift')).toBe('110.0px')
pm.remove()
})
})
describe('alignTableGapFills', () => {
/** paper at x=0, 816 wide; the gap cell follows its table's box */
const pmWithFill = (cellLeft: number, cellWidth: number) => {
@@ -0,0 +1,126 @@
import { describe, expect, it } from 'vitest'
import { EDGE_LEAK_PX, leadLeakCss } from '../src/renderer/components/PaginationPreview'
import type { BlockBox, PageSlice } from '../src/renderer/pagination'
const block = (
idx: number,
top: number,
height: number,
extra: Partial<BlockBox> = {},
): BlockBox => {
const el = document.createElement('p')
el.dataset.idx = String(idx)
return { top, height, el, ...extra }
}
const slice = (start: number, end: number, extra: Partial<PageSlice> = {}): PageSlice => ({
start,
end,
section: 0,
...extra,
})
const hidden = (css: string): Array<[number, number]> =>
[
...css.matchAll(
/data-pv-page="(\d+)"\] \.pv-content > \[data-idx="(\d+)"\]\{visibility:hidden;\}/g,
),
].map((m) => [Number(m[1]), Number(m[2])])
describe('leadLeakCss', () => {
// a break-only paragraph (two line boxes) ends page 1; the heading it pushes
// opens page 2 exactly at the window end, where its glyph tops would leak
const pages = [slice(0, 739), slice(739, 1500), slice(1500, 2000)]
const breakPara = block(3, 665, 43)
const heading = block(4, 739, 21)
const body = block(5, 760, 64)
it('hides the next page lead block on the page before it only', () => {
expect(hidden(leadLeakCss([breakPara, heading, body], pages))).toEqual([[0, 4]])
})
it('leaves blocks that straddle the window end visible', () => {
const straddling = block(4, 700, 100)
expect(hidden(leadLeakCss([breakPara, straddling], pages))).toEqual([])
})
it('ignores blocks too far below the window to reach it', () => {
const far = block(4, 739 + EDGE_LEAK_PX, 21)
expect(hidden(leadLeakCss([far], pages))).toEqual([])
})
it('never hides on the last page (its window opens to full capacity)', () => {
const tail = block(9, 2000, 21)
expect(hidden(leadLeakCss([tail], pages))).toEqual([])
})
it('leaves floated blocks and pinned-box carriers alone', () => {
const floated = block(4, 739, 21, { floated: true })
const carrier = block(4, 739, 21)
carrier.el!.innerHTML = '<div data-pin-page="0"></div>'
expect(hidden(leadLeakCss([floated, carrier], pages))).toEqual([])
})
it('skips column-region pages, whose windows are per column', () => {
const regioned = [slice(0, 739, { regions: [] }), slice(739, 1500)]
expect(hidden(leadLeakCss([heading], regioned))).toEqual([])
})
})
describe('leadLeakCss table seams', () => {
const table = (top: number, heights: number[]) => {
const el = document.createElement('table')
el.dataset.idx = '7'
const tbody = document.createElement('tbody')
for (const h of heights) {
const tr = document.createElement('tr')
tr.innerHTML = `<td><p>${h}</p></td>`
tbody.appendChild(tr)
}
el.appendChild(tbody)
document.body.appendChild(el)
const height = heights.reduce((a, b) => a + b, 0)
return { top, height, el, tableRows: heights.map((h) => ({ height: h })) } as BlockBox
}
it('hides the cell contents of the row opening the next page, keeping the row itself', () => {
const t = table(700, [20, 30, 40])
const css = leadLeakCss([t], [slice(0, 750), slice(750, 1500)])
expect(css).toBe(
'.pv-page[data-pv-page="0"] .pv-content tr[data-pv-lead="0"] > * > *{visibility:hidden;}',
)
expect(t.el!.querySelectorAll('tr')[2].dataset.pvLead).toBe('0')
})
it('leaves a row cut mid-way alone and clears stale stamps', () => {
const t = table(700, [20, 30, 40])
t.el!.querySelectorAll('tr')[1].dataset.pvLead = '9'
expect(leadLeakCss([t], [slice(0, 735), slice(735, 1500)])).toBe('')
expect(t.el!.querySelectorAll('tr')[1].dataset.pvLead).toBeUndefined()
})
})
describe('leadLeakCss short rows', () => {
it('stamps the row whose top is the window end, not a hairline row just above it', () => {
const el = document.createElement('table')
el.dataset.idx = '8'
const tbody = document.createElement('tbody')
for (const h of [20, 1, 40]) {
const tr = document.createElement('tr')
tr.innerHTML = `<td><p>${h}</p></td>`
tbody.appendChild(tr)
}
el.appendChild(tbody)
document.body.appendChild(el)
const t = {
top: 700,
height: 61,
el,
tableRows: [{ height: 20 }, { height: 1 }, { height: 40 }],
} as BlockBox
leadLeakCss([t], [slice(0, 721), slice(721, 1500)])
const trs = el.querySelectorAll('tr')
expect(trs[1].dataset.pvLead).toBeUndefined()
expect(trs[2].dataset.pvLead).toBe('0')
})
})
+381 -10
View File
@@ -1900,6 +1900,101 @@ describe('computeSectionedSlicesF2 — table row-level page breaks', () => {
expect(legacy[1].start).toBe(150)
})
it('keepNext rows chain to the next row; a lone last row may open a page', () => {
// 200px pages, paragraph 150 leaves 50: rows 0 (keepNext) and 1 (30 each)
// only fit one at a time, so row 0 moves down with row 1 (probe 2026-09-17,
// cases 10-12); without keepNext row 0 stays. A chain taller than a page is
// placed normally. A table's last row alone on the next page is Word's
// behaviour too (case 14).
const page = [{ contentHeight: 200, forceBreak: false }]
const slicesOf = (rows: TableRowBox[]) =>
computeSectionedSlicesF2(
[{ top: 0, height: 150 }, makeTableBlock(150, rows)],
page,
150 + rows.reduce((s, r) => s + r.height, 0),
).map((s) => [s.start, s.end])
expect(slicesOf([{ height: 30, keepNext: true }, { height: 30 }, { height: 30 }])).toEqual([
[0, 150],
[150, 240],
])
expect(slicesOf([{ height: 30 }, { height: 30 }, { height: 30 }])).toEqual([
[0, 180],
[180, 240],
])
// chain of two keepNext rows with the anchor's first cut segment as its demand
expect(
slicesOf([
{ height: 20, keepNext: true },
{ height: 20, keepNext: true },
{ height: 60, cutYs: [20, 40] },
]),
).toEqual([
[0, 150],
[150, 250],
])
expect(
slicesOf([{ height: 120, keepNext: true }, { height: 120, keepNext: true }, { height: 30 }]),
).toEqual([
[0, 150],
[150, 270],
[270, 420],
])
expect(slicesOf([{ height: 25 }, { height: 25 }, { height: 25 }])).toEqual([
[0, 200],
[200, 225],
])
// the anchor's demand is widow-aware: its 3-line cell paragraph cannot be
// cut 2+1, so the chain needs the whole 60px paragraph and moves although a
// raw first cut (20px) would have fit below the keepNext row
const lines = (n: number, pitch: number) => ({
lines: Array.from({ length: n }, (_, i): [number, number] => [i * pitch, (i + 1) * pitch]),
childOf: Array.from({ length: n }, () => 0),
paraOf: Array.from({ length: n }, () => 0),
alignDy: 0,
alignFrac: 0,
})
const anchor: TableRowBox = {
height: 60,
contentBottom: 60,
cutYs: [20, 40],
cells: [lines(3, 20)],
}
const chain = (rows: TableRowBox[], out?: SliceOutputs) =>
computeSectionedSlicesF2(
[
{ top: 0, height: 150 },
{ ...makeTableBlock(150, rows), modernTableHeaders: true },
],
page,
230,
out,
).map((s) => [s.start, s.end])
const moved = [
[0, 150],
[150, 230],
]
expect(chain([{ height: 20, keepNext: true }, anchor], { rowSplits: [] })).toEqual(moved)
// without a cell split path the anchor is atomic and demands its full height;
// a declared-height anchor demands at least its (page-capped) minimum
expect(
chain([
{ height: 20, keepNext: true },
{ ...anchor, cutYs: [] },
]),
).toEqual(moved)
expect(
chain(
[
{ height: 20, keepNext: true },
{ ...anchor, cells: [lines(1, 20)], minHPx: 60 },
],
{
rowSplits: [],
},
),
).toEqual(moved)
})
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)
@@ -2389,6 +2484,57 @@ describe('fillLineBoxes — keepNext chain anchors', () => {
{ offsetInBlock: 20, height: 20 },
])
})
const twoPages = (cut: number): PageSlice[] => [
{ start: 0, end: cut, section: 0 },
{ start: cut, end: 200, section: 0 },
]
it('keeps lines apart when tall glyph boxes overlap the next line (KR 1.3029 pitch)', () => {
// GenOffice Sans KR content area 1.448em under a 1.3029 line: each rect
// runs 2.35px into the next line, so a fixed 1px tolerance merged whole
// paragraphs into one line and made them atomic at page bottoms
const el = document.createElement('p')
el.textContent = 'four lines'
const para: BlockBox = { top: 0, height: 83.4, el }
const rects = [0, 20.85, 41.7, 62.55].map((top) => ({
top,
bottom: top + 23.2,
height: 23.2,
width: 50,
left: 0,
}))
const orig = Range.prototype.getClientRects
Range.prototype.getClientRects = () => rects as unknown as DOMRectList
try {
expect(fillLineBoxes([para], geoms, 1, twoPages(50))).toBe(true)
} finally {
Range.prototype.getClientRects = orig
}
expect(para.lineBoxes?.length).toBe(4)
expect(para.lineBoxes?.map((b) => Math.round(b.offsetInBlock * 10) / 10)).toEqual([
0, 20.9, 41.7, 62.6,
])
})
it('still joins same-line rects of different font sizes', () => {
// a 12pt run baseline-aligned on a 24pt line sits 18px below the line top
const el = document.createElement('p')
el.textContent = 'one line'
const para: BlockBox = { top: 0, height: 46, el }
const rects = [
{ top: 0, bottom: 46, height: 46, width: 80, left: 0 },
{ top: 18.4, bottom: 41.6, height: 23.2, width: 40, left: 80 },
]
const orig = Range.prototype.getClientRects
Range.prototype.getClientRects = () => rects as unknown as DOMRectList
try {
fillLineBoxes([para], geoms, 1, twoPages(30))
} finally {
Range.prototype.getClientRects = orig
}
expect(para.lineBoxes).toBeUndefined()
})
})
describe('measureBlocks — page-anchored floated tables', () => {
@@ -2951,6 +3097,22 @@ describe('tableHeaderFlags', () => {
])
})
it('tableRowFlags: a keepNext paragraph in any cell (direct or via pStyle) marks the row keepNext', () => {
const xml =
'<w:tbl><w:tr><w:tc><w:p><w:pPr><w:keepNext/></w:pPr></w:p></w:tc><w:tc><w:p/></w:tc></w:tr>' +
'<w:tr><w:tc><w:p><w:pPr><w:pStyle w:val="Heading2"/></w:pPr></w:p></w:tc></w:tr>' +
'<w:tr><w:tc><w:p><w:pPr><w:pStyle w:val="Heading2"/><w:keepNext w:val="0"/></w:pPr></w:p></w:tc></w:tr>' +
'<w:tr><w:tc><w:p><w:pPr><w:pStyle w:val="Normal"/></w:pPr></w:p></w:tc></w:tr></w:tbl>'
const keep = (id: string) => id === 'Heading2'
expect(tableRowFlags(xml, keep).map((f) => f.keepNext ?? false)).toEqual([
true,
true,
false,
false,
])
expect(tableRowFlags(xml).map((f) => f.keepNext ?? false)).toEqual([true, false, false, false])
})
it('tableRowFlags parses atLeast trHeight into minHPx (exact/auto-only rows excluded)', () => {
const xml =
'<w:tbl><w:tr><w:trPr><w:trHeight w:val="1500"/></w:trPr><w:tc/></w:tr>' +
@@ -4363,10 +4525,12 @@ describe('fillLineBoxes — empty paragraphs above a cell heading are row cut po
})
describe('computeSectionedSlicesF2 — multi-cell rows split per cell (Word row break)', () => {
// Word 2013+ layout: widow/orphan control applies inside cells (legacy mode cuts after any line)
const makeTableBlock = (top: number, rows: TableRowBox[]): BlockBox => ({
top,
height: rows.reduce((s, r) => s + r.height, 0),
tableRows: rows,
modernTableHeaders: true,
})
/** 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) => ({
@@ -4638,11 +4802,87 @@ describe('computeSectionedSlicesF2 — multi-cell rows split per cell (Word row
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
it('modernTableHeaders: a header row never stays alone at the page bottom, but a legal first-row split is fine', () => {
// 200px pages, paragraph 130 leaves 70: the 20px header fits and the first
// body row has 50px of room. Cell 0 is a 3-line paragraph (2 lines fit -> a
// 2+1 cut is illegal): Word 2013+ moves the row whole and takes the header
// with it (probe 2026-09-17, cases 1/18); legacy mode leaves the header and
// cuts the cell after any line.
const held = () => ({
height: 90,
contentBottom: 90,
cells: [
{ ...linesOf(3, 20, 3), alignDy: 0, alignFrac: 0 },
{ ...linesOf(5, 18, 5), alignDy: 0, alignFrac: 0 },
],
})
const table = (rows: TableRowBox[], modern: boolean) => {
const b = makeTableBlock(130, rows)
b.modernTableHeaders = modern
return b
}
const page = [{ contentHeight: 200, forceBreak: false }]
const run = (rows: TableRowBox[], modern: boolean) => {
const out: SliceOutputs = { rowSplits: [] }
const slices = computeSectionedSlicesF2(
[{ top: 0, height: 130 }, table(rows, modern)],
page,
300,
out,
)
return { slices, out }
}
const body = Array.from({ length: 3 }, () => ({ height: 20 }))
const modern = run([{ height: 20, isHeader: true }, held(), ...body], true)
expect(modern.slices.map((s) => [s.start, s.end])).toEqual([
[0, 130],
[130, 300],
])
expect(modern.slices[1].repeatHeader).toBeUndefined()
expect(modern.out.rowSplits).toEqual([])
const legacy = run([{ height: 20, isHeader: true }, held(), ...body], false)
expect(legacy.slices.map((s) => [s.start, s.end])).toEqual([
[0, 200],
[200, 300],
])
expect(legacy.slices[1].repeatHeader).toEqual({ top: 130, height: 20 })
// a first row whose cells all break legally splits under the header in modern mode too
const legal = run(
[
{ height: 20, isHeader: true },
{
height: 90,
contentBottom: 90,
cells: [{ ...linesOf(5, 18, 5), alignDy: 0, alignFrac: 0 }],
},
...body,
],
true,
)
expect(legal.slices.map((s) => [s.start, s.end])).toEqual([
[0, 200],
[200, 300],
])
expect(legal.slices[1].repeatHeader).toEqual({ top: 130, height: 20 })
// the header is only retracted when the first body row turns the page: a
// cantSplit first row does the same, a later row leaves the header in place
const cant = run(
[{ height: 20, isHeader: true }, { height: 60, cantSplit: true }, ...body],
true,
)
expect(cant.slices[0].end).toBe(130)
const later = run(
[{ height: 20, isHeader: true }, { height: 20 }, { height: 60, cantSplit: true }, ...body],
true,
)
expect(later.slices[0].end).toBe(170)
expect(later.slices[1].repeatHeader).toEqual({ top: 130, height: 20 })
})
it('a cell that cannot break legally moves the whole row; a fresh page still pushes it onto the continuation centered', () => {
// cell 1: one 2-line paragraph (60px) with room for one line in the 40px
// remainder: the widow rule holds it, and Word moves the row to page 2
// instead of leaving the cell empty (probe 2026-09-17, 2-line cell / 1.5 lines)
const rows: TableRowBox[] = [
{ height: 160 },
{
@@ -4655,12 +4895,37 @@ describe('computeSectionedSlicesF2 — multi-cell rows split per cell (Word row
},
]
const out: SliceOutputs = { rowSplits: [] }
computeSectionedSlicesF2([makeTableBlock(0, rows)], page, 460, out)
const slices = computeSectionedSlicesF2([makeTableBlock(0, rows)], page, 460, out)
expect(slices.map((s) => [s.start, s.end])).toEqual([
[0, 160],
[160, 360],
[360, 460],
])
// page 2 holds the whole 2-line cell centered in the page-filling fragment
// (cell 0 runs on to page 3): (200 - 60) / 2 minus the canvas centering offset
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 },
{ from: 160, cell: 1, child: 0, tail: true, dy: 70 - 120 },
{ from: 360, cell: 1, child: 0, tail: true, hide: true },
])
// on a fresh page the held cell cannot move the row any further: it lands
// whole on the continuation, flush at the page top (shift 40) plus centering
const fresh: TableRowBox[] = [
{
height: 300,
contentBottom: 300,
cells: [
{ ...linesOf(15, 20, 5), alignDy: 0, alignFrac: 0 },
{ ...linesOf(2, 30, 2, 0, 160), alignDy: 40, alignFrac: 0.5 },
],
},
]
const out2: SliceOutputs = { rowSplits: [] }
computeSectionedSlicesF2([makeTableBlock(0, fresh)], page, 300, out2)
// the 100px closing fragment centers the 60px cell: (100 - 60) / 2
expect(out2.rowSplits![0].rules.filter((r) => r.cell === 1)).toEqual([
{ from: 0, cell: 1, child: 0, tail: true, dy: -40 },
{ from: 0, cell: 1, child: 0, tail: true, hide: true },
{ from: 200, cell: 1, child: 0, tail: true, dy: 20 },
])
})
@@ -4851,3 +5116,109 @@ describe('vertical-text sections (sectPr w:textDirection)', () => {
expect(rules).toHaveLength(5)
})
})
describe('row splits cut between line boxes (box-relative clips)', () => {
// 20px line pitch with 14px ink bands: each line's ink sits 3px inside its box
const inkLines = (n: number, child = 0) => ({
lines: Array.from({ length: n }, (_, i): [number, number] => [i * 20 + 3, i * 20 + 17]),
childOf: Array.from({ length: n }, () => child),
paraOf: Array.from({ length: n }, () => child),
})
const cells = () => [
{ ...inkLines(10), childBox: [[0, 200]] as Array<[number, number]>, alignDy: 0, alignFrac: 0 },
{ ...inkLines(3), childBox: [[0, 60]] as Array<[number, number]>, alignDy: 0, alignFrac: 0 },
]
const bodyRow = (): TableRowBox => ({ height: 200, contentBottom: 197, cells: cells() })
const page = [{ contentHeight: 120, forceBreak: false }]
const tableBlock = (rows: TableRowBox[]): BlockBox => ({
top: 0,
height: rows.reduce((s, r) => s + r.height, 0),
tableRows: rows,
})
it('clips the outgoing fragment in the leading gap, measured from the box bottom', () => {
// 90px available: 4 lines (ink bottoms 17..77) fit, line 5 (83..97) does not.
// The boundary is the gap middle (80) and the inset counts from the 200px box
// bottom: 120. The old ink-relative inset (197 - 83 = 114) left the top 3px
// of line 5's glyphs on the page.
const plan = planRowSplit(bodyRow(), 90, 120, () => 120)
const rules = plan && plan !== 'nofit' ? plan.rules : []
expect(rules).toContainEqual({ from: 0, cell: 0, child: 0, clipBottom: 120 })
// the continuation opens at that boundary: line 5's box top lands on the page top
expect(rules).toContainEqual({ from: 90, cell: 0, child: 0, tail: true, dy: 10 })
expect(rules).toContainEqual({ from: 90, cell: 0, child: 0, clipTop: 80 })
expect(rules).toContainEqual({ from: 90, cell: 1, child: 0, tail: true, hide: true })
})
it('a row under a tblHeader row continues below the repeated header from its first unseen line', () => {
const out: SliceOutputs = { rowFills: [], rowSplits: [] }
const slices = computeSectionedSlicesF2(
[tableBlock([{ height: 30, isHeader: true }, bodyRow()])],
page,
230,
out,
)
expect(slices.map((s) => [s.start, s.repeatHeader?.height])).toEqual([
[0, undefined],
[120, 30],
[210, 30],
])
expect(out.rowSplits![0].rules.filter((r) => r.cell === 0)).toEqual([
{ from: 30, cell: 0, child: 0, clipBottom: 120 },
{ from: 30, cell: 0, child: 1, tail: true, hide: true },
{ from: 120, cell: 0, child: 0, tail: true, dy: 10 },
{ from: 120, cell: 0, child: 0, clipTop: 80, clipBottom: 40 },
{ from: 120, cell: 0, child: 1, tail: true, hide: true },
{ from: 210, cell: 0, child: 0, tail: true, dy: 20 },
{ from: 210, cell: 0, child: 0, clipTop: 160 },
])
expect(out.rowFills).toEqual([{ blockTop: 0, row: 1, targetPx: 220, extraPx: 20 }])
})
it('without a header the boundary at the page bottom leaves the continuation a plain clip', () => {
// 6 lines fit (ink bottom 117); the boundary (120) is the page bottom itself
const out: SliceOutputs = { rowFills: [], rowSplits: [] }
const slices = computeSectionedSlicesF2([tableBlock([bodyRow()])], page, 200, out)
expect(slices.map((s) => s.start)).toEqual([0, 120])
expect(slices[1].repeatHeader).toBeUndefined()
expect(out.rowSplits![0].rules.filter((r) => r.cell === 0)).toEqual([
{ from: 0, cell: 0, child: 0, clipBottom: 80 },
{ from: 0, cell: 0, child: 1, tail: true, hide: true },
{ from: 120, cell: 0, child: 0, clipTop: 120 },
])
expect(out.rowFills).toEqual([])
})
it('fillLineBoxes records each cell child box next to its ink lines', () => {
const wrap = document.createElement('div')
wrap.innerHTML =
'<table><tbody><tr><td><p>long</p></td><td><p>short</p></td></tr></tbody></table>'
const [longP, shortP] = Array.from(wrap.querySelectorAll('p'))
const rect = (top: number, bottom: number) =>
({ top, bottom, height: bottom - top, left: 0, right: 100, width: 100 }) as DOMRect
const elProto = Element.prototype
const origBox = elProto.getBoundingClientRect
const rangeProto = Range.prototype as unknown as { getClientRects?: () => DOMRect[] }
const origRects = rangeProto.getClientRects
elProto.getBoundingClientRect = function (this: Element) {
if (this === longP) return rect(3, 203)
if (this === shortP) return rect(3, 63)
return rect(0, 200)
}
rangeProto.getClientRects = function (this: Range) {
const n = this.startContainer.parentElement === longP ? 10 : 3
return Array.from({ length: n }, (_, i) => rect(i * 20 + 6, i * 20 + 20))
}
try {
const table: BlockBox = { top: 0, height: 200, el: wrap }
expect(fillLineBoxes([table], [{ contentHeight: 120, forceBreak: false }], 1)).toBe(true)
const [c0, c1] = table.tableRows![0].cells!
expect(c0.childBox).toEqual([[3, 203]])
expect(c0.lines[0]).toEqual([6, 20])
expect(c1.childBox).toEqual([[3, 63]])
} finally {
elProto.getBoundingClientRect = origBox
rangeProto.getClientRects = origRects
}
})
})
+149
View File
@@ -0,0 +1,149 @@
import { describe, expect, it } from 'vitest'
import { Fragment, Schema, type Node as PmNode } from '@tiptap/pm/model'
import { Decoration, DecorationSet } from '@tiptap/pm/view'
import {
fastFindIndex,
fastForChild,
withOriginalFindIndex,
withOriginalForChild,
} from '../src/renderer/editor/prosemirror-perf'
const schema = new Schema({
nodes: {
doc: { content: 'block+' },
paragraph: { content: 'text*', group: 'block' },
quote: { content: 'paragraph+', group: 'block' },
text: {},
},
})
// deterministic LCG so a failure reproduces
let seed = 12345
const rnd = (n: number) => {
seed = (seed * 1103515245 + 12345) & 0x7fffffff
return seed % n
}
function makeDoc(blocks: number): PmNode {
const children: PmNode[] = []
for (let i = 0; i < blocks; i++) {
const para = () => schema.node('paragraph', null, schema.text('x'.repeat(1 + rnd(12))))
children.push(rnd(5) === 0 ? schema.node('quote', null, [para(), para()]) : para())
}
return schema.node('doc', null, children)
}
function randomDecorations(doc: PmNode, count: number): Decoration[] {
const size = doc.content.size
const out: Decoration[] = []
for (let i = 0; i < count; i++) {
const kind = rnd(4)
if (kind === 0) {
// node decoration on a top-level or nested block
const pos = rnd(size)
const $pos = doc.resolve(pos)
const depth = Math.max(1, $pos.depth)
const before = $pos.before(depth)
const node = doc.nodeAt(before)!
out.push(Decoration.node(before, before + node.nodeSize, { class: `n${i}` }))
} else if (kind === 1) {
out.push(Decoration.widget(rnd(size + 1), () => document.createElement('span'), { id: i }))
} else {
// inline decoration; every other one deliberately crosses a block boundary
const a = rnd(size)
const b = Math.min(size, a + 1 + rnd(kind === 2 ? 3 : 40))
if (a < b) out.push(Decoration.inline(a, b, { class: `i${i}` }))
}
}
return out
}
type Source = DecorationSet | { members: DecorationSet[] }
const flatten = (set: Source): Decoration[] =>
'members' in set ? set.members.flatMap((m) => m.find()) : set.find()
const dump = (set: Source) =>
flatten(set)
.map((d) => `${d.from}-${d.to}:${JSON.stringify(d.spec)}`)
.sort()
function compareAll(doc: PmNode, set: DecorationSet, parent: PmNode, base: number): number {
let checked = 0
parent.forEach((child, offset) => {
const at = base + offset
const fast = fastForChild.call(set, at, child)
const slow = withOriginalForChild(() => set.forChild(at, child))
expect(dump(fast as unknown as Source)).toEqual(dump(slow as unknown as Source))
checked++
if (
!child.isLeaf &&
!child.isTextblock &&
fast !== DecorationSet.empty &&
fast instanceof DecorationSet
) {
checked += compareAll(doc, fast, child, at + 1)
}
})
return checked
}
describe('DecorationSet.forChild override', () => {
it('matches the upstream result on random documents and decoration mixes', () => {
let checked = 0
for (let round = 0; round < 40; round++) {
const doc = makeDoc(5 + rnd(60))
const set = DecorationSet.create(doc, randomDecorations(doc, rnd(80)))
checked += compareAll(doc, set, doc, 0)
}
expect(checked).toBeGreaterThan(1000)
})
it('returns the shared empty set and child subtrees by identity like upstream', () => {
const doc = makeDoc(30)
const decos = randomDecorations(doc, 60).filter(
(d) => !(d as unknown as { inline: boolean }).inline || d.to - d.from < 3,
)
const set = DecorationSet.create(doc, decos)
doc.forEach((child, offset) => {
const fast = fastForChild.call(set, offset, child)
const slow = withOriginalForChild(() => set.forChild(offset, child))
expect(fast).toBe(slow)
})
})
})
const findIndexOf = (frag: Fragment, pos: number) =>
(frag as unknown as { findIndex: (p: number) => { index: number; offset: number } }).findIndex(
pos,
)
describe('Fragment.findIndex override', () => {
it('matches the upstream walk for every position of small and large fragments', () => {
for (const blocks of [1, 3, 63, 64, 65, 200, 1000]) {
const doc = makeDoc(blocks)
const frag = doc.content
for (let pos = 0; pos <= frag.size; pos++) {
const fast = { ...fastFindIndex.call(frag, pos) }
const slow = withOriginalFindIndex(() => ({ ...findIndexOf(frag, pos) }))
expect(fast).toEqual(slow)
}
expect(() => fastFindIndex.call(frag, frag.size + 1)).toThrow(RangeError)
expect(() => fastFindIndex.call(frag, -1)).toThrow(RangeError)
}
})
it('keeps resolve / nodeAt / childAfter exact on a long document', () => {
const doc = makeDoc(500)
for (let round = 0; round < 300; round++) {
const pos = rnd(doc.content.size + 1)
const fast = doc.resolve(pos)
const slow = withOriginalFindIndex(() => doc.resolve(pos))
expect([fast.depth, fast.parentOffset, fast.index(0)]).toEqual([
slow.depth,
slow.parentOffset,
slow.index(0),
])
expect(doc.nodeAt(pos)).toBe(withOriginalFindIndex(() => doc.nodeAt(pos)))
}
expect(findIndexOf(Fragment.empty, 0)).toEqual({ index: 0, offset: 0 })
})
})
@@ -63,6 +63,7 @@ describe('text effect declarations', () => {
'transform:scaleX(0.33)',
'transform-origin:0 50%',
'margin-right:-0.348em',
'text-indent:0',
])
expect(charScaleXDecls('nope')).toEqual([])
})
@@ -102,8 +102,6 @@ function ribbonProps(editor: Editor) {
onShowRuler: noop,
showNav: false,
onShowNav: noop,
showFiles: false,
onShowFiles: noop,
commentCount: 0,
openCommentCount: 0,
onShowComments: noop,
@@ -0,0 +1,28 @@
/**
* Flow gaps the paginated preview inherits from the canvas stylesheet: Word
* gives a table no vertical margin of its own, and an anchored shape keeps
* its declared extent past the text column.
*/
import { readFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'
const css = readFileSync(
join(dirname(fileURLToPath(import.meta.url)), '../src/renderer/styles.css'),
'utf8',
)
const rule = (selector: string) =>
new RegExp(`${selector.replace(/[.>*+?^$(){}|[\\]\\]/g, '\\$&')}\\s*\\{([^}]*)\\}`).exec(
css,
)?.[1] ?? ''
describe('styles.css flow gaps', () => {
it('body tables carry no vertical margin', () => {
expect(rule('.doc-page > .doc-table')).toMatch(/margin:\s*0;/)
})
it('anchored textboxes are not capped at the column width', () => {
expect(rule('.doc-protected-floating > .doc-textbox')).toMatch(/max-width:\s*none/)
})
})
+11 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
import { tabSegmentWidth } from '../src/renderer/editor/decoration-extensions'
import { sameVisualLine, tabSegmentWidth } from '../src/renderer/editor/decoration-extensions'
const line = (left: number, top: number) => ({ left, top, bottom: top + 20 })
@@ -16,4 +16,14 @@ describe('tabSegmentWidth', () => {
expect(tabSegmentWidth(line(100, 0), line(620, 28), 600, 1)).toBe(600)
expect(tabSegmentWidth(line(100, 0), line(90, 56), 600, 1)).toBe(600)
})
// line=177 auto: 20px inline boxes on a 15px pitch overlap, yet the next
// line's tab is not a same-line continuation (its segment measured 0 and the
// following tab chained from the first stop onto the default grid)
it('does not read an overlapping next line as the tab line', () => {
expect(tabSegmentWidth(line(100, 0), line(60, 15), 600, 1)).toBe(600)
expect(sameVisualLine(line(0, 0), line(0, 15))).toBe(false)
// spans of different sizes on one line keep matching
expect(sameVisualLine(line(0, 0), { top: 12, bottom: 18 })).toBe(true)
})
})
+20
View File
@@ -108,6 +108,26 @@ describe('resolveTabTarget', () => {
expect(resolveTabTarget({ ...base, stops: [], gridPx: 0 }).target).toBe(105)
})
it('keeps a left stop under a breakable segment that overflows by more than a space', () => {
// Word wraps the segment at its spaces (probe 2026-09-17); pinning would
// pull the stop left and let text that Word wraps ride the line
const input = {
...base,
x: 22,
stops: [{ x: 65, val: 'left' as const }],
segWidth: 570,
restWidth: 570,
}
expect(resolveTabTarget({ ...input, segBreakable: true }).target).toBe(65)
// an unbreakable segment (single word) still pins: Chromium would
// otherwise drop the whole word to the next line
expect(resolveTabTarget({ ...input, segBreakable: false }).target).toBe(PARA_W - 1 - 570)
// a rounding-class overflow (under a space) pins either way
expect(
resolveTabTarget({ ...input, segWidth: 560, restWidth: 560, segBreakable: true }).target,
).toBe(PARA_W - 1 - 560)
})
it('pins a stop past the edge flush right, reserving the trailing segments', () => {
const r = resolveTabTarget({
...base,
@@ -0,0 +1,61 @@
/** A cell paints only what its table style hands to bare runs. Colour and bold
* aggregated from the runs stay on the runs, so clearing them really clears. */
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'
;(globalThis as { CSS?: unknown }).CSS ??= { escape: (s: string) => s }
const RED = (t: string) =>
`<w:r><w:rPr><w:b/><w:color w:val="FF0000"/></w:rPr><w:t>${t}</w:t></w:r>`
const TABLE = (tblPr: string) =>
`<w:tbl><w:tblPr>${tblPr}</w:tblPr><w:tblGrid><w:gridCol w:w="4000"/></w:tblGrid>` +
`<w:tr><w:tc><w:p>${RED('M/F')}${RED(' choose')}</w:p></w:tc></w:tr></w:tbl>`
const STYLE =
'<w:style w:type="table" w:styleId="Tinted"><w:name w:val="Tinted"/>' +
'<w:rPr><w:color w:val="365F91"/></w:rPr></w:style>'
async function open(bodyXml: string, extraStylesXml?: string) {
const parsed = await parseDocx(await buildDocx({ bodyXml, extraStylesXml }))
const editor = new Editor({
element: document.createElement('div'),
extensions: editorExtensions,
content: blocksToPmDoc(parsed.blocks) as never,
})
return { editor, td: editor.view.dom.querySelector('td') as HTMLElement }
}
function clearRuns(editor: Editor) {
editor.commands.selectAll()
editor.chain().setMark('docTextStyle', { color: null }).unsetMark('bold').run()
}
describe('uniformly formatted cell runs', () => {
it('leave nothing on the cell, so clearing the runs clears the paint', async () => {
const { editor, td } = await open(TABLE(''))
expect(td.style.color).toBe('')
expect(td.style.fontWeight).toBe('')
expect((td.querySelector('span[data-doc-style]') as HTMLElement).style.color).toBe(
'rgb(255, 0, 0)',
)
clearRuns(editor)
for (const span of td.querySelectorAll<HTMLElement>('span[data-doc-style]')) {
expect(span.style.color).toBe('')
}
expect(td.querySelector('strong')).toBeNull()
expect(td.style.color).toBe('')
editor.destroy()
})
it('still fall back to the table style colour once cleared', async () => {
const { editor, td } = await open(TABLE('<w:tblStyle w:val="Tinted"/>'), STYLE)
expect(td.style.color).toBe('rgb(54, 95, 145)')
clearRuns(editor)
expect(td.style.color).toBe('rgb(54, 95, 145)')
editor.destroy()
})
})
+156 -11
View File
@@ -196,39 +196,139 @@ describe('expandAutofitColWidths', () => {
it('compresses tblW-auto preferred widths past the text column back to it', () => {
// centered autofit table whose tcW sum (11338) runs ~24% past a 9122-twip
// text column: Word treats tcW as preferred and fits the table to the
// column plus its two 108-twip side cell margins (measured 623px at 96dpi)
// column; a compat < 15 document measures to the cell text, so the border
// box hangs by the two 108-twip side cell margins (measured 623px at 96dpi)
const model: TableModel = {
rows: [[cell('Marco'), cell('Autores'), cell('Autores'), cell('Aporte')]],
colWidthsTwips: [2551, 2948, 2721, 3118],
autoLayout: true,
align: 'center',
}
const fitted = expandAutofitColWidths(model, 12240, 9122)
const total = fitted.colWidthsTwips!.reduce((a, b) => a + b, 0)
expect(Math.abs(total - 9338)).toBeLessThanOrEqual(2)
const sum = (m: TableModel) => m.colWidthsTwips!.reduce((a, b) => a + b, 0)
const fitted = expandAutofitColWidths(model, 12240, 9122, undefined, false, true)
expect(Math.abs(sum(fitted) - 9338)).toBeLessThanOrEqual(2)
// proportions survive the cut
expect(fitted.colWidthsTwips![3]).toBeGreaterThan(fitted.colWidthsTwips![0])
expect(model.colWidthsTwips).toEqual([2551, 2948, 2721, 3118])
// compat 15: the column itself (Word probe: 10800 of tcW -> 9360 column)
expect(Math.abs(sum(expandAutofitColWidths(model, 12240, 9122)) - 9122)).toBeLessThanOrEqual(2)
})
it('compat 15 fits over-wide tblW-auto preferred widths to the column less the signed indent', () => {
// Word probe (Letter, 9360 column, tcW 3600 x 3): no indent -> 9352 (line
// centres), tblInd -108 -> 9456 (left edge moves out, right edge stays on
// the margin), tblInd +558 -> 8794; an audit table (grid 9016 = column,
// tcW 9740) draws at exactly the column, not column + cell margins
const model: TableModel = {
rows: [[cell('Annual Objective'), cell('RAG'), cell('Achievement')]],
colWidthsTwips: [3840, 1520, 4380],
autoLayout: true,
}
const sum = (m: TableModel) => m.colWidthsTwips!.reduce((a, b) => a + b, 0)
expect(Math.abs(sum(expandAutofitColWidths(model, 10466, 9026)) - 9026)).toBeLessThanOrEqual(2)
const hanging = { ...model, indentTwips: -108 }
expect(Math.abs(sum(expandAutofitColWidths(hanging, 10466, 9026)) - 9134)).toBeLessThanOrEqual(
2,
)
const indented = { ...model, indentTwips: 558 }
expect(Math.abs(sum(expandAutofitColWidths(indented, 10466, 9026)) - 8468)).toBeLessThanOrEqual(
2,
)
})
it('legacy compat hangs the fitted box by the cell margins around the text-measured indent', () => {
// letterhead schedule (compat 14, A4 with a 1916 right margin: 8550 column,
// tblInd 558, tcW 8568): Word draws 8208 = 8550 - 558 + 2 x 108, the left
// border at indent - 108 and the right border 108 past the margin
const model: TableModel = {
rows: [[cell('Item No.'), cell('Milestone'), cell('Date'), cell('Authority')]],
colWidthsTwips: [1170, 3420, 1656, 2322],
autoLayout: true,
indentTwips: 558,
}
const shifted = legacyIndentTable(model)
expect(shifted.indentTwips).toBe(450)
const fitted = expandAutofitColWidths(shifted, 10466, 8550, undefined, false, true)
expect(Math.abs(fitted.colWidthsTwips!.reduce((a, b) => a + b, 0) - 8208)).toBeLessThanOrEqual(
2,
)
})
it('a grid Word laid out grows a column only past a bare word overflow', () => {
// Word saved 1132 twips for a column whose widest word it measured at 60px:
// 60 x 15 + 216 margins = 1116 fits; the 2px edge + 2% slack that guards
// generator grids would push it to 1165 and wrap the header one line more
const model: TableModel = {
rows: [[cell('MLA-01'), cell('Issuance of Official Conclave Notification')]],
colWidthsTwips: [1132, 3223],
autoLayout: true,
}
const metrics = { measure: () => 60, metrics: () => ({ ascent: 0, descent: 0, lineHeight: 0 }) }
expect(expandAutofitColWidths(model, 10466, 8550, metrics).colWidthsTwips![0]).toBe(1165)
const laidOut = { ...model, layoutGrid: true }
expect(expandAutofitColWidths(laidOut, 10466, 8550, metrics)).toBe(laidOut)
// a word that really overflows still widens the column (fallback font much wider)
const wide = { ...metrics, measure: () => 70 }
expect(expandAutofitColWidths(laidOut, 10466, 8550, wide).colWidthsTwips![0]).toBe(1266)
})
it('keeps a tblW-auto grid that hangs into the margins by no more than its cell margins', () => {
// six-column timesheet grid of 9824 twips in a 9749-twip text column: Word
// draws it at full width, the border 108 twips outside each margin edge
// (legacy compat: the indent measures to the cell text, so the display
// pipeline shifts the border out by the left margin first)
const model: TableModel = {
rows: [[cell('Date'), cell('Org'), cell('Code'), cell('Work'), cell('Time'), cell('Level')]],
colWidthsTwips: [1296, 1008, 1296, 4032, 1008, 1184],
autoLayout: true,
}
expect(expandAutofitColWidths(model, 10829, 9749)).toBe(model)
const legacy = (m: TableModel) =>
expandAutofitColWidths(legacyIndentTable(m), 10829, 9749, undefined, false, true)
expect(legacy(model).colWidthsTwips).toEqual(model.colWidthsTwips)
// the hang follows the table's own cell margins
const narrowMar = { ...model, cellMarTwips: { left: 28, right: 28 } }
const fitted = expandAutofitColWidths(narrowMar, 10829, 9749)
expect(fitted.colWidthsTwips!.reduce((a, b) => a + b, 0)).toBe(9749 + 56)
expect(legacy(narrowMar).colWidthsTwips!.reduce((a, b) => a + b, 0)).toBe(9749 + 56)
// past the hang the grid compresses to column + margins, wide column first
const wide = { ...model, colWidthsTwips: [1296, 1008, 1296, 4332, 1008, 1184] }
const fittedWide = expandAutofitColWidths(wide, 10829, 9749).colWidthsTwips!
const fittedWide = legacy(wide).colWidthsTwips!
expect(Math.abs(fittedWide.reduce((a, b) => a + b, 0) - 9965)).toBeLessThanOrEqual(2)
expect(fittedWide[3]).toBeLessThan(4332)
// compat 15 has no hang: the same grid compresses to the column
const modern = expandAutofitColWidths(model, 10829, 9749).colWidthsTwips!
expect(Math.abs(modern.reduce((a, b) => a + b, 0) - 9749)).toBeLessThanOrEqual(2)
})
it('keeps an explicit dxa tblW wider than the column while the table stays on the paper', () => {
// a permit form: tblW 10632 dxa (= grid = tcW) with tblInd -714 in a
// 9026-twip column; Word draws the full width, hanging 714 twips into the
// left margin and 892 into the right one (measured 709px at 96dpi)
const model: TableModel = {
rows: [[cell('No.'), cell('Type'), cell('Count'), cell('Area'), cell('Point'), cell('')]],
colWidthsTwips: [603, 1807, 1276, 1418, 1842, 3686],
indentTwips: -714,
}
expect(expandAutofitColWidths(model, 10466, 9026)).toBe(model)
// the same grid under tblW auto compresses to the column plus the
// negative indent (the right edge stays on the margin) ...
const sum = (widths: number[]) => widths.reduce((a, b) => a + b, 0)
const auto: TableModel = { ...model, autoLayout: true }
expect(
Math.abs(sum(expandAutofitColWidths(auto, 10466, 9026).colWidthsTwips!) - 9740),
).toBeLessThanOrEqual(2)
// ... hanging by the cell margins on both sides under legacy compat
const legacyAuto = expandAutofitColWidths(
legacyIndentTable(auto),
10466,
9026,
undefined,
false,
true,
)
expect(Math.abs(sum(legacyAuto.colWidthsTwips!) - 9956)).toBeLessThanOrEqual(2)
// past the paper edge the dxa width is only a preference again
const wide: TableModel = { ...model, colWidthsTwips: [603, 1807, 1276, 1418, 1842, 4600] }
const wideTotal = expandAutofitColWidths(wide, 10466, 9026).colWidthsTwips!
expect(Math.abs(sum(wideTotal) - 9740)).toBeLessThanOrEqual(2)
})
it('leaves a full-width pct table alone even when its indent pushes it past the column', () => {
@@ -421,9 +521,46 @@ describe('autofit expansion wiring', () => {
expect(parsed.blocks[0].table!.colWidthsTwips).toEqual([2551, 2948, 2721, 3118])
const sections = readSections(parsed)
const pm = blocksToPmDoc(parsed.blocks, sections).content![0]
// ... but the display width is the text column plus the side cell margins, not the 11338-twip tcW sum
const fitPx = (sections[0].settings.pageWidth - 2 * 1440 + 216) / 15
expect(Math.abs((pm.attrs!.widthPx as number) - fitPx)).toBeLessThanOrEqual(2)
// ... but the display width is the text column, not the 11338-twip tcW sum
const columnPx = (sections[0].settings.pageWidth - 2 * 1440) / 15
expect(Math.abs((pm.attrs!.widthPx as number) - columnPx)).toBeLessThanOrEqual(2)
// legacy compat hangs the box by the side cell margins
const legacy = blocksToPmDoc(parsed.blocks, sections, { legacyTableIndent: true }).content![0]
expect(Math.abs((legacy.attrs!.widthPx as number) - columnPx - 216 / 15)).toBeLessThanOrEqual(2)
})
const dxaTable = (tblW: number, tblInd: number, grid: number[], tcw: number[]) =>
`<w:tbl><w:tblPr><w:tblW w:w="${tblW}" w:type="dxa"/><w:tblInd w:w="${tblInd}" w:type="dxa"/></w:tblPr>` +
`<w:tblGrid>${grid.map((w) => `<w:gridCol w:w="${w}"/>`).join('')}</w:tblGrid>` +
'<w:tr>' +
tcw
.map(
(w) =>
`<w:tc><w:tcPr><w:tcW w:w="${w}" w:type="dxa"/></w:tcPr><w:p><w:r><w:t>a</w:t></w:r></w:p></w:tc>`,
)
.join('') +
'</w:tr></w:tbl>'
it('draws dxa tables wider than the column at their grid width when they fit on the paper', async () => {
const hanging = [603, 1807, 1276, 1418, 1842, 3686]
// Word lays an autofit table out from its tblGrid: unequal grid columns
// beat disagreeing tcW (the header cells of this construct broke letter
// by letter at the tcW widths)
const grid = [571, 999, 766, 1036, 1549, 999, 1574, 1011]
const tcw = [542, 1038, 719, 966, 1435, 1167, 1458, 943]
const parsed = await parseDocx(
await buildDocx({
bodyXml:
dxaTable(10632, -714, hanging, hanging) + '<w:p/>' + dxaTable(8268, 1080, grid, tcw),
}),
)
const [first, second] = parsed.blocks.filter((b) => b.table)
expect(first.table!.autoLayout).toBeUndefined()
expect(second.table!.colWidthsTwips).toEqual(grid)
const pm = blocksToPmDoc(parsed.blocks, readSections(parsed))
const tables = pm.content!.filter((n) => n.type === 'docTable')
expect(tables[0].attrs!.widthPx).toBe(Math.round(10632 / 15))
expect(tables[1].attrs!.widthPx).toBe(Math.round(8505 / 15))
})
it('parse does not flag fixed-layout tables but keeps pct tables autofit', async () => {
@@ -458,6 +595,14 @@ describe('renderTableSpec width budget', () => {
expect(spec[1].style).toContain('margin-left:96.7px')
const nestedSpec = renderTableSpec(model, true) as Spec
expect(nestedSpec[1].style).toContain('width:min(624px,calc(100% - 96.7px))')
// a negative indent hangs into the left margin and widens the spill by as much
const hanging = renderTableSpec({ ...model, indentTwips: -714 }) as Spec
expect(hanging[1].style).toContain(
'width:min(624px,calc(var(--doc-content-w,100%) + var(--doc-margin-right,0px) + 47.6px))',
)
expect((renderTableSpec({ ...model, indentTwips: -714 }, true) as Spec)[1].style).toContain(
'width:min(624px,100%)',
)
})
it('fixed-layout tables hold the declared width past the paper edge (Word clips there)', () => {
+13 -4
View File
@@ -101,7 +101,7 @@ describe('renderTableSpec rich cell content', () => {
],
],
}
const spans = renderTable(model).querySelectorAll('td span')
const spans = renderTable(model).querySelectorAll('td span:not(.doc-ltr-runs)')
const arabic = spans[0].getAttribute('style')!
expect(arabic).toMatch(/font-family:\s*['"]Traditional Arabic['"]/)
expect(arabic).toContain('Calibri')
@@ -181,19 +181,28 @@ describe('renderTableSpec rich cell content', () => {
expect(para.querySelector('img.doc-inline-img')).not.toBeNull()
})
it('cell-level color/bold stay as td-level fallback', () => {
const model: TableModel = {
it('paints table-style color/bold on the td, never the run aggregates', () => {
const aggregated: TableModel = {
rows: [[{ ...cell(['t'], [{ runs: [{ text: 't' }] }]), color: '112233', bold: true }]],
}
const plain = renderTable(aggregated).querySelector('td')!.getAttribute('style') ?? ''
expect(plain).not.toMatch(/color:/)
expect(plain).not.toMatch(/font-weight/)
const styled: TableModel = {
rows: [
[
{
...cell(['t'], [{ runs: [{ text: 't' }] }]),
color: '112233',
bold: true,
styleColor: '112233',
styleBold: true,
},
],
],
}
const td = renderTable(model).querySelector('td')!
const td = renderTable(styled).querySelector('td')!
const tdStyle = td.getAttribute('style')!
expect(tdStyle).toMatch(/color:\s*(#112233|rgb\(17,\s*34,\s*51\))/i)
expect(tdStyle).toMatch(/font-weight:\s*600/)
+62 -1
View File
@@ -1,6 +1,6 @@
// @vitest-environment jsdom
import { describe, expect, it } from 'vitest'
import { markTableSeamSlices, TABLE_SEAM_PX } from '../src/renderer/pagination-slices'
import { markTableSeamSlices, seamWindow, TABLE_SEAM_PX } from '../src/renderer/pagination-slices'
import type { BlockBox, PageSlice } from '../src/renderer/pagination-types'
const block = (tag: string, top: number, height: number): BlockBox => ({
@@ -66,7 +66,68 @@ describe('markTableSeamSlices', () => {
expect(slices.some((s) => s.cutTable)).toBe(false)
})
it('flags a page opening on the bottom edge of the previous table', () => {
const blocks = [block('p', 0, 100), block('table', 100, 500), block('p', 600, 100)]
const slices: PageSlice[] = [
{ start: 0, end: 600, section: 0 },
{ start: 600, end: 700, section: 0 },
]
markTableSeamSlices(slices, blocks)
expect(slices.map((s) => s.tailTable ?? false)).toEqual([false, true])
expect(slices.some((s) => s.cutTable || s.leadTable)).toBe(false)
})
it('reads the table box bottom under a folded inter-block gap', () => {
const gapped = { ...block('table', 100, 508), spaceAfterPx: 8 }
const blocks = [block('p', 0, 100), gapped, block('p', 608, 100)]
const slices: PageSlice[] = [
{ start: 0, end: 608, section: 0 },
{ start: 608, end: 708, section: 0 },
]
markTableSeamSlices(slices, blocks)
expect(slices[1].tailTable).toBeUndefined()
expect(slices[1].cutTable).toBeUndefined()
})
it('prefers the lead flag when a table opens right under the previous one', () => {
const blocks = [block('table', 0, 300), block('table', 300, 300)]
const slices: PageSlice[] = [
{ start: 0, end: 300, section: 0 },
{ start: 300, end: 600, section: 0 },
]
markTableSeamSlices(slices, blocks)
expect(slices[1].leadTable).toBe(true)
expect(slices[1].tailTable).toBeUndefined()
})
it('shaves a whole CSS pixel, inside the table margin', () => {
expect(TABLE_SEAM_PX).toBe(1)
})
})
describe('seamWindow', () => {
const s = (extra: Partial<PageSlice> = {}): PageSlice => ({
start: 0,
end: 100,
section: 0,
...extra,
})
it('opens a cut page up and grows the page before it', () => {
expect(seamWindow(s({ cutTable: true }), undefined)).toEqual({ lift: 1, extend: 0 })
expect(seamWindow(s(), s({ cutTable: true }))).toEqual({ lift: 0, extend: 1 })
})
it('moves the pixel from a tail page to the page before it', () => {
expect(seamWindow(s({ tailTable: true }), undefined)).toEqual({ lift: -1, extend: 0 })
expect(seamWindow(s(), s({ tailTable: true }))).toEqual({ lift: 0, extend: 1 })
})
it('shaves the page before a lead table and leaves lifted tail pages alone', () => {
expect(seamWindow(s(), s({ leadTable: true }))).toEqual({ lift: 0, extend: -1 })
expect(seamWindow(s({ tailTable: true, liftTop: 4 }), undefined)).toEqual({
lift: 0,
extend: 0,
})
})
})
@@ -0,0 +1,102 @@
import { afterEach, describe, expect, it } from 'vitest'
import { Editor } from '@tiptap/core'
import type { DecorationSet } from '@tiptap/pm/view'
import { editorExtensions } from '../src/renderer/editor/extensions'
const editors: Editor[] = []
afterEach(() => {
for (const e of editors.splice(0)) e.destroy()
})
const EA_HINT_RPR = '<w:rPr><w:rFonts w:hint="eastAsia"/></w:rPr>'
const styledSpace = {
type: 'text',
text: ' ',
marks: [{ type: 'docTextStyle', attrs: { sizeHalfPoints: 72 } }],
}
const hintedQuote = (text: string) => ({
type: 'text',
text,
marks: [{ type: 'docTextStyle', attrs: { rawRPr: EA_HINT_RPR } }],
})
const para = (...content: unknown[]) => ({ type: 'docParagraph', content })
function decosOf(editor: Editor, pluginName: string): string[] {
const plugin = editor.state.plugins.find((p) =>
String((p as unknown as { key: string }).key).startsWith(pluginName),
)!
const set = (plugin.props.decorations as (s: unknown) => DecorationSet | null).call(
plugin,
editor.state,
)
return (set?.find() ?? [])
.map(
(d) =>
`${d.from}-${d.to}:${(d.spec as { class?: string }).class ?? ''}${JSON.stringify((d as unknown as { type: { attrs: unknown } }).type.attrs)}`,
)
.sort()
}
/** the same decorations a plugin computes from scratch for the current document */
function rebuilt(editor: Editor, pluginName: string): string[] {
const probe = new Editor({
element: document.createElement('div'),
extensions: editorExtensions,
content: editor.state.doc.toJSON(),
})
editors.push(probe)
return decosOf(probe, pluginName)
}
describe('incremental text decorations', () => {
it('whitespace-run and hinted-quote decorations follow edits exactly like a rebuild', () => {
const editor = new Editor({
element: document.createElement('div'),
extensions: editorExtensions,
content: {
type: 'doc',
content: [
para({ type: 'text', text: 'lead ' }, styledSpace, { type: 'text', text: 'tail' }),
para(hintedQuote('“quoted” plain'), { type: 'text', text: ' after' }),
para({ type: 'text', text: 'plain paragraph' }),
],
} as never,
})
editors.push(editor)
for (const name of ['wsRunLineHeight', 'eaHintQuotes']) {
expect(decosOf(editor, name).length).toBeGreaterThan(0)
expect(decosOf(editor, name)).toEqual(rebuilt(editor, name))
}
const check = () => {
for (const name of ['wsRunLineHeight', 'eaHintQuotes'])
expect(decosOf(editor, name)).toEqual(rebuilt(editor, name))
}
// typing before the decorated runs shifts them
editor.view.dispatch(editor.state.tr.insertText('xx', 2))
check()
// typing into the whitespace run retires it
const wsPos = editor.state.doc.child(0).firstChild!.nodeSize + 2
editor.view.dispatch(editor.state.tr.insertText('a', wsPos))
check()
// streamed-style append at the end brings new decorated runs
const tail = [para(hintedQuote('‘more’'), { type: 'text', text: ' x' }), para(styledSpace)].map(
(n) => editor.schema.nodeFromJSON(n),
)
editor.view.dispatch(editor.state.tr.insert(editor.state.doc.content.size, tail))
check()
// delete a whole block ahead of the decorated ones
editor.view.dispatch(editor.state.tr.delete(0, editor.state.doc.child(0).nodeSize))
check()
// mark change without position moves
editor.commands.setTextSelection({ from: 1, to: 6 })
editor.commands.setMark('docTextStyle', { sizeHalfPoints: 28 })
check()
// full replacement
editor.commands.setContent({
type: 'doc',
content: [para(styledSpace), para(hintedQuote('“q”'))],
} as never)
check()
})
})
+56
View File
@@ -0,0 +1,56 @@
import { describe, expect, it } from 'vitest'
import { Schema } from '@tiptap/pm/model'
import { EditorState } from '@tiptap/pm/state'
import { Decoration, DecorationSet, EditorView } from '@tiptap/pm/view'
import { TopLevelPositions } from '../src/renderer/editor/top-level-pos'
const schema = new Schema({
nodes: {
doc: { content: 'block+' },
paragraph: { content: 'text*', group: 'block', toDOM: () => ['p', 0] },
quote: { content: 'paragraph+', group: 'block', toDOM: () => ['blockquote', 0] },
text: {},
},
})
describe('TopLevelPositions', () => {
it('matches posAtDOM for every top-level block, with widgets between them', () => {
const blocks = []
for (let i = 0; i < 40; i++) {
const p = schema.node('paragraph', null, schema.text(`para ${i} ${'x'.repeat(i % 7)}`))
blocks.push(
i % 5 === 0
? schema.node('quote', null, [p, schema.node('paragraph', null, schema.text('q'))])
: p,
)
}
const doc = schema.node('doc', null, blocks)
const widgets: Decoration[] = []
doc.forEach((_, offset, i) => {
if (i % 3 === 0)
widgets.push(Decoration.widget(offset, () => document.createElement('hr'), { side: -1 }))
})
const set = DecorationSet.create(doc, widgets)
const view = new EditorView(document.body.appendChild(document.createElement('div')), {
state: EditorState.create({ doc }),
decorations: () => set,
})
const positions = new TopLevelPositions(view)
let checked = 0
for (const el of Array.from(view.dom.children)) {
if (el.tagName === 'HR') {
expect(positions.of(el)).toBeNull()
continue
}
const $pos = view.state.doc.resolve(view.posAtDOM(el, 0))
expect(positions.of(el)).toEqual({ from: $pos.before(1), to: $pos.after(1) })
// nested elements resolve to their top-level block
const inner = el.querySelector('p') ?? el
expect(positions.of(inner)).toEqual({ from: $pos.before(1), to: $pos.after(1) })
checked++
}
expect(checked).toBe(40)
expect(positions.of(document.createElement('p'))).toBeNull()
view.destroy()
})
})
+24 -1
View File
@@ -24,13 +24,18 @@ function createEditor(text: string): Editor {
})
}
function render(element: React.ReactElement): { container: HTMLElement; unmount: () => void } {
function render(element: React.ReactElement): {
container: HTMLElement
rerender: (next: React.ReactElement) => void
unmount: () => void
} {
const container = document.createElement('div')
document.body.appendChild(container)
const root = createRoot(container)
act(() => root.render(element))
return {
container,
rerender: (next) => act(() => root.render(next)),
unmount: () => {
act(() => root.unmount())
container.remove()
@@ -120,4 +125,22 @@ describe('FindPanel', () => {
unmount()
editor.destroy()
})
it('focuses the find input on mount and again when focusFindNonce bumps', () => {
const editor = createEditor('hello world')
const { container, rerender, unmount } = render(
createElement(FindPanel, { editor, onClose: () => {}, focusFindNonce: 0 }),
)
const input = container.querySelector<HTMLInputElement>('.find-input')!
expect(document.activeElement).toBe(input)
// user clicks back into the document, then hits Ctrl+F with the panel open
act(() => {
input.blur()
})
expect(document.activeElement).not.toBe(input)
rerender(createElement(FindPanel, { editor, onClose: () => {}, focusFindNonce: 1 }))
expect(document.activeElement).toBe(input)
unmount()
editor.destroy()
})
})
+2 -1
View File
@@ -1,4 +1,4 @@
import { RENDERER_SCHEME_PRIVILEGE } from '@genoffice/electron-utils'
import { DOCX_MEDIA_SCHEME_PRIVILEGE, RENDERER_SCHEME_PRIVILEGE } from '@genoffice/electron-utils'
import { protocol } from 'electron'
import { ASSET_SCHEME, PREVIEW_SCHEME, buildPreviewDocument } from './preview-document'
@@ -10,6 +10,7 @@ export { assetBaseHref, previewUrlFor } from './preview-document'
export function registerPrivilegedSchemes(): void {
protocol.registerSchemesAsPrivileged([
RENDERER_SCHEME_PRIVILEGE,
DOCX_MEDIA_SCHEME_PRIVILEGE,
{
scheme: PREVIEW_SCHEME,
privileges: { standard: true, secure: true, supportFetchAPI: true, corsEnabled: true },
-3
View File
@@ -4,7 +4,6 @@ import type { Lang } from '@genoffice/i18n'
import type { AiStreamChunk } from '@genoffice/ai-provider'
import type { ProjectApi } from '@genoffice/project-store'
import { installDropOpenBridge } from '@genoffice/electron-utils/drop-open'
import { installFilesPaneBridge } from '@genoffice/electron-utils/files-pane-bridge'
import { AI_CHANNELS, HTML_CHANNELS } from '../shared/ipc'
import type { AutoSaveDefault, ExportFormat, HtmlApi, SaveMode, UiTheme } from '../shared/ipc'
@@ -126,5 +125,3 @@ contextBridge.exposeInMainWorld('projectApi', projectApi)
// open documents dragged from the OS onto this tab as a new shell tab
installDropOpenBridge()
// folder tree over the default save folder (Files pane)
installFilesPaneBridge()
+2 -28
View File
@@ -36,13 +36,7 @@ import {
type CanvasMode,
type ViewMode,
} from './components/Ribbon'
import {
CropDialog,
CutoutDialog,
FilesEdgeTab,
FilesPane,
type ImageDialogLabels,
} from '@genoffice/ui'
import { CropDialog, CutoutDialog, type ImageDialogLabels } from '@genoffice/ui'
import { FloatToolbar } from './components/FloatToolbar'
import {
insertOp,
@@ -119,7 +113,7 @@ async function loadImageDataUrl(src: string): Promise<string | null> {
}
export default function App() {
const { t, lang } = useI18n()
const { t } = useI18n()
const [status, setStatus] = useState<LoadStatus>('loading')
const [path, setPath] = useState<string | null>(null)
const [text, setText] = useState('')
@@ -139,9 +133,6 @@ export default function App() {
const [draftHtml, setDraftHtml] = useState<string | null>(null)
const [historyState, setHistoryState] = useState({ undo: false, redo: false })
const [aiOpen, setAiOpen] = useState(() => localStorage.getItem('htmlapp.showAi') !== '0')
const [filesOpen, setFilesOpen] = useState(
() => localStorage.getItem('htmlapp.showFiles') === '1',
)
const [aiPreset, setAiPreset] = useState<AiPreset | null>(null)
const [editQueue, setEditQueue] = useState<EditQueueItem[]>([])
const [askMode, setAskMode] = useState<AskMode | null>(null)
@@ -339,10 +330,6 @@ export default function App() {
localStorage.setItem('htmlapp.showAi', aiOpen ? '1' : '0')
}, [aiOpen])
useEffect(() => {
localStorage.setItem('htmlapp.showFiles', filesOpen ? '1' : '0')
}, [filesOpen])
useEffect(() => {
localStorage.setItem('htmlapp.device', device)
}, [device])
@@ -1441,8 +1428,6 @@ export default function App() {
onView={setView}
aiOpen={aiOpen}
onToggleAi={() => setAiOpen((v) => !v)}
filesOpen={filesOpen}
onToggleFiles={() => setFilesOpen((v) => !v)}
canInsert={canvasMode === 'edit'}
onInsert={(kind, opts) => void insertElement(kind, opts)}
onAiPreset={(text) => {
@@ -1480,18 +1465,7 @@ export default function App() {
onCollapse={() => setAiOpen(false)}
/>
</div>
{filesOpen && canvasMode !== 'present' && (
<FilesPane
api={window.filesPaneApi}
lang={lang}
currentPath={path}
onClose={() => setFilesOpen(false)}
/>
)}
<div className="app-content">
{!filesOpen && canvasMode !== 'present' && (
<FilesEdgeTab lang={lang} onOpen={() => setFilesOpen(true)} />
)}
{findTarget && (
<FindPanel
target={findTarget}
+1 -16
View File
@@ -4,7 +4,6 @@ import {
RibbonExpandButton,
useDismissablePopover,
useRibbonCollapse,
filesPaneTitle,
} from '@genoffice/ui'
import { useI18n } from '../i18n/locale'
import type { StringKey } from '../i18n/locale'
@@ -14,7 +13,6 @@ import {
IconBullets,
IconButton,
IconChevronDown,
IconFolderTree,
IconCode,
IconDivider,
IconExpand,
@@ -77,8 +75,6 @@ interface Props {
onView: (view: ViewMode) => void
aiOpen: boolean
onToggleAi: () => void
filesOpen: boolean
onToggleFiles: () => void
canInsert: boolean
/** images come from a picked file by default; `url` places a remote image instead; tables take the picker's rows × cols */
onInsert: (kind: InsertKind, opts?: InsertOptions) => void
@@ -132,7 +128,7 @@ const TABLE_PICKER_COLS = 10
const ICON = 20
export function Ribbon(p: Props) {
const { t, lang } = useI18n()
const { t } = useI18n()
const collapse = useRibbonCollapse('htmlapp.ribbonCollapsed')
const [themeOpen, setThemeOpen] = useState(false)
const themeRef = useRef<HTMLDivElement>(null)
@@ -535,17 +531,6 @@ export function Ribbon(p: Props) {
</button>
)
})}
<button
type="button"
className={`rb-btn rb-view${p.filesOpen ? ' active' : ''}`}
aria-pressed={p.filesOpen}
data-tip={filesPaneTitle(lang)}
onMouseDown={(e) => e.preventDefault()}
onClick={p.onToggleFiles}
>
<IconFolderTree size={ICON} />
<span>{filesPaneTitle(lang)}</span>
</button>
</div>
</div>
@@ -215,17 +215,3 @@ export function IconSummarize({ size = 24 }: IconProps) {
</svg>
)
}
export function IconFolderTree({ size = 18 }: { size?: number }) {
return (
<svg width={size} height={size} viewBox="0 0 20 20" fill="none" aria-hidden="true">
<path
d="M2.5 5.5A1.5 1.5 0 0 1 4 4h3.6c.4 0 .8.16 1.07.45L10 5.8h6A1.5 1.5 0 0 1 17.5 7.3v7.2A1.5 1.5 0 0 1 16 16H4a1.5 1.5 0 0 1-1.5-1.5v-9z"
stroke="currentColor"
strokeWidth="1.4"
strokeLinejoin="round"
/>
<path d="M2.5 8.5h15" stroke="currentColor" strokeWidth="1.4" />
</svg>
)
}
-3
View File
@@ -3,12 +3,9 @@
import type { ProjectApi } from '@genoffice/project-store'
import type { HtmlApi } from '../shared/ipc'
import type { FilesPaneApi } from '@genoffice/ui'
declare global {
interface Window {
htmlApi: HtmlApi
filesPaneApi: FilesPaneApi
projectApi?: Pick<ProjectApi, 'resolveChat' | 'appendChat' | 'loadChat' | 'rebindChat'>
}
}
-1
View File
@@ -9,7 +9,6 @@ import '@genoffice/ui/tokens.css'
import '@genoffice/ui/screentip.css'
import '@genoffice/ui/dropdown.css'
import '@genoffice/ui/find-panel.css'
import '@genoffice/ui/files-pane.css'
import '@genoffice/ui/color-picker.css'
import '@genoffice/ui/ribbon-collapse.css'
import '@genoffice/ui/ai-panel-prefs.css'
+2 -2
View File
@@ -51,7 +51,7 @@ function renderRibbon(disabled = false) {
function saveAsButton(container: HTMLElement): HTMLButtonElement {
const button = container.querySelector<HTMLButtonElement>(
'.ribbon-tabs button[aria-label="另存为…"]',
'.ribbon-tabs button[aria-label="\u53e6\u5b58\u4e3a\u2026"]',
)
expect(button, 'Save As must be available in the top-left quick-access row').not.toBeNull()
return button!
@@ -61,7 +61,7 @@ describe('Save As quick-access button', () => {
it('can save a copy of an unchanged document without triggering normal save', () => {
const { container, onSave, onSaveAs } = renderRibbon()
const button = saveAsButton(container)
expect(button.textContent).toBe('另存为…')
expect(button.textContent).toBe('\u53e6\u5b58\u4e3a\u2026')
expect(button.disabled).toBe(false)
act(() => button.click())
expect(onSaveAs).toHaveBeenCalledOnce()
+8 -1
View File
@@ -23,8 +23,13 @@
"@genoffice/project-store": "*",
"@genoffice/ui": "*",
"@tiptap/core": "3.31.0",
"@tiptap/extension-bold": "3.31.0",
"@tiptap/extension-code-block": "3.31.0",
"@tiptap/extension-hard-break": "3.31.0",
"@tiptap/extension-heading": "3.31.0",
"@tiptap/extension-horizontal-rule": "3.31.0",
"@tiptap/extension-image": "3.31.0",
"@tiptap/extension-italic": "3.31.0",
"@tiptap/extension-list": "3.31.0",
"@tiptap/extension-table": "3.31.0",
"@tiptap/extensions": "3.31.0",
@@ -49,6 +54,8 @@
"dependencies": {
"@tiptap/extension-mathematics": "3.31.0",
"katex": "^0.16.47",
"mermaid": "^11.17.2"
"json5": "^2.2.3",
"mermaid": "^11.17.2",
"wavedrom": "^3.7.0"
}
}
+3 -1
View File
@@ -1,5 +1,7 @@
import { defineConfig } from '@playwright/test'
const port = Number(process.env.MARKDOWN_DEV_PORT) || 5177
/** Browser-only renderer coverage: it must not boot the Electron shell. */
export default defineConfig({
testDir: './tests/browser',
@@ -9,7 +11,7 @@ export default defineConfig({
workers: 1,
webServer: {
command: 'npm run dev:renderer -w @genoffice/markdown',
url: 'http://localhost:5177',
url: `http://localhost:${port}`,
reuseExistingServer: true,
timeout: 60_000,
},
-3
View File
@@ -4,7 +4,6 @@ import type { Lang } from '@genoffice/i18n'
import type { AiStreamChunk } from '@genoffice/ai-provider'
import type { ProjectApi } from '@genoffice/project-store'
import { installDropOpenBridge } from '@genoffice/electron-utils/drop-open'
import { installFilesPaneBridge } from '@genoffice/electron-utils/files-pane-bridge'
import { AI_CHANNELS, MARKDOWN_CHANNELS } from '../shared/ipc'
import type { AutoSaveDefault, ExportFormat, MarkdownApi, SaveMode, UiTheme } from '../shared/ipc'
@@ -119,5 +118,3 @@ contextBridge.exposeInMainWorld('projectApi', projectApi)
// open documents dragged from the OS onto this tab as a new shell tab
installDropOpenBridge()
// folder tree over the default save folder (Files pane)
installFilesPaneBridge()
+53 -30
View File
@@ -5,7 +5,7 @@ import {
type MarkdownSourceSnapshot,
} from './markdown/roundtripSerializer'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { ImageViewer, useAutoSavePref, FilesPane, FilesEdgeTab } from '@genoffice/ui'
import { ImageViewer, useAutoSavePref } from '@genoffice/ui'
import {
pollUntilReady,
runHeadlessRendererExport,
@@ -22,6 +22,7 @@ import {
stripLegacyFencedDivs,
type DocEnvelope,
} from './markdown/docText'
import { buildSourceMap, spliceMarkdown, type SourceMap } from './markdown/sourceSplice'
import { buildExtensions } from './editor/extensions'
import { tiptapFindTarget } from './editor/findTarget'
import { collectOutline, type OutlineItem } from './editor/outline'
@@ -40,7 +41,8 @@ import { EDIT_QUEUE_MAX, selectionForAnchor, type EditQueueItem } from './ai/edi
import { addQueueAnchor, clearQueueAnchors, removeQueueAnchors } from './editor/aiQueueAnchors'
import { DOCX_MAX_IMAGE_PX, exportDocxBytes } from './export/docxExport'
import { buildPrintHtml } from './export/printHtml'
import { mermaidSvgToPng, renderMermaid } from './editor/mermaid'
import { diagramSvgToPng, renderDiagram } from './editor/diagrams'
import type { DiagramLanguage } from './editor/diagrams'
import { resolveImageSrc } from './editor/localImage'
import type { ExportFormat, SaveMode } from '../shared/ipc'
import { uiOp } from './editor/ops'
@@ -123,7 +125,7 @@ export function deriveAutoFileName(editor: Editor): string {
}
export default function App() {
const { t, lang } = useI18n()
const { t } = useI18n()
const [status, setStatus] = useState<LoadStatus>('loading')
const [filePath, setFilePath] = useState<string | null>(null)
const [dirty, setDirty] = useState(false)
@@ -142,7 +144,6 @@ export default function App() {
const [showFind, setShowFind] = useState(false)
const [findFocus, setFindFocus] = useState<FindFocusRequest>({ field: 'find', nonce: 0 })
const [outlineOpen, setOutlineOpen] = useState(false)
const [filesOpen, setFilesOpen] = useState(() => localStorage.getItem('mdapp.showFiles') === '1')
const [outlineWidth, setOutlineWidth] = useState(
() => Number(localStorage.getItem('mdapp.outlineWidth')) || undefined,
)
@@ -169,6 +170,14 @@ export default function App() {
const originalSourceRef = useRef<MarkdownSourceSnapshot | undefined>(undefined)
const envelopeRef = useRef<DocEnvelope>(EMPTY_ENVELOPE)
const editorRef = useRef<Editor | null>(null)
// blocks of the text on disk paired with the editor's nodes; null until a
// file is loaded or saved, and whenever the pairing could not be established
const sourceMapRef = useRef<SourceMap | null>(null)
/** the body a save writes: unchanged blocks verbatim from disk, edited runs re-serialized */
const bodyMarkdown = (current: Editor): string => {
const map = sourceMapRef.current
return map ? spliceMarkdown(current, current.state.doc, map) : current.getMarkdown()
}
const filePathRef = useRef<string | null>(null)
const slashMenuRef = useRef<SlashMenuHandle>(null)
const scrollRef = useRef<HTMLDivElement>(null)
@@ -257,11 +266,13 @@ export default function App() {
setImageBaseDir(dirOf(path))
// the initial load must not be undoable — Cmd+Z right after opening
// would otherwise blank the document (and Cmd+S overwrite the file)
const body = stripLegacyFencedDivs(envelope.body)
editor
.chain()
.setMeta('addToHistory', false)
.setContent(stripLegacyFencedDivs(envelope.body), { contentType: 'markdown' })
.setContent(body, { contentType: 'markdown' })
.run()
sourceMapRef.current = buildSourceMap(editor, editor.state.doc, body)
originalSourceRef.current = roundTripEnabled
? captureMarkdownSource(raw, envelope, editor.state.doc)
: undefined
@@ -308,10 +319,11 @@ export default function App() {
const docAtSave = current.state.doc
const fmAtSave = envelopeRef.current.frontmatter
const sourceAtSave = originalSourceRef.current
let body: string | undefined
const text = serializeMarkdown(
envelopeRef.current,
current.state.doc,
() => current.getMarkdown(),
() => (body = bodyMarkdown(current)),
sourceAtSave,
)
const imageSources = imageSourcesFromEditor(current)
@@ -325,6 +337,24 @@ export default function App() {
if (result.imageRewrites?.length && editorRef.current) {
applyImageRewrites(editorRef.current, result.imageRewrites)
}
// the next save splices against what is now on disk: after image
// rewrites that is writtenText paired with the rewritten document
if (result.writtenText === undefined) {
sourceMapRef.current = buildSourceMap(
current,
docAtSave,
body ?? stripLegacyFencedDivs(parseDocText(text).body),
)
} else {
sourceMapRef.current =
unchanged && editorRef.current
? buildSourceMap(
editorRef.current,
editorRef.current.state.doc,
stripLegacyFencedDivs(parseDocText(result.writtenText).body),
)
: null
}
if (
unchanged &&
sourceAtSave?.source === text &&
@@ -395,11 +425,11 @@ export default function App() {
}
return { base64: data.base64, mime: data.mime, widthPx: width, heightPx: height }
}
const renderDiagram = async (source: string) => {
const result = await renderMermaid(source)
return result.ok ? mermaidSvgToPng(result.svg, DOCX_MAX_IMAGE_PX) : null
const rasterizeDiagram = async (source: string, language: DiagramLanguage) => {
const result = await renderDiagram(language, source)
return result.ok ? diagramSvgToPng(result.svg, DOCX_MAX_IMAGE_PX) : null
}
const bytes = await exportDocxBytes(current.getJSON(), loadImage, renderDiagram)
const bytes = await exportDocxBytes(current.getJSON(), loadImage, rasterizeDiagram)
const result = await window.markdownApi.exportDocx({
base64: bytesToBase64(bytes),
suggestedName,
@@ -501,9 +531,16 @@ export default function App() {
}, [])
useEffect(() => {
const offSave = window.markdownApi.onSaveRequest(
(mode) => void doSave(mode).then((ok) => window.markdownApi.sendSaveRequestAck(ok)),
)
const offSave = window.markdownApi.onSaveRequest((mode) => {
void (async () => {
// same as the close-save path: wait out an in-flight autosave instead of
// answering false, or an MCP save-and-close during a blur autosave fails
while (savingRef.current) {
await new Promise((resolve) => setTimeout(resolve, 50))
}
window.markdownApi.sendSaveRequestAck(await doSave(mode))
})()
})
// MCP read of this open document: hand back the same serialization a save
// would write, so unsaved edits are included. Staying silent while the
// editor is still loading keeps the main process retrying its request
@@ -515,7 +552,7 @@ export default function App() {
const text = serializeMarkdown(
envelopeRef.current,
current.state.doc,
() => current.getMarkdown(),
() => bodyMarkdown(current),
originalSourceRef.current,
)
window.markdownApi.sendReadTextResult({ text })
@@ -598,10 +635,6 @@ export default function App() {
localStorage.setItem('mdapp.showAi', aiOpen ? '1' : '0')
}, [aiOpen])
useEffect(() => {
localStorage.setItem('mdapp.showFiles', filesOpen ? '1' : '0')
}, [filesOpen])
// autosave: every 30s and on window blur, silently persist pending changes
// (same policy as the docs app; untitled documents are skipped — the first
// save must go through the explicit save path that names the file)
@@ -691,7 +724,7 @@ export default function App() {
// file-text round-trip) so a rollback also reverts set_frontmatter and
// an untouched block restores byte-for-byte
getSnapshot: () => ({
body: editorRef.current?.getMarkdown() ?? '',
body: editorRef.current ? bodyMarkdown(editorRef.current) : '',
frontmatter: envelopeRef.current.frontmatter,
}),
restoreSnapshot: (snapshot) => {
@@ -702,6 +735,7 @@ export default function App() {
setFmText(inner)
setFmOpen(inner !== '')
current.commands.setContent(snapshot.body, { contentType: 'markdown' })
sourceMapRef.current = buildSourceMap(current, current.state.doc, snapshot.body)
markDirty()
},
onRunDone: (mutated) => {
@@ -762,8 +796,6 @@ export default function App() {
onToggleFrontmatter={() => setFmOpen((v) => !v)}
outlineOpen={outlineOpen}
onToggleOutline={() => setOutlineOpen((v) => !v)}
filesOpen={filesOpen}
onToggleFiles={() => setFilesOpen((v) => !v)}
hasOutline={outlineItems.length > 0}
spellcheck={spellcheck}
onToggleSpellcheck={() => setSpellcheck((v) => !v)}
@@ -803,14 +835,6 @@ export default function App() {
/>
)}
</div>
{filesOpen && (
<FilesPane
api={window.filesPaneApi}
lang={lang}
currentPath={filePath}
onClose={() => setFilesOpen(false)}
/>
)}
{outlineOpen && (
<OutlinePane
items={outlineItems}
@@ -820,7 +844,6 @@ export default function App() {
/>
)}
<div className="app-content">
{!filesOpen && <FilesEdgeTab lang={lang} onOpen={() => setFilesOpen(true)} />}
{showFind && findTarget && (
<FindPanel
target={findTarget}
@@ -11,9 +11,10 @@ import {
export const MARKDOWN_RULES = [
'All markdown passed to tools must be pure GFM plus math. Rules:',
'- Allowed syntax, and nothing else: `#`–`######` headings, paragraphs, `**bold**`, `*italic*`, `~~strikethrough~~`, `` `inline code` ``, `[links](url)`, `![images](path)`, `-` / `1.` lists, `- [ ]` task lists, `>` blockquotes, ``` fenced code blocks, `|` pipe tables, `---` horizontal rules, hard line breaks (two trailing spaces), LaTeX math, and ```mermaid diagrams.',
'- Allowed syntax, and nothing else: `#`–`######` headings, paragraphs, `**bold**`, `*italic*`, `~~strikethrough~~`, `` `inline code` ``, `[links](url)`, `![images](path)`, `-` / `1.` lists, `- [ ]` task lists, `>` blockquotes, ``` fenced code blocks, `|` pipe tables, `---` horizontal rules, hard line breaks (two trailing spaces), LaTeX math, ```mermaid diagrams, and ```wavedrom timing diagrams.',
'- Math: `$...$` inline and `$$...$$` blocks are rendered with KaTeX. The content of `$...$` must not start or end with whitespace, and the closing `$` must not be followed by a digit (so currency amounts stay text).',
'- Diagrams: a fenced code block with the `mermaid` language (flowchart, sequenceDiagram, classDiagram, stateDiagram-v2, erDiagram, gantt, pie, mindmap, timeline) renders as a diagram. Use it when the user asks for a flow, process, architecture, or timeline chart. The syntax must be valid mermaid — an invalid block falls back to showing its source.',
"- Timing diagrams: a fenced code block with the `wavedrom` language holding WaveJSON (`{ signal: [{ name: 'clk', wave: 'p....' }, …] }`) renders as a digital timing diagram. Use it only for clock / bus / signal waveforms.",
'- Never emit raw HTML — no tag of any kind (`<span>`, `<div>`, `<p>`, `<img>`, `<br>`, `<u>`, `<mark>`, …) and no style attributes. The editor forces everything through its GFM-only schema: semantic tags degrade to plain GFM and all other tags and styling are silently dropped.',
'- Never emit other non-GFM extensions: `==highlight==`, `++underline++`, `:::` fenced divs, footnotes, or emoji shortcodes. They are not parsed and end up as literal text in the document.',
'- This editor has no colored text, fonts, font sizes, underline, highlight, alignment, or line spacing. If the user asks for such styling, explain that pure markdown cannot express it — never fake it with HTML.',
@@ -8,7 +8,6 @@ import {
RibbonExpandButton,
useDismissablePopover,
useRibbonCollapse,
filesPaneTitle,
} from '@genoffice/ui'
import { useI18n } from '../i18n/locale'
import type { StringKey } from '../i18n/locale'
@@ -21,7 +20,6 @@ import {
IconLink,
IconNumbered,
IconOutlineView,
IconFolderTree,
IconPicture,
IconProperties,
IconRedo,
@@ -48,8 +46,6 @@ interface Props {
onToggleFrontmatter: () => void
outlineOpen: boolean
onToggleOutline: () => void
filesOpen: boolean
onToggleFiles: () => void
hasOutline: boolean
spellcheck: boolean
onToggleSpellcheck: () => void
@@ -174,8 +170,6 @@ export function Ribbon({
onToggleFrontmatter,
outlineOpen,
onToggleOutline,
filesOpen,
onToggleFiles,
hasOutline,
spellcheck,
onToggleSpellcheck,
@@ -183,7 +177,7 @@ export function Ribbon({
onToggleAi,
onAiPreset,
}: Props) {
const { t, lang } = useI18n()
const { t } = useI18n()
const collapse = useRibbonCollapse('mdapp.ribbonCollapsed')
const [linkOpen, setLinkOpen] = useState(false)
const [linkUrl, setLinkUrl] = useState('')
@@ -528,9 +522,6 @@ export function Ribbon({
>
<IconOutlineView size={ICON} />
</IconBtn>
<IconBtn title={filesPaneTitle(lang)} active={filesOpen} onClick={onToggleFiles}>
<IconFolderTree size={ICON} />
</IconBtn>
<IconBtn
title={t('spellcheck')}
active={spellcheck}
@@ -185,17 +185,3 @@ export function IconQuoteMark(props: IconProps) {
</Svg>
)
}
export function IconFolderTree({ size = 18 }: { size?: number }) {
return (
<svg width={size} height={size} viewBox="0 0 20 20" fill="none" aria-hidden="true">
<path
d="M2.5 5.5A1.5 1.5 0 0 1 4 4h3.6c.4 0 .8.16 1.07.45L10 5.8h6A1.5 1.5 0 0 1 17.5 7.3v7.2A1.5 1.5 0 0 1 16 16H4a1.5 1.5 0 0 1-1.5-1.5v-9z"
stroke="currentColor"
strokeWidth="1.4"
strokeLinejoin="round"
/>
<path d="M2.5 8.5h15" stroke="currentColor" strokeWidth="1.4" />
</svg>
)
}
@@ -3,8 +3,8 @@ import { NodeViewContent, NodeViewWrapper } from '@tiptap/react'
import type { NodeViewProps } from '@tiptap/react'
import { Dropdown } from '@genoffice/ui'
import { t } from '../i18n/locale'
import { MERMAID_LANGUAGE, renderMermaid } from './mermaid'
import type { MermaidResult } from './mermaid'
import { DIAGRAM_LANGUAGES, diagramLanguage, renderDiagram } from './diagrams'
import type { DiagramLanguage, DiagramResult } from './diagrams'
const LANGUAGES = [
'plaintext',
@@ -24,7 +24,6 @@ const LANGUAGES = [
'kotlin',
'lua',
'markdown',
MERMAID_LANGUAGE,
'objectivec',
'php',
'python',
@@ -38,7 +37,8 @@ const LANGUAGES = [
'typescript',
'xml',
'yaml',
]
...DIAGRAM_LANGUAGES,
].sort()
const RERENDER_DEBOUNCE_MS = 300
@@ -47,10 +47,15 @@ export function CodeBlockView({ node, updateAttributes, editor, getPos }: NodeVi
const copyTimerRef = useRef<number | null>(null)
const mountedRef = useRef(true)
const language = String(node.attrs.language ?? '') || 'plaintext'
const isMermaid = language === MERMAID_LANGUAGE
const diagramLang = diagramLanguage(language)
const source = node.textContent
const [diagram, setDiagram] = useState<MermaidResult | null>(null)
const [rendered, setRendered] = useState<{
language: DiagramLanguage
result: DiagramResult
} | null>(null)
// a result for another language is stale the moment the fence is relabelled
const diagram = rendered && rendered.language === diagramLang ? rendered.result : null
const hasDiagramRef = useRef(false)
hasDiagramRef.current = diagram !== null
const [caretInside, setCaretInside] = useState(false)
@@ -64,7 +69,7 @@ export function CodeBlockView({ node, updateAttributes, editor, getPos }: NodeVi
}, [])
useEffect(() => {
if (!isMermaid) return
if (!diagramLang) return
const update = () => {
const pos = getPos()
if (pos === undefined) return
@@ -79,26 +84,26 @@ export function CodeBlockView({ node, updateAttributes, editor, getPos }: NodeVi
return () => {
editor.off('selectionUpdate', update)
}
}, [editor, getPos, isMermaid])
}, [editor, getPos, diagramLang])
useEffect(() => {
if (!isMermaid || !source.trim()) {
setDiagram(null)
if (!diagramLang || !source.trim()) {
setRendered(null)
return
}
let cancelled = false
// first paint right away, then debounce while the user types
const delay = hasDiagramRef.current ? RERENDER_DEBOUNCE_MS : 0
const timer = window.setTimeout(() => {
void renderMermaid(source).then((result) => {
if (!cancelled) setDiagram(result)
void renderDiagram(diagramLang, source).then((result) => {
if (!cancelled) setRendered({ language: diagramLang, result })
})
}, delay)
return () => {
cancelled = true
window.clearTimeout(timer)
}
}, [isMermaid, source])
}, [diagramLang, source])
const copy = () => {
void navigator.clipboard
@@ -125,20 +130,20 @@ export function CodeBlockView({ node, updateAttributes, editor, getPos }: NodeVi
.run()
}
const rendered = isMermaid && diagram?.ok === true
const showSource = !rendered || caretInside
const error = isMermaid && diagram && !diagram.ok && source.trim() ? diagram.error : null
const hasPicture = diagram?.ok === true
const showSource = !hasPicture || caretInside
const error = diagram && !diagram.ok && source.trim() ? diagram.error : null
const className = [
'md-codeblock',
isMermaid && 'md-mermaid',
!showSource && 'md-mermaid-collapsed',
diagramLang && 'md-diagram',
!showSource && 'md-diagram-collapsed',
]
.filter(Boolean)
.join(' ')
return (
<NodeViewWrapper className={className} data-mermaid={rendered ? 'rendered' : undefined}>
<NodeViewWrapper className={className} data-diagram={hasPicture ? 'rendered' : undefined}>
<div className="md-codeblock-bar" contentEditable={false}>
<Dropdown
className="md-codeblock-lang"
@@ -155,13 +160,13 @@ export function CodeBlockView({ node, updateAttributes, editor, getPos }: NodeVi
<NodeViewContent<'code'> as="code" />
</pre>
{error && (
<div className="md-mermaid-error" contentEditable={false}>
<div className="md-diagram-error" contentEditable={false}>
{t('mermaidError')}: {error}
</div>
)}
{isMermaid && diagram?.ok && (
{diagram?.ok && (
<div
className="md-mermaid-preview"
className="md-diagram-preview"
contentEditable={false}
onClick={editSource}
dangerouslySetInnerHTML={{ __html: diagram.svg }}
@@ -0,0 +1,64 @@
import type { NewImage } from '@genoffice/docx-engine'
import { MERMAID_LANGUAGE, renderMermaid } from './mermaid'
import { WAVEDROM_LANGUAGE, renderWavedrom } from './wavedrom'
/** Fenced-code languages that render as a picture instead of source */
export const DIAGRAM_LANGUAGES = [MERMAID_LANGUAGE, WAVEDROM_LANGUAGE] as const
export type DiagramLanguage = (typeof DIAGRAM_LANGUAGES)[number]
export type DiagramResult = { ok: true; svg: string } | { ok: false; error: string }
export function diagramLanguage(language: unknown): DiagramLanguage | null {
return (DIAGRAM_LANGUAGES as readonly unknown[]).includes(language)
? (language as DiagramLanguage)
: null
}
export function renderDiagram(language: DiagramLanguage, source: string): Promise<DiagramResult> {
return language === WAVEDROM_LANGUAGE ? renderWavedrom(source) : renderMermaid(source)
}
const VIEWBOX_RE = /\bviewBox="[\d.\s-]*?\s([\d.]+)\s([\d.]+)"/
/** Rasterize a rendered diagram for the docx export; null when it cannot be drawn */
export async function diagramSvgToPng(svg: string, maxWidthPx: number): Promise<NewImage | null> {
const box = VIEWBOX_RE.exec(svg)
const width = Math.ceil(Number(box?.[1]))
const height = Math.ceil(Number(box?.[2]))
if (!width || !height) return null
// pin the intrinsic size (mermaid emits width="100%") so <img> decodes at the
// viewBox dimensions instead of the 300×150 SVG default
const sized = svg.replace(/<svg\b[^>]*>/, (tag) => {
const stripped = tag.replace(/\s(?:width|height)="[^"]*"/g, '')
return stripped.replace(/^<svg\b/, `<svg width="${width}" height="${height}"`)
})
const url = URL.createObjectURL(new Blob([sized], { type: 'image/svg+xml' }))
try {
const img = new Image()
await new Promise<void>((resolve, reject) => {
img.onload = () => resolve()
img.onerror = () => reject(new Error('svg decode failed'))
img.src = url
})
const scale = 2
const canvas = document.createElement('canvas')
canvas.width = width * scale
canvas.height = height * scale
const ctx = canvas.getContext('2d')
if (!ctx) return null
ctx.fillStyle = '#ffffff'
ctx.fillRect(0, 0, canvas.width, canvas.height)
ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
const dataUrl = canvas.toDataURL('image/png')
const base64 = dataUrl.slice(dataUrl.indexOf(',') + 1)
if (!base64) return null
const widthPx = Math.min(width, maxWidthPx)
const heightPx = Math.round((height * widthPx) / width)
return { base64, mime: 'image/png', widthPx, heightPx, align: 'center' }
} catch {
return null
} finally {
URL.revokeObjectURL(url)
}
}
@@ -1,7 +1,7 @@
import type { AnyExtension } from '@tiptap/core'
import StarterKit from '@tiptap/starter-kit'
import { Table, TableKit } from '@tiptap/extension-table'
import { OrderedList, TaskItem, TaskList } from '@tiptap/extension-list'
import { OrderedList, TaskList } from '@tiptap/extension-list'
import { CodeBlock } from '@tiptap/extension-code-block'
import { ReactNodeViewRenderer } from '@tiptap/react'
import { Placeholder } from '@tiptap/extensions'
@@ -16,6 +16,16 @@ import { SearchHighlight } from './searchHighlight'
import { buildMathExtensions } from './math'
import { SelectiveEscapeMarkdown } from './markdownEscape'
import { SlashCommand } from './slashCommand'
import {
renderFencedCode,
StyledBold,
StyledHardBreak,
StyledHeading,
StyledHorizontalRule,
StyledItalic,
StyledListItem,
StyledTaskItem,
} from './markdownStyleRenderers'
import { boundOrderedList, boundTable, boundTaskList } from './boundedTokenizers'
import type { SlashController, SlashItem } from './slashCommand'
import { t } from '../i18n/locale'
@@ -36,7 +46,20 @@ export function buildExtensions(options: BuildExtensionsOptions): AnyExtension[]
underline: false,
// re-added below with a linear-time markdown tokenizer
orderedList: false,
// re-added below with renderers that follow the document's own conventions
bold: false,
italic: false,
heading: false,
horizontalRule: false,
hardBreak: false,
listItem: false,
}),
StyledBold,
StyledItalic,
StyledHeading,
StyledHorizontalRule,
StyledHardBreak,
StyledListItem,
OrderedList.extend({
markdownTokenizer: boundOrderedList(OrderedList.config.markdownTokenizer!),
}),
@@ -44,6 +67,11 @@ export function buildExtensions(options: BuildExtensionsOptions): AnyExtension[]
addNodeView() {
return ReactNodeViewRenderer(CodeBlockView)
},
renderMarkdown: (node, h) =>
renderFencedCode(
String(node.attrs?.language ?? ''),
node.content ? h.renderChildren(node.content) : null,
),
}),
// 4-space nesting: the default 2 spaces is below the content column of
// ordered items ("1. " = 3), so strict CommonMark parsers (GitHub) would
@@ -57,7 +85,7 @@ export function buildExtensions(options: BuildExtensionsOptions): AnyExtension[]
renderWrapper: true,
}),
TaskList.extend({ markdownTokenizer: boundTaskList(TaskList.config.markdownTokenizer!) }),
TaskItem.configure({ nested: true }),
StyledTaskItem.configure({ nested: true }),
// KaTeX-rendered $...$ / $$...$$ formulas (issue #100)
...buildMathExtensions(),
LocalImage,
@@ -0,0 +1,99 @@
import { renderNestedMarkdownContent } from '@tiptap/core'
import { Bold } from '@tiptap/extension-bold'
import { HardBreak } from '@tiptap/extension-hard-break'
import { Heading } from '@tiptap/extension-heading'
import { HorizontalRule } from '@tiptap/extension-horizontal-rule'
import { Italic } from '@tiptap/extension-italic'
import { getListMarker, ListItem, TaskItem } from '@tiptap/extension-list'
import { activeMarkdownStyle } from '../markdown/markdownStyle'
/**
* The stock renderers hardcode `-`, `1.`, `*`, `**`, `#`, ```` ``` ````, `---`
* and two-space breaks. These read the style in force instead (see
* markdownStyle.ts); outside a style scope they produce the same output.
*/
export const StyledBold = Bold.extend({
renderMarkdown: (node, h) => {
const strong = activeMarkdownStyle().strong
return `${strong}${h.renderChildren(node)}${strong}`
},
})
export const StyledItalic = Italic.extend({
renderMarkdown: (node, h) => {
const em = activeMarkdownStyle().em
return `${em}${h.renderChildren(node)}${em}`
},
})
/**
* A setext underline only makes a heading of plain paragraph lines: a line
* CommonMark reads as a list item, quote, heading, indented code or thematic
* break first would come back as something else, and a fence opener or a
* bare `===` line would end the heading early. Line breaks are fine — a
* setext heading may span lines, which ATX cannot.
*/
const NOT_SETEXT_LINE =
/^ {0,3}(?:[-+*]|\d{1,9}[.)])(?:\s|$)|^ {0,3}[>#]|^ {4}|^ {0,3}(?:[-*_]\s*){3,}$|^ {0,3}(?:`{3,}|~{3,})|^ {0,3}=+\s*$/
function setextSafe(text: string): boolean {
if (text.trim() === '') return false
return text.split('\n').every((line) => line.trim() !== '' && !NOT_SETEXT_LINE.test(line))
}
export const StyledHeading = Heading.extend({
renderMarkdown: (node, h) => {
if (!node.content) return ''
const level = node.attrs?.level ? parseInt(String(node.attrs.level), 10) : 1
const text = h.renderChildren(node.content)
if (activeMarkdownStyle().setext && level <= 2 && setextSafe(text)) {
const width = Math.max(3, ...text.split('\n').map((line) => line.length))
return `${text}\n${(level === 1 ? '=' : '-').repeat(width)}`
}
return `${'#'.repeat(level)} ${text}`
},
})
export const StyledHorizontalRule = HorizontalRule.extend({
renderMarkdown: () => activeMarkdownStyle().rule,
})
export const StyledHardBreak = HardBreak.extend({
renderMarkdown: () => (activeMarkdownStyle().hardBreak === 'backslash' ? '\\\n' : ' \n'),
})
export const StyledListItem = ListItem.extend({
renderMarkdown: (node, h, ctx) =>
renderNestedMarkdownContent(
node,
h,
(context) => {
const style = activeMarkdownStyle()
if (context.parentType !== 'orderedList') return `${style.bullet} `
const attrs = context.meta?.parentAttrs as { start?: number; type?: string } | undefined
const start = attrs?.start || 1
const index = style.orderedRepeat ? 0 : context.index || 0
return getListMarker(attrs?.type, start - 1 + index, `${style.orderedDelimiter} `)
},
ctx,
{ alignNestedToPrefix: ctx?.parentType === 'orderedList' },
),
})
export const StyledTaskItem = TaskItem.extend({
renderMarkdown: (node, h) => {
const prefix = `${activeMarkdownStyle().bullet} [${node.attrs?.checked ? 'x' : ' '}] `
return renderNestedMarkdownContent(node, h, prefix)
},
})
/** fence long enough that the code's own backtick or tilde runs cannot close it */
export function renderFencedCode(language: string, body: string | null): string {
const char = activeMarkdownStyle().fence
const runs = body?.match(char === '`' ? /`{3,}/g : /~{3,}/g) ?? []
const fence = char.repeat(Math.max(3, ...runs.map((run) => run.length + 1)))
return body === null
? `${fence}${language}\n\n${fence}`
: `${fence}${language}\n${body}\n${fence}`
}
+2 -49
View File
@@ -1,5 +1,5 @@
import type { Mermaid } from 'mermaid'
import type { NewImage } from '@genoffice/docx-engine'
import type { DiagramResult } from './diagrams'
export const MERMAID_LANGUAGE = 'mermaid'
@@ -33,11 +33,9 @@ export function loadMermaid(): Promise<Mermaid> {
return loading
}
export type MermaidResult = { ok: true; svg: string } | { ok: false; error: string }
let renderSeq = 0
export async function renderMermaid(source: string): Promise<MermaidResult> {
export async function renderMermaid(source: string): Promise<DiagramResult> {
const mermaid = await loadMermaid()
try {
const { svg } = await mermaid.render(`md-mermaid-${++renderSeq}`, source)
@@ -46,48 +44,3 @@ export async function renderMermaid(source: string): Promise<MermaidResult> {
return { ok: false, error: err instanceof Error ? err.message : String(err) }
}
}
const VIEWBOX_RE = /\bviewBox="[\d.\s-]*?\s([\d.]+)\s([\d.]+)"/
/** Rasterize a rendered diagram for the docx export; null when it cannot be drawn */
export async function mermaidSvgToPng(svg: string, maxWidthPx: number): Promise<NewImage | null> {
const box = VIEWBOX_RE.exec(svg)
const width = Math.ceil(Number(box?.[1]))
const height = Math.ceil(Number(box?.[2]))
if (!width || !height) return null
// mermaid emits width="100%": pin the intrinsic size so <img> decodes at the
// viewBox dimensions instead of the 300×150 SVG default
const sized = svg.replace(
/<svg\b([^>]*?)\swidth="[^"]*"/,
`<svg$1 width="${width}" height="${height}"`,
)
const url = URL.createObjectURL(new Blob([sized], { type: 'image/svg+xml' }))
try {
const img = new Image()
await new Promise<void>((resolve, reject) => {
img.onload = () => resolve()
img.onerror = () => reject(new Error('svg decode failed'))
img.src = url
})
const scale = 2
const canvas = document.createElement('canvas')
canvas.width = width * scale
canvas.height = height * scale
const ctx = canvas.getContext('2d')
if (!ctx) return null
ctx.fillStyle = '#ffffff'
ctx.fillRect(0, 0, canvas.width, canvas.height)
ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
const dataUrl = canvas.toDataURL('image/png')
const base64 = dataUrl.slice(dataUrl.indexOf(',') + 1)
if (!base64) return null
const widthPx = Math.min(width, maxWidthPx)
const heightPx = Math.round((height * widthPx) / width)
return { base64, mime: 'image/png', widthPx, heightPx, align: 'center' }
} catch {
return null
} finally {
URL.revokeObjectURL(url)
}
}
@@ -6,6 +6,7 @@ import type { StringKey } from '../i18n/locale'
import { t } from '../i18n/locale'
import { openMathCreate } from './mathEdit'
import { MERMAID_TEMPLATE } from './mermaid'
import { WAVEDROM_TEMPLATE } from './wavedrom'
import { uiOp, type MdOp } from './ops'
export interface SlashItem {
@@ -125,6 +126,12 @@ export function buildSlashItems(extra?: { insertImage?: () => void }): SlashItem
keywords: ['mermaid', 'chart', 'flowchart', 'graph'],
run: slashOp({ op: 'insertContent', after: 'selection', markdown: MERMAID_TEMPLATE }),
},
{
id: 'waveform',
labelKey: 'insertWaveform',
keywords: ['wavedrom', 'timing', 'waveform', 'signal', 'clock'],
run: slashOp({ op: 'insertContent', after: 'selection', markdown: WAVEDROM_TEMPLATE }),
},
]
if (extra?.insertImage) {
items.push({
@@ -0,0 +1,88 @@
import type { DiagramResult } from './diagrams'
export const WAVEDROM_LANGUAGE = 'wavedrom'
export const WAVEDROM_TEMPLATE = [
'```wavedrom',
'{ signal: [',
" { name: 'clk', wave: 'p.....' },",
" { name: 'data', wave: 'x.345x', data: ['head', 'body', 'tail'] },",
" { name: 'req', wave: '0.1..0' },",
']}',
'```',
].join('\n')
type WaveDromModule = typeof import('wavedrom')
type Json5Module = typeof import('json5')
let loading: Promise<[WaveDromModule, Json5Module]> | null = null
/** Loaded on first use so documents without timing diagrams never pay for the bundle */
function loadWavedrom() {
loading ??= Promise.all([import('wavedrom'), import('json5')]).then(([wd, json5]) => [
wd,
json5.default ?? json5,
])
return loading
}
let renderSeq = 0
export async function renderWavedrom(source: string): Promise<DiagramResult> {
const [wavedrom, json5] = await loadWavedrom()
let parsed: unknown
try {
// WaveJSON is JS-object-literal flavoured (unquoted keys, single quotes, comments)
parsed = json5.parse(source)
} catch (err) {
return { ok: false, error: err instanceof Error ? err.message : String(err) }
}
if (!isWaveJson(parsed)) {
return { ok: false, error: 'expected an object with a "signal", "assign" or "reg" array' }
}
try {
const tree = wavedrom.renderAny(++renderSeq, parsed, wavedrom.waveSkin)
if (tree[0] !== 'svg') return { ok: false, error: 'nothing to draw' }
return { ok: true, svg: scopeSkinStyles(wavedrom.onml.stringify(tree)) }
} catch (err) {
return { ok: false, error: err instanceof Error ? err.message : String(err) }
}
}
function isWaveJson(value: unknown): value is object {
if (typeof value !== 'object' || value === null || Array.isArray(value)) return false
const v = value as Record<string, unknown>
return Array.isArray(v.signal) || Array.isArray(v.assign) || Array.isArray(v.reg)
}
/**
* The skin's inline stylesheet uses bare selectors (`text`, `.h1`, `.error`)
* that an inline <svg> would apply to the whole page. Shapes are drawn via
* <use>, whose shadow tree cannot see outer ancestors, so an ancestor prefix
* would not reach them: namespace the class names instead.
*/
function scopeSkinStyles(svg: string): string {
return svg
.replace(/<style([^>]*)>([\s\S]*?)<\/style>/, (_m, attrs: string, css: string) => {
const scoped = css.replace(/(^|\})\s*([^{}]+)\{/g, (_r, sep: string, selectors: string) => {
const list = selectors
.split(',')
.map((s) => s.trim())
.map((s) =>
s.startsWith('.') ? s.replace(/\.([\w-]+)/g, '.wd-$1') : `svg.WaveDrom ${s}`,
)
.join(',')
return `${sep}${list}{`
})
return `<style${attrs}>${scoped}</style>`
})
.replace(/\bclass="([^"]*)"/g, (m, names: string) =>
names === 'WaveDrom'
? m
: `class="${names
.split(/\s+/)
.filter(Boolean)
.map((n) => `wd-${n}`)
.join(' ')}"`,
)
}
-3
View File
@@ -3,12 +3,9 @@
import type { ProjectApi } from '@genoffice/project-store'
import type { MarkdownApi } from '../shared/ipc'
import type { FilesPaneApi } from '@genoffice/ui'
declare global {
interface Window {
markdownApi: MarkdownApi
filesPaneApi: FilesPaneApi
projectApi?: Pick<ProjectApi, 'resolveChat' | 'appendChat' | 'loadChat' | 'rebindChat'>
}
}
@@ -20,12 +20,17 @@ import type {
TableModel,
TableParagraph,
} from '@genoffice/docx-engine'
import { diagramLanguage } from '../editor/diagrams'
import type { DiagramLanguage } from '../editor/diagrams'
/** Resolve an authored image src to embeddable bytes; null → fall back to alt text */
export type ImageLoader = (src: string) => Promise<NewImage | null>
/** Rasterize a ```mermaid block; null → the source is exported as code */
export type DiagramRenderer = (source: string) => Promise<NewImage | null>
/** Rasterize a diagram code block; null → the source is exported as code */
export type DiagramRenderer = (
source: string,
language: DiagramLanguage,
) => Promise<NewImage | null>
/** widest image that fits the A4 text column */
export const DOCX_MAX_IMAGE_PX = 620
@@ -87,7 +92,7 @@ interface WalkContext {
loadImage: ImageLoader
renderDiagram?: DiagramRenderer
pendingImages: Array<{ index: number; src: string; alt: string }>
pendingDiagrams: Array<{ index: number; source: string }>
pendingDiagrams: Array<{ index: number; source: string; language: DiagramLanguage }>
}
function mergeFormat(base: ParaFormat | undefined, extra: ParaFormat): ParaFormat {
@@ -221,8 +226,9 @@ function walkBlock(ctx: WalkContext, node: JSONContent, base?: ParaFormat): void
runs: [{ text: source, font: CODE_FONT, sizeHalfPoints: 19 }],
format: mergeFormat(base, { shadingFill: CODE_FILL }),
}
if (node.attrs?.language === 'mermaid' && ctx.renderDiagram && source.trim()) {
ctx.pendingDiagrams.push({ index: ctx.blocks.length, source })
const language = diagramLanguage(node.attrs?.language)
if (language && ctx.renderDiagram && source.trim()) {
ctx.pendingDiagrams.push({ index: ctx.blocks.length, source, language })
}
pushParagraph(ctx, code)
break
@@ -285,7 +291,7 @@ export async function mapDocToSaveBlocks(
for (const node of doc.content ?? []) walkBlock(ctx, node)
for (const pending of ctx.pendingDiagrams) {
const image = await ctx.renderDiagram!(pending.source).catch(() => null)
const image = await ctx.renderDiagram!(pending.source, pending.language).catch(() => null)
if (image) ctx.blocks[pending.index] = { kind: 'image', image }
}
@@ -30,8 +30,8 @@ pre code { background: none; padding: 0; font-size: 0.85em; line-height: 1.6; }
hr { border: none; border-top: 2px solid #e4e7eb; margin: 1.6em 0; }
a { color: #0a69da; }
img { max-width: 100%; height: auto; }
.md-mermaid-preview { margin: 0.8em 0; text-align: center; break-inside: avoid; }
.md-mermaid-preview svg { max-width: 100%; height: auto; }
.md-diagram-preview { margin: 0.8em 0; text-align: center; break-inside: avoid; }
.md-diagram-preview svg { max-width: 100%; height: auto; }
.tableWrapper { margin: 0.8em 0; }
table { border-collapse: collapse; width: 100%; margin: 0; break-inside: avoid; }
th, td { border: 1px solid #d0d5db; padding: 6px 10px; vertical-align: top; text-align: start; }
@@ -61,9 +61,9 @@ export function buildPrintHtml(editorRoot: HTMLElement, title: string): string {
el.removeAttribute('contenteditable')
// editor-only code block chrome (language picker + copy button) must not print
for (const bar of clone.querySelectorAll('.md-codeblock-bar, .md-mermaid-error')) bar.remove()
// a rendered mermaid block prints as its diagram; an unrendered one keeps its source
for (const block of clone.querySelectorAll('[data-mermaid="rendered"] pre')) block.remove()
for (const bar of clone.querySelectorAll('.md-codeblock-bar, .md-diagram-error')) bar.remove()
// a rendered diagram block prints as its picture; an unrendered one keeps its source
for (const block of clone.querySelectorAll('[data-diagram="rendered"] pre')) block.remove()
const escapedTitle = title.replace(/&/g, '&amp;').replace(/</g, '&lt;')
// <base> lets the inlined KaTeX CSS resolve its relative font URLs from the
@@ -118,6 +118,7 @@ export const strings = {
insertHr: '分隔线',
insertMath: '公式',
insertDiagram: '图表',
insertWaveform: '时序图',
mermaidError: '图表语法错误',
mathPlaceholder: '输入 LaTeX 公式,如 E = mc^2',
slashNoResults: '无匹配项',
@@ -319,6 +320,7 @@ export const strings = {
insertHr: 'Divider',
insertMath: 'Formula',
insertDiagram: 'Diagram',
insertWaveform: 'Timing diagram',
mermaidError: 'Diagram syntax error',
mathPlaceholder: 'Enter LaTeX, e.g. E = mc^2',
slashNoResults: 'No results',
@@ -520,6 +522,7 @@ export const strings = {
insertHr: '区切り線',
insertMath: '数式',
insertDiagram: '図',
insertWaveform: 'タイミング図',
mermaidError: '図の構文エラー',
mathPlaceholder: 'LaTeX を入力(例:E = mc^2)',
slashNoResults: '該当なし',
@@ -722,6 +725,7 @@ export const strings = {
insertHr: '구분선',
insertMath: '수식',
insertDiagram: '다이어그램',
insertWaveform: '타이밍 다이어그램',
mermaidError: '다이어그램 문법 오류',
mathPlaceholder: 'LaTeX 입력 (예: E = mc^2)',
slashNoResults: '결과 없음',
@@ -927,6 +931,7 @@ export const strings = {
insertHr: 'Séparateur',
insertMath: 'Formule',
insertDiagram: 'Diagramme',
insertWaveform: 'Chronogramme',
mermaidError: 'Erreur de syntaxe du diagramme',
mathPlaceholder: 'Saisir du LaTeX, ex. E = mc^2',
slashNoResults: 'Aucun résultat',
@@ -1134,6 +1139,7 @@ export const strings = {
insertHr: 'Trennlinie',
insertMath: 'Formel',
insertDiagram: 'Diagramm',
insertWaveform: 'Zeitdiagramm',
mermaidError: 'Syntaxfehler im Diagramm',
mathPlaceholder: 'LaTeX eingeben, z. B. E = mc^2',
slashNoResults: 'Keine Treffer',
@@ -1339,6 +1345,7 @@ export const strings = {
insertHr: 'Separador',
insertMath: 'Fórmula',
insertDiagram: 'Diagrama',
insertWaveform: 'Diagrama de tiempos',
mermaidError: 'Error de sintaxis del diagrama',
mathPlaceholder: 'Escribe LaTeX, p. ej. E = mc^2',
slashNoResults: 'Sin resultados',
@@ -1541,6 +1548,7 @@ export const strings = {
insertHr: 'เส้นแบ่ง',
insertMath: 'สูตร',
insertDiagram: 'แผนภาพ',
insertWaveform: 'แผนภาพเวลา',
mermaidError: 'ไวยากรณ์แผนภาพไม่ถูกต้อง',
mathPlaceholder: 'ป้อน LaTeX เช่น E = mc^2',
slashNoResults: 'ไม่พบรายการ',
@@ -1743,6 +1751,7 @@ export const strings = {
insertHr: 'Pembatas',
insertMath: 'Rumus',
insertDiagram: 'Diagram',
insertWaveform: 'Diagram pewaktuan',
mermaidError: 'Kesalahan sintaks diagram',
mathPlaceholder: 'Masukkan LaTeX, mis. E = mc^2',
slashNoResults: 'Tidak ada hasil',
@@ -1946,6 +1955,7 @@ export const strings = {
insertHr: 'Разделитель',
insertMath: 'Формула',
insertDiagram: 'Диаграмма',
insertWaveform: 'Временная диаграмма',
mermaidError: 'Синтаксическая ошибка диаграммы',
mathPlaceholder: 'Введите LaTeX, напр. E = mc^2',
slashNoResults: 'Нет результатов',
@@ -2145,6 +2155,7 @@ export const strings = {
insertHr: 'فاصل',
insertMath: 'معادلة',
insertDiagram: 'مخطط',
insertWaveform: 'مخطط توقيت',
mermaidError: 'خطأ في صياغة المخطط',
mathPlaceholder: 'أدخل LaTeX، مثل E = mc^2',
slashNoResults: 'لا نتائج',
@@ -2349,6 +2360,7 @@ export const strings = {
insertHr: 'Divisor',
insertMath: 'Fórmula',
insertDiagram: 'Diagrama',
insertWaveform: 'Diagrama de tempo',
mermaidError: 'Erro de sintaxe do diagrama',
mathPlaceholder: 'Digite LaTeX, ex.: E = mc^2',
slashNoResults: 'Sem resultados',
@@ -2554,6 +2566,7 @@ export const strings = {
insertHr: 'Divisore',
insertMath: 'Formula',
insertDiagram: 'Diagramma',
insertWaveform: 'Diagramma temporale',
mermaidError: 'Errore di sintassi del diagramma',
mathPlaceholder: 'Inserisci LaTeX, es. E = mc^2',
slashNoResults: 'Nessun risultato',
@@ -2758,6 +2771,7 @@ export const strings = {
insertHr: 'Separator',
insertMath: 'Wzór',
insertDiagram: 'Diagram',
insertWaveform: 'Diagram czasowy',
mermaidError: 'Błąd składni diagramu',
mathPlaceholder: 'Wpisz LaTeX, np. E = mc^2',
slashNoResults: 'Brak wyników',
@@ -3038,6 +3052,7 @@ export const strings = {
replaceAll: 'Nahradit vše',
findTip: 'Najít a nahradit (⌘F)',
insertDiagram: 'Diagram',
insertWaveform: 'Časový diagram',
mermaidError: 'Chyba syntaxe diagramu',
},
nl: {
@@ -3164,6 +3179,7 @@ export const strings = {
insertHr: 'Scheidingslijn',
insertMath: 'Formule',
insertDiagram: 'Diagram',
insertWaveform: 'Timingdiagram',
mermaidError: 'Syntaxisfout in diagram',
mathPlaceholder: 'Voer LaTeX in, bijv. E = mc^2',
slashNoResults: 'Geen resultaten',
@@ -3366,6 +3382,7 @@ export const strings = {
insertHr: 'Pemisah',
insertMath: 'Rumus',
insertDiagram: 'Rajah',
insertWaveform: 'Rajah pemasaan',
mermaidError: 'Ralat sintaks rajah',
mathPlaceholder: 'Masukkan LaTeX, cth. E = mc^2',
slashNoResults: 'Tiada hasil',
@@ -3565,6 +3582,7 @@ export const strings = {
insertHr: 'קו מפריד',
insertMath: 'נוסחה',
insertDiagram: 'דיאגרמה',
insertWaveform: 'דיאגרמת תזמון',
mermaidError: 'שגיאת תחביר בדיאגרמה',
mathPlaceholder: 'הזן LaTeX, למשל E = mc^2',
slashNoResults: 'אין תוצאות',
@@ -3766,6 +3784,7 @@ export const strings = {
insertHr: 'विभाजक',
insertMath: 'सूत्र',
insertDiagram: 'आरेख',
insertWaveform: 'टाइमिंग आरेख',
mermaidError: 'आरेख सिंटैक्स त्रुटि',
mathPlaceholder: 'LaTeX दर्ज करें, जैसे E = mc^2',
slashNoResults: 'कोई परिणाम नहीं',
@@ -3965,6 +3984,7 @@ export const strings = {
insertHr: '分隔線',
insertMath: '公式',
insertDiagram: '圖表',
insertWaveform: '時序圖',
mermaidError: '圖表語法錯誤',
mathPlaceholder: '輸入 LaTeX 公式,如 E = mc^2',
slashNoResults: '無符合項目',
-1
View File
@@ -7,7 +7,6 @@ import '@genoffice/ui/tokens.css'
import '@genoffice/ui/screentip.css'
import '@genoffice/ui/dropdown.css'
import '@genoffice/ui/find-panel.css'
import '@genoffice/ui/files-pane.css'
import '@genoffice/ui/ribbon-collapse.css'
import '@genoffice/ui/markdown.css'
import '@genoffice/ui/ai-panel-prefs.css'

Some files were not shown because too many files have changed in this diff Show More