Sync snapshot (2026-08-12) (#87)

- Add text insertion and improved text editing in PDF files
- Expand PDF form filling, annotations, highlighting, and visual signature workflows
- Add PDF image crop, flip, transparency, replacement, and background removal
- Improve Sheets validation rendering, undo behavior, and workbook stability
- Add system font discovery and improve shared Office interface consistency
- Improve AI network resilience and response validation

Co-authored-by: GenOffice <merrick-2002@users.noreply.github.com>
This commit is contained in:
merrick-2002
2026-08-12 08:36:35 +08:00
committed by GitHub
co-authored by GenOffice
parent 2c1f0e821a
commit dc4d7e5927
157 changed files with 10981 additions and 1646 deletions
+4 -3
View File
@@ -1,3 +1,4 @@
import { aiFetch } from './fetch'
import { httpBodyDetail } from './http-error'
import { GENSPARK_LLM_BASE_URLS, gensparkAttributionHeaders } from './providers'
import type { AiChatResponse, AiProviderConfig, AiProviderId } from './types'
@@ -10,7 +11,7 @@ async function chatAnthropic(
user: string,
baseUrl = 'https://api.anthropic.com',
): Promise<AiChatResponse> {
const response = await fetch(`${baseUrl.replace(/\/$/, '')}/v1/messages`, {
const response = await aiFetch(`${baseUrl.replace(/\/$/, '')}/v1/messages`, {
method: 'POST',
signal: wd.signal,
headers: {
@@ -52,7 +53,7 @@ async function chatGemini(
baseUrl = 'https://generativelanguage.googleapis.com/v1beta',
): Promise<AiChatResponse> {
const url = `${baseUrl.replace(/\/$/, '')}/models/${config.model}:generateContent`
const response = await fetch(url, {
const response = await aiFetch(url, {
method: 'POST',
signal: wd.signal,
headers: {
@@ -88,7 +89,7 @@ async function chatOpenAiCompatible(
system: string,
user: string,
): Promise<AiChatResponse> {
const response = await fetch(`${baseUrl.replace(/\/$/, '')}/chat/completions`, {
const response = await aiFetch(`${baseUrl.replace(/\/$/, '')}/chat/completions`, {
method: 'POST',
signal: wd.signal,
headers: {
+32
View File
@@ -0,0 +1,32 @@
/**
* In Electron main processes AI requests run on Node's fetch (undici), which
* connects directly instead of going through Chromium's network stack. Under
* VPN/tun setups those direct connections can get reset (ECONNRESET) while
* Chromium traffic — login, renderer fetches — works fine. Main processes
* inject Electron's net.fetch here as a rescue path: when the primary fetch
* fails at the network layer, the request is retried once over the Chromium
* stack. Renderers never inject one (their fetch already is Chromium's).
*/
type FetchLike = (url: string, init?: RequestInit) => Promise<Response>
let rescueFetch: FetchLike | null = null
export function setRescueFetch(fn: FetchLike | null): void {
rescueFetch = fn
}
export async function aiFetch(url: string, init: RequestInit): Promise<Response> {
try {
return await fetch(url, init)
} catch (primaryError) {
const signal = init.signal as AbortSignal | null | undefined
if (!rescueFetch || signal?.aborted) throw primaryError
console.warn('[ai-provider] fetch failed, retrying via rescue fetch:', String(primaryError))
try {
return await rescueFetch(url, init)
} catch {
throw primaryError
}
}
}
+1
View File
@@ -17,6 +17,7 @@ export {
resolveAiSettings,
} from './providers'
export { chatForProvider } from './chat'
export { setRescueFetch } from './fetch'
export { AiCreditsError, sseLines, streamForProvider } from './stream'
export type { StreamCallbacks } from './stream'
export {
+7 -6
View File
@@ -1,4 +1,5 @@
import type { AgentMessage, AgentToolCall, AgentToolDef } from '@genoffice/agent-core'
import { aiFetch } from './fetch'
import { httpBodyDetail } from './http-error'
import { GENSPARK_LLM_BASE_URLS, gensparkAttributionHeaders } from './providers'
import type { AiProviderConfig, AiProviderId } from './types'
@@ -272,16 +273,16 @@ async function anthropicTurn(
}
let response: Response
try {
response = await fetch(`${baseUrl.replace(/\/$/, '')}/v1/messages`, {
response = await aiFetch(`${baseUrl.replace(/\/$/, '')}/v1/messages`, {
method: 'POST',
signal: wd.signal,
headers: {
'Content-Type': 'application/json',
'x-api-key': config.apiKey,
'anthropic-version': '2023-06-01',
// Fetch in the Electron main process goes through Chromium's network stack, which adds
// browser-semantics headers; Anthropic rejects those with 403 "Request not allowed". This
// header is the official opt-in for direct access from browser/Electron environments.
// Renderer fetches and the net.fetch rescue path go through Chromium's network stack,
// which adds browser-semantics headers; Anthropic rejects those with 403 "Request not
// allowed". This header is the official opt-in for browser/Electron environments.
'anthropic-dangerous-direct-browser-access': 'true',
...gensparkAttributionHeaders(baseUrl),
},
@@ -506,7 +507,7 @@ async function geminiTurn(
cb.onActivity?.()
}
const url = `${baseUrl.replace(/\/$/, '')}/models/${config.model}:streamGenerateContent?alt=sse`
const response = await fetch(url, {
const response = await aiFetch(url, {
method: 'POST',
signal: wd.signal,
headers: {
@@ -719,7 +720,7 @@ async function openAiCompatibleTurn(
wd.touch()
cb.onActivity?.()
}
const response = await fetch(`${baseUrl.replace(/\/$/, '')}/chat/completions`, {
const response = await aiFetch(`${baseUrl.replace(/\/$/, '')}/chat/completions`, {
method: 'POST',
signal: wd.signal,
headers: {
+48
View File
@@ -0,0 +1,48 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { aiFetch, setRescueFetch } from '../src/fetch'
afterEach(() => {
vi.unstubAllGlobals()
setRescueFetch(null)
})
describe('aiFetch', () => {
it('returns the primary response without touching the rescue path', async () => {
const ok = new Response('ok')
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(ok))
const rescue = vi.fn()
setRescueFetch(rescue)
expect(await aiFetch('https://x/', {})).toBe(ok)
expect(rescue).not.toHaveBeenCalled()
})
it('retries over the rescue fetch when the primary fails', async () => {
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('fetch failed')))
const ok = new Response('rescued')
const rescue = vi.fn().mockResolvedValue(ok)
setRescueFetch(rescue)
expect(await aiFetch('https://x/', {})).toBe(ok)
expect(rescue).toHaveBeenCalledOnce()
})
it('throws the primary error when no rescue fetch is set', async () => {
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('ECONNRESET')))
await expect(aiFetch('https://x/', {})).rejects.toThrow('ECONNRESET')
})
it('throws the primary error when the rescue fetch also fails', async () => {
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('primary down')))
setRescueFetch(vi.fn().mockRejectedValue(new Error('rescue down')))
await expect(aiFetch('https://x/', {})).rejects.toThrow('primary down')
})
it('does not retry an aborted request', async () => {
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('aborted')))
const rescue = vi.fn()
setRescueFetch(rescue)
const controller = new AbortController()
controller.abort()
await expect(aiFetch('https://x/', { signal: controller.signal })).rejects.toThrow('aborted')
expect(rescue).not.toHaveBeenCalled()
})
})
+34 -16
View File
@@ -7,7 +7,7 @@ import type {
TableCell,
TableModel,
} from './types'
import { escapeXmlAttr, escapeXmlText } from './xml-utils'
import { escapeXmlAttr, escapeXmlText, textHasComplexScript } from './xml-utils'
export interface GenerateContext {
/** heading level -> styleId existing in the original styles.xml */
@@ -1011,6 +1011,10 @@ function formatPPrChildren(format: ParaFormat | undefined): PPrChild[] {
xml: `<w:framePr w:dropCap="${type}" w:lines="${lines}" w:wrap="around" w:vAnchor="text" w:hAnchor="text"/>`,
})
}
if (format.emptyRunSizeHalfPoints) {
const sz = Math.round(format.emptyRunSizeHalfPoints)
out.push({ name: 'w:rPr', xml: `<w:rPr><w:sz w:val="${sz}"/><w:szCs w:val="${sz}"/></w:rPr>` })
}
return out
}
@@ -1182,6 +1186,10 @@ function pprGroupUnchanged(tag: string, raw: string | undefined, f: ParaFormat):
return rawTabsUnchanged(raw, f.tabStops ?? [])
case 'w:framePr':
return rawFramePrUnchanged(raw, f)
case 'w:rPr': {
const m = raw ? /<w:sz\b[^>]*w:val="(\d+)"/.exec(raw) : null
return (m ? parseInt(m[1], 10) : undefined) === f.emptyRunSizeHalfPoints
}
default:
return false
}
@@ -1216,6 +1224,8 @@ export function mergePPrFormat(rawPPr: string, format: ParaFormat | undefined):
const managedTags = new Set(FORMAT_MANAGED_TAGS)
if (format?.tabStops !== undefined) managedTags.add('w:tabs')
if (format?.dropCap !== undefined) managedTags.add('w:framePr')
// only when the model carries a size: otherwise the paragraph-mark rPr stays unmanaged
if (format?.emptyRunSizeHalfPoints !== undefined) managedTags.add('w:rPr')
const rawChildren = splitXmlChildren(inner)
const rawOf = (tag: string) => rawChildren.find((c) => c.name === tag)?.xml
const rebuilt = new Set(
@@ -1493,22 +1503,16 @@ function tableCellXml(
runs: text === '' ? [] : [{ text, bold: cell.bold, color: cell.color }],
}))
const paraXmls = paragraphs.map((paragraph) => {
// cell.align is a raw w:jc, so it is Word's logical value, while paragraph.align has already
// been converted to a visual one and the format model converts it back on the way out. Only
// left and right differ between the two, so an RTL paragraph still takes the cell fallback
// for centre and justify and skips it for the sided values, which cannot be placed in either
// coordinate system with confidence.
const bidi = 'bidi' in paragraph && paragraph.bidi === true
const sided = cell.align === 'left' || cell.align === 'right'
const align = paragraph.align ?? (bidi && sided ? undefined : cell.align)
const list = 'list' in paragraph ? paragraph.list : undefined
const numPr = list
? `<w:numPr><w:ilvl w:val="${list.ilvl}"/><w:numId w:val="${escapeXmlAttr(list.numId)}"/></w:numPr>`
: ''
// the parsed format, not just w:jc: hand-building it here dropped w:bidi and wrote the visual
// align back as the logical one, flipping RTL cells to LTR, and discarded every other
// paragraph property the model carries
const pPr = mergePPrFormat(`<w:pPr>${numPr}</w:pPr>`, { ...paragraph, align })
// no cell.align fallback here: it is a display aggregate of the paragraphs' own
// jc values, and writing it back would stamp w:jc into paragraphs that never had one
// (rich paragraphs carry their own align; the plain-paras fallback above sets it).
// The parsed format, not just w:jc: hand-building the pPr here dropped w:bidi and
// discarded every other paragraph property the model carries.
const pPr = mergePPrFormat(`<w:pPr>${numPr}</w:pPr>`, paragraph)
return `<w:p>${pPr}${runsXml(paragraph.runs, null)}</w:p>`
})
// nested tables are regenerated from the model at their paragraph anchors (reverse
@@ -1969,6 +1973,7 @@ const RUN_MANAGED_GROUPS: Array<{ key: string; tags: string[] }> = [
{ key: 'size', tags: ['w:sz', 'w:szCs'] },
{ key: 'highlight', tags: ['w:highlight'] },
{ key: 'underline', tags: ['w:u'] },
{ key: 'shading', tags: ['w:shd'] },
{ key: 'vertAlign', tags: ['w:vertAlign'] },
{ key: 'rPrChange', tags: ['w:rPrChange'] },
]
@@ -2077,6 +2082,12 @@ function modelRPrChildren(run: Run, insideLink: boolean): PPrChild[] {
if (run.highlight)
out.push({ name: 'w:highlight', xml: `<w:highlight w:val="${escapeXmlAttr(run.highlight)}"/>` })
if (run.underline) out.push({ name: 'w:u', xml: '<w:u w:val="single"/>' })
if (run.shading) {
out.push({
name: 'w:shd',
xml: `<w:shd w:val="clear" w:color="auto" w:fill="${escapeXmlAttr(run.shading)}"/>`,
})
}
if (run.vertAlign)
out.push({ name: 'w:vertAlign', xml: `<w:vertAlign w:val="${run.vertAlign}"/>` })
const rPrChange = revisionRPrChangeXml(run)
@@ -2100,6 +2111,9 @@ export function mergeRPrModel(rawRPr: string, run: Run, insideLink: boolean): st
const inner = rawRPr.slice(open.length, rawRPr.length - '</w:rPr>'.length)
const rawChildren = splitXmlChildren(inner)
const rawOf = (tag: string) => rawChildren.find((c) => c.name === tag)?.xml
// complex-script runs decode bold/italic/size from the Cs twins on the parse side;
// compare against the same elements or every untouched cs run would get "rebuilt"
const cs = run.cs ?? textHasComplexScript(run.text)
// Compare model vs raw-encoded values group by group; equal → keep the original bytes
// (drop the group from fresh)
@@ -2126,9 +2140,9 @@ export function mergeRPrModel(rawRPr: string, run: Run, insideLink: boolean): st
return (rawAttr(attrs, 'w:eastAsia') ?? ascii) === run.font && ascii === run.fontAscii
}
case 'bold':
return rawBool(rawOf('w:b')) === !!run.bold
return rawBool(rawOf(cs ? 'w:bCs' : 'w:b')) === !!run.bold
case 'italic':
return rawBool(rawOf('w:i')) === !!run.italic
return rawBool(rawOf(cs ? 'w:iCs' : 'w:i')) === !!run.italic
case 'strike':
return rawBool(rawOf('w:strike')) === !!run.strike
case 'color': {
@@ -2136,13 +2150,17 @@ export function mergeRPrModel(rawRPr: string, run: Run, insideLink: boolean): st
return (raw === 'auto' ? undefined : raw) === run.color
}
case 'size': {
const raw = rawAttr(rawOf('w:sz'), 'w:val')
const raw = rawAttr(rawOf(cs ? 'w:szCs' : 'w:sz'), 'w:val')
return (raw ? parseInt(raw, 10) || undefined : undefined) === run.sizeHalfPoints
}
case 'highlight': {
const raw = rawAttr(rawOf('w:highlight'), 'w:val')
return (raw === 'none' ? undefined : raw) === run.highlight
}
case 'shading': {
const raw = rawAttr(rawOf('w:shd'), 'w:fill')
return (raw && raw !== 'auto' ? raw : undefined) === run.shading
}
case 'underline': {
// w:u is not a boolean prop: no w:val (or val="none") means no
// underline, regardless of other attributes like w:color. Must match
+48 -16
View File
@@ -58,6 +58,7 @@ import {
findChildren,
nameOf,
serializeXNode,
textHasComplexScript,
textOf,
underlineProp,
xmlParser,
@@ -1033,6 +1034,10 @@ function buildTextParagraph(
rubyFragmentsOf(mathXml),
withImages,
)
if (runs.length === 0) {
const emptySz = emptyParaSizeHalfPoints(pNode, pPr)
if (emptySz) format = { ...(format ?? {}), emptyRunSizeHalfPoints: emptySz }
}
const { bookmarks, hiddenBookmarks } = bookmarkNamesOf(stripTextboxes(xml))
const { commentStarts, commentEnds } = crossParaCommentMarkers(stripTextboxes(xml))
@@ -2071,6 +2076,25 @@ function onlyXeFields(xml: string): boolean {
})
}
/**
* w:sz governing a run-less paragraph's line height: the paragraph-mark rPr
* (pPr/w:rPr), else the last run's rPr — those runs are all empty and get
* dropped, but Word still sizes the empty line by them (1pt spacer lines).
*/
function emptyParaSizeHalfPoints(pNode: XNode, pPr: XNode | undefined): number | undefined {
let sz = pPr
? attrsOf(findChild(findChild(pPr, 'w:rPr') ?? {}, 'w:sz') ?? {})['w:val']
: undefined
if (!sz) {
for (const r of findChildren(pNode, 'w:r')) {
const v = attrsOf(findChild(findChild(r, 'w:rPr') ?? {}, 'w:sz') ?? {})['w:val']
if (v) sz = v
}
}
const n = sz ? parseInt(sz, 10) : NaN
return Number.isFinite(n) && n > 0 ? n : undefined
}
function extractRuns(
pNode: XNode,
ctx: BuildContext,
@@ -2402,9 +2426,13 @@ function buildRun(
run.rawRPr = serializeXNode(rPr)
const rStyle = attrsOf(findChild(rPr, 'w:rStyle') ?? {})['w:val']
if (rStyle && rStyle !== 'Hyperlink') run.styleId = rStyle
const bold = onOffOf(rPr, 'w:b')
// complex-script runs take bold/italic/size from the Cs twins only: w:b/w:i/w:sz
// do not apply to them, and a missing twin means regular (no fallback), per OOXML
const cs = onOffOf(rPr, 'w:rtl') ?? textHasComplexScript(text)
if (cs) run.cs = true
const bold = onOffOf(rPr, cs ? 'w:bCs' : 'w:b')
if (bold !== undefined) run.bold = bold
const italic = onOffOf(rPr, 'w:i')
const italic = onOffOf(rPr, cs ? 'w:iCs' : 'w:i')
if (italic !== undefined) run.italic = italic
if (underlineProp(rPr)) run.underline = true
else if (attrsOf(findChild(rPr, 'w:u') ?? {})['w:val'] === 'none') run.underline = false
@@ -2412,7 +2440,7 @@ function buildRun(
if (strike !== undefined) run.strike = strike
const color = colorFrom(rPr, theme)
if (color) run.color = color
const sz = attrsOf(findChild(rPr, 'w:sz') ?? {})['w:val']
const sz = attrsOf(findChild(rPr, cs ? 'w:szCs' : 'w:sz') ?? {})['w:val']
if (sz) run.sizeHalfPoints = parseInt(sz, 10) || undefined
const rf = themedRFonts(attrsOf(findChild(rPr, 'w:rFonts') ?? {}), themeFonts)
const font = rf.eastAsia ?? rf.ascii ?? rf.hAnsi
@@ -2427,6 +2455,8 @@ function buildRun(
if (wScale > 0 && wScale !== 100) run.charScalePct = wScale
const highlight = attrsOf(findChild(rPr, 'w:highlight') ?? {})['w:val']
if (highlight && highlight !== 'none') run.highlight = highlight
const shdFill = attrsOf(findChild(rPr, 'w:shd') ?? {})['w:fill']
if (shdFill && shdFill !== 'auto') run.shading = shdFill
const vertAlign = attrsOf(findChild(rPr, 'w:vertAlign') ?? {})['w:val']
if (vertAlign === 'superscript' || vertAlign === 'subscript') run.vertAlign = vertAlign
const em = attrsOf(findChild(rPr, 'w:em') ?? {})['w:val']
@@ -2504,6 +2534,8 @@ function sameStyle(a: Run, b: Run): boolean {
return (
(a.rawRPr ?? '') === (b.rawRPr ?? '') &&
a.styleId === b.styleId &&
// same rPr can decode differently for cs vs non-cs text; merging would misapply the twins
!!a.cs === !!b.cs &&
!!a.bold === !!b.bold &&
!!a.italic === !!b.italic &&
!!a.underline === !!b.underline &&
@@ -2888,6 +2920,7 @@ function extractCell(tc: XNode, ctx: BuildContext): TableCell {
let sawBold = false
let sawNonBold = false
const runColors = new Set<string>()
const textParaJcs = new Set<string>()
for (const block of childrenThroughSdt(tc, ['w:p', 'w:tbl'])) {
if (nameOf(block) === 'w:tbl') {
const model = extractTableModel(block, ctx)
@@ -2898,7 +2931,8 @@ function extractCell(tc: XNode, ctx: BuildContext): TableCell {
continue
}
const p = block
cell.paras.push(textOf(p))
const paraText = textOf(p)
cell.paras.push(paraText)
const pPr = findChild(p, 'w:pPr')
const format = extractParaFormat(pPr ?? {})
const cellStyleId = pPr ? attrsOf(findChild(pPr, 'w:pStyle') ?? {})['w:val'] : undefined
@@ -2910,17 +2944,15 @@ function extractCell(tc: XNode, ctx: BuildContext): TableCell {
ilvl: cellRef.ilvl,
}
: undefined
const runs = extractRuns(p, ctx, [], [], true)
const emptySz = runs.length === 0 ? emptyParaSizeHalfPoints(p, pPr) : undefined
richParas.push({
...format,
...(emptySz ? { emptyRunSizeHalfPoints: emptySz } : {}),
...(list ? { list } : {}),
runs: extractRuns(p, ctx, [], [], true),
runs,
})
if (!cell.align) {
const jc = attrsOf(findChild(findChild(p, 'w:pPr') ?? {}, 'w:jc') ?? {})['w:val']
if (jc === 'center' || jc === 'right' || jc === 'left' || jc === 'justify') {
cell.align = jc
}
}
if (paraText !== '') textParaJcs.add(attrsOf(findChild(pPr ?? {}, 'w:jc') ?? {})['w:val'] ?? '')
for (const r of findChildren(p, 'w:r')) {
const rPr = findChild(r, 'w:rPr')
if (rPr && boolProp(rPr, 'w:b')) sawBold = true
@@ -2928,15 +2960,15 @@ function extractCell(tc: XNode, ctx: BuildContext): TableCell {
if (textOf(r) !== '') runColors.add((rPr && colorFrom(rPr, ctx.themeColors)) ?? 'none')
}
}
// drop trailing empty paragraphs so cells don't get artificially tall
while (cell.paras.length > 1 && cell.paras[cell.paras.length - 1] === '') {
cell.paras.pop()
richParas.pop()
// cell.align only when every text paragraph declares the same jc; a first-wins
// td-level text-align would leak onto the cell's jc-less paragraphs
if (textParaJcs.size === 1) {
const jc = textParaJcs.values().next().value
if (jc === 'center' || jc === 'right' || jc === 'left' || jc === 'justify') cell.align = jc
}
cell.richParas = richParas
if (nested.length > 0) {
cell.nestedTables = nested
// clamp anchors that pointed past the trimmed tail
cell.nestedTableAnchors = nestedAnchors.map((a) => Math.min(a, cell.paras.length))
}
if (sawBold && !sawNonBold) cell.bold = true
+3
View File
@@ -1580,6 +1580,9 @@ function retargetImageBlip(xml: string, rId: string): string {
return (
(xml.slice(0, blip.index) + tag + xml.slice(blip.index + blip[0].length))
.replace(/<a:srcRect\b[^>]*\/>/, '')
// A non-default fill window would clip the swapped bytes the same way a
// crop would — reset it (the editor clears its imageFillRect in step)
.replace(/<a:fillRect\b[^>]+\/>/, '<a:fillRect/>')
// The replacement is always raster and Word prefers a leftover Office-2016
// <asvg:svgBlip> extension over the retargeted r:embed — drop the extension
.replace(/<a:ext\b[^>]*>\s*<\w+:svgBlip\b[\s\S]*?<\/a:ext>/, '')
+10
View File
@@ -43,6 +43,10 @@ export interface Run {
charScalePct?: number
/** OOXML named highlight color (w:highlight), e.g. "yellow" */
highlight?: string
/** character shading fill, hex without '#' (w:shd w:fill, non-auto); highlight wins when both are set */
shading?: string
/** bold/italic/size were read from the Cs twins (w:bCs/w:iCs/w:szCs): w:rtl run or complex-script text */
cs?: boolean
/** superscript / subscript (w:vertAlign) */
vertAlign?: 'superscript' | 'subscript'
/** East Asian emphasis mark (w:em). Display only; saving is kept faithful by rawRPr */
@@ -239,6 +243,12 @@ export interface ParaFormat {
* visual direction and writing back converts again.
*/
bidi?: boolean
/**
* w:sz (half-points) governing a run-less paragraph's line height: the
* paragraph-mark rPr, else the last (dropped) empty run's rPr. Set only when
* the paragraph has no runs, so empty lines keep their Word height.
*/
emptyRunSizeHalfPoints?: number
}
/**
+7
View File
@@ -120,3 +120,10 @@ export function escapeXmlText(text: string): string {
export function escapeXmlAttr(text: string): string {
return escapeXmlText(text).replace(/"/g, '&quot;')
}
/** Text contains complex-script characters (Arabic/Hebrew/Syriac/Thaana/NKo), i.e. the w:*Cs run properties apply */
export function textHasComplexScript(text: string): boolean {
return /[\u0590-\u05FF\u0600-\u077F\u0780-\u07FF\u08A0-\u08FF\uFB1D-\uFDFF\uFE70-\uFEFF]/.test(
text,
)
}
@@ -49,7 +49,7 @@ describe('nested table editing (surgical text patch + regeneration)', () => {
expect(xml).toContain('InnerA')
expect(xml).toContain('InnerB')
// nested table is followed by an empty paragraph (OOXML: tc must end with w:p)
expect(/<\/w:tbl><w:p\/><\/w:tc>/.test(xml)).toBe(true)
expect(/<\/w:tbl><w:p(?:\/>|><\/w:p>)<\/w:tc>/.test(xml)).toBe(true)
// reparsing still yields the nested structure
const saved = await saveDocx(doc, [{ kind: 'xml', xml }])
const reparsed = await parseDocx(saved)
@@ -60,7 +60,8 @@ describe('nested table editing (surgical text patch + regeneration)', () => {
it('parses paragraph anchors for interleaved nested tables and regenerates in reading order', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: INTERLEAVED_TABLE_XML }))
const cell = doc.blocks[0].table!.rows[0][0]
expect(cell.paras).toEqual(['Title1', 'Title2'])
// the trailing empty paragraph is kept: Word renders it as a visible line
expect(cell.paras).toEqual(['Title1', 'Title2', ''])
expect(cell.nestedTableAnchors).toEqual([1, 2])
const xml = generateTableModelXml(doc.blocks[0].table!)
@@ -68,7 +69,7 @@ describe('nested table editing (surgical text patch + regeneration)', () => {
expect(order.every((idx) => idx >= 0)).toBe(true)
expect([...order].sort((a, b) => a - b)).toEqual(order)
// trailing nested table is still followed by an empty paragraph
expect(/<\/w:tbl><w:p\/><\/w:tc>/.test(xml)).toBe(true)
expect(/<\/w:tbl><w:p(?:\/>|><\/w:p>)<\/w:tc>/.test(xml)).toBe(true)
// reparse of the regenerated table keeps the anchors
const reparsed = await parseDocx(await saveDocx(doc, [{ kind: 'xml', xml }]))
+17 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import { parseDocx } from '../src/index'
import { buildKitchenSinkDocx } from './helpers/build-docx'
import { buildDocx, buildKitchenSinkDocx } from './helpers/build-docx'
describe('parseDocx', () => {
it('parses the kitchen-sink document into anchored blocks', async () => {
@@ -147,3 +147,19 @@ describe('parseDocx', () => {
])
})
})
describe('empty paragraph line size', () => {
it('records the w:sz that governs a run-less paragraph', async () => {
const bodyXml =
'<w:p><w:r><w:t>before</w:t></w:r></w:p>' +
// paragraph-mark rPr wins
'<w:p><w:pPr><w:rPr><w:sz w:val="2"/></w:rPr></w:pPr><w:r><w:rPr><w:sz w:val="4"/></w:rPr><w:t></w:t></w:r></w:p>' +
// no pPr rPr: falls back to the (dropped) empty run
'<w:p><w:r><w:rPr><w:sz w:val="16"/></w:rPr><w:t></w:t></w:r></w:p>'
const doc = await parseDocx(await buildDocx({ bodyXml }))
expect(doc.blocks[0].format?.emptyRunSizeHalfPoints).toBeUndefined()
expect(doc.blocks[1].runs).toEqual([])
expect(doc.blocks[1].format?.emptyRunSizeHalfPoints).toBe(2)
expect(doc.blocks[2].format?.emptyRunSizeHalfPoints).toBe(16)
})
})
@@ -93,3 +93,23 @@ describe('explicit w:after="0"', () => {
expect(out).toBe('<w:pPr><w:spacing w:after="0"/></w:pPr>')
})
})
describe('empty-paragraph size write-back (pPr w:rPr)', () => {
it('inserts a fresh paragraph-mark rPr when the model carries a size', () => {
expect(mergePPrFormat('<w:pPr></w:pPr>', { emptyRunSizeHalfPoints: 2 })).toBe(
'<w:pPr><w:rPr><w:sz w:val="2"/><w:szCs w:val="2"/></w:rPr></w:pPr>',
)
})
it('keeps the original paragraph-mark rPr bytes when the size is unchanged', () => {
const raw = '<w:pPr><w:rPr><w:rFonts w:ascii="Georgia"/><w:sz w:val="2"/></w:rPr></w:pPr>'
expect(mergePPrFormat(raw, { emptyRunSizeHalfPoints: 2 })).toBe(raw)
})
it('leaves the paragraph-mark rPr unmanaged when the model has no size', () => {
const raw = '<w:pPr><w:rPr><w:b/><w:sz w:val="28"/></w:rPr></w:pPr>'
expect(mergePPrFormat(raw, { align: 'center' })).toBe(
'<w:pPr><w:jc w:val="center"/><w:rPr><w:b/><w:sz w:val="28"/></w:rPr></w:pPr>',
)
})
})
+101 -12
View File
@@ -4,7 +4,13 @@
* rebuilds; editing a modeled field rebuilds only its group.
*/
import { describe, expect, it } from 'vitest'
import { generateParagraphXml, parseDocx, saveDocx, type GenerateContext, type SaveBlock } from '../src/index'
import {
generateParagraphXml,
parseDocx,
saveDocx,
type GenerateContext,
type SaveBlock,
} from '../src/index'
import { buildDocx } from './helpers/build-docx'
import { existsSync, readFileSync } from 'node:fs'
import { join, dirname } from 'node:path'
@@ -33,9 +39,14 @@ const RICH_RPR =
const RICH_PARA = `<w:p><w:r>${RICH_RPR}<w:t>富格式文本</w:t></w:r></w:p>`
const UNMODELED_TAGS = [
'<w:caps/>', '<w:dstrike/>', '<w:vanish/>',
'<w:caps/>',
'<w:dstrike/>',
'<w:vanish/>',
'w:themeColor="accent1"',
'<w:spacing w:val="20"/>', '<w:w w:val="90"/>', '<w:kern w:val="24"/>', '<w:position w:val="6"/>',
'<w:spacing w:val="20"/>',
'<w:w w:val="90"/>',
'<w:kern w:val="24"/>',
'<w:position w:val="6"/>',
'<w:szCs w:val="32"/>',
'<w:u w:val="double"/>',
'<w:bdr w:val="single" w:sz="4" w:space="1" w:color="auto"/>',
@@ -63,10 +74,7 @@ describe('rawRPr passthrough', () => {
const run = doc.blocks[0].runs![0]
// Add bold (not there originally): w:b is inserted at its schema position, the other
// groups keep their original bytes
const xml = generateParagraphXml(
{ type: 'paragraph', runs: [{ ...run, bold: true }] },
GEN_CTX,
)
const xml = generateParagraphXml({ type: 'paragraph', runs: [{ ...run, bold: true }] }, GEN_CTX)
expect(xml).toContain('<w:b/>')
// schema order: rFonts < b < caps
expect(xml.indexOf('<w:rFonts')).toBeLessThan(xml.indexOf('<w:b/>'))
@@ -107,15 +115,22 @@ describe('rawRPr passthrough', () => {
it('adjacent runs with different unmodeled props are not merged at parse', async () => {
const body =
'<w:p><w:r><w:rPr><w:caps/></w:rPr><w:t>大写</w:t></w:r>' +
'<w:r><w:t>普通</w:t></w:r></w:p>'
'<w:p><w:r><w:rPr><w:caps/></w:rPr><w:t>大写</w:t></w:r>' + '<w:r><w:t>普通</w:t></w:r></w:p>'
const doc = await parseDocx(await buildDocx({ bodyXml: body }))
expect(doc.blocks[0].runs).toHaveLength(2) // modeled fields all equal, but rawRPr differs → no merge
})
})
const here = dirname(fileURLToPath(import.meta.url))
const REAL = join(here, '..', '..', '..', 'example', 'docx', 'OpenClaw开源项目调研分析报告文档.docx')
const REAL = join(
here,
'..',
'..',
'..',
'example',
'docx',
'OpenClaw开源项目调研分析报告文档.docx',
)
// Runs only when the local (gitignored) sample document is present.
describe.skipIf(!existsSync(REAL))('real document invariant (example/docx)', () => {
@@ -154,7 +169,9 @@ describe.skipIf(!existsSync(REAL))('real document invariant (example/docx)', ()
const JSZip = (await import('jszip')).default
const [zBefore, zAfter] = await Promise.all([JSZip.loadAsync(bytes), JSZip.loadAsync(saved)])
const fileNames = (z: InstanceType<typeof JSZip>) =>
Object.keys(z.files).filter((n) => !z.files[n].dir).sort()
Object.keys(z.files)
.filter((n) => !z.files[n].dir)
.sort()
expect(fileNames(zAfter)).toEqual(fileNames(zBefore))
for (const name of fileNames(zBefore)) {
// core.xml is the exception: a real save updates dcterms:modified / cp:revision
@@ -167,7 +184,9 @@ describe.skipIf(!existsSync(REAL))('real document invariant (example/docx)', ()
}
// Untouched paragraphs' original slices remain; the edited one keeps its character spacing
const newXml = new TextDecoder().decode(await zAfter.files['word/document.xml'].async('uint8array'))
const newXml = new TextDecoder().decode(
await zAfter.files['word/document.xml'].async('uint8array'),
)
let checked = 0
for (const b of visible) {
if (b === target || !b.originalXml || b.originalXml.length < 40) continue
@@ -188,3 +207,73 @@ describe.skipIf(!existsSync(REAL))('real document invariant (example/docx)', ()
expect(reparsed.blocks.length).toBe(doc.blocks.length)
})
})
describe('complex-script runs read the Cs twins (w:bCs/w:iCs/w:szCs)', () => {
it('w:b / w:sz do not apply to Arabic text; the Cs twins do', async () => {
const bodyXml =
'<w:p><w:r><w:rPr><w:b/><w:sz w:val="28"/></w:rPr><w:t>عنوان</w:t></w:r></w:p>' +
'<w:p><w:r><w:rPr><w:bCs/><w:iCs/><w:szCs w:val="36"/></w:rPr><w:t>عنوان</w:t></w:r></w:p>' +
'<w:p><w:r><w:rPr><w:b/><w:sz w:val="28"/></w:rPr><w:t>latin</w:t></w:r></w:p>'
const doc = await parseDocx(await buildDocx({ bodyXml }))
const [bOnly, csTwins, latin] = doc.blocks.filter((b) => b.runs?.length).map((b) => b.runs![0])
expect(bOnly.cs).toBe(true)
expect(bOnly.bold).toBeUndefined()
expect(bOnly.sizeHalfPoints).toBeUndefined()
expect(csTwins.bold).toBe(true)
expect(csTwins.italic).toBe(true)
expect(csTwins.sizeHalfPoints).toBe(36)
expect(latin.cs).toBeUndefined()
expect(latin.bold).toBe(true)
expect(latin.sizeHalfPoints).toBe(28)
})
it('w:rtl marks a run complex-script regardless of its characters', async () => {
const bodyXml = '<w:p><w:r><w:rPr><w:rtl/><w:b/></w:rPr><w:t>123</w:t></w:r></w:p>'
const doc = await parseDocx(await buildDocx({ bodyXml }))
expect(doc.blocks[0].runs![0].cs).toBe(true)
expect(doc.blocks[0].runs![0].bold).toBeUndefined()
})
it('an untouched Arabic run keeps its w:b/w:sz bytes on paragraph rebuild', async () => {
const bodyXml = '<w:p><w:r><w:rPr><w:b/><w:sz w:val="28"/></w:rPr><w:t>عنوان</w:t></w:r></w:p>'
const doc = await parseDocx(await buildDocx({ bodyXml }))
const run = doc.blocks[0].runs![0]
const xml = generateParagraphXml({ type: 'paragraph', runs: [{ ...run }] }, GEN_CTX)
expect(xml).toContain('<w:b/>')
expect(xml).toContain('<w:sz w:val="28"/>')
expect(xml).not.toContain('<w:bCs/>')
})
})
describe('run-level character shading (w:shd)', () => {
it('parses the non-auto fill alongside highlight', async () => {
const bodyXml =
'<w:p><w:r><w:rPr><w:shd w:val="clear" w:color="auto" w:fill="FFC000"/></w:rPr><w:t>badge</w:t></w:r>' +
'<w:r><w:rPr><w:highlight w:val="yellow"/><w:shd w:val="clear" w:fill="FFC000"/></w:rPr><w:t>both</w:t></w:r>' +
'<w:r><w:rPr><w:shd w:val="clear" w:fill="auto"/></w:rPr><w:t>none</w:t></w:r></w:p>'
const doc = await parseDocx(await buildDocx({ bodyXml }))
const runs = doc.blocks[0].runs!
expect(runs[0].shading).toBe('FFC000')
expect(runs[1].shading).toBe('FFC000')
expect(runs[1].highlight).toBe('yellow')
expect(runs[2].shading).toBeUndefined()
})
it('unchanged shading keeps its exact bytes; a modeled value writes fresh', async () => {
const bodyXml =
'<w:p><w:r><w:rPr><w:shd w:val="pct15" w:color="FF0000" w:fill="FFC000"/></w:rPr><w:t>x</w:t></w:r></w:p>'
const doc = await parseDocx(await buildDocx({ bodyXml }))
const run = doc.blocks[0].runs![0]
expect(run.shading).toBe('FFC000')
const kept = generateParagraphXml(
{ type: 'paragraph', runs: [{ ...run, text: 'edited' }] },
GEN_CTX,
)
expect(kept).toContain('<w:shd w:val="pct15" w:color="FF0000" w:fill="FFC000"/>')
const fresh = generateParagraphXml(
{ type: 'paragraph', runs: [{ text: 'z', shading: '00B050' }] },
GEN_CTX,
)
expect(fresh).toContain('<w:shd w:val="clear" w:color="auto" w:fill="00B050"/>')
})
})
@@ -42,7 +42,12 @@ describe('table display model', () => {
const header = table.rows[0]
expect(header.map((c) => c.paras[0])).toEqual(['排名', '品牌', '份额'])
expect(header[0]).toMatchObject({ fill: '1F3864', color: 'FFFFFF', bold: true, align: 'center' })
expect(header[0]).toMatchObject({
fill: '1F3864',
color: 'FFFFFF',
bold: true,
align: 'center',
})
const dataRow = table.rows[1]
expect(dataRow[1].colSpan).toBe(2)
@@ -143,3 +148,35 @@ describe('table display model', () => {
expect(table.cellMarTwips).toEqual({ left: 200, right: 200 })
})
})
describe('cell alignment aggregation and trailing empty paragraphs', () => {
it('sets cell.align only when every text paragraph declares the same jc', async () => {
const xml =
'<w:tbl><w:tblGrid><w:gridCol w:w="3000"/><w:gridCol w:w="3000"/></w:tblGrid><w:tr>' +
// centered title + jc-less body: a td-level center would leak onto the body
'<w:tc><w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t>标题</w:t></w:r></w:p>' +
'<w:p><w:r><w:t>要点</w:t></w:r></w:p></w:tc>' +
// all text paragraphs agree (the empty one does not vote)
'<w:tc><w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t>甲</w:t></w:r></w:p>' +
'<w:p/>' +
'<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t>乙</w:t></w:r></w:p></w:tc>' +
'</w:tr></w:tbl>'
const doc = await parseDocx(await buildDocx({ bodyXml: xml }))
const [mixed, agreed] = doc.blocks[0].table!.rows[0]
expect(mixed.align).toBeUndefined()
expect(agreed.align).toBe('center')
})
it('keeps trailing empty cell paragraphs and their empty-run size', async () => {
const xml =
'<w:tbl><w:tblGrid><w:gridCol w:w="3000"/></w:tblGrid><w:tr><w:tc>' +
'<w:p><w:r><w:t>内容</w:t></w:r></w:p>' +
'<w:p><w:pPr><w:rPr><w:sz w:val="2"/></w:rPr></w:pPr></w:p>' +
'</w:tc></w:tr></w:tbl>'
const doc = await parseDocx(await buildDocx({ bodyXml: xml }))
const cell = doc.blocks[0].table!.rows[0][0]
expect(cell.paras).toEqual(['内容', ''])
expect(cell.richParas?.[1].emptyRunSizeHalfPoints).toBe(2)
expect(cell.richParas?.[1].runs).toEqual([])
})
})
+34 -7
View File
@@ -301,20 +301,20 @@ describe('cell paragraph properties survive a table rebuild', () => {
expect(out).toContain('<w:shd w:val="clear" w:color="auto" w:fill="DDEEFF"/>')
})
it('still falls back to the cell alignment for a paragraph that declared none', async () => {
// control: this case is unchanged from before, and passes with or without the fix
it("does not stamp another paragraph's alignment onto one that declared none", async () => {
// mixed jc: no cell-level alignment, and the jc-less paragraph must stay that way
const out = await rebuild(
'<w:tbl><w:tblGrid><w:gridCol w:w="4000"/></w:tblGrid><w:tr><w:tc>' +
'<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t>a</w:t></w:r></w:p>' +
'<w:p><w:r><w:t>b</w:t></w:r></w:p>' +
'</w:tc></w:tr></w:tbl>',
)
expect(out.match(/<w:jc w:val="center"\/>/g)).toHaveLength(2)
expect(out.match(/<w:jc w:val="center"\/>/g)).toHaveLength(1)
const second = out.slice(out.lastIndexOf('<w:p>'))
expect(second).not.toContain('<w:jc ')
})
it('keeps a direction-neutral cell alignment on a bidi paragraph', async () => {
// only left/right are swapped between logical and visual, so centre and justify are safe
// to take from the cell even when the paragraph is RTL
it('keeps a bidi paragraph free of alignment it never declared', async () => {
const out = await rebuild(
'<w:tbl><w:tblGrid><w:gridCol w:w="4000"/></w:tblGrid><w:tr><w:tc>' +
'<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t>a</w:t></w:r></w:p>' +
@@ -323,6 +323,33 @@ describe('cell paragraph properties survive a table rebuild', () => {
)
const second = out.slice(out.lastIndexOf('<w:p>'))
expect(second).toContain('<w:bidi/>')
expect(second).toContain('<w:jc w:val="center"/>')
expect(second).not.toContain('<w:jc ')
})
it("writes every paragraph's jc back when they all agree (cell.align set)", async () => {
const out = await rebuild(
'<w:tbl><w:tblGrid><w:gridCol w:w="4000"/></w:tblGrid><w:tr><w:tc>' +
'<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t>a</w:t></w:r></w:p>' +
'<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t>b</w:t></w:r></w:p>' +
'</w:tc></w:tr></w:tbl>',
)
expect(out.match(/<w:jc w:val="center"\/>/g)).toHaveLength(2)
})
})
describe('trailing empty cell paragraph size survives regeneration', () => {
it('writes the empty paragraph and its w:sz back', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml:
'<w:tbl><w:tblGrid><w:gridCol w:w="3000"/></w:tblGrid><w:tr><w:tc>' +
'<w:p><w:r><w:t>内容</w:t></w:r></w:p>' +
'<w:p><w:pPr><w:rPr><w:sz w:val="2"/></w:rPr></w:pPr></w:p>' +
'</w:tc></w:tr></w:tbl>',
}),
)
const out = generateTableModelXml(doc.blocks[0].table!)
expect(out.match(/<w:p[\s>]|<w:p\/>/g)).toHaveLength(2)
expect(out).toContain('<w:pPr><w:rPr><w:sz w:val="2"/><w:szCs w:val="2"/></w:rPr></w:pPr>')
})
})
+20
View File
@@ -0,0 +1,20 @@
{
"name": "@genoffice/font-metrics",
"version": "0.1.0",
"license": "Apache-2.0",
"private": true,
"type": "module",
"description": "System font location and vertical-metrics extraction for the Electron main processes (targeted sfnt table reads, no whole-file parsing)",
"exports": {
".": "./src/index.ts"
},
"scripts": {
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test:watch": "vitest"
},
"devDependencies": {
"typescript": "^5.9.3",
"vitest": "^4.1.0"
}
}
+68
View File
@@ -0,0 +1,68 @@
/**
* Locate an installed font matching a PDF font's PostScript name (nameID 6) or family
* (nameID 1/16), for text-edit rebuilds that keep the original typeface.
*/
import { readFileSync } from 'node:fs'
import { getFontIndex, norm, styleScore, styleTokens, OTTO_TAG, TTC_TAG } from './sfnt'
/** Picks FPDFText_LoadFont's font_type: glyf faces embed as FontFile2 (TRUETYPE),
CFF faces as FontFile3 (TYPE1) */
export const isTruetype = (b: Buffer): boolean => b.length >= 4 && b.readUInt32BE(0) !== OTTO_TAG
/** Extract a single face from a ttc into a standalone sfnt (rewrite the table directory,
copy table data; passthrough for plain ttf) */
function extractFace(buf: Buffer, offset: number): Buffer {
if (buf.readUInt32BE(0) !== TTC_TAG) return buf
const numTables = buf.readUInt16BE(offset + 4)
let total = 12 + 16 * numTables
const entries: Array<{ dirPos: number; tOff: number; tLen: number; newOff: number }> = []
for (let t = 0; t < numTables; t++) {
const e = offset + 12 + 16 * t
const tLen = buf.readUInt32BE(e + 12)
entries.push({ dirPos: e, tOff: buf.readUInt32BE(e + 8), tLen, newOff: total })
total += (tLen + 3) & ~3
}
const out = Buffer.alloc(total)
buf.copy(out, 0, offset, offset + 12)
for (let t = 0; t < numTables; t++) {
const e = entries[t]!
buf.copy(out, 12 + 16 * t, e.dirPos, e.dirPos + 8)
out.writeUInt32BE(e.newOff, 12 + 16 * t + 8)
out.writeUInt32BE(e.tLen, 12 + 16 * t + 12)
buf.copy(out, e.newOff, e.tOff, e.tOff + e.tLen)
}
return out
}
const faceCache = new Map<string, Buffer>()
/**
* Standalone sfnt bytes of the installed font best matching (psName, family):
* exact PostScript name first, then family with the PS name's style tokens
* (Regular preferred when there are none). Null when nothing matches.
*/
export function findSystemFont(psName: string, family: string): Buffer | null {
const index = getFontIndex()
let face = psName ? index.byPs.get(norm(psName)) : undefined
if (!face && family) {
const candidates = index.byFamily.get(norm(family))
if (candidates?.length) {
const want = styleTokens(psName)
face = [...candidates].sort((a, b) => styleScore(b, want) - styleScore(a, want))[0]
}
}
if (!face) return null
const key = `${face.path}#${face.offset}`
let bytes = faceCache.get(key)
if (!bytes) {
try {
bytes = extractFace(readFileSync(face.path), face.offset)
} catch {
return null
}
if (faceCache.size >= 4) faceCache.clear()
faceCache.set(key, bytes)
}
return bytes
}
+2
View File
@@ -0,0 +1,2 @@
export { findSystemFont, isTruetype } from './font-locate'
export { configureMetricsCache, familyVerticalMetrics, type FaceVerticalMetrics } from './metrics'
+163
View File
@@ -0,0 +1,163 @@
/**
* Vertical metrics of installed fonts, resolved by exact family name (nameID
* 1/16, all languages, normalized) — never fuzzy: a wrong-font match is worse
* than a miss, the caller's heuristic fallback handles misses.
*
* Both metric groups are returned: Word uses win metrics unless OS/2
* fsSelection bit 7 (USE_TYPO_METRICS) is set, in which case it honors the
* typo group — deciding is the consumer's policy, not this package's.
*/
import { closeSync, mkdirSync, openSync, readFileSync, statSync, writeFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { getFontIndex, norm, readTable, readTableDir, styleScore } from './sfnt'
export interface FaceVerticalMetrics {
unitsPerEm: number
hheaAscender: number
hheaDescender: number
hheaLineGap: number
typoAscender: number | null
typoDescender: number | null
typoLineGap: number | null
winAscent: number | null
winDescent: number | null
/** OS/2 fsSelection bit 7 (USE_TYPO_METRICS) */
useTypoMetrics: boolean
}
function parseFaceMetrics(fd: number, offset: number): FaceVerticalMetrics | null {
const tables = readTableDir(fd, offset)
if (!tables) return null
// head 54B / hhea 36B / OS/2 ≤ ~100B: bounded targeted reads, like the name index
const head = readTable(fd, tables, 'head', 512)
const hhea = readTable(fd, tables, 'hhea', 512)
if (!head || head.length < 20 || !hhea || hhea.length < 10) return null
const unitsPerEm = head.readUInt16BE(18)
if (unitsPerEm === 0) return null
const os2 = readTable(fd, tables, 'OS/2', 512)
const hasTypo = !!os2 && os2.length >= 74
const hasWin = !!os2 && os2.length >= 78
return {
unitsPerEm,
hheaAscender: hhea.readInt16BE(4),
hheaDescender: hhea.readInt16BE(6),
hheaLineGap: hhea.readInt16BE(8),
typoAscender: hasTypo ? os2.readInt16BE(68) : null,
typoDescender: hasTypo ? os2.readInt16BE(70) : null,
typoLineGap: hasTypo ? os2.readInt16BE(72) : null,
winAscent: hasWin ? os2.readUInt16BE(74) : null,
winDescent: hasWin ? os2.readUInt16BE(76) : null,
useTypoMetrics: !!os2 && os2.length >= 64 && (os2.readUInt16BE(62) & 0x80) !== 0,
}
}
interface CacheEntry {
path: string
offset: number
mtimeMs: number
size: number
/** null = family known to be uninstalled at (re)build time; revalidated per process */
m: FaceVerticalMetrics | null
}
let cacheFile: string | null = null
let persisted: Record<string, CacheEntry> | null = null
const misses = new Set<string>()
/** Point the persistent cache at a directory (e.g. Electron userData); optional. */
export function configureMetricsCache(dir: string): void {
cacheFile = join(dir, 'font-vertical-metrics.json')
persisted = null
misses.clear()
}
function loadCache(): Record<string, CacheEntry> {
if (persisted) return persisted
persisted = {}
if (cacheFile) {
try {
const parsed: unknown = JSON.parse(readFileSync(cacheFile, 'utf8'))
if (parsed && typeof parsed === 'object') persisted = parsed as Record<string, CacheEntry>
} catch {
/* absent or corrupt cache: rebuild lazily */
}
}
return persisted
}
function saveCache(): void {
if (!cacheFile || !persisted) return
try {
mkdirSync(dirname(cacheFile), { recursive: true })
writeFileSync(cacheFile, JSON.stringify(persisted))
} catch {
/* cache is an optimization; queries still work without it */
}
}
function cacheValid(entry: CacheEntry): boolean {
try {
const st = statSync(entry.path)
return st.mtimeMs === entry.mtimeMs && st.size === entry.size
} catch {
return false
}
}
/**
* Vertical metrics of the installed family's Regular-ish face, or null when the
* family is not installed (exact normalized-name match only). Results persist
* across runs keyed by font path+mtime+size; installed-set changes invalidate
* naturally (missing families are only cached per process).
*/
export function familyVerticalMetrics(family: string): FaceVerticalMetrics | null {
const key = norm(family)
if (!key) return null
if (misses.has(key)) return null
const cache = loadCache()
const hit = cache[key]
if (hit && cacheValid(hit)) return hit.m
const candidates = getFontIndex().byFamily.get(key)
const face = candidates?.length
? [...candidates].sort((a, b) => styleScore(b, []) - styleScore(a, []))[0]
: undefined
if (!face) {
misses.add(key)
if (hit) {
delete cache[key]
saveCache()
}
return null
}
let metrics: FaceVerticalMetrics | null = null
let st: { mtimeMs: number; size: number } | null = null
let parsed = false
try {
st = statSync(face.path)
const fd = openSync(face.path, 'r')
try {
// a null here is deterministic (non-sfnt face / missing tables) and safe
// to persist; thrown reads are transient (Windows font locks) and are not
metrics = parseFaceMetrics(fd, face.offset)
parsed = true
} finally {
closeSync(fd)
}
} catch {
/* transient stat/open/read failure: no cache write, retried next call */
}
if (st && parsed) {
cache[key] = {
path: face.path,
offset: face.offset,
mtimeMs: st.mtimeMs,
size: st.size,
m: metrics,
}
saveCache()
}
return metrics
}
+252
View File
@@ -0,0 +1,252 @@
/**
* Shared sfnt/ttc plumbing: system font directory scan, per-face name-table
* index, and targeted table reads. Everything works from small fd reads of the
* tables it needs — CJK collections run 100MB+ (PingFang.ttc ~180MB), so
* whole-file reads at scan time are not an option.
*/
import { closeSync, openSync, readdirSync, readSync, statSync } from 'node:fs'
import type { Dirent } from 'node:fs'
import { homedir } from 'node:os'
import { join } from 'node:path'
export const norm = (s: string) =>
s
.normalize('NFKC')
.toLowerCase()
.replace(/[\s\-_]/g, '')
function fontDirs(): string[] {
switch (process.platform) {
case 'darwin':
return [
'/System/Library/Fonts',
'/System/Library/Fonts/Supplemental',
'/Library/Fonts',
join(homedir(), 'Library/Fonts'),
// On-demand system font assets: PingFang and other CJK faces live here on
// recent macOS ( <hash>.asset/AssetData/*.ttc ), not under /System/Library/Fonts
'/System/Library/AssetsV2/com_apple_MobileAsset_Font7',
'/System/Library/AssetsV2/com_apple_MobileAsset_Font6',
]
case 'win32':
return ['C:\\Windows\\Fonts', join(homedir(), 'AppData/Local/Microsoft/Windows/Fonts')]
default:
return ['/usr/share/fonts', '/usr/local/share/fonts', join(homedir(), '.fonts')]
}
}
export const TTC_TAG = 0x74746366 // 'ttcf'
export const OTTO_TAG = 0x4f54544f // CFF-flavored sfnt (e.g. PingFang on recent macOS)
const SFNT_FLAVORS = new Set([0x00010000, 0x74727565, OTTO_TAG]) // 1.0 / 'true' / 'OTTO'
export function readAt(fd: number, pos: number, len: number): Buffer {
const buf = Buffer.alloc(len)
if (readSync(fd, buf, 0, len, pos) !== len) throw new Error('short read')
return buf
}
export interface FaceNames {
ps: string[]
families: string[]
subfamilies: string[]
}
function parseNames(buf: Buffer): FaceNames {
const out: FaceNames = { ps: [], families: [], subfamilies: [] }
const count = buf.readUInt16BE(2)
const strBase = buf.readUInt16BE(4)
for (let i = 0; i < count; i++) {
const r = 6 + 12 * i
if (r + 12 > buf.length) break
const platform = buf.readUInt16BE(r)
const encoding = buf.readUInt16BE(r + 2)
const nameId = buf.readUInt16BE(r + 6)
const list =
nameId === 6
? out.ps
: nameId === 1 || nameId === 16
? out.families
: nameId === 2 || nameId === 17
? out.subfamilies
: null
if (!list) continue
const len = buf.readUInt16BE(r + 8)
const off = strBase + buf.readUInt16BE(r + 10)
if (off + len > buf.length) continue
let s: string
if (platform === 0 || platform === 3) {
s = Buffer.from(buf.subarray(off, off + len))
.swap16()
.toString('utf16le')
} else if (platform === 1 && encoding === 0) {
s = buf.toString('latin1', off, off + len)
} else {
continue // Mac-platform legacy CJK codepages: not decodable here
}
if (s && !list.includes(s)) list.push(s)
}
return out
}
/** Table directory of the face whose offset table starts at `offset`; null for non-sfnt faces */
export function readTableDir(
fd: number,
offset: number,
): Map<string, { off: number; len: number }> | null {
const head = readAt(fd, offset, 12)
if (!SFNT_FLAVORS.has(head.readUInt32BE(0))) return null
const numTables = head.readUInt16BE(4)
if (numTables === 0 || numTables > 64) return null
const dir = readAt(fd, offset + 12, 16 * numTables)
const tables = new Map<string, { off: number; len: number }>()
for (let t = 0; t < numTables; t++) {
tables.set(dir.toString('latin1', 16 * t, 16 * t + 4), {
off: dir.readUInt32BE(16 * t + 8),
len: dir.readUInt32BE(16 * t + 12),
})
}
return tables
}
/** Bytes of one table, bounded by `maxLen`; null when absent or implausibly sized */
export function readTable(
fd: number,
tables: Map<string, { off: number; len: number }>,
tag: string,
maxLen: number,
): Buffer | null {
const entry = tables.get(tag)
if (!entry || entry.len < 2 || entry.len > maxLen) return null
return readAt(fd, entry.off, entry.len)
}
/** Names of the face whose offset table starts at `offset`; null for non-sfnt faces */
export function readFaceNames(fd: number, offset: number): FaceNames | null {
const tables = readTableDir(fd, offset)
if (!tables) return null
const name = readTable(fd, tables, 'name', 1 << 20)
return name && name.length >= 6 ? parseNames(name) : null
}
export interface FaceRef {
path: string
/** Position of the face's offset table within the file (0 unless .ttc) */
offset: number
/** Normalized family + subfamily text, for style ranking on family matches */
style: string
}
export interface FontIndex {
byPs: Map<string, FaceRef>
byFamily: Map<string, FaceRef[]>
}
function* fontFiles(dir: string, depth: number): Generator<string> {
let entries: Dirent[]
try {
entries = readdirSync(dir, { withFileTypes: true })
} catch {
return
}
for (const e of entries) {
const full = join(dir, e.name)
let isDir = e.isDirectory()
let isFile = e.isFile()
if (e.isSymbolicLink()) {
try {
const st = statSync(full)
isDir = st.isDirectory()
isFile = st.isFile()
} catch {
continue
}
}
if (isDir && depth > 0) yield* fontFiles(full, depth - 1)
else if (isFile && /\.(ttf|otf|ttc|otc)$/i.test(e.name)) yield full
}
}
/** Offsets of every face's offset table within the file (many for .ttc, [0] otherwise) */
export function faceOffsets(fd: number): number[] {
if (readAt(fd, 0, 4).readUInt32BE(0) !== TTC_TAG) return [0]
const n = readAt(fd, 8, 4).readUInt32BE(0)
if (n > 64) return []
const o = readAt(fd, 12, 4 * n)
return Array.from({ length: n }, (_, i) => o.readUInt32BE(4 * i))
}
function indexFile(path: string, index: FontIndex): void {
let fd: number
try {
fd = openSync(path, 'r')
} catch {
return
}
try {
for (const offset of faceOffsets(fd)) {
let names: FaceNames | null
try {
names = readFaceNames(fd, offset)
} catch {
names = null
}
if (!names) continue
const face: FaceRef = {
path,
offset,
style: norm([...names.families, ...names.subfamilies].join(' ')),
}
for (const p of names.ps) if (!index.byPs.has(norm(p))) index.byPs.set(norm(p), face)
for (const f of names.families) {
const k = norm(f)
index.byFamily.set(k, [...(index.byFamily.get(k) ?? []), face])
}
}
} catch {
/* unreadable or malformed file: skip */
} finally {
closeSync(fd)
}
}
let index: FontIndex | null = null
export function getFontIndex(): FontIndex {
if (!index) {
index = { byPs: new Map(), byFamily: new Map() }
for (const dir of fontDirs()) for (const path of fontFiles(dir, 2)) indexFile(path, index)
}
return index
}
// "bolditalic" deliberately has no atomic alternative: a BoldItalic face must yield
// ['bold', 'italic'] so it can score against each want separately (a keep-original
// bold toggle on an italic run wants both tokens; an atomic token would score zero).
// "oblique" folds into "italic": families like Helvetica name their slanted faces
// Oblique, and an italic want must still count them as hits.
export const styleTokens = (ps: string): string[] =>
(
norm(ps).match(
/semibold|extrabold|bold|italic|oblique|light|thin|medium|heavy|black|regular|w\d/g,
) ?? []
).map((t) => (t === 'oblique' ? 'italic' : t))
const REGULARISH = ['regular', 'medium', 'w3', 'w4']
/**
* Token-level style score of a face against wanted tokens, not substring: a
* wanted "bold" must not also credit Semibold/ExtraBold faces (the tokenizer
* consumes the longest alternative first), and unmatched face tokens push
* style variants below the exact face instead of tying with it (BoldItalic
* loses to Bold on a bold-only want via the extras penalty, but beats both
* single-style faces when both are wanted). With no wanted tokens, Regular-ish
* tokens count as wanted so the Regular face outranks untagged subfamilies.
*/
export function styleScore(face: FaceRef, want: string[]): number {
const have = styleTokens(face.style)
const wanted = want.length > 0 ? want : REGULARISH
const hits = want.filter((t) => have.includes(t)).length
const extras = have.filter((t) => !wanted.includes(t)).length
const regularBonus = want.length === 0 && have.some((t) => REGULARISH.includes(t)) ? 1 : 0
return hits * 4 - extras + regularBonus
}
@@ -0,0 +1,69 @@
import { existsSync, readFileSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { configureMetricsCache, familyVerticalMetrics, findSystemFont } from '../src/index'
const darwin = process.platform === 'darwin'
const hasHelvetica = darwin && existsSync('/System/Library/Fonts/Helvetica.ttc')
const cacheDir = join(tmpdir(), `font-metrics-test-${process.pid}`)
afterEach(() => rmSync(cacheDir, { recursive: true, force: true }))
describe('familyVerticalMetrics', () => {
it('returns plausible metrics for an installed family', () => {
if (!hasHelvetica) return
const m = familyVerticalMetrics('Helvetica')
expect(m).not.toBeNull()
expect(m!.unitsPerEm).toBeGreaterThan(0)
expect(m!.hheaAscender).toBeGreaterThan(0)
expect(m!.hheaDescender).toBeLessThan(0)
// Helvetica.ttc carries an OS/2 table: both metric groups present
expect(m!.winAscent).toBeGreaterThan(0)
expect(m!.winDescent).toBeGreaterThan(0)
expect(m!.typoAscender).not.toBeNull()
expect(typeof m!.useTypoMetrics).toBe('boolean')
})
it('matches family names exactly after normalization, never fuzzily', () => {
expect(familyVerticalMetrics('No Such Font Family ZZZ')).toBeNull()
if (!hasHelvetica) return
// NFKC + case + separator folding is the only tolerated variance
const a = familyVerticalMetrics('Helvetica')
const b = familyVerticalMetrics('helvetica')
expect(b).toEqual(a)
expect(familyVerticalMetrics('Helveticaish')).toBeNull()
})
it('resolves ttc faces (metrics come from the Regular face)', () => {
if (!hasHelvetica) return
const m = familyVerticalMetrics('Helvetica')
const bytes = findSystemFont('Helvetica', '')
expect(m).not.toBeNull()
expect(bytes).not.toBeNull()
// same face: the standalone sfnt's hhea ascender equals the metrics value
const num = bytes!.readUInt16BE(4)
for (let t = 0; t < num; t++) {
if (bytes!.toString('latin1', 12 + 16 * t, 12 + 16 * t + 4) !== 'hhea') continue
const off = bytes!.readUInt32BE(12 + 16 * t + 8)
expect(bytes!.readInt16BE(off + 4)).toBe(m!.hheaAscender)
}
})
it('persists results keyed by path+mtime+size and reloads them', () => {
if (!hasHelvetica) return
configureMetricsCache(cacheDir)
const first = familyVerticalMetrics('Helvetica')
expect(first).not.toBeNull()
const file = join(cacheDir, 'font-vertical-metrics.json')
expect(existsSync(file)).toBe(true)
const stored = JSON.parse(readFileSync(file, 'utf8')) as Record<
string,
{ path: string; mtimeMs: number; size: number; m: unknown }
>
expect(stored['helvetica']!.m).toEqual(first)
// fresh in-memory state must serve the query from the persisted entry
configureMetricsCache(cacheDir)
expect(familyVerticalMetrics('Helvetica')).toEqual(first)
})
})
+4
View File
@@ -0,0 +1,4 @@
{
"extends": "../../tsconfig.base.json",
"include": ["src", "tests", "vitest.config.ts"]
}
+8
View File
@@ -0,0 +1,8 @@
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
include: ['tests/**/*.test.ts'],
environment: 'node',
},
})
+8 -6
View File
@@ -499,17 +499,19 @@ function patchRunFont(runXml: string, family: string): string {
// silently doing nothing: a payload's own closing tag can truncate the slice this is given
if (!rPr) return patchRunFontUnscannable(runXml, esc)
const el = runXml.slice(rPr.start, rPr.end)
const rPrOpen = /^<a:rPr\b(?:"[^"]*"|'[^']*'|[^"'>])*?>/.exec(el)?.[0]
// Self-closing rPr → expand to a pair around the slots
if (!rPrOpen) {
const attrs = /^<a:rPr\b((?:"[^"]*"|'[^']*'|[^"'>])*?)\/>$/.exec(el)?.[1]
if (attrs === undefined) return patchRunFontUnscannable(runXml, esc)
// Self-closing rPr → expand to a pair around the slots. Checked before the open-tag match:
// that pattern's [^"'>] accepts '/', so it would swallow a self-closing tag whole and this
// branch could never run.
const selfAttrs = /^<a:rPr\b((?:"[^"]*"|'[^']*'|[^"'>])*?)\/>$/.exec(el)?.[1]
if (selfAttrs !== undefined) {
return (
runXml.slice(0, rPr.start) +
`<a:rPr${attrs}>${fontSlotsXml(esc)}</a:rPr>` +
`<a:rPr${selfAttrs}>${fontSlotsXml(esc)}</a:rPr>` +
runXml.slice(rPr.end)
)
}
const rPrOpen = /^<a:rPr\b(?:"[^"]*"|'[^']*'|[^"'>])*?>/.exec(el)?.[0]
if (!rPrOpen) return patchRunFontUnscannable(runXml, esc)
const innerStart = rPr.start + rPrOpen.length
// the closing tag's own start, since a valid one may carry whitespace before its '>'
const innerEnd = rPr.start + el.lastIndexOf('</')
@@ -200,6 +200,22 @@ describe('complex-script font follows the font change', () => {
expect(out).not.toContain("typeface='Old'")
})
it('expands a self-closing rPr to the full slot group, attributes kept', () => {
// the open-tag pattern's [^"'>] accepts '/', so an unguarded match would swallow a
// self-closing tag whole and route it to the latin/ea-only fallback
const out = refont('<a:r><a:rPr lang="ar-SA" b="1"/><a:t>مرحبا</a:t></a:r>')
// the run attribute writer may add its own attrs (e.g. i="0"); the declared ones survive
expect(out).toMatch(/<a:rPr[^>]*\blang="ar-SA"[^>]*\bb="1"[^>]*>/)
expect(slotOrder(out)).toEqual(['latin', 'ea', 'cs'])
expect(/<a:cs[^>]*typeface="([^"]*)"/.exec(out)?.[1]).toBe('Amiri')
})
it('expands a bare self-closing rPr as well', () => {
const out = refont('<a:r><a:rPr/><a:t>مرحبا</a:t></a:r>')
expect(slotOrder(out)).toEqual(['latin', 'ea', 'cs'])
expect(/<a:cs[^>]*typeface="([^"]*)"/.exec(out)?.[1]).toBe('Amiri')
})
it('does not add a second slot group to a run using mc:AlternateContent', () => {
// the branch children only exist once a consumer picks a branch, so injecting a direct
// group alongside them would leave two a:latin after preprocessing
+28 -9
View File
@@ -7,6 +7,11 @@
* data-tip — command name (required; the tip line)
* data-tip-kbd — optional shortcut, rendered dimmed after the name
* data-tip-detail — optional one-line description under the name
* data-tip-anchor — optional descendant selector; the tip is positioned
* relative to that element instead of the host (e.g. a
* wide row anchoring its tip to a trailing icon)
* data-tip-place — optional 'right' places the tip beside the anchor,
* vertically centered (default: below, centered)
*
* Timing follows the Windows/Office ScreenTip standard: 500ms initial delay,
* fast (100ms) reshow while "warm" — a tip was visible less than 500ms ago —
@@ -85,20 +90,34 @@ function show(el: Element, doc: Document): void {
t.detail.textContent = detail ?? ''
t.detail.style.display = detail ? '' : 'none'
// measure hidden, then place below the control (above when it would clip)
// measure hidden, then place below the control (above when it would clip);
// data-tip-anchor re-anchors to a descendant, data-tip-place='right' puts
// the tip beside the anchor instead of under it
t.el.style.visibility = 'hidden'
t.el.style.left = '0px'
t.el.style.top = '0px'
const rect = el.getBoundingClientRect()
const anchorSel = el.getAttribute('data-tip-anchor')
const rect = ((anchorSel && el.querySelector(anchorSel)) || el).getBoundingClientRect()
const tipRect = t.el.getBoundingClientRect()
const maxLeft = window.innerWidth - tipRect.width - EDGE_PAD_PX
const left = Math.max(
EDGE_PAD_PX,
Math.min(rect.left + rect.width / 2 - tipRect.width / 2, maxLeft),
)
let top = rect.bottom + OFFSET_PX
if (top + tipRect.height > window.innerHeight - EDGE_PAD_PX)
top = rect.top - tipRect.height - OFFSET_PX
let left: number
let top: number
if (el.getAttribute('data-tip-place') === 'right') {
left = rect.right + OFFSET_PX
if (left > maxLeft) left = Math.max(EDGE_PAD_PX, rect.left - tipRect.width - OFFSET_PX)
top = Math.max(
EDGE_PAD_PX,
Math.min(
rect.top + rect.height / 2 - tipRect.height / 2,
window.innerHeight - tipRect.height - EDGE_PAD_PX,
),
)
} else {
left = Math.max(EDGE_PAD_PX, Math.min(rect.left + rect.width / 2 - tipRect.width / 2, maxLeft))
top = rect.bottom + OFFSET_PX
if (top + tipRect.height > window.innerHeight - EDGE_PAD_PX)
top = rect.top - tipRect.height - OFFSET_PX
}
t.el.style.left = `${Math.round(left)}px`
t.el.style.top = `${Math.round(top)}px`
t.el.style.visibility = 'visible'
+2 -2
View File
@@ -21,9 +21,9 @@
--text-tertiary: #909499;
--text-muted: #878e96;
--text-dim: #605e5c;
--hover: #f3f2f1;
--hover: #f5f5f5;
--pressed: #edebe9;
--active-bg: #e2e0de;
--active-bg: #eaeaea;
--bg-hover: #f5f5f5;
--bg-hover-subtle: #f0f2f5;
--bg-hover-strong: #e8eaee;