Sync snapshot (2026-08-13) (#92)

- Docs: print dialog with live page preview and range selection; WYSIWYG print preview across apps
- Docs: header/footer fidelity - alignment, color, size, images, and tab layout (w:tabs, w:ptab)
- Docs: pagination and layout fixes - keepNext crash, blank pages, footnotes, line-height, font substitution, Tamil support
- Sheets: import implicit cell addresses and row/column default styles; keep dialog inputs inside narrow grid columns
- Slides: PowerPoint-style stage rulers, wheel page turning, and notes bar
- Slides: insert 3-D pie and 3-D column charts; render 3-D chart variants as 2-D projections
- PDF: comments margin with pin leader lines, note threads with replies, and selection-level text styles
- PDF: searchable text insertion, page management, and auto-opening of extract/split output

Co-authored-by: GenOffice <merrick-2002@users.noreply.github.com>
This commit is contained in:
merrick-2002
2026-08-13 21:37:38 +08:00
committed by GitHub
co-authored by GenOffice
parent 945c370fb9
commit d5558b6bbb
214 changed files with 19607 additions and 3168 deletions
+153 -29
View File
@@ -20,6 +20,44 @@ const PALETTE = ['#4472C4', '#ED7D31', '#A5A5A5', '#FFC000', '#5B9BD5', '#70AD47
const LABEL_FONT = 'Arial'
/** Series/wedge default colors: the file theme's accent1..6 when available, else the fixed approximation. */
function chartPalette(model: ChartModel): string[] {
return model.themePalette?.length ? model.themePalette : PALETTE
}
/** Chart body text size (pt): chartSpace-level c:txPr default, else 10pt. */
function chartTextPt(model: ChartModel): number {
return model.defaultTextPt ?? 10
}
/** Multiply an #RRGGBB color's channels (pseudo-3D face shading); non-hex passes through. */
function shade(color: string, f: number): string {
const m = /^#([0-9a-f]{6})$/i.exec(color)
if (!m) return color
const ch = (i: number) =>
Math.min(255, Math.round(parseInt(m[1]!.slice(i, i + 2), 16) * f))
.toString(16)
.padStart(2, '0')
return `#${ch(0)}${ch(2)}${ch(4)}`
}
/** Pseudo-3D extrusion faces for one bar (top + right, painter-ready before the front rect). */
function barFaces(
x: number,
y: number,
w: number,
h: number,
d: number,
color: string,
): Array<{ d: string; fill: string }> {
const top = `M ${x} ${y} L ${x + w} ${y} L ${x + w + d} ${y - d} L ${x + d} ${y - d} Z`
const side = `M ${x + w} ${y} L ${x + w + d} ${y - d} L ${x + w + d} ${y + h - d} L ${x + w} ${y + h} Z`
return [
{ d: top, fill: shade(color, 1.18) },
{ d: side, fill: shade(color, 0.78) },
]
}
export function buildChartNode(
id: string,
sourceId: string,
@@ -28,9 +66,14 @@ export function buildChartNode(
vp: Viewport,
metrics: FontMetricsProvider,
): ChartRenderNode | null {
if (!model.title) return buildChartNodeInner(id, sourceId, model, box, vp, metrics)
// With a title: the content area yields a top row; shift everything down and draw the title centered on top
const titleSizePx = ptToPx(12, vp.scale)
if (!model.title) {
const node = buildChartNodeInner(id, sourceId, model, box, vp, metrics)
if (node) extrudeBars(node, model)
return node
}
// With a title: the content area yields a top row; shift everything down and draw the title
// centered on top. PowerPoint sizes the auto title at 1.2× the chart's default text.
const titleSizePx = ptToPx(chartTextPt(model) * 1.2, vp.scale)
const titleH = titleSizePx * 1.7
const node = buildChartNodeInner(
id,
@@ -42,6 +85,7 @@ export function buildChartNode(
)
if (!node) return null
shiftChartNode(node, titleH)
extrudeBars(node, model)
node.box = box
const tw = metrics.measure(model.title, {
fontFamily: LABEL_FONT,
@@ -60,6 +104,17 @@ export function buildChartNode(
return node
}
/** Pseudo-3D bars: extrusion faces (top + right) behind every bar rect. */
function extrudeBars(node: ChartRenderNode, model: ChartModel): void {
if (!model.pseudo3D || !node.bars.length) return
const faces: NonNullable<ChartRenderNode['paths']> = []
for (const b of node.bars) {
const d = Math.min(Math.max(Math.min(b.w, b.h) * 0.35, 3), 14)
faces.push(...barFaces(b.x, b.y, b.w, b.h, d, b.color))
}
node.paths = [...faces, ...(node.paths ?? [])]
}
/** Shifts all chart draw primitives vertically (moving the content area down after the title claims space). */
function shiftChartNode(node: ChartRenderNode, dy: number): void {
for (const g of node.gridLines) {
@@ -77,6 +132,7 @@ function shiftChartNode(node: ChartRenderNode, dy: number): void {
for (const m of node.markers) m.y += dy
for (const s of node.swatches) s.y += dy
for (const w of node.wedges ?? []) w.cy += dy
for (const p of node.paths ?? []) p.dy = (p.dy ?? 0) + dy
}
function buildChartNodeInner(
@@ -131,10 +187,10 @@ function buildChartNodeInner(
swatches: [],
}
const labelSizePx = ptToPx(model.valAxis?.labelSizePt ?? 10, vp.scale)
const labelSizePx = ptToPx(model.valAxis?.labelSizePt ?? chartTextPt(model), vp.scale)
const labelColor = model.valAxis?.labelColor ?? '#666666'
const catLabelSizePx = ptToPx(
model.catAxis?.labelSizePt ?? model.valAxis?.labelSizePt ?? 10,
model.catAxis?.labelSizePt ?? model.valAxis?.labelSizePt ?? chartTextPt(model),
vp.scale,
)
const catLabelColor = model.catAxis?.labelColor ?? labelColor
@@ -146,7 +202,8 @@ function buildChartNodeInner(
})
const measure = (text: string, sizePx: number) => metrics.measure(text, style(sizePx))
const seriesColor = (i: number) => model.series[i]?.color ?? PALETTE[i % PALETTE.length]!
const palette = chartPalette(model)
const seriesColor = (i: number) => model.series[i]?.color ?? palette[i % palette.length]!
// ── Value range + nice ticks (primary/secondary axes independent) ──
if (!priVals.length) return null
@@ -208,7 +265,7 @@ function buildChartNodeInner(
const axisTitleW = model.valAxis?.title ? labelSizePx * 2.2 : 0
// Secondary axis (right): tick label width + optional axis-title placeholder
const secLabelSizePx = ptToPx(
model.valAxis2?.labelSizePt ?? model.valAxis?.labelSizePt ?? 10,
model.valAxis2?.labelSizePt ?? model.valAxis?.labelSizePt ?? chartTextPt(model),
vp.scale,
)
const secTickLabels = sec ? sec.ticks.map((t) => fmtNum(t)) : []
@@ -536,7 +593,7 @@ function buildPieNode(
wedges: [],
}
const labelSizePx = ptToPx(10, vp.scale)
const labelSizePx = ptToPx(chartTextPt(model), vp.scale)
const style: RunStyle = {
fontFamily: LABEL_FONT,
fontSizePx: labelSizePx,
@@ -544,7 +601,8 @@ function buildPieNode(
italic: false,
}
const measure = (text: string) => metrics.measure(text, style)
const sliceColor = (i: number) => ser.pointColors?.[i] ?? PALETTE[i % PALETTE.length]!
const palette = chartPalette(model)
const sliceColor = (i: number) => ser.pointColors?.[i] ?? palette[i % palette.length]!
const pad = Math.max(6, Math.min(box.w, box.h) * 0.03)
// Legend space (without a legend, the whole box goes to the pie)
@@ -579,20 +637,82 @@ function buildPieNode(
const cy = plotY + plotH / 2
const innerR = (outerR * Math.min(Math.max(model.holePct ?? 0, 0), 90)) / 100
// Pseudo-3D pie: the tilted disc projects to an ellipse (ry = sin(rotX) · rx) with a darker
// side rim of depth below the front-facing arcs; wedges become elliptical sector paths.
const p3d = !!model.pseudo3D && innerR === 0
const kY = p3d
? Math.min(Math.max(Math.sin(((model.rotXDeg ?? 30) * Math.PI) / 180), 0.35), 0.9)
: 1
const rx = p3d ? Math.max(Math.min(plotW / 2, plotH / 2 / (kY + 0.3)), 5) : outerR
const ry = rx * kY
const depth = p3d ? ry * 0.3 : 0
const ptAt = (deg: number) => {
const t = (deg * Math.PI) / 180
return { x: cx + Math.cos(t) * rx, y: cy + Math.sin(t) * ry }
}
if (p3d) {
node.paths = node.paths ?? []
// Rim: the front half is the parametric range [0°, 180°) (screen lower half)
let a = -90 + (model.firstSliceAngDeg ?? 0)
vals.forEach((v, i) => {
if (v <= 0) return
const sweep = (v / total) * 360
// normalize wedge interval into [-180, 180) then clamp to the front range [0, 180]
for (const off of [-360, 0, 360]) {
const b1 = Math.max(a + off, 0)
const b2 = Math.min(a + off + sweep, 180)
if (b2 <= b1) continue
const p1 = ptAt(b1)
const p2 = ptAt(b2)
const large = b2 - b1 > 180 ? 1 : 0
node.paths!.push({
d:
`M ${p1.x} ${p1.y} A ${rx} ${ry} 0 ${large} 1 ${p2.x} ${p2.y} ` +
`L ${p2.x} ${p2.y + depth} A ${rx} ${ry} 0 ${large} 0 ${p1.x} ${p1.y + depth} Z`,
fill: shade(sliceColor(i), 0.72),
})
}
a += sweep
})
}
// Wedges: start at 12 o'clock (Konva rotation 0 = 3 o'clock, hence -90°), clockwise
let angle = -90 + (model.firstSliceAngDeg ?? 0)
vals.forEach((v, i) => {
if (v <= 0) return
const sweep = (v / total) * 360
node.wedges!.push({
cx,
cy,
outerR,
innerR,
startDeg: angle,
sweepDeg: sweep,
color: sliceColor(i),
})
if (p3d) {
const p1 = ptAt(angle)
if (sweep >= 359.999) {
// Full circle: an SVG arc with coincident endpoints renders nothing, so use two half arcs
const pm = ptAt(angle + 180)
node.paths!.push({
d:
`M ${p1.x} ${p1.y} A ${rx} ${ry} 0 1 1 ${pm.x} ${pm.y} ` +
`A ${rx} ${ry} 0 1 1 ${p1.x} ${p1.y} Z`,
fill: sliceColor(i),
stroke: '#ffffff',
})
} else {
const p2 = ptAt(angle + sweep)
const large = sweep > 180 ? 1 : 0
node.paths!.push({
d: `M ${cx} ${cy} L ${p1.x} ${p1.y} A ${rx} ${ry} 0 ${large} 1 ${p2.x} ${p2.y} Z`,
fill: sliceColor(i),
stroke: '#ffffff',
})
}
} else {
node.wedges!.push({
cx,
cy,
outerR,
innerR,
startDeg: angle,
sweepDeg: sweep,
color: sliceColor(i),
})
}
if (model.dataLabels) {
// At the wedge midline radius: doughnut uses the ring-band midpoint, pie uses 2/3 radius
const midRad = ((angle + sweep / 2) * Math.PI) / 180
@@ -600,8 +720,8 @@ function buildPieNode(
const text = model.dataLabelsPct ? `${Math.round((v / total) * 100)}%` : fmtNum(v)
node.labels.push({
text,
x: cx + Math.cos(midRad) * r - measure(text) / 2,
y: cy + Math.sin(midRad) * r - labelSizePx * 0.55,
x: cx + Math.cos(midRad) * (p3d ? rx * 0.66 : r) - measure(text) / 2,
y: cy + Math.sin(midRad) * (p3d ? ry * 0.66 : r) - labelSizePx * 0.55,
fontSizePx: labelSizePx * 0.9,
color: '#FFFFFF',
})
@@ -674,10 +794,10 @@ function buildHBarNode(
const stacked = grouping === 'stacked' || grouping === 'percentStacked'
const node = emptyChartNode(id, sourceId, box)
const labelSizePx = ptToPx(model.valAxis?.labelSizePt ?? 10, vp.scale)
const labelSizePx = ptToPx(model.valAxis?.labelSizePt ?? chartTextPt(model), vp.scale)
const labelColor = model.valAxis?.labelColor ?? '#666666'
const catLabelSizePx = ptToPx(
model.catAxis?.labelSizePt ?? model.valAxis?.labelSizePt ?? 10,
model.catAxis?.labelSizePt ?? model.valAxis?.labelSizePt ?? chartTextPt(model),
vp.scale,
)
const catLabelColor = model.catAxis?.labelColor ?? labelColor
@@ -688,7 +808,8 @@ function buildHBarNode(
italic: false,
})
const measure = (text: string, sizePx: number) => metrics.measure(text, style(sizePx))
const seriesColor = (i: number) => model.series[i]?.color ?? PALETTE[i % PALETTE.length]!
const palette = chartPalette(model)
const seriesColor = (i: number) => model.series[i]?.color ?? palette[i % palette.length]!
const allVals = model.series.flatMap((s) => s.values.filter((v): v is number => v != null))
if (!allVals.length) return null
@@ -785,11 +906,12 @@ function buildHBarNode(
widthPx: axisW,
})
// Category labels (y axis, left). By default the first category is on top; c:orientation maxMin reverses
// Category labels (y axis, left). PowerPoint default (minMax) puts the first category at the
// BOTTOM for horizontal bars; c:orientation maxMin flips the first one to the top
const n = Math.max(model.categories.length, 1)
const slotH = plot.h / n
const rowY = (i: number) => {
const pos = model.catAxis?.reversed ? n - 1 - i : i
const pos = model.catAxis?.reversed ? i : n - 1 - i
return plot.y + pos * slotH
}
model.categories.forEach((cat, i) => {
@@ -880,7 +1002,7 @@ function buildScatterNode(
metrics: FontMetricsProvider,
): ChartRenderNode | null {
const node = emptyChartNode(id, sourceId, box)
const labelSizePx = ptToPx(model.valAxis?.labelSizePt ?? 10, vp.scale)
const labelSizePx = ptToPx(model.valAxis?.labelSizePt ?? chartTextPt(model), vp.scale)
const labelColor = model.valAxis?.labelColor ?? '#666666'
const style = (sizePx: number): RunStyle => ({
fontFamily: LABEL_FONT,
@@ -889,7 +1011,8 @@ function buildScatterNode(
italic: false,
})
const measure = (text: string, sizePx: number) => metrics.measure(text, style(sizePx))
const seriesColor = (i: number) => model.series[i]?.color ?? PALETTE[i % PALETTE.length]!
const palette = chartPalette(model)
const seriesColor = (i: number) => model.series[i]?.color ?? palette[i % palette.length]!
// Point sets: x defaults to indices 1..n
const points = model.series.map((s) =>
@@ -1057,7 +1180,7 @@ function buildRadarNode(
if (!allVals.length) return null
const node = emptyChartNode(id, sourceId, box)
const labelSizePx = ptToPx(model.valAxis?.labelSizePt ?? 10, vp.scale)
const labelSizePx = ptToPx(model.valAxis?.labelSizePt ?? chartTextPt(model), vp.scale)
const labelColor = model.valAxis?.labelColor ?? '#666666'
const catLabelColor = model.catAxis?.labelColor ?? labelColor
const style = (sizePx: number): RunStyle => ({
@@ -1067,7 +1190,8 @@ function buildRadarNode(
italic: false,
})
const measure = (text: string, sizePx: number) => metrics.measure(text, style(sizePx))
const seriesColor = (i: number) => model.series[i]?.color ?? PALETTE[i % PALETTE.length]!
const palette = chartPalette(model)
const seriesColor = (i: number) => model.series[i]?.color ?? palette[i % palette.length]!
const { min, max, ticks } = ppTicks(
model.valAxis?.min ?? Math.min(...allVals, 0),
+12 -2
View File
@@ -179,6 +179,10 @@ function buildNode(
}
if (node.type === 'chart') {
;(node as import('./render-tree').ChartRenderNode).styleInfo = chartStyleInfo(chartEl.chart)
if (chartEl.chart.bgFill) {
const bg = resolveFill(chartEl.chart.bgFill, vp, media)
if (bg.kind !== 'none') (node as import('./render-tree').ChartRenderNode).bgFill = bg
}
}
return node
}
@@ -462,6 +466,7 @@ function buildTable(
boxHeightPx: rowPx[r] ?? 0,
metrics,
vp,
trimEdgeSpacing: true,
})
const needed = probe.contentHeight + probe.insets.t + probe.insets.b
if (needed > (rowPx[r] ?? 0)) rowPx[r] = needed
@@ -509,6 +514,7 @@ function buildTable(
boxHeightPx: h,
metrics,
vp,
trimEdgeSpacing: true,
})
}
cells.push(out)
@@ -535,11 +541,15 @@ function chartStyleInfo(m: ChartElement['chart']): import('./render-tree').Chart
? 'comboBarLine'
: m.grouping === 'stacked' || m.grouping === 'percentStacked'
? 'barStacked'
: 'bar'
: m.pseudo3D
? 'bar3D'
: 'bar'
: m.kind === 'pie'
? (m.holePct ?? 0) > 0
? 'doughnut'
: 'pie'
: m.pseudo3D
? 'pie3D'
: 'pie'
: m.kind
return {
kind,
+8
View File
@@ -27,6 +27,14 @@ export function resolveFill(
stops: fill.stops.map((s) => ({ pos: s.pos, color: s.color })),
angleDeg: fill.angle != null ? fill.angle / 60000 : 0,
...(fill.path ? { radial: true } : {}),
...(fill.path && fill.fillTo
? {
center: {
x: (fill.fillTo.l + (1 - fill.fillTo.r)) / 2,
y: (fill.fillTo.t + (1 - fill.fillTo.b)) / 2,
},
}
: {}),
}
case 'image':
return {
+10
View File
@@ -47,6 +47,8 @@ export type RenderFill =
stops: Array<{ pos: number; color: string }>
angleDeg: number
radial?: boolean
/** Radial focus center as width/height fractions (from <a:fillToRect>; default 0.5/0.5) */
center?: { x: number; y: number }
}
| { kind: 'image'; dataUrl?: string; mode: 'stretch' | 'tile' }
@@ -93,6 +95,8 @@ export interface GlyphRun {
underline: boolean
/** Strikethrough (<a:rPr strike>) */
strike?: boolean
/** Text highlight color (<a:rPr><a:highlight>, drawn as a background behind the run) */
highlight?: string
/** Raw super/subscript baseline % (positive = superscript; for editor round-trips, the shift is baked into baselineY) */
baselinePct?: number
/** Run width (px, including metrics and letter spacing) */
@@ -288,10 +292,12 @@ export interface ChartLabel {
export interface ChartStyleInfo {
kind:
| 'bar'
| 'bar3D'
| 'barStacked'
| 'line'
| 'area'
| 'pie'
| 'pie3D'
| 'doughnut'
| 'scatter'
| 'radar'
@@ -311,6 +317,8 @@ export interface ChartRenderNode extends RenderNodeBase {
/** Inserted by this app (cNvPr descr="aislides-chart"): chart editing enabled; passthrough charts lack this flag */
appCreated?: boolean
styleInfo?: ChartStyleInfo
/** Whole-chart background (chartSpace spPr, e.g. picture fill) drawn under all primitives */
bgFill?: RenderFill
/** Gridlines / axis lines */
gridLines: Array<{
x1: number
@@ -345,6 +353,8 @@ export interface ChartRenderNode extends RenderNodeBase {
markers: Array<{ x: number; y: number; r: number; color: string }>
/** Legend swatches */
swatches: Array<{ x: number; y: number; w: number; h: number; color: string }>
/** Freeform filled paths (SVG data), painter's order — pseudo-3D pie rims / bar extrusion faces */
paths?: Array<{ d: string; fill: string; stroke?: string; dy?: number }>
/** Pie/doughnut wedges (angles: 12 o'clock = -90°, clockwise, Konva Arc semantics) */
wedges?: Array<{
cx: number
+47 -10
View File
@@ -34,6 +34,8 @@ interface Token {
color: string
underline: boolean
strike?: boolean
/** Text highlight color (<a:rPr><a:highlight>, drawn as a background behind the run) */
highlight?: string
/** Raw super/subscript baseline % (for editor round-trips; blShift is the baked px) */
blPct?: number
/** Letter spacing (px/char, may be negative; <a:rPr spc>, counted in both width and rendering) */
@@ -76,6 +78,20 @@ function tokenWidth(tok: Token, metrics: FontMetricsProvider): number {
return tok.ls ? w + tok.ls * [...tok.text].length : w
}
/**
* rPr cap="all"/"small" display transform. Length-preserving: code points whose uppercase
* expands (ß→SS) stay as-is so click-to-caret offsets keep mapping 1:1 to source text.
*/
function applyCap(text: string, cap: string | undefined): string {
if (cap !== 'all' && cap !== 'small') return text
let out = ''
for (const ch of text) {
const u = ch.toUpperCase()
out += [...u].length === 1 ? u : ch
}
return out
}
/** Splits a paragraph's runs into a breakable token stream (whitespace / single CJK chars / Latin words). */
function tokenizeParagraph(p: Paragraph, scale: number, fontScale: number): Token[] {
const tokens: Token[] = []
@@ -95,6 +111,7 @@ function tokenizeParagraph(p: Paragraph, scale: number, fontScale: number): Toke
...(run.fontFamily ? { srcFont: run.fontFamily } : {}),
...(run.hyperlink ? { link: run.hyperlink } : {}),
...(run.strike ? { strike: true } : {}),
...(run.highlight ? { highlight: run.highlight } : {}),
...(run.baseline ? { blPct: run.baseline } : {}),
...(blShift ? { blShift } : {}),
...(run.outline
@@ -120,7 +137,7 @@ function tokenizeParagraph(p: Paragraph, scale: number, fontScale: number): Toke
buf = ''
}
// Per grapheme cluster: combining marks / ZWJ emoji always share a token with their base char, never split by wrapping
for (const ch of graphemes(run.text)) {
for (const ch of graphemes(applyCap(run.text, run.cap))) {
const cp = ch.codePointAt(0) ?? 0
if (ch === '\n' || ch === '\v') {
flushWord()
@@ -392,6 +409,7 @@ function buildLine(
italic: tok.style.italic,
underline: tok.underline,
...(tok.strike ? { strike: true } : {}),
...(tok.highlight ? { highlight: tok.highlight } : {}),
widthPx: w,
...(tok.ls ? { letterSpacingPx: tok.ls } : {}),
...(tok.outline ? { outline: tok.outline } : {}),
@@ -444,6 +462,9 @@ export interface TextLayoutInput {
boxHeightPx: number
metrics: FontMetricsProvider
vp: Viewport
/** 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
}
/** Main entry: TextBody → RenderTextLayout (including autofit shrink stepping). */
@@ -472,7 +493,7 @@ export function layoutText(input: TextLayoutInput): RenderTextLayout {
)
const build = (fontScale: number, lnSpcRed: number) =>
layoutAll(body, availWidth, wrap, metrics, vp.scale, fontScale, lnSpcRed)
layoutAll(body, availWidth, wrap, metrics, vp.scale, fontScale, lnSpcRed, input.trimEdgeSpacing)
// PowerPoint's stored shrink ratio takes priority (files with shrunk text render
// as-is; we don't scale back up per our own metrics). Only if content still
@@ -483,7 +504,18 @@ export function layoutText(input: TextLayoutInput): RenderTextLayout {
let fontScale = storedScale
let lnSpcReduction = storedRed
let result = build(fontScale, lnSpcReduction)
if (body.autofit === 'shrink' && result.contentHeight > availHeight) {
// PowerPoint's autofit ignores trailing blank paragraphs (files where the stored
// ratio only fits when they are excluded), so overflow is judged by the bottom of
// the last non-blank line — plus 3% slack for residual metric drift, since
// PowerPoint renders the authored scale as-is.
const fitBottom = (r: { lines: TextLine[]; contentHeight: number }): number => {
for (let i = r.lines.length - 1; i >= 0; i--) {
const ln = r.lines[i]!
if (ln.runs.some((run) => run.text.trim())) return ln.top + ln.height
}
return r.contentHeight
}
if (body.autofit === 'shrink' && fitBottom(result) > availHeight * 1.03) {
for (const [fs, red] of SHRINK_STEPS) {
if (fs >= storedScale - 1e-6) continue
const effRed = Math.max(red, storedRed)
@@ -491,7 +523,7 @@ export function layoutText(input: TextLayoutInput): RenderTextLayout {
fontScale = fs
lnSpcReduction = effRed
result = r
if (r.contentHeight <= availHeight) break
if (fitBottom(r) <= availHeight) break
// Still doesn't fit after all steps → stop at 25% (overflow allowed)
}
}
@@ -638,6 +670,7 @@ function layoutTextVertical(
italic: tok.style.italic,
underline: tok.underline,
...(tok.strike ? { strike: true } : {}),
...(tok.highlight ? { highlight: tok.highlight } : {}),
...(tok.outline ? { outline: tok.outline } : {}),
widthPx: metrics.measure(g, tok.style),
...(tok.blPct ? { baselinePct: tok.blPct } : {}),
@@ -670,6 +703,7 @@ function layoutTextVertical(
italic: tok.style.italic,
underline: tok.underline,
...(tok.strike ? { strike: true } : {}),
...(tok.highlight ? { highlight: tok.highlight } : {}),
...(tok.outline ? { outline: tok.outline } : {}),
widthPx: adv,
rotate90: true,
@@ -790,11 +824,12 @@ function layoutAll(
scale: number,
fontScale: number,
lnSpcRed: number,
trimEdgeSpacing?: boolean,
): { lines: TextLine[]; contentHeight: number } {
const outLines: TextLine[] = []
let y = 0
let autoNum = 0 // buAutoNum sequential numbering (reset on a non-numbered paragraph)
for (const p of body.paragraphs) {
for (const [pIdx, p] of body.paragraphs.entries()) {
// Indent and bullets (body lines start at marL; the bullet
// draws at marL+indent, negative indent = hanging indent; without a bullet the
// first line starts at marL+indent)
@@ -843,9 +878,10 @@ function layoutAll(
)
// Space before/after: spcPts is absolute pt; spcPct is a percentage of the paragraph's single line height (100 = one line)
const singleH = laid[0]?.singleH ?? 0
y +=
ptToPx(p.spaceBefore ?? 0, scale) +
(p.spaceBeforePct ? singleH * (p.spaceBeforePct / 100) : 0)
if (!(trimEdgeSpacing && pIdx === 0))
y +=
ptToPx(p.spaceBefore ?? 0, scale) +
(p.spaceBeforePct ? singleH * (p.spaceBeforePct / 100) : 0)
laid.forEach((ln, li) => {
const baseline = y + ln.ascent
const lineWidth = ln.runs.reduce((acc, r) => acc + r.widthPx, 0)
@@ -921,8 +957,9 @@ function layoutAll(
})
y += ln.height
})
y +=
ptToPx(p.spaceAfter ?? 0, scale) + (p.spaceAfterPct ? singleH * (p.spaceAfterPct / 100) : 0)
if (!(trimEdgeSpacing && pIdx === body.paragraphs.length - 1))
y +=
ptToPx(p.spaceAfter ?? 0, scale) + (p.spaceAfterPct ? singleH * (p.spaceAfterPct / 100) : 0)
}
return { lines: outLines, contentHeight: y }
}
+44 -5
View File
@@ -213,6 +213,26 @@ describe('buildChartNode', () => {
expect(node.swatches).toHaveLength(3)
})
it('pseudo-3D pie with a single 360° slice still emits a filled face path', () => {
const pie: ChartModel = {
kind: 'pie',
pseudo3D: true,
categories: ['only', 'zero'],
series: [{ values: [5, 0] }],
}
const node = buildChartNode('r_5b', 'el5b', pie, box, vp, metrics)!
expect(node.wedges ?? []).toHaveLength(0)
const faces = node.paths!.filter((p) => p.stroke === '#ffffff')
expect(faces).toHaveLength(1)
// The full-circle face must be two half arcs, not one degenerate arc
expect(faces[0]!.d.match(/A /g)).toHaveLength(2)
expect(faces[0]!.d.startsWith('M ')).toBe(true)
// Endpoints of the two arcs differ (top of the ellipse vs its opposite point)
const nums = faces[0]!.d.match(/-?\d+(\.\d+)?/g)!.map(Number)
// d = M x0 y0 A rx ry 0 1 1 x1 y1 A rx ry 0 1 1 x0 y0 Z → y0 at index 1, y1 at index 8
expect(nums[1]).not.toBeCloseTo(nums[8]!, 3)
})
it('doughnut hole uses holePct of outer radius', () => {
const dough: ChartModel = {
kind: 'pie',
@@ -225,7 +245,7 @@ describe('buildChartNode', () => {
expect(w.innerR).toBeCloseTo(w.outerR / 2, 5)
})
it('builds horizontal bar: bars extend along x axis, first category on top, larger values give longer bars', () => {
it('builds horizontal bar: bars extend along x axis, first category at bottom, larger values give longer bars', () => {
const model: ChartModel = {
kind: 'bar',
barDir: 'bar',
@@ -237,8 +257,8 @@ describe('buildChartNode', () => {
const node = buildChartNode('r_h', 'elh', model, box, vp, metrics)!
expect(node.bars).toHaveLength(2)
const [b1, b2] = node.bars
// The first category is on top
expect(b1!.y).toBeLessThan(b2!.y)
// PowerPoint default (minMax): the first category is at the bottom
expect(b1!.y).toBeGreaterThan(b2!.y)
// The value-30 bar is longer than the value-10 bar (in the width direction)
expect(b2!.w).toBeGreaterThan(b1!.w)
// Bar height > 0 and within the box
@@ -248,7 +268,7 @@ describe('buildChartNode', () => {
}
})
it('horizontal bar reversed (orientation maxMin): first category at bottom', () => {
it('horizontal bar reversed (orientation maxMin): first category on top', () => {
const model: ChartModel = {
kind: 'bar',
barDir: 'bar',
@@ -258,7 +278,7 @@ describe('buildChartNode', () => {
}
const node = buildChartNode('r_h2', 'elh2', model, box, vp, metrics)!
const [b1, b2] = node.bars
expect(b1!.y).toBeGreaterThan(b2!.y)
expect(b1!.y).toBeLessThan(b2!.y)
})
it('builds scatter: positioned by two value axes, lineMarker draws points and lines by default', () => {
@@ -341,3 +361,22 @@ describe('buildChartNode', () => {
expect(p.points[1]).toBeCloseTo(p.points[p.points.length - 1]!, 5)
})
})
describe('chartSpace default text size reaches every label group', () => {
const ptToPxAt = (pt: number) => (pt * 96) / 72 // vp scale is 1280/12192000EMU ≈ 96dpi ⇒ px = pt×96/72×(scale)
it('category + value labels fall back to defaultTextPt, not 10pt', () => {
const model: ChartModel = {
kind: 'bar',
barDir: 'col',
grouping: 'clustered',
categories: ['A', 'B'],
series: [{ name: 'S', values: [1, 2] }],
defaultTextPt: 18,
}
const node = buildChartNode('r_1', 'el1', model, box, vp, metrics)!
const sizes = new Set(node.labels.map((l) => Math.round(l.fontSizePx)))
const scale = vp.scale
expect(sizes.has(Math.round(ptToPxAt(18) * scale))).toBe(true)
expect(sizes.has(Math.round(ptToPxAt(10) * scale))).toBe(false)
})
})
@@ -720,3 +720,104 @@ describe('vertical layout latin word rotation', () => {
expect(rotated[0]!.x).toBeLessThanOrEqual(300)
})
})
describe('text highlight propagation', () => {
it('run highlight lands on every glyph run split from it, others stay clean', () => {
const layout = layoutText({
body: body({
paragraphs: [
{
runs: [
{ text: 'marked text', fontSize: 18, highlight: '#FF0000' },
{ text: ' plain', fontSize: 18 },
],
},
],
}),
boxWidthPx: 400,
boxHeightPx: 200,
metrics: new HeuristicMetrics(),
vp,
})
const runs = layout.lines.flatMap((l) => l.runs)
const marked = runs.filter((r) => r.highlight)
expect(marked.length).toBeGreaterThan(0)
expect(marked.every((r) => r.highlight === '#FF0000')).toBe(true)
expect(marked.map((r) => r.text).join('')).toBe('marked text')
expect(
runs
.filter((r) => !r.highlight)
.map((r) => r.text)
.join(''),
).toBe(' plain')
})
})
describe('table cell edge spacing (trimEdgeSpacing)', () => {
const paras = [
{ runs: [{ text: 'first', fontSize: 12 }], spaceBefore: 10, spaceAfter: 10 },
{ runs: [{ text: 'last', fontSize: 12 }], spaceBefore: 10, spaceAfter: 10 },
]
it('drops the first space-before and last space-after only', () => {
const plain = layoutText({
body: body({ paragraphs: paras }),
boxWidthPx: 400,
boxHeightPx: 200,
metrics: new HeuristicMetrics(),
vp,
})
const trimmed = layoutText({
body: body({ paragraphs: paras }),
boxWidthPx: 400,
boxHeightPx: 200,
metrics: new HeuristicMetrics(),
vp,
trimEdgeSpacing: true,
})
// 10pt before-first + 10pt after-last dropped (pt → px at scale 1: ×96/72)
expect(plain.contentHeight - trimmed.contentHeight).toBeCloseTo((20 * 96) / 72, 1)
// inner spacing (after-first + before-last) is kept
expect(trimmed.lines[1]!.top - (trimmed.lines[0]!.top + trimmed.lines[0]!.height)).toBeCloseTo(
(20 * 96) / 72,
1,
)
// first line starts at the very top
expect(trimmed.lines[0]!.top).toBe(0)
})
})
describe('autofit ignores trailing blank paragraphs', () => {
it('keeps the stored scale when only trailing blanks overflow', () => {
// 3 content lines fit the box; 4 trailing blanks push contentHeight past it
const paragraphs = [
{ runs: [{ text: 'one', fontSize: 18 }] },
{ runs: [{ text: 'two', fontSize: 18 }] },
{ runs: [{ text: 'three', fontSize: 18 }] },
{ runs: [] },
{ runs: [] },
{ runs: [] },
{ runs: [] },
]
const layout = layoutText({
body: body({ paragraphs, autofit: 'shrink' }),
boxWidthPx: 400,
boxHeightPx: 100,
metrics: new HeuristicMetrics(),
vp,
})
expect(layout.fontScale).toBe(1)
})
it('still shrinks when real content overflows', () => {
const paragraphs = Array.from({ length: 12 }, () => ({
runs: [{ text: 'line of text', fontSize: 18 }],
}))
const layout = layoutText({
body: body({ paragraphs, autofit: 'shrink' }),
boxWidthPx: 400,
boxHeightPx: 100,
metrics: new HeuristicMetrics(),
vp,
})
expect(layout.fontScale).toBeLessThan(1)
})
})