Sync snapshot (2026-08-05) (#34)

- Add a user-selectable update channel (Stable/Beta) with a manual promote-to-stable release flow
- PDF: image signatures and WYSIWYG typed signatures with better placement, plus a status bar, keyboard navigation, and two-page spread reading upgrades
- Docs: Word-parity ribbon font controls and style gallery, an AI Format one-click preset, and restored headers/footers and TOC formatting for Pages-style docx
- Add GenOffice device-code sign-in for AI features
- Refresh UI: AI panel and ribbon styling aligned with the design system, new icons, save toasts, and content-width status bars beside a full-height AI dock
- AI reliability: retry transient image-download failures, detect empty gateway streams without killing long generations, and forward the resolved proxy to spawned CLI children
- Slides: bullet list gallery, type-ahead font filtering, and shorter clarify buttons across locales
- Add a Linux (AppImage) packaging target

Co-authored-by: GenOffice <merrick-2002@users.noreply.github.com>
This commit is contained in:
merrick-2002
2026-08-05 21:44:14 +08:00
committed by GitHub
co-authored by GenOffice
parent 3a440f7944
commit d1de6ac44b
126 changed files with 8391 additions and 3490 deletions
+1
View File
@@ -88,3 +88,4 @@ export { bibliographyLine, citationText, parseSourcesXml } from './sources'
export { readThemeColors, readThemeFonts } from './theme'
export { hashProtectionPassword, verifyProtectionPassword } from './protection'
export { decodeSymbolChar, decodeSymbolText, isSymbolFont } from './symbol-fonts'
export { computeListMarkers, formatNumber, type ListItemRef } from './list-markers'
+152
View File
@@ -0,0 +1,152 @@
import { decodeSymbolText, isSymbolFont } from './symbol-fonts'
import type { NumberingDef } from './types'
/** Word represents bullets with Symbol/Wingdings private-use characters; map them to common glyphs */
const BULLET_GLYPHS: Record<string, string> = {
'': '•',
'': '▪',
'': '➢',
'': '❖',
'': '✓',
o: '◦',
}
const DEFAULT_BULLETS = ['•', '◦', '▪', '•', '◦', '▪', '•', '◦', '▪']
function toLetters(value: number): string {
// Word: 1..26 -> A..Z, 27 -> AA (repeated same letter, not positional notation)
const n = ((value - 1) % 26) + 1
const repeat = Math.floor((value - 1) / 26) + 1
return String.fromCharCode(64 + n).repeat(repeat)
}
const ROMAN: Array<[number, string]> = [
[1000, 'M'],
[900, 'CM'],
[500, 'D'],
[400, 'CD'],
[100, 'C'],
[90, 'XC'],
[50, 'L'],
[40, 'XL'],
[10, 'X'],
[9, 'IX'],
[5, 'V'],
[4, 'IV'],
[1, 'I'],
]
function toRoman(value: number): string {
let n = Math.max(1, value)
let out = ''
for (const [v, s] of ROMAN) {
while (n >= v) {
out += s
n -= v
}
}
return out
}
const CN_DIGITS = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
function toChinese(value: number): string {
if (value <= 0 || value > 9999) return String(value)
if (value < 10) return CN_DIGITS[value]
const units = ['', '十', '百', '千']
const digits = String(value).split('').map(Number)
let out = ''
for (let i = 0; i < digits.length; i++) {
const d = digits[i]
const unit = units[digits.length - 1 - i]
if (d === 0) {
if (!out.endsWith('零') && i < digits.length - 1) out += '零'
} else {
out += CN_DIGITS[d] + unit
}
}
out = out.replace(/零+$/, '')
// 10-19 drop the leading "one" digit: read as "shi x" rather than "yi shi x"
return out.replace(/^一十/, '十')
}
export function formatNumber(value: number, numFmt: string): string {
switch (numFmt) {
case 'decimalZero':
return value < 10 && value >= 0 ? `0${value}` : String(value)
case 'lowerLetter':
return toLetters(value).toLowerCase()
case 'upperLetter':
return toLetters(value)
case 'lowerRoman':
return toRoman(value).toLowerCase()
case 'upperRoman':
return toRoman(value)
case 'chineseCounting':
case 'chineseCountingThousand':
case 'japaneseCounting':
return toChinese(value)
case 'decimalEnclosedCircle':
return value >= 1 && value <= 20 ? String.fromCodePoint(0x2460 + value - 1) : String(value)
case 'none':
return ''
default:
return String(value)
}
}
export interface ListItemRef {
numId: string | null
ilvl: number
}
/**
* Word numbering semantics: counters accumulate document-wide per abstractNum
* (plain paragraphs in between don't break the sequence); when a level appears,
* its deeper levels reset; startOverride applies the first time that numId uses
* the level. Returns a marker array the same length as items; items without a
* definition return null (CSS fallback handles them).
*/
export function computeListMarkers(
items: ListItemRef[],
defs: Map<string, NumberingDef>,
): (string | null)[] {
const counters = new Map<string, number[]>()
const overrideApplied = new Set<string>()
return items.map((item) => {
const def = item.numId !== null ? defs.get(item.numId) : undefined
if (!def) return null
const lvl = Math.max(0, item.ilvl)
const level = def.levels[lvl]
if (!level) return null
if (level.numFmt === 'bullet') {
// symbol-encoded marker fonts (Wingdings "l" = ●): decode by font first
const decoded = level.font ? decodeSymbolText(level.font, level.lvlText) : null
const glyph = decoded ?? BULLET_GLYPHS[level.lvlText] ?? level.lvlText
// undecodable symbol-font glyphs, private-use or empty ones fall back to the per-level default
if (!glyph || /[-]/.test(glyph) || (decoded === null && isSymbolFont(level.font)))
return DEFAULT_BULLETS[lvl % 9]
return glyph
}
const c = counters.get(def.abstractNumId) ?? []
counters.set(def.abstractNumId, c)
const overrideKey = `${def.numId}:${lvl}`
if (def.startOverrides[lvl] !== undefined && !overrideApplied.has(overrideKey)) {
overrideApplied.add(overrideKey)
c[lvl] = def.startOverrides[lvl]
} else {
c[lvl] = (c[lvl] ?? level.start - 1) + 1
}
c.length = lvl + 1
const marker = level.lvlText.replace(/%(\d)/g, (_, d: string) => {
const refLvl = Number(d) - 1
const refDef = def.levels[refLvl]
const value = c[refLvl] ?? refDef?.start ?? 1
return formatNumber(value, refDef?.numFmt ?? 'decimal')
})
return marker || null
})
}
+70 -12
View File
@@ -1,6 +1,7 @@
import JSZip from 'jszip'
import { parseChartPartXml } from './chart'
import { findInkRuns, stripInkRuns } from './ink'
import { computeListMarkers, type ListItemRef } from './list-markers'
import { ommlFragmentsOf, ommlToLatex, ommlToMathML } from './math'
import { splitXmlChildren } from './generate'
import { NOTE_PART_PATH, parseNotesXml } from './notes'
@@ -199,6 +200,7 @@ export async function parseDocx(bytes: Uint8Array): Promise<ParsedDoc & { extras
elements.push(el)
blocks.push(await buildBlock(el, i, xml, buildCtx))
}
applyTocEntryNumbers(blocks, numbering)
const header = await readHeaderFooterPart(
zip,
@@ -641,7 +643,8 @@ async function buildBlock(
// TOC-styled paragraphs are part of a TOC field result even when they carry
// no field chars themselves (entries with literal page numbers). Editing
// them individually would corrupt the field, so they stay protected.
if (/<w:pStyle w:val="TOC[1-9]"/.test(xml)) {
// Word writes styleIds "TOC1".."TOC9"; Pages exports "TOC 1"/"TOC 2" (with space).
if (/<w:pStyle w:val="TOC ?[1-9]"/.test(xml)) {
return {
...base,
type: 'passthrough',
@@ -2102,16 +2105,35 @@ function hfContentFromXml(
theme?: ThemeColors | null,
): { text: string; hasPageNumber: boolean; watermark: string | null; paras: HfParagraph[] } {
const hasPageNumber = /<w:instrText[^>]*>[^<]*\bPAGE\b/.test(xml)
// drop cached field results (e.g. the stale page number between separate/end),
// then mark the PAGE field position with '#' so "- PAGE -" reads "- # -";
// NUMPAGES gets the private-use marker (renderer substitutes the total)
const cleaned = xml
.replace(/<w:fldChar w:fldCharType="separate"\/>[\s\S]*?<w:fldChar w:fldCharType="end"\/>/g, '')
.replace(
/<w:instrText[^>]*>[^<]*\bNUMPAGES\b[^<]*<\/w:instrText>/g,
`<w:t>${TOTAL_PAGES_MARK}</w:t>`,
)
.replace(/<w:instrText[^>]*>[^<]*\bPAGE\b[^<]*<\/w:instrText>/g, '<w:t>#</w:t>')
// Rewrite each field span (begin..end) for display. PAGE becomes the '#'
// marker and NUMPAGES the private-use marker (the renderer substitutes real
// numbers), dropping their stale cached results; other fields (DATE, STYLEREF,
// ...) keep their cached result runs (Word refreshes them on open). fldChar
// attribute matching is tolerant (Pages writes w:fldLock="0" etc.).
const cleaned = xml.replace(
/<w:fldChar[^>]*w:fldCharType="begin"[^>]*\/>[\s\S]*?<w:fldChar[^>]*w:fldCharType="end"[^>]*\/>/g,
(span) => {
const instr = (span.match(/<w:instrText[^>]*>[\s\S]*?<\/w:instrText>/g) ?? [])
.map((m) => m.replace(/<[^>]+>/g, ''))
.join('')
const rPr = /<w:rPr>[\s\S]*?<\/w:rPr>/.exec(span)?.[0] ?? ''
// the span starts inside the begin run and ends inside the end run, so
// the replacement closes/reopens the enclosing w:r to stay balanced
// (the leftover edge runs end up empty and are dropped later)
const emit = (inner: string) => `</w:r>${inner}<w:r>`
if (/\bNUMPAGES\b/.test(instr)) {
return emit(`<w:r>${rPr}<w:t>${TOTAL_PAGES_MARK}</w:t></w:r>`)
}
if (/\bPAGE\b/.test(instr)) return emit(`<w:r>${rPr}<w:t>#</w:t></w:r>`)
const cached = /<w:fldChar[^>]*w:fldCharType="separate"[^>]*\/>([\s\S]*)$/.exec(span)?.[1]
// complete result runs between separate and end (partial run fragments at the edges drop out)
return emit(
(cached?.match(/<w:r(?:\s[^>]*)?>[\s\S]*?<\/w:r>/g) ?? [])
.filter((run) => run.includes('<w:t'))
.join(''),
)
},
)
return {
text: plainText(cleaned),
hasPageNumber,
@@ -2303,7 +2325,8 @@ function decodeEntities(text: string): string {
*/
function fieldDisplayOf(xml: string): FieldDisplay | undefined {
const styleId = /<w:pStyle w:val="([^"]+)"/.exec(xml)?.[1] ?? ''
const tocLevel = /^TOC([1-9])$/i.exec(styleId)
// "TOC1" (Word) or "TOC 1" (Pages export)
const tocLevel = /^TOC ?([1-9])$/i.exec(styleId)
if (tocLevel) {
// TOC entry: title <tab with dot leader> page number
let left = ''
@@ -2335,6 +2358,41 @@ function fieldDisplayOf(xml: string): FieldDisplay | undefined {
return undefined
}
/**
* TOC entries carry their outline number ("1.", "1.1.") as w:numPr numbering
* (Pages exports one numId per entry with startOverride restarts). The field
* result is a display-only cache, so the marker is computed once at parse time
* and stored on the tocLine FieldDisplay. Counters run document-wide in block
* order, shared with editable list items (same abstractNum semantics).
*/
function applyTocEntryNumbers(blocks: Block[], numbering: Map<string, NumberingDef>): void {
if (numbering.size === 0) return
const items: ListItemRef[] = []
const tocAt = new Map<number, FieldDisplay>()
for (const block of blocks) {
if (block.list?.numId) {
items.push({ numId: block.list.numId, ilvl: block.list.ilvl })
continue
}
const fd = block.fieldDisplay
if (block.type !== 'passthrough' || fd?.kind !== 'tocLine' || !block.originalXml) continue
const numPr = /<w:numPr>[\s\S]*?<\/w:numPr>/.exec(block.originalXml)?.[0]
if (!numPr) continue
const numId = /<w:numId w:val="([^"]+)"/.exec(numPr)?.[1]
if (!numId) continue
const ilvl = parseInt(/<w:ilvl w:val="(\d+)"/.exec(numPr)?.[1] ?? '0', 10)
tocAt.set(items.length, fd)
items.push({ numId, ilvl })
}
if (tocAt.size === 0) return
const markers = computeListMarkers(items, numbering)
for (const [i, fd] of tocAt) {
const marker = markers[i]
// bullets make no sense in front of a TOC entry; only ordered markers show
if (marker && !/^[•◦▪➢❖✓]$/.test(marker)) fd.num = marker
}
}
const FIELD_LABELS: Record<string, string> = {
TOC: 'Auto TOC (updates when opened in Word)',
PAGE: 'Page number field',
+2
View File
@@ -386,6 +386,8 @@ export interface FieldDisplay {
level?: number
/** bookmark anchor of the tocLine hyperlink (_Toc...), for click-to-jump */
anchor?: string
/** numbering marker of the entry's w:numPr ("1.", "1.1."), computed at parse time */
num?: string
}
/** Editable text tokens inside an OMML formula; the surrounding math tree is preserved. */