Sync snapshot (2026-08-30) (#168)

- Docs: DOCX rendering fidelity - drop caps, hidden (vanish) runs, paragraph pattern shading, floating-table anchoring and clamping, footnote sizing, justified-line spacing
- Docs: editing - page breaks split the paragraph correctly, URLs auto-linkify, Insert Hyperlink prefills from the selection, more stable table pagination
- Sheets: large streamed workbooks are splittable and formula-capable for the AI; copy_range carries live formulas; range sort up to 200k cells; 1M-cell copies over 2x faster
- Sheets: correctness - sort by raw values, shared-formula edits, typed cached strings, empty-string cells, note edits reach the save; risky structural deletes are rejected up front
- Sheets: AI chat can export sheets as standalone files; the formula bar grows to fit wrapped formulas
- Slides: right-to-left support - paragraph direction toggle, RTL tables, mirrored margins and bullets
- Slides: rendering - scaled gradients, embedded fonts, complex-script shaping, chart plot layouts and legends, theme-override colors
- Shell: open documents by dropping them onto the window; per-type document icons for OS file associations
- AI: localized busy message for overloaded providers; degenerate tool loops stopped with a unified turn budget
- Markdown: prompts to save before pasting images into untitled documents

Co-authored-by: GenOffice <merrick-2002@users.noreply.github.com>
This commit is contained in:
merrick-2002
2026-08-30 21:26:55 +08:00
committed by GitHub
co-authored by GenOffice
parent 583a045212
commit 2239cce9e7
229 changed files with 14881 additions and 3420 deletions
+94 -30
View File
@@ -144,12 +144,13 @@ export function buildChartNode(
const titleH = titleSizePx * 1.4 * titleLines.length + titleSizePx * 0.3
// A manual plot layout already positions the plot in full-frame fractions (title space
// included), so the content must not shrink or shift — but only the cartesian builder
// consumes plotLayout; pie/scatter/radar/hbar still lay out from the (shrunk) frame
// consumes plotLayout; pie/scatter/radar still lay out from the (shrunk) frame
const manual =
(!!model.plotLayout &&
(model.kind === 'line' ||
model.kind === 'area' ||
(model.kind === 'bar' && model.barDir !== 'bar'))) ||
model.kind === 'bar' ||
model.kind === 'pie')) ||
// <c:overlay val="1"/>: the title floats over the plot without reserving space
!!model.titleOverlay
const node = buildChartNodeInner(
@@ -1280,6 +1281,16 @@ function buildPieNode(
plotY += legendRowH
plotH -= legendRowH
} else if (legendPos === 'b') plotH -= legendRowH
// The deck-authored inner plot rect wins over all the legend-reservation
// heuristics (same contract as the bar/line builders); the legend then
// places itself from its own manual layout
const L = model.plotLayout
if (L) {
plotX = L.x * box.w
plotY = L.y * box.h
plotW = Math.max(L.w * box.w, 10)
plotH = Math.max(L.h * box.h, 10)
}
// Explosion: slice offset = (explosion/100)·diameter along its mid-angle; the radius
// shrinks so the exploded footprint stays ≈ the unexploded one (PowerPoint keeps bounds)
@@ -1295,7 +1306,11 @@ function buildPieNode(
let pieHalfPx = Math.min(plotW, plotH) / 2 + pad
if (legendPos === 'l') pieHalfPx = Math.min(pieHalfPx, plotW / 2)
if (legendPos === 't') pieHalfPx = Math.min(pieHalfPx, plotH / 2)
const outerR = Math.max(pieHalfPx - pieReservePx, 5) / (1 + 2 * maxExpl)
// A deck-authored inner rect already IS the pie's bounding area — the frame-
// relative 4mm ring and pad correction don't apply on top of it
const outerR = L
? Math.max(Math.min(plotW, plotH) / 2, 5) / (1 + 2 * maxExpl)
: Math.max(pieHalfPx - pieReservePx, 5) / (1 + 2 * maxExpl)
const cx = plotX + plotW / 2
let cy = plotY + plotH / 2
const innerR = (outerR * Math.min(Math.max(model.holePct ?? 0, 0), 90)) / 100
@@ -1415,28 +1430,67 @@ function buildPieNode(
// Legend
if (legendPos) {
const sw = labelSizePx * 0.5
if (legendPos === 't' || legendPos === 'b') {
const itemWs = legendItems.map((it) => sw + 4 + measure(it.label) + labelSizePx * 0.5)
const totalW = itemWs.reduce((a, b) => a + b, 0)
let x = Math.max((box.w - totalW) / 2, pad)
const y = legendPos === 't' ? pad * 0.5 : box.h - pad * 0.5 - labelSizePx * 1.2
legendItems.forEach((it, i) => {
node.swatches.push({
x,
y: y + labelSizePx * 0.25,
w: sw,
h: labelSizePx * 0.5,
color: it.color,
})
node.labels.push({
text: it.label,
x: x + sw + 4,
y,
fontSizePx: labelSizePx,
color: labelColor,
})
x += itemWs[i]!
const lay = model.legendLayout
const rtl = !!model.legendRtl
const entry = (
x: number,
y: number,
it: { label: string; color: string },
itemW: number,
textW: number,
) => {
// RTL entries mirror: swatch at the right edge, text tight against it —
// itemW's trailing 0.5em stays as the inter-item gap on the left side
const swX = rtl ? x + itemW - sw : x
const txX = rtl ? x + itemW - sw - 4 - textW : x + sw + 4
node.swatches.push({
x: swX,
y: y + labelSizePx * 0.25,
w: sw,
h: labelSizePx * 0.5,
color: it.color,
})
node.labels.push({ text: it.label, x: txX, y, fontSizePx: labelSizePx, color: labelColor })
}
if (legendPos === 't' || legendPos === 'b') {
const textWs = legendItems.map((it) => measure(it.label))
const itemWs = textWs.map((w) => sw + 4 + w + labelSizePx * 0.5)
const totalW = itemWs.reduce((a, b) => a + b, 0)
const rect =
lay?.w !== undefined && lay.x !== undefined && lay.xMode === 'edge'
? {
x: lay.x * box.w,
y: (lay.y ?? (legendPos === 't' ? 0 : 0.85)) * box.h,
w: lay.w * box.w,
}
: null
if (rect && totalW > rect.w) {
// The authored rect cannot fit one row: flow one entry per row, aligned
// to the reading direction (PowerPoint wraps inside the legend frame)
const rowH = labelSizePx * 1.5
legendItems.forEach((it, i) => {
const w = itemWs[i]!
// over-wide entries clamp to the rect's left edge instead of spilling out
const x = rtl ? Math.max(rect.x + rect.w - w, rect.x) : rect.x
entry(x, rect.y + i * rowH, it, w, textWs[i]!)
})
} else {
let x = rect
? rtl
? rect.x + rect.w - totalW
: rect.x
: Math.max((box.w - totalW) / 2, pad)
const y = rect
? rect.y
: legendPos === 't'
? pad * 0.5
: box.h - pad * 0.5 - labelSizePx * 1.2
const ordered = rtl ? [...legendItems.keys()].reverse() : [...legendItems.keys()]
for (const i of ordered) {
entry(x, y, legendItems[i]!, itemWs[i]!, textWs[i]!)
x += itemWs[i]!
}
}
} else {
const x = legendPos === 'l' ? pad : box.w - sideLegendW
let y = Math.max(cy - (legendItems.length * legendRowH) / 2, pad)
@@ -2096,12 +2150,22 @@ function buildHBarNode(
const plotR = box.w - pad - labelSizePx * 0.7 - legendW
// Bottom row = 0.75em tick gap + one label line (PPT-measured ≈2em at 18pt)
const plotB = box.h - pad - labelSizePx * 2.0 - (legendPos === 'b' ? legendH : 0)
const plot = {
x: plotX,
y: plotY,
w: Math.max(plotR - plotX, 10),
h: Math.max(plotB - plotY, 10),
}
// An explicit inner plot rect wins over the heuristics — decks position hbar
// frames partly off-slide and rely on the manual layout for what stays visible
const L = model.plotLayout
const plot = L
? {
x: L.x * box.w,
y: L.y * box.h,
w: Math.max(L.w * box.w, 10),
h: Math.max(L.h * box.h, 10),
}
: {
x: plotX,
y: plotY,
w: Math.max(plotR - plotX, 10),
h: Math.max(plotB - plotY, 10),
}
// c:orientation maxMin flips the mapping (max at the left)
const rev = !!model.valAxis?.reversed
+2
View File
@@ -26,6 +26,7 @@ export function resolveFill(
kind: 'gradient',
stops: fill.stops.map((s) => ({ pos: s.pos, color: s.color })),
angleDeg: fill.angle != null ? fill.angle / 60000 : 0,
...(fill.scaled ? { scaled: true } : {}),
...(fill.path ? { radial: true, path: fill.path } : {}),
...(fill.path && fill.fillTo
? {
@@ -86,6 +87,7 @@ export function resolveStroke(stroke: Stroke | undefined, vp: Viewport): RenderS
gradient = {
stops: rf.stops.map((s) => ({ pos: s.pos, color: s.color })),
angleDeg: rf.angle != null ? rf.angle / 60000 : 0,
...(rf.scaled ? { scaled: true } : {}),
}
color = rf.stops[0]!.color
} else if (rf.type === 'none') return undefined
+6 -2
View File
@@ -50,6 +50,8 @@ export type RenderFill =
kind: 'gradient'
stops: Array<{ pos: number; color: string }>
angleDeg: number
/** <a:lin scaled="1">: angle stretches with the box aspect (45° runs corner-to-corner) */
scaled?: boolean
radial?: boolean
/** Actual <a:path path> kind (circle/rect/shape); rendering approximates all as radial */
path?: 'circle' | 'rect' | 'shape'
@@ -98,7 +100,7 @@ export interface RenderStroke {
/** Compound line type (<a:ln cmpd>; drawn single on canvas, kept for editing round-trip) */
compound?: 'sng' | 'dbl' | 'thickThin' | 'thinThick' | 'tri'
/** Gradient line (<a:ln><a:gradFill>); color then holds the first stop as a fallback */
gradient?: { stops: Array<{ pos: number; color: string }>; angleDeg: number }
gradient?: { stops: Array<{ pos: number; color: string }>; angleDeg: number; scaled?: boolean }
}
/** Outer shadow converted to px. */
@@ -175,7 +177,7 @@ export interface GlyphRun {
/** Run outer shadow (px), drawn via canvas shadow props */
shadow?: { color: string; blurPx: number; offsetX: number; offsetY: number }
/** WordArt gradient text fill (resolved stops; angleDeg 0 = left→right, 90 = top→bottom) */
gradient?: { stops: Array<{ pos: number; color: string }>; angleDeg: number }
gradient?: { stops: Array<{ pos: number; color: string }>; angleDeg: number; scaled?: boolean }
/** Run glow (zero-offset canvas shadow) */
glow?: { color: string; blurPx: number }
/** Run reflection: the renderer draws a faded mirrored copy below the baseline */
@@ -217,6 +219,8 @@ export interface TextLine {
softBreakAfter?: number
/** Paragraph horizontal alignment (editor display) */
align?: 'left' | 'center' | 'right' | 'justify'
/** Effective paragraph base direction is RTL (explicit a:pPr rtl or first-strong-character inference); ribbon/editor display state */
rtl?: boolean
/** Paragraph indent level (editor Tab multi-level list display) */
level?: number
/** Paragraph left margin in px (editor display: body text starts here, not at the inset edge) */
+51 -15
View File
@@ -66,7 +66,7 @@ interface Token {
/** Run outer shadow (px, offset resolved from dist/dir) */
shadow?: { color: string; blurPx: number; offsetX: number; offsetY: number }
/** WordArt gradient text fill (resolved stops + screen angle) */
gradient?: { stops: Array<{ pos: number; color: string }>; angleDeg: number }
gradient?: { stops: Array<{ pos: number; color: string }>; angleDeg: number; scaled?: boolean }
/** Run glow (px radius) */
glow?: { color: string; blurPx: number }
/** Run reflection (faded mirror below the baseline) */
@@ -326,6 +326,7 @@ function tokenizeParagraph(p: Paragraph, scale: number, fontScale: number): Toke
stops: run.gradient.stops.map((s) => ({ pos: s.pos, color: s.color })),
// OOXML gradient angle is 1/60000° clockwise from the +x axis
angleDeg: (run.gradient.angle ?? 5400000) / 60000,
...(run.gradient.scaled ? { scaled: true } : {}),
},
}
: {}),
@@ -517,11 +518,15 @@ let bidiApi: ReturnType<typeof bidiFactory> | null = null
* logical order (UAX#9 requires wrap first, reorder after); visualOrder reorders
* each line once formed.
*/
function applyBidi(tokens: Token[]): Token[] {
function applyBidi(tokens: Token[], baseRtl?: boolean): Token[] {
const text = tokens.map((t) => t.text).join('')
if (!RTL_RE.test(text)) return tokens
// An explicit RTL base still needs analysis for pure-LTR text (neutrals move to the left edge)
if (!RTL_RE.test(text) && !baseRtl) return tokens
bidiApi ??= bidiFactory()
const { levels } = bidiApi.getEmbeddingLevels(text)
const { levels } = bidiApi.getEmbeddingLevels(
text,
baseRtl == null ? undefined : baseRtl ? 'rtl' : 'ltr',
)
const out: Token[] = []
let off = 0
for (const tok of tokens) {
@@ -568,8 +573,9 @@ function visualOrder(toks: Token[]): Token[] {
return arr
}
/** Paragraph base direction: decided by the first strong-direction character (used for the default alignment; RTL paragraphs without explicit alignment align right). */
/** Paragraph base direction: explicit a:pPr rtl wins, else the first strong-direction character (used for the default alignment; RTL paragraphs without explicit alignment align right). */
function paraBaseRtl(p: Paragraph): boolean {
if (p.rtl != null) return p.rtl
for (const r of p.runs) {
for (const ch of r.text) {
if (RTL_RE.test(ch)) return true
@@ -610,10 +616,12 @@ function layoutParagraph(
* pushes the first line's text start right, so it must wrap that much earlier. */
firstLineShrinkPx = 0,
): LaidLine[] {
const tokens = applyBidi(tokenizeParagraph(p, scale, fontScale)).map((tok, logicalOrder) => ({
...substituteKerning(tok, metrics),
logicalOrder,
}))
const tokens = applyBidi(tokenizeParagraph(p, scale, fontScale), p.rtl).map(
(tok, logicalOrder) => ({
...substituteKerning(tok, metrics),
logicalOrder,
}),
)
const lines: LaidLine[] = []
let cur: Token[] = []
let curW = 0
@@ -1142,6 +1150,7 @@ function layoutTextVertical(
paraStart: boolean
align?: Paragraph['align']
alignExplicit?: boolean
rtl?: boolean
softBreakAfter?: number
/** Space-before/after maps to horizontal gaps between columns (carried by a paragraph's first/last column) */
gapBefore: number
@@ -1321,6 +1330,7 @@ function layoutTextVertical(
c.alignExplicit = true
}
}
if (paraBaseRtl(p)) for (const c of paraCols) c.rtl = true
cols.push(...paraCols)
}
@@ -1365,6 +1375,7 @@ function layoutTextVertical(
paraStart: c.paraStart,
...(c.softBreakAfter != null ? { softBreakAfter: c.softBreakAfter } : {}),
...(c.alignExplicit && c.align ? { align: c.align } : {}),
...(c.rtl ? { rtl: true } : {}),
}
})
@@ -1414,10 +1425,13 @@ function layoutAll(
const textX = marLPx
const avail = Math.max(availWidth - textX, 1)
// Paragraphs with an RTL base direction (first strong char is RTL) default to right
// alignment when none is explicit; affects layout only, not written back to
// TextLine.align (an editor commit would store it as an explicit value)
const align = p.align ?? (paraBaseRtl(p) ? ('right' as const) : undefined)
// RTL base direction mirrors the paragraph box (PowerPoint semantics, probe-measured):
// marL/indent measure from the RIGHT edge, the bullet glyph hangs on the right, and the
// default alignment is right. Explicit algn values stay physical (l = left edge).
const mirror = paraBaseRtl(p)
// Affects layout only, not written back to TextLine.align (an editor commit would
// store it as an explicit value)
const align = p.align ?? (mirror ? ('right' as const) : undefined)
// Bullet glyph style/advance (drawn on the first line only). PowerPoint reserves
// the glyph's advance like a tab stop: body text can never start before the glyph
// ends, even when the glyph is wider than the hanging indent (-indent).
@@ -1535,7 +1549,21 @@ function layoutAll(
}
// Center/right alignment counts the overflow push so the text stays inside the box
const off = alignOffset(align, avail, lineWidth + bulletShift)
const dx = textX + firstShift + bulletShift + off
let dx = textX + firstShift + bulletShift + off
// Mirrored box: the body's right boundary sits marL (+ first-line shifts) from the
// right edge; every line lives inside [0, rightEdge]. Spread justified lines fill
// that whole span (the spread width already equals it), unspread ones (paragraph-
// final, hard breaks) go flush right like PowerPoint.
const rightEdge = availWidth - textX - firstShift - bulletShift
const mirrorSpread = mirror && align === 'justify' && lineRuns !== ln.runs
if (mirror) {
dx =
mirrorSpread || align === 'left'
? 0
: align === 'center'
? (rightEdge - lineWidth) / 2
: rightEdge - lineWidth
}
const runs = lineRuns.map((r) => ({
...r,
x: r.x + dx,
@@ -1543,9 +1571,16 @@ function layoutAll(
}))
if (hasBullet && li === 0) {
const st = bulletSt!
// Mirrored: the glyph keeps its reserved advance but on the right of the body text
// (right edge at availWidth - bulletX when the line is flush right); numbered
// glyphs render with an RTL base so "1." displays as ".1" like PowerPoint
const bx = mirror
? dx + (mirrorSpread ? rightEdge : lineWidth) + (textX + bulletShift - bulletX - bulletW)
: bulletX + off
runs.unshift({
text: bulletText,
x: bulletX + off,
x: bx,
...(mirror ? { rtl: true } : {}),
baselineY: baseline,
fontFamily: metrics.displayFamily?.(st, bulletText) ?? st.fontFamily,
fontSizePx: st.fontSizePx,
@@ -1567,6 +1602,7 @@ function layoutAll(
...(ln.trailingSpace ? { trailingSpace: true } : {}),
...(ln.softBreakAfter != null ? { softBreakAfter: ln.softBreakAfter } : {}),
...(p.align ? { align: p.align } : {}),
...(paraBaseRtl(p) ? { rtl: true } : {}),
...(p.level ? { level: p.level } : {}),
...(marLPx ? { marLPx } : {}),
...(indentPx ? { indentPx } : {}),
@@ -338,6 +338,31 @@ describe('buildChartNode', () => {
}
})
it('horizontal bar honors the manual inner plot layout (labels stay in the reserved strip)', () => {
const model: ChartModel = {
kind: 'bar',
barDir: 'bar',
grouping: 'clustered',
categories: ['Alpha', 'Beta'],
series: [{ name: 's1', color: '#111111', values: [10, 30] }],
// Deck-authored inner rect: decks place hbar frames partly off-slide and
// rely on this for what stays visible
plotLayout: { x: 0.2, y: 0.05, w: 0.7, h: 0.8 },
}
const node = buildChartNode('r_hl', 'elhl', model, box, vp, metrics)!
for (const b of node.bars) {
expect(b.x).toBeCloseTo(0.2 * box.w, 5) // bars start at the manual plot left edge
expect(b.x + b.w).toBeLessThanOrEqual(0.9 * box.w + 1)
}
// Category labels sit inside the reserved left strip, right-aligned to the plot
const cats = node.labels.filter((l) => l.text === 'Alpha' || l.text === 'Beta')
expect(cats).toHaveLength(2)
for (const l of cats) {
expect(l.x).toBeGreaterThanOrEqual(0)
expect(l.x).toBeLessThan(0.2 * box.w)
}
})
it('horizontal bar reversed (orientation maxMin): first category on top', () => {
const model: ChartModel = {
kind: 'bar',
@@ -351,6 +376,56 @@ describe('buildChartNode', () => {
expect(b1!.y).toBeLessThan(b2!.y)
})
it('doughnut honors the manual inner plot rect and skips the 4mm ring on it', () => {
const model: ChartModel = {
kind: 'pie',
holePct: 50,
categories: ['A', 'B', 'C'],
series: [{ values: [8, 2, 2] }],
legendPos: 'b',
// the title must not shrink/shift the frame the manual rect measures against
title: 'Chart title',
plotLayout: { x: 0.2, y: 0.05, w: 0.5, h: 0.5 },
}
const node = buildChartNode('r_d', 'eld', model, box, vp, metrics)!
expect(node.wedges!.length).toBe(3)
const w0 = node.wedges![0]!
// Center = manual rect center; radius = half the rect's short side (no ring shrink)
expect(w0.cx).toBeCloseTo((0.2 + 0.25) * box.w, 3)
expect(w0.cy).toBeCloseTo((0.05 + 0.25) * box.h, 3)
expect(w0.outerR).toBeCloseTo(Math.min(0.5 * box.w, 0.5 * box.h) / 2, 3)
})
it('legend flows one entry per row inside a too-narrow manual rect, RTL rows right-aligned', () => {
const model: ChartModel = {
kind: 'pie',
categories: [
'first long legend entry text',
'second long legend entry text',
'third long legend entry text',
],
series: [{ values: [5, 3, 2] }],
legendPos: 'b',
plotLayout: { x: 0.2, y: 0.05, w: 0.5, h: 0.5 },
legendLayout: { x: 0.05, xMode: 'edge', y: 0.6, yMode: 'edge', w: 0.3, h: 0.35 },
legendRtl: true,
}
const node = buildChartNode('r_dl', 'eldl', model, box, vp, metrics)!
const rows = node.labels.filter((l) => String(l.text).includes('legend entry'))
expect(rows).toHaveLength(3)
const ys = rows.map((l) => l.y)
expect(new Set(ys).size).toBe(3) // one row each
// right-aligned to the rect's right edge: every row ends at x + width ~= rect right
for (const l of rows) {
expect(l.x).toBeGreaterThanOrEqual(0.05 * box.w - 1)
}
// RTL: each row's swatch sits right of its text start
for (const swatch of node.swatches) {
const row = rows.find((l) => Math.abs(l.y - swatch.y + 0) < 20)!
expect(swatch.x).toBeGreaterThan(row.x)
}
})
it('builds scatter: positioned by two value axes, lineMarker draws points and lines by default', () => {
const model: ChartModel = {
kind: 'scatter',
+189 -1
View File
@@ -2,7 +2,7 @@ import { describe, it, expect } from 'vitest'
import { HeuristicMetrics, OpentypeMetrics, type OpentypeFontLike } from '../src/metrics'
import { DEFAULT_INSETS_EMU, layoutText } from '../src/text-layout'
import { makeViewport } from '../src/coords'
import { DEFAULT_BODY_INSETS, type TextBody } from '@genoffice/pptx-engine'
import { DEFAULT_BODY_INSETS, type Paragraph, type TextBody } from '@genoffice/pptx-engine'
const vp = makeViewport({ cx: 9525 * 1000, cy: 9525 * 1000 }, 1000) // scale 1
@@ -71,6 +71,194 @@ describe('2.3 metrics', () => {
})
describe('2.3 text layout', () => {
it('vertical layout stamps effective rtl on columns (ribbon/editor state parity with horizontal)', () => {
const lay = (vert: 'eaVert' | 'vert') =>
layoutText({
body: body({
paragraphs: [{ runs: [{ text: '\u05d0\u05d1\u05d2', fontSize: 18 }] }],
vert,
}),
boxWidthPx: 200,
boxHeightPx: 200,
metrics: new HeuristicMetrics(),
vp,
})
expect(lay('eaVert').lines.every((l) => l.rtl === true)).toBe(true)
expect(lay('vert').lines.every((l) => l.rtl === true)).toBe(true)
})
describe('RTL list mirroring (PowerPoint probe-measured)', () => {
const HE = '\u05d0\u05d1\u05d2'
const lay = (paragraphs: Paragraph[]) =>
layoutText({
body: body({ paragraphs }),
boxWidthPx: 400,
boxHeightPx: 300,
metrics: new HeuristicMetrics(),
vp,
}).lines[0]!
const bulletOf = (l: ReturnType<typeof lay>) => l.runs.find((r) => r.isBullet)!
const textSpan = (l: ReturnType<typeof lay>) => {
const rs = l.runs.filter((r) => !r.isBullet)
return [Math.min(...rs.map((r) => r.x)), Math.max(...rs.map((r) => r.x + r.widthPx))]
}
it('RTL bullet hangs on the right of the text, flush right by default (marL from the right edge)', () => {
const marL = 228600 // 24px at scale 1
const line = lay([
{
runs: [{ text: HE, fontSize: 18 }],
rtl: true,
marL,
indent: -marL,
bullet: { type: 'char', char: '•' },
},
])
const b = bulletOf(line)
const [tl, tr] = textSpan(line)
expect(b.x).toBeGreaterThan(tr) // glyph right of the body text
// bulletX = marL + indent = 0 → glyph right edge at the box right edge
expect(b.x + b.widthPx).toBeCloseTo(400, 0)
// body text ends marL short of the right edge
expect(tr).toBeCloseTo(400 - 24, 0)
expect(tl).toBeGreaterThan(0)
})
it('explicit physical left align keeps the RTL bullet adjacent at the text right', () => {
const marL = 228600
const line = lay([
{
runs: [{ text: HE, fontSize: 18 }],
rtl: true,
align: 'left',
marL,
indent: -marL,
bullet: { type: 'char', char: '•' },
},
])
const b = bulletOf(line)
const [tl, tr] = textSpan(line)
expect(tl).toBeCloseTo(0, 0) // physical left, like PowerPoint
// reserved advance between text end and glyph = -indent - bulletW
expect(b.x - tr).toBeCloseTo(24 - b.widthPx, 0)
})
it('numbered RTL bullet renders with an RTL base ("1." displays as ".1")', () => {
const marL = 342900
const line = lay([
{
runs: [{ text: HE, fontSize: 18 }],
rtl: true,
marL,
indent: -marL,
bullet: { type: 'number' },
},
])
expect(bulletOf(line).rtl).toBe(true)
})
it('justified RTL paragraph: spread and final lines share the mirrored right boundary', () => {
const marL = 228600 // 24px: mirrored to the right edge
const long = '\u05d0\u05d1\u05d2 '.repeat(20).trim()
const layout = layoutText({
body: body({
paragraphs: [{ runs: [{ text: long, fontSize: 18 }], rtl: true, align: 'justify', marL }],
}),
boxWidthPx: 200,
boxHeightPx: 400,
metrics: new HeuristicMetrics(),
vp,
})
expect(layout.lines.length).toBeGreaterThan(1)
const edges = layout.lines.map((l) => Math.max(...l.runs.map((r) => r.x + r.widthPx)))
for (const e of edges) expect(e).toBeCloseTo(200 - 24, 0)
expect(Math.min(...layout.lines[0]!.runs.map((r) => r.x))).toBeCloseTo(0, 0)
})
it('LTR control: bullet stays at the left', () => {
const marL = 228600
const line = lay([
{
runs: [{ text: 'Latin', fontSize: 18 }],
marL,
indent: -marL,
bullet: { type: 'char', char: '•' },
},
])
const b = bulletOf(line)
const [tl] = textSpan(line)
expect(b.x).toBeCloseTo(0, 0)
expect(tl).toBeCloseTo(24, 0)
expect(b.rtl).toBeUndefined()
})
})
it('paragraph rtl=true: RTL base for pure-LTR text (trailing neutral moves left, default align right)', () => {
const lay = (rtl?: boolean) =>
layoutText({
body: body({ paragraphs: [{ runs: [{ text: 'Hi!', fontSize: 18 }], rtl }] }),
boxWidthPx: 400,
boxHeightPx: 200,
metrics: new HeuristicMetrics(),
vp,
}).lines[0]!
const rtlLine = lay(true)
// UAX#9 with an RTL base: the trailing '!' (neutral) takes the base level and
// renders at the visual left of the LTR word
const bang = rtlLine.runs.find((r) => r.text.includes('!'))!
const word = rtlLine.runs.find((r) => r.text.includes('Hi'))!
expect(bang.x).toBeLessThan(word.x)
// Default alignment is right (applied as an x offset; TextLine.align only carries explicit values)
const rightEdge = Math.max(...rtlLine.runs.map((r) => r.x + r.widthPx))
expect(rightEdge).toBeCloseTo(400, 0)
expect(rtlLine.align).toBeUndefined()
// Without the attribute the first strong char (LTR) wins: single run, no reorder, left aligned
const ltrLine = lay(undefined)
expect(ltrLine.runs.map((r) => r.text).join('')).toBe('Hi!')
expect(Math.min(...ltrLine.runs.map((r) => r.x))).toBeCloseTo(0, 0)
})
it('paragraph rtl=true: logical-first LTR run renders at the right in mixed text', () => {
const lay = (rtl?: boolean) =>
layoutText({
body: body({
paragraphs: [{ runs: [{ text: 'AB \u05d0\u05d1\u05d2', fontSize: 18 }], rtl }],
}),
boxWidthPx: 400,
boxHeightPx: 200,
metrics: new HeuristicMetrics(),
vp,
}).lines[0]!
const xOf = (line: ReturnType<typeof lay>, t: string) =>
line.runs.find((r) => r.text.includes(t))!.x
const rtlLine = lay(true)
expect(xOf(rtlLine, 'AB')).toBeGreaterThan(xOf(rtlLine, '\u05d0'))
// Inferred base is LTR here (first strong char is 'A'): 'AB' stays left
const autoLine = lay(undefined)
expect(xOf(autoLine, 'AB')).toBeLessThan(xOf(autoLine, '\u05d0'))
})
it('paragraph rtl=false: explicit LTR base overrides RTL-first inference (no default right align)', () => {
const lay = (rtl?: boolean) =>
layoutText({
body: body({
paragraphs: [{ runs: [{ text: '\u05d0\u05d1\u05d2 AB', fontSize: 18 }], rtl }],
}),
boxWidthPx: 400,
boxHeightPx: 200,
metrics: new HeuristicMetrics(),
vp,
}).lines[0]!
// Inferred RTL base right-aligns (as an x offset); explicit rtl="0" restores the left edge
const inferred = lay(undefined)
expect(Math.max(...inferred.runs.map((r) => r.x + r.widthPx))).toBeCloseTo(400, 0)
const ltrLine = lay(false)
expect(Math.min(...ltrLine.runs.map((r) => r.x))).toBeCloseTo(0, 0)
// Base LTR keeps the logical-first Hebrew run at the visual left
const xOf = (t: string) => ltrLine.runs.find((r) => r.text.includes(t))!.x
expect(xOf('\u05d0')).toBeLessThan(xOf('AB'))
})
it('single short line stays one line', () => {
const layout = layoutText({
body: body({ paragraphs: [{ runs: [{ text: 'Hi', fontSize: 18 }] }] }),