Sync snapshot (2026-08-23) (#130)

- Convert scanned PDFs to editable text with local OCR, running through the operating system's own engine on macOS and Windows
- Add a much richer AI workflow to Docs, PDF, and Markdown: selection-scoped questions, batched edits, character-level edits, comment and tracked-change awareness, citations back to the source block, and in-document image generation
- Let Slides open the same presentation in a second window and edit it from both
- Improve PDF to Excel table recovery: tables spanning pages merge into one worksheet, and label/value grids and rule-less statement bands become real rows
- Fix a large wave of Word layout fidelity in Docs, Excel parity in Sheets, and PowerPoint import fidelity in Slides

Co-authored-by: GenOffice <merrick-2002@users.noreply.github.com>
This commit is contained in:
merrick-2002
2026-08-23 23:10:02 +08:00
committed by GitHub
co-authored by GenOffice
parent f68df70e22
commit 6d9b6812dd
372 changed files with 34693 additions and 3274 deletions
+16 -5
View File
@@ -501,7 +501,10 @@ function buildChartNodeInner(
// Category label mode: an explicit txPr rotation wins; otherwise crowded labels wrap
// to ≤3 horizontal lines when the words fit the slot, and rotate ~45° as a last resort
// (PowerPoint thins labels only after that)
const heuristicSlotW = Math.max(plotR - plotX, 10) / nCats
// Explicit c:tickLblSkip thins the labels: crowding decisions (wrap/rotate/reserve)
// size against the labeled slot, not the raw per-category slot
const lblSkip = model.catAxis?.tickLblSkip ?? 1
const heuristicSlotW = (Math.max(plotR - plotX, 10) / nCats) * lblSkip
const catRotDeg = model.catAxis?.labelRotDeg
const catWrapLines = (slotW: number): string[][] | null => {
if (model.categories.length < 2 || maxCatW <= slotW * 1.05) return null
@@ -799,7 +802,10 @@ function buildChartNodeInner(
? Math.max(emuToPx(model.catAxis.minorGridWidthEmu, vp.scale), 0.75)
: undefined
const gy = plot.y - depth3d
for (let i = 0; i <= n; i++) {
// c:tickMarkSkip: ticks (and their gridlines) land every Nth slot boundary only —
// dense axes (1400+ samples) otherwise flood the plot with one hairline per category
const markSkip = model.catAxis?.tickMarkSkip ?? 1
for (let i = 0; i <= n; i += markSkip) {
const gx = plot.x + depth3d * 0.5 + i * slotW
if (catGrid && i > 0) {
node.gridLines.push({
@@ -827,11 +833,15 @@ function buildChartNodeInner(
}
}
const catBold = model.catAxis?.labelBold ? { bold: true as const } : {}
// Re-derive the mode from the final plot width (a manual plot layout can differ from the heuristic frame)
const drawWrap = catRotDeg == null ? catWrapLines(slotW) : null
// Re-derive the mode from the final plot width (a manual plot layout can differ from the
// heuristic frame); the labeled slot spans lblSkip raw slots
const drawWrap = catRotDeg == null ? catWrapLines(slotW * lblSkip) : null
const drawRotate =
(catRotDeg != null && catRotDeg !== 0) ||
(catRotDeg == null && !drawWrap && model.categories.length > 1 && maxCatW > slotW * rotFactor)
(catRotDeg == null &&
!drawWrap &&
model.categories.length > 1 &&
maxCatW > slotW * lblSkip * rotFactor)
const rotCos = Math.cos((Math.abs(catRotUsed) * Math.PI) / 180)
const rotSin = Math.sin((Math.abs(catRotUsed) * Math.PI) / 180)
// Labels hang off the category axis (the zero line when the range spans it, the plot
@@ -839,6 +849,7 @@ function buildChartNodeInner(
const catLabelBase = catAtZero ? crossY : plot.y + plot.h
if (!catLabelsOff)
model.categories.forEach((cat, i) => {
if (i % lblSkip) return
const cx = plot.x + (catSlot(i) + 0.5) * slotW
if (drawRotate) {
// Rotation is about the text's origin (left end). Negative angles slant up-right:
+20 -1
View File
@@ -53,6 +53,7 @@ import {
import {
buildExtrusion,
inPlaneRotationDeg,
flatCameraMirror,
flattenSvgPath,
ellipseRing,
roundRectRing,
@@ -372,6 +373,7 @@ function buildShape(
fill: resolveFill(el.fill, vp, media),
...(el.fillOverlay ? { fillOverlay: resolveFill(el.fillOverlay, vp, media) } : {}),
...(el.placeholder ? { placeholder: el.placeholder } : {}),
...(el.txBox ? { txBox: true } : {}),
...(el.presetGeometry ? { presetGeometry: el.presetGeometry } : {}),
}
// Raw avLst values ride along for the edit layer (yellow adjust handles)
@@ -518,7 +520,24 @@ function buildPicture(
media: MediaResolver | undefined,
): PictureRenderNode {
const dataUrl = el.dataUrl ?? (el.mediaRef ? media?.(el.mediaRef) : undefined)
const clip = pictureClip(el.presetGeometry, box, el.adjust)
// custGeom picture frame: clip the bitmap to the freeform path (normalized 0..1 → local px)
const geomPath = el.customGeometry
? (el.customGeometry.path ?? el.customGeometry.fillPath)
: undefined
const clip = geomPath
? { pathData: scaleUnitPath(geomPath, box.w, box.h) }
: pictureClip(el.presetGeometry, box, el.adjust)
// scene3d flat 180° camera: the bitmap content mirrors, so fold it into the container flips
if (el.scene3d) {
const m = flatCameraMirror(el.scene3d)
if (m)
box = {
...box,
flipH: box.flipH !== m.flipH,
flipV: box.flipV !== m.flipV,
rotationDeg: box.rotationDeg + m.rotationDeg,
}
}
// GDI metafiles play back on an opaque white DC: PowerPoint shows a white panel for
// an EMF/WMF that never paints its background (PlanS academy banner, measured)
const isMetafile =
+5 -2
View File
@@ -20,6 +20,8 @@ export interface RunStyle {
fontSizePx: number
bold: boolean
italic: boolean
/** Apply kern pairs when measuring (PowerPoint kerns only at fontSize ≥ rPr kern; default true) */
kerning?: boolean
}
export interface FontMetrics {
@@ -171,7 +173,8 @@ export interface OpentypeFontLike {
descender: number
/** hhea lineGap (external leading, font units); part of the single-spacing line height */
lineGap?: number
getAdvanceWidth(text: string, fontSize: number): number
/** options matches opentype.js Font.getAdvanceWidth (kerning defaults to true) */
getAdvanceWidth(text: string, fontSize: number, options?: { kerning?: boolean }): number
/** Optional: char → glyph index (0 = missing glyph). Used for the missing-glyph heuristic fallback. */
charToGlyphIndex?(char: string): number
}
@@ -217,7 +220,7 @@ export class OpentypeMetrics implements FontMetricsProvider {
if (font.charToGlyphIndex(ch) === 0) return this.fallback.measure(text, style)
}
}
return font.getAdvanceWidth(text, style.fontSizePx)
return font.getAdvanceWidth(text, style.fontSizePx, { kerning: style.kerning !== false })
} catch {
return this.fallback.measure(text, style)
}
+6
View File
@@ -144,6 +144,8 @@ export interface GlyphRun {
logicalOrder?: number
/** Letter spacing (px, appended after each char, may be negative; maps to <a:rPr spc>, fed to canvas letterSpacing by the renderer) */
letterSpacingPx?: number
/** Kern pairs disabled (fontSize below the rPr kern threshold): the draw layer must not kern either */
kerningOff?: boolean
/** Text outline (<a:rPr><a:ln>, commonly used by WordArt) */
outline?: { color: string; widthPx: number }
/** Run outer shadow (px), drawn via canvas shadow props */
@@ -216,6 +218,8 @@ export interface RenderTextLayout {
inkBottom?: number
/** bodyPr wrap (false = no wrapping, overflows the box; the editor also doesn't wrap) */
wrap: boolean
/** bodyPr autofit mode (noAutofit/normAutofit/spAutoFit), surfaced for the format pane */
autofit?: 'none' | 'shrink' | 'resize'
/** bodyPr vert: vertical column layout (lines = columns, right→left); vert/vert270/wordArtVert degrade to eaVert */
vert?: 'eaVert' | 'vert' | 'vert270' | 'wordArtVert'
/** WordArt text extrusion: glyphs get offset copies in this color behind them (px) */
@@ -236,6 +240,8 @@ export interface ShapeRenderNode extends RenderNodeBase {
type: 'shape' | 'text'
/** Placeholder type (title/ctrTitle/subTitle/body/…); empty placeholders draw hint text on the canvas */
placeholder?: string
/** Insert > Text Box rather than Insert > Shape: the edit overlay must not center a fresh body */
txBox?: boolean
presetGeometry?: string
/** Raw avLst adjust values (OOXML units) for the edit layer's adjust handles */
adjust?: Record<string, number>
+29
View File
@@ -712,6 +712,35 @@ export function inPlaneRotationDeg(scene: Scene3DProps): number | null {
return rev === 0 ? 0 : -rev
}
/**
* Parallel camera whose lat/lon are exact multiples of 180°: the flat content projects
* as a plain mirror (lon 180° = horizontal, lat 180° = vertical) plus the in-plane rev
* rotation. PowerPoint uses this as a bitmap-flip idiom on pictures
* (orthographicFront + <a:rot lon="10800000">). Null for anything needing real 3D
* (perspective/oblique camera, extrusion, z shift, non-flat angles) or for identity.
*/
export function flatCameraMirror(
scene: Scene3DProps,
): { flipH: boolean; flipV: boolean; rotationDeg: number } | null {
const preset = CAMERA_PRESETS[scene.cameraPreset]
if (!preset || !preset.parallel || preset.skewAmount !== 0) return null
if ((scene.extrusionEmu ?? 0) > 0) return null
if ((scene.zEmu ?? 0) !== 0) return null
const lat = scene.cameraRot ? scene.cameraRot.lat * D : preset.rx
const lon = scene.cameraRot ? scene.cameraRot.lon * D : preset.ry
const rev = scene.cameraRot ? scene.cameraRot.rev * D : preset.rz
const norm = (a: number) => ((a % 360) + 360) % 360
const isHalf = (a: number) => Math.abs(norm(a) - 180) < 0.5
const isZero = (a: number) => norm(a) < 0.5 || norm(a) > 359.5
const flipV = isHalf(lat)
const flipH = isHalf(lon)
if ((!flipV && !isZero(lat)) || (!flipH && !isZero(lon))) return null
if (!flipH && !flipV && rev === 0) return null
// rev folds in with the same screen-clockwise sign as inPlaneRotationDeg; the mirror
// is the innermost transform (container flip), so the rotation sign is flip-independent.
return { flipH, flipV, rotationDeg: rev === 0 ? 0 : -rev }
}
export function buildExtrusion(input: BuildExtrusionInput): ExtrusionRender | null {
const { rings, w, h, depthPx, scene } = input
const preset = CAMERA_PRESETS[scene.cameraPreset]
+43 -15
View File
@@ -28,6 +28,11 @@ import { emuToPx, ptToPx, type Viewport } from './coords'
const DEFAULT_FONT = 'Arial'
const DEFAULT_SIZE_PT = 18
/** <a:bodyPr> inset defaults (EMU): 0.1" left/right, 0.05" top/bottom. Mirrors the
* engine's DEFAULT_BODY_INSETS — importing it would drag the engine runtime into the
* renderer bundle, so a test asserts the two stay equal instead. */
export const DEFAULT_INSETS_EMU = { l: 91440, t: 45720, r: 91440, b: 45720 }
interface Token {
text: string
style: RunStyle
@@ -84,11 +89,15 @@ function scaleHexAlpha(hex: string, factor: number): string {
function runStyle(run: TextRun, scale: number, fontScale: number): RunStyle {
const sizePt = run.fontSize ?? DEFAULT_SIZE_PT
// PowerPoint kerns only at effective size ≥ the rPr kern threshold (absent = 12 pt
// default, 0 = never; probe-measured). The autofit fontScale counts toward the size.
const kernMinPt = run.kern ?? 12
return {
fontFamily: run.fontFamily || DEFAULT_FONT,
fontSizePx: ptToPx(sizePt, scale) * fontScale,
bold: !!run.bold,
italic: !!run.italic,
kerning: kernMinPt > 0 && sizePt * fontScale >= kernMinPt,
}
}
@@ -673,6 +682,7 @@ function buildLine(
...(tok.highlight ? { highlight: tok.highlight } : {}),
widthPx: w,
...(tok.ls ? { letterSpacingPx: tok.ls } : {}),
...(tok.style.kerning === false ? { kerningOff: true } : {}),
...(tok.outline ? { outline: tok.outline } : {}),
...(tok.gradient ? { gradient: tok.gradient } : {}),
...(tok.glow ? { glow: tok.glow } : {}),
@@ -739,6 +749,9 @@ export interface TextLayoutInput {
/** Table cells: PowerPoint drops the first paragraph's space-before and the last
paragraph's space-after (rows stay at their minimum height regardless of them). */
trimEdgeSpacing?: boolean
/** Re-run the autofit ladder below a stored fontScale (edit flows only): plain rendering
honors the cache as-is like PowerPoint on open. */
refitAutofit?: boolean
}
/**
@@ -783,26 +796,29 @@ function flowIntoColumns(
export function layoutText(input: TextLayoutInput): RenderTextLayout {
const { body, boxWidthPx, boxHeightPx, metrics, vp } = input
const insets = {
l: emuToPx(body.insets?.l ?? 91440, vp.scale),
t: emuToPx(body.insets?.t ?? 45720, vp.scale),
r: emuToPx(body.insets?.r ?? 91440, vp.scale),
b: emuToPx(body.insets?.b ?? 45720, vp.scale),
l: emuToPx(body.insets?.l ?? DEFAULT_INSETS_EMU.l, vp.scale),
t: emuToPx(body.insets?.t ?? DEFAULT_INSETS_EMU.t, vp.scale),
r: emuToPx(body.insets?.r ?? DEFAULT_INSETS_EMU.r, vp.scale),
b: emuToPx(body.insets?.b ?? DEFAULT_INSETS_EMU.b, vp.scale),
}
const availWidth = Math.max(boxWidthPx - insets.l - insets.r, 1)
const availHeight = Math.max(boxHeightPx - insets.t - insets.b, 1)
const wrap = body.wrap !== false
if (body.vert)
return layoutTextVertical(
body,
body.vert,
availWidth,
availHeight,
insets,
wrap,
metrics,
vp.scale,
)
return {
...layoutTextVertical(
body,
body.vert,
availWidth,
availHeight,
insets,
wrap,
metrics,
vp.scale,
),
autofit: body.autofit ?? 'none',
}
// bodyPr numCol: paragraphs wrap at the column width and fill column after column
const numCol = body.numCol && body.numCol > 1 ? Math.floor(body.numCol) : 1
@@ -838,7 +854,16 @@ export function layoutText(input: TextLayoutInput): RenderTextLayout {
}
// With columns, the single-stream span may spread over numCol columns of availHeight
const fitTarget = availHeight * numCol
if (body.autofit === 'shrink' && fitSpan(result) > fitTarget * 1.03) {
// A stored fontScale is authoritative: PowerPoint renders the cached ratio as-is on
// open/export and never re-fits (probe-measured — a bare <a:normAutofit/> even renders
// at 100% overflowing the box). Stepping below the cache when our metrics run a hair
// long shrank whole pages a visible notch (autofit ladder only serves cache-less boxes,
// i.e. live edits).
if (
body.autofit === 'shrink' &&
(input.refitAutofit || body.fontScale == null) &&
fitSpan(result) > fitTarget * 1.03
) {
for (const [fs, red] of SHRINK_STEPS) {
if (fs >= storedScale - 1e-6) continue
const effRed = Math.max(red, storedRed)
@@ -893,6 +918,7 @@ export function layoutText(input: TextLayoutInput): RenderTextLayout {
contentHeight: result.contentHeight,
...(result.inkBottom ? { inkBottom: result.inkBottom } : {}),
wrap,
autofit: body.autofit ?? 'none',
...(extrusion ? { extrusion } : {}),
}
}
@@ -1050,6 +1076,8 @@ function layoutTextVertical(
...(tok.reflection ? { reflection: true } : {}),
...(tok.shadow ? { shadow: tok.shadow } : {}),
widthPx: adv,
// Rotated Latin words draw as whole strings too: keep draw kerning in step with the measure
...(tok.style.kerning === false ? { kerningOff: true } : {}),
rotate90: true,
srcRunIdx: tok.srcRun,
...(tok.link ? { link: tok.link } : {}),
@@ -189,6 +189,70 @@ describe('buildRenderSlide (end-to-end on real fixture)', () => {
expect(build(mk('unknownPreset9')).clip).toBeUndefined()
})
it('picture custGeom -> clip pathData scaled to the box; scene3d 180° camera -> container flips', async () => {
const { deck } = await openPptx(enginePptx('01_standard_business.pptx'))
const slide = deck.slides[0]!
const mk = (extra: Record<string, any>): any => ({
id: 'pic_cg',
type: 'picture',
anchor: { spIndex: -1, originalXml: '', range: [0, 0] },
transform: {
offset: { x: 0, y: 0, cx: 914400, cy: 914400 },
rot: 0,
flipH: false,
flipV: false,
},
mediaRef: '',
...extra,
})
const build = (el: any) =>
buildRenderSlide({ ...slide, elements: [el], decorations: [] }, deck.size, {
fitWidthPx: 1280,
}).nodes[0] as any
const cg = build(mk({ customGeometry: { path: 'M 0 1 L 0.5 0 L 1 1 Z' } }))
const px = (n: number, dim: number) => Math.round(n * dim * 100) / 100
expect(cg.clip?.pathData).toBe(
`M 0 ${px(1, cg.box.h)} L ${px(0.5, cg.box.w)} 0 L ${px(1, cg.box.w)} ${px(1, cg.box.h)} Z`,
)
const mirrorH = build(
mk({
scene3d: {
cameraPreset: 'orthographicFront',
cameraRot: { lat: 0, lon: 10800000, rev: 0 },
},
}),
)
expect(mirrorH.box.flipH).toBe(true)
expect(mirrorH.box.flipV).toBe(false)
const mirrorBoth = build(
mk({
scene3d: {
cameraPreset: 'orthographicFront',
cameraRot: { lat: 10800000, lon: 10800000, rev: 0 },
},
}),
)
expect(mirrorBoth.box.flipH).toBe(true)
expect(mirrorBoth.box.flipV).toBe(true)
// perspective camera / non-flat angle: leave the picture untouched (no fake mirror)
const persp = build(
mk({
scene3d: { cameraPreset: 'perspectiveFront', cameraRot: { lat: 0, lon: 10800000, rev: 0 } },
}),
)
expect(persp.box.flipH).toBe(false)
const tilted = build(
mk({
scene3d: { cameraPreset: 'orthographicFront', cameraRot: { lat: 0, lon: 5400000, rev: 0 } },
}),
)
expect(tilted.box.flipH).toBe(false)
})
it('slidenum field displays opts.slideNo without mutating the model', async () => {
const { deck } = await openPptx(enginePptx('01_standard_business.pptx'))
const slide = deck.slides[0]!
+84 -3
View File
@@ -1,8 +1,8 @@
import { describe, it, expect } from 'vitest'
import { HeuristicMetrics, OpentypeMetrics, type OpentypeFontLike } from '../src/metrics'
import { layoutText } from '../src/text-layout'
import { DEFAULT_INSETS_EMU, layoutText } from '../src/text-layout'
import { makeViewport } from '../src/coords'
import type { TextBody } from '@genoffice/pptx-engine'
import { DEFAULT_BODY_INSETS, type TextBody } from '@genoffice/pptx-engine'
const vp = makeViewport({ cx: 9525 * 1000, cy: 9525 * 1000 }, 1000) // scale 1
@@ -16,6 +16,10 @@ function body(partial: Partial<TextBody> & Pick<TextBody, 'paragraphs'>): TextBo
}
}
it('the layout inset defaults mirror the parser (kept separate so the renderer bundle stays engine-free)', () => {
expect(DEFAULT_INSETS_EMU).toEqual(DEFAULT_BODY_INSETS)
})
describe('2.3 metrics', () => {
const m = new HeuristicMetrics()
@@ -625,7 +629,7 @@ describe('shrink discrete steps + superscript/subscript baseline', () => {
if (layout.fontScale <= 0.85) expect(layout.lnSpcReduction).toBeGreaterThan(0)
})
it('existing scale caps the ceiling: only steps smaller than it are used', () => {
it('a stored fontScale renders as-is (PowerPoint-on-open: no re-fit even when overflowing)', () => {
const many = Array.from({ length: 20 }, () => ({
runs: [{ text: '很长的一行文字内容', fontSize: 20 }],
}))
@@ -636,6 +640,24 @@ describe('shrink discrete steps + superscript/subscript baseline', () => {
metrics: new HeuristicMetrics(),
vp,
})
// Probe-measured: PowerPoint honors the cached ratio on open/export and overflows
// rather than re-fitting (a bare <a:normAutofit/> even renders at 100%).
expect(layout.fontScale).toBe(0.7)
expect(layout.lnSpcReduction).toBe(0.2)
})
it('refitAutofit (edit flows): steps below the stored scale, capped by it', () => {
const many = Array.from({ length: 20 }, () => ({
runs: [{ text: '很长的一行文字内容', fontSize: 20 }],
}))
const layout = layoutText({
body: body({ autofit: 'shrink', fontScale: 0.7, lnSpcReduction: 0.2, paragraphs: many }),
boxWidthPx: 400,
boxHeightPx: 120,
metrics: new HeuristicMetrics(),
vp,
refitAutofit: true,
})
expect(layout.fontScale).toBeLessThan(0.7)
// Existing 20% line-spacing reduction: stepping down further never regresses to a smaller reduction
expect(layout.lnSpcReduction).toBe(0.2)
@@ -1067,3 +1089,62 @@ describe('WordArt effect passthrough', () => {
expect(layout.extrusion!.dy).toBeGreaterThan(0)
})
})
describe('kerning threshold (rPr kern)', () => {
const kernFont: OpentypeFontLike = {
unitsPerEm: 1000,
ascender: 800,
descender: -200,
getAdvanceWidth: (text, size, options) =>
// 0.5em per char, minus a fake 0.1em kern pair per boundary when kerning is on
((text.length * 500 - (options?.kerning !== false ? (text.length - 1) * 100 : 0)) / 1000) *
size,
charToGlyphIndex: () => 1,
}
const om = new OpentypeMetrics(() => kernFont)
const run = (kern: number | undefined, fontSize: number) => ({
anchor: 'top' as const,
insets: { l: 0, t: 0, r: 0, b: 0 },
autofit: 'none' as const,
wrap: true,
paragraphs: [
{
runs: [{ text: 'AVAV', fontSize, ...(kern != null ? { kern } : {}) }],
pPrExplicit: {},
},
],
})
const width = (kern: number | undefined, fontSize: number) =>
layoutText({
body: run(kern, fontSize) as any,
boxWidthPx: 500,
boxHeightPx: 100,
metrics: om,
vp,
}).lines[0]!.runs[0]!.widthPx
it('kerns at or above the threshold, not below (absent = 12 pt default)', () => {
expect(width(undefined, 18)).toBeCloseTo(width(12, 18), 5) // both kerned
expect(width(undefined, 10)).toBeGreaterThan(width(undefined, 18) * (10 / 18) + 1e-6) // 10pt unkerned = wider per pt
expect(width(0, 18)).toBeGreaterThan(width(undefined, 18)) // kern=0 disables at any size
})
it('marks below-threshold glyph runs kerningOff for the draw layer', () => {
const l = layoutText({
body: run(undefined, 10) as any,
boxWidthPx: 500,
boxHeightPx: 100,
metrics: om,
vp,
})
expect(l.lines[0]!.runs[0]!.kerningOff).toBe(true)
const l2 = layoutText({
body: run(undefined, 18) as any,
boxWidthPx: 500,
boxHeightPx: 100,
metrics: om,
vp,
})
expect(l2.lines[0]!.runs[0]!.kerningOff).toBeUndefined()
})
})