Initial public release
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"name": "@genoffice/pptx-render",
|
||||
"version": "0.1.0",
|
||||
"license": "Apache-2.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "pptx high-fidelity render layer: EMU->px coordinate system, data-driven RenderTree (shapes/pictures/fills/strokes + text layout via opentype.js metrics). Konva adapter is a thin layer on top.",
|
||||
"exports": {
|
||||
".": "./src/index.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest"
|
||||
},
|
||||
"dependencies": {
|
||||
"@genoffice/pptx-engine": "*",
|
||||
"opentype.js": "^2.0.0",
|
||||
"bidi-js": "^1.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.10.1",
|
||||
"@types/opentype.js": "^1.3.8",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "^5.9.3",
|
||||
"vitest": "^4.1.0"
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
declare module 'bidi-js' {
|
||||
interface BidiApi {
|
||||
getEmbeddingLevels(
|
||||
text: string,
|
||||
explicitDirection?: 'ltr' | 'rtl',
|
||||
): { levels: Uint8Array; paragraphs: Array<{ start: number; end: number; level: number }> }
|
||||
}
|
||||
export default function bidiFactory(): BidiApi
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,555 @@
|
||||
/**
|
||||
* Slide → RenderSlide builder — turns the pptx-engine Slide element tree into a
|
||||
* RenderTree with pixel geometry, resolved styles, and laid-out text (core of approach A).
|
||||
*/
|
||||
import type {
|
||||
Slide,
|
||||
SlideDeck,
|
||||
SlideElement,
|
||||
TextElement,
|
||||
PictureElement,
|
||||
GroupElement,
|
||||
TableElement,
|
||||
ChartElement,
|
||||
PassthroughElement,
|
||||
ArrowEnd,
|
||||
} from '@genoffice/pptx-engine'
|
||||
// Subpath import: the renderer bundles this package, so pulling the engine's index
|
||||
// (Node-only imports like node:crypto) would break the browser build
|
||||
import { tableRowGridCols } from '@genoffice/pptx-engine/table-grid'
|
||||
import { buildChartNode } from './build-chart'
|
||||
import type {
|
||||
RenderSlide,
|
||||
RenderNode,
|
||||
ShapeRenderNode,
|
||||
PictureRenderNode,
|
||||
GroupRenderNode,
|
||||
TableRenderNode,
|
||||
TableCellRender,
|
||||
ChipRenderNode,
|
||||
ArrowEndRender,
|
||||
} from './render-tree'
|
||||
import {
|
||||
makeViewport,
|
||||
placeTransform,
|
||||
emuToPx,
|
||||
type Viewport,
|
||||
type PlacedBox,
|
||||
type ParentPlacement,
|
||||
} from './coords'
|
||||
import { resolveFill, resolveStroke, resolveShadow, resolveGlow, type MediaResolver } from './fill'
|
||||
import { layoutText } from './text-layout'
|
||||
import { HeuristicMetrics, type FontMetricsProvider } from './metrics'
|
||||
import {
|
||||
isConnectorPreset,
|
||||
isPillPreset,
|
||||
connectorPoints,
|
||||
connectorBezier,
|
||||
presetPolygon,
|
||||
presetPath,
|
||||
} from './preset-geometry'
|
||||
|
||||
export interface BuildOptions {
|
||||
/** Target canvas width (px); height follows the slide aspect ratio. */
|
||||
fitWidthPx: number
|
||||
/** Font metrics provider (heuristic by default; the frontend injects exact opentype metrics). */
|
||||
metrics?: FontMetricsProvider
|
||||
/** Image/fill mediaRef → dataUrl. */
|
||||
media?: MediaResolver
|
||||
/**
|
||||
* Current slide number (1-based): slidenum fields display it (model bytes untouched).
|
||||
* If omitted, the cached text in <a:fld> is used (which may be stale from before slides were moved).
|
||||
*/
|
||||
slideNo?: number
|
||||
}
|
||||
|
||||
/** Refresh slidenum field display to the current slide number (returns a replaced copy; returns the input as-is on no match, never mutates the model). */
|
||||
function withSlideNum(el: SlideElement, num: number): SlideElement {
|
||||
if (el.type === 'group') {
|
||||
const g = el as GroupElement
|
||||
const children = g.children.map((c) => withSlideNum(c, num))
|
||||
return children.some((c, i) => c !== g.children[i]) ? { ...g, children } : el
|
||||
}
|
||||
const text = (el as TextElement).text
|
||||
const hit = text?.paragraphs.some((p) =>
|
||||
p.runs.some((r) => r.field === 'slidenum' && r.text !== String(num)),
|
||||
)
|
||||
if (!hit) return el
|
||||
return {
|
||||
...el,
|
||||
text: {
|
||||
...text!,
|
||||
paragraphs: text!.paragraphs.map((p) => ({
|
||||
...p,
|
||||
runs: p.runs.map((r) => (r.field === 'slidenum' ? { ...r, text: String(num) } : r)),
|
||||
})),
|
||||
},
|
||||
} as SlideElement
|
||||
}
|
||||
|
||||
const CHIP_LABEL: Record<string, string> = {
|
||||
chart: 'Chart',
|
||||
table: 'Table',
|
||||
smartart: 'SmartArt',
|
||||
ole: 'Embedded object',
|
||||
connector: 'Connector',
|
||||
media: 'Media',
|
||||
unknown: 'Unsupported element',
|
||||
}
|
||||
|
||||
export function buildRenderSlide(
|
||||
slide: Slide,
|
||||
size: SlideDeck['size'],
|
||||
opts: BuildOptions,
|
||||
): RenderSlide {
|
||||
const vp = makeViewport(size, opts.fitWidthPx)
|
||||
const metrics = opts.metrics ?? new HeuristicMetrics()
|
||||
const sub =
|
||||
opts.slideNo != null
|
||||
? (el: SlideElement) => withSlideNum(el, opts.slideNo!)
|
||||
: (el: SlideElement) => el
|
||||
const nodes: RenderNode[] = []
|
||||
// master/layout decoration layer: drawn at the bottom (above the background, below content), read-only
|
||||
for (const el of slide.decorations ?? []) {
|
||||
const node = buildNode(sub(el), vp, metrics, opts.media, { x: 0, y: 0 })
|
||||
if (node && node.type !== 'placeholder-chip') {
|
||||
node.decoration = true
|
||||
nodes.push(node)
|
||||
}
|
||||
}
|
||||
for (const el of slide.elements) {
|
||||
const node = buildNode(sub(el), vp, metrics, opts.media, { x: 0, y: 0 })
|
||||
if (node) nodes.push(node)
|
||||
}
|
||||
// Hidden-slide flag (<p:sld show="0">). Same logic as the engine's readSlideHiddenXml,
|
||||
// inlined here as a small regex so we only depend on pptx-engine types (safe to bundle in the renderer).
|
||||
const sldOpen = /<p:sld\b[^>]*>/.exec(slide.bodyPrefix)?.[0]
|
||||
const hidden = !!sldOpen && /\sshow="0"/.test(sldOpen)
|
||||
return {
|
||||
widthPx: vp.widthPx,
|
||||
heightPx: vp.heightPx,
|
||||
scale: vp.scale,
|
||||
background: resolveFill(slide.background, vp, opts.media),
|
||||
nodes,
|
||||
...(hidden ? { hidden: true } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
function buildNode(
|
||||
el: SlideElement,
|
||||
vp: Viewport,
|
||||
metrics: FontMetricsProvider,
|
||||
media: MediaResolver | undefined,
|
||||
parentOffset: ParentPlacement,
|
||||
): RenderNode | null {
|
||||
const box = placeTransform(el.transform, vp, parentOffset)
|
||||
switch (el.type) {
|
||||
case 'text':
|
||||
case 'shape':
|
||||
return buildShape(el as TextElement, box, vp, metrics, media)
|
||||
case 'picture':
|
||||
return buildPicture(el as PictureElement, box, vp, media)
|
||||
case 'group':
|
||||
return buildGroup(el as GroupElement, box, vp, metrics, media)
|
||||
case 'table':
|
||||
return buildTable(el as TableElement, box, vp, metrics, media)
|
||||
case 'chart': {
|
||||
const chartEl = el as ChartElement
|
||||
const appCreated = chartEl.descr === 'aislides-chart'
|
||||
// Unsupported chart types fall back to a placeholder chip
|
||||
const node =
|
||||
buildChartNode(`r_${el.id}`, el.id, chartEl.chart, box, vp, metrics) ??
|
||||
chipNode(el.id, box, 'chart', CHIP_LABEL['chart']!)
|
||||
if (appCreated && node.type === 'chart') {
|
||||
;(node as import('./render-tree').ChartRenderNode).appCreated = true
|
||||
}
|
||||
if (node.type === 'chart') {
|
||||
;(node as import('./render-tree').ChartRenderNode).styleInfo = chartStyleInfo(chartEl.chart)
|
||||
}
|
||||
return node
|
||||
}
|
||||
case 'passthrough': {
|
||||
const pt = el as PassthroughElement
|
||||
// SmartArt read-only preview: pre-rendered drawing shapes rendered with group semantics
|
||||
// (diagram canvas coordinate size = frame ext, equivalent to chOff 0,0 / chExt ext)
|
||||
if (pt.previewShapes?.length) {
|
||||
const pseudo: GroupElement = {
|
||||
id: pt.id,
|
||||
type: 'group',
|
||||
anchor: pt.anchor,
|
||||
transform: pt.transform,
|
||||
children: pt.previewShapes,
|
||||
childOffset: { x: 0, y: 0, cx: pt.transform.offset.cx, cy: pt.transform.offset.cy },
|
||||
}
|
||||
return buildGroup(pseudo, box, vp, metrics, media)
|
||||
}
|
||||
// OLE read-only preview: the embedded preview image stretches to fill the frame (ignoring the pic's own xfrm)
|
||||
if (pt.previewPicture) {
|
||||
return buildPicture({ ...pt.previewPicture, id: pt.id }, box, vp, media)
|
||||
}
|
||||
return buildChip(pt, box)
|
||||
}
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ArrowEnd (OOXML Stroke model) → ArrowEndRender (px sizes).
|
||||
* PowerPoint arrow sizing rules (ECMA-376 §20.1.8.27):
|
||||
* sm / med / lg map to approximate multiples of line width (empirically):
|
||||
* width: sm≈2×lw, med≈3×lw, lg≈5×lw
|
||||
* length: sm≈2×lw, med≈3×lw, lg≈5×lw
|
||||
* A 4px minimum keeps arrows visible.
|
||||
*/
|
||||
function resolveArrowEnd(end: ArrowEnd, strokeWidthEmu: number, scale: number): ArrowEndRender {
|
||||
const lw = Math.max(emuToPx(strokeWidthEmu, scale), 1)
|
||||
const sizeMultW = end.w === 'sm' ? 2 : end.w === 'lg' ? 5 : 3
|
||||
const sizeMultL = end.len === 'sm' ? 2 : end.len === 'lg' ? 5 : 3
|
||||
return {
|
||||
type: end.type as ArrowEndRender['type'],
|
||||
widthPx: Math.max(lw * sizeMultW, 4),
|
||||
lengthPx: Math.max(lw * sizeMultL, 4),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalized path (0..1) → local px: numeric tokens alternate x/y, multiplied by w/h
|
||||
* (M/L/C/Q all have an even coordinate count, so the alternation always holds).
|
||||
*/
|
||||
function scaleUnitPath(d: string, w: number, h: number): string {
|
||||
let i = 0
|
||||
return d
|
||||
.split(' ')
|
||||
.map((tok) => {
|
||||
const n = Number(tok)
|
||||
if (!Number.isFinite(n)) return tok
|
||||
return String(Math.round(n * (i++ % 2 === 0 ? w : h) * 100) / 100)
|
||||
})
|
||||
.join(' ')
|
||||
}
|
||||
|
||||
function buildShape(
|
||||
el: TextElement,
|
||||
box: PlacedBox,
|
||||
vp: Viewport,
|
||||
metrics: FontMetricsProvider,
|
||||
media: MediaResolver | undefined,
|
||||
): ShapeRenderNode {
|
||||
const node: ShapeRenderNode = {
|
||||
id: `r_${el.id}`,
|
||||
type: el.type,
|
||||
box,
|
||||
sourceId: el.id,
|
||||
fill: resolveFill(el.fill, vp, media),
|
||||
...(el.placeholder ? { placeholder: el.placeholder } : {}),
|
||||
...(el.presetGeometry ? { presetGeometry: el.presetGeometry } : {}),
|
||||
}
|
||||
// custGeom: the normalized path is scaled to local px by the element box (mutually exclusive with preset, takes priority)
|
||||
if (el.customGeometry) {
|
||||
const g = el.customGeometry
|
||||
if (g.path) node.pathData = scaleUnitPath(g.path, box.w, box.h)
|
||||
if (g.fillPath) node.fillPathData = scaleUnitPath(g.fillPath, box.w, box.h)
|
||||
if (g.strokePath) node.strokePathData = scaleUnitPath(g.strokePath, box.w, box.h)
|
||||
} else if (el.presetGeometry === 'roundRect') {
|
||||
// roundRect corner radius: avLst adj (1/1000 %, default 16667≈16.7%) × short side; 50000 = pill
|
||||
const adj = el.adjust?.adj ?? 16667
|
||||
node.cornerRadiusPx = (Math.min(box.w, box.h) * Math.min(Math.max(adj, 0), 50000)) / 100000
|
||||
} else if (isPillPreset(el.presetGeometry)) {
|
||||
node.cornerRadiusPx = Math.min(box.w, box.h) / 2
|
||||
} else if (isConnectorPreset(el.presetGeometry)) {
|
||||
// Connectors: after baking flips into the points, clear the box flip flags (the render container no longer mirrors)
|
||||
const pts = connectorPoints(el.presetGeometry!, box.w, box.h, box.flipH, box.flipV, el.adjust)
|
||||
const isCurved = /^curvedConnector/.test(el.presetGeometry ?? '')
|
||||
const bezier = isCurved ? connectorBezier(pts) : undefined
|
||||
const strokeWidth = el.stroke?.width ?? 12700
|
||||
node.line = {
|
||||
points: pts,
|
||||
...(bezier?.length ? { bezier } : {}),
|
||||
...(el.stroke?.headEnd
|
||||
? { headEnd: resolveArrowEnd(el.stroke.headEnd, strokeWidth, vp.scale) }
|
||||
: {}),
|
||||
...(el.stroke?.tailEnd
|
||||
? { tailEnd: resolveArrowEnd(el.stroke.tailEnd, strokeWidth, vp.scale) }
|
||||
: {}),
|
||||
}
|
||||
node.box = { ...box, flipH: false, flipV: false }
|
||||
} else if (el.presetGeometry && el.presetGeometry !== 'rect') {
|
||||
const poly = presetPolygon(el.presetGeometry, box.w, box.h, el.adjust)
|
||||
if (poly) node.polygonPoints = poly
|
||||
else {
|
||||
const p = presetPath(el.presetGeometry, box.w, box.h, el.adjust)
|
||||
if (p) {
|
||||
if (p.path) node.pathData = p.path
|
||||
if (p.fillPath) node.fillPathData = p.fillPath
|
||||
if (p.strokePath) node.strokePathData = p.strokePath
|
||||
}
|
||||
}
|
||||
}
|
||||
const stroke = resolveStroke(el.stroke, vp)
|
||||
if (stroke) node.stroke = stroke
|
||||
const shadow = resolveShadow(el.shadow, vp)
|
||||
if (shadow) node.shadow = shadow
|
||||
const glow = resolveGlow(el.glow, vp)
|
||||
if (glow) node.glow = glow
|
||||
if (el.text && el.text.paragraphs.length) {
|
||||
node.text = layoutText({
|
||||
body: el.text,
|
||||
boxWidthPx: box.w,
|
||||
boxHeightPx: box.h,
|
||||
metrics,
|
||||
vp,
|
||||
})
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
/** Picture shape geometry -> three clip channels (same preset implementation as shape geometry). */
|
||||
function pictureClip(
|
||||
preset: string | undefined,
|
||||
box: PlacedBox,
|
||||
adjust?: Record<string, number>,
|
||||
): PictureRenderNode['clip'] {
|
||||
if (!preset || preset === 'rect') return undefined
|
||||
if (preset === 'roundRect') {
|
||||
const adj = adjust?.adj ?? 16667
|
||||
return { cornerRadiusPx: (Math.min(box.w, box.h) * Math.min(Math.max(adj, 0), 50000)) / 100000 }
|
||||
}
|
||||
if (isPillPreset(preset)) return { cornerRadiusPx: Math.min(box.w, box.h) / 2 }
|
||||
if (preset === 'ellipse') {
|
||||
// ellipse goes through the Konva primitive channel in the render layer and produces no path; clip with an SVG two-arc path
|
||||
const rx = box.w / 2
|
||||
const ry = box.h / 2
|
||||
return {
|
||||
pathData: `M 0 ${ry} A ${rx} ${ry} 0 1 0 ${box.w} ${ry} A ${rx} ${ry} 0 1 0 0 ${ry} Z`,
|
||||
}
|
||||
}
|
||||
const poly = presetPolygon(preset, box.w, box.h, adjust)
|
||||
if (poly) return { polygonPoints: poly }
|
||||
const p = presetPath(preset, box.w, box.h, adjust)
|
||||
if (p?.path) return { pathData: p.path }
|
||||
return undefined
|
||||
}
|
||||
|
||||
function buildPicture(
|
||||
el: PictureElement,
|
||||
box: PlacedBox,
|
||||
vp: Viewport,
|
||||
media: MediaResolver | undefined,
|
||||
): PictureRenderNode {
|
||||
const dataUrl = el.dataUrl ?? (el.mediaRef ? media?.(el.mediaRef) : undefined)
|
||||
const clip = pictureClip(el.presetGeometry, box, el.adjust)
|
||||
const node: PictureRenderNode = {
|
||||
id: `r_${el.id}`,
|
||||
type: 'picture',
|
||||
box,
|
||||
sourceId: el.id,
|
||||
...(dataUrl ? { dataUrl } : {}),
|
||||
...(clip ? { clip } : {}),
|
||||
...(el.srcRect ? { srcRect: el.srcRect } : {}),
|
||||
...(el.opacity != null ? { opacity: el.opacity } : {}),
|
||||
...(el.softEdge ? { softEdgePx: emuToPx(el.softEdge, vp.scale) } : {}),
|
||||
...(el.media ? { media: el.media.kind } : {}),
|
||||
...(el.name ? { name: el.name } : {}),
|
||||
...(el.descr ? { descr: el.descr } : {}),
|
||||
}
|
||||
const stroke = resolveStroke(el.stroke, vp)
|
||||
if (stroke) node.stroke = stroke
|
||||
const shadow = resolveShadow(el.shadow, vp)
|
||||
if (shadow) node.shadow = shadow
|
||||
const glow = resolveGlow(el.glow, vp)
|
||||
if (glow) node.glow = glow
|
||||
return node
|
||||
}
|
||||
|
||||
function buildGroup(
|
||||
el: GroupElement,
|
||||
box: PlacedBox,
|
||||
vp: Viewport,
|
||||
metrics: FontMetricsProvider,
|
||||
media: MediaResolver | undefined,
|
||||
): GroupRenderNode {
|
||||
// Child coordinate system: child element EMU coords are based on <a:chOff>/<a:chExt>.
|
||||
// The size difference between the group box and the child coordinate system (the group
|
||||
// was scaled as a whole; ext/chExt may be non-uniform) is **baked into child geometry**
|
||||
// at placement time (position/size converted to group-local px by scale), while font
|
||||
// size and stroke width keep their declared values unscaled -- group scaling only
|
||||
// affects geometry, and text lays out in the scaled box at the
|
||||
// original font size (MS-OE376 §2.1.1360/2.1.1364). The render container no longer
|
||||
// stretches as a whole (which would make line-wrap widths wrong and distort glyphs
|
||||
// non-uniformly). childScaleX/Y are still written on the node so the edit pipeline can
|
||||
// convert between group-local px and child EMU.
|
||||
const ch = el.childOffset
|
||||
const chX = ch?.x ?? el.transform.offset.x
|
||||
const chY = ch?.y ?? el.transform.offset.y
|
||||
const chCx = ch?.cx || el.transform.offset.cx
|
||||
const chCy = ch?.cy || el.transform.offset.cy
|
||||
const chWpx = emuToPx(chCx, vp.scale)
|
||||
const chHpx = emuToPx(chCy, vp.scale)
|
||||
const childScaleX = chWpx > 0 ? box.w / chWpx : 1
|
||||
const childScaleY = chHpx > 0 ? box.h / chHpx : 1
|
||||
const parentOffset: ParentPlacement = {
|
||||
x: -emuToPx(chX, vp.scale) * childScaleX,
|
||||
y: -emuToPx(chY, vp.scale) * childScaleY,
|
||||
scaleX: childScaleX,
|
||||
scaleY: childScaleY,
|
||||
}
|
||||
|
||||
const children: RenderNode[] = []
|
||||
for (const child of el.children ?? []) {
|
||||
const c = buildNode(child, vp, metrics, media, parentOffset)
|
||||
if (c) children.push(c)
|
||||
}
|
||||
return {
|
||||
id: `r_${el.id}`,
|
||||
type: 'group',
|
||||
box,
|
||||
sourceId: el.id,
|
||||
children,
|
||||
...(Math.abs(childScaleX - 1) > 1e-6 ? { childScaleX } : {}),
|
||||
...(Math.abs(childScaleY - 1) > 1e-6 ? { childScaleY } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Table → TableRenderNode. Cell coordinates are relative to the table's top-left (px).
|
||||
* Column widths/row heights are distributed by EMU ratio over the frame's actual px size.
|
||||
* Row height is a minimum in PPT: rows whose wrapped cell text needs more space grow to
|
||||
* fit it, and the node box grows with the total so nothing is clipped.
|
||||
*/
|
||||
function buildTable(
|
||||
el: TableElement,
|
||||
box: PlacedBox,
|
||||
vp: Viewport,
|
||||
metrics: FontMetricsProvider,
|
||||
media: MediaResolver | undefined,
|
||||
): TableRenderNode {
|
||||
const sumW = el.colWidths.reduce((a, b) => a + b, 0) || 1
|
||||
const sumH = el.rowHeights.reduce((a, b) => a + b, 0) || 1
|
||||
const colPx = el.colWidths.map((w) => (w / sumW) * box.w)
|
||||
const rowPx = el.rowHeights.map((h) => (h / sumH) * box.h)
|
||||
// Prefix sums → start of each column
|
||||
const colX: number[] = [0]
|
||||
for (const w of colPx) colX.push(colX[colX.length - 1]! + w)
|
||||
|
||||
// Measure pass: grow any row whose cell content wraps taller than the stored height
|
||||
// (rowSpan cells are skipped — their height is ambiguous to attribute to one row).
|
||||
el.rows.forEach((row, r) => {
|
||||
const gridCols = tableRowGridCols(row)
|
||||
row.forEach((cell, tcIdx) => {
|
||||
const cIdx = gridCols[tcIdx]!
|
||||
if (cell.merged || (cell.rowSpan ?? 1) > 1) return
|
||||
if (!cell.text || !cell.text.paragraphs.length) return
|
||||
const x = colX[cIdx] ?? 0
|
||||
const w = (colX[Math.min(cIdx + (cell.gridSpan ?? 1), colX.length - 1)] ?? x) - x
|
||||
const probe = layoutText({
|
||||
body: cell.text,
|
||||
boxWidthPx: w,
|
||||
boxHeightPx: rowPx[r] ?? 0,
|
||||
metrics,
|
||||
vp,
|
||||
})
|
||||
const needed = probe.contentHeight + probe.insets.t + probe.insets.b
|
||||
if (needed > (rowPx[r] ?? 0)) rowPx[r] = needed
|
||||
})
|
||||
})
|
||||
|
||||
const rowY: number[] = [0]
|
||||
for (const h of rowPx) rowY.push(rowY[rowY.length - 1]! + h)
|
||||
const totalH = rowY[rowY.length - 1]!
|
||||
if (totalH > box.h + 0.5) box = { ...box, h: totalH }
|
||||
|
||||
const cells: TableCellRender[] = []
|
||||
el.rows.forEach((row, r) => {
|
||||
const gridCols = tableRowGridCols(row)
|
||||
row.forEach((cell, tcIdx) => {
|
||||
const cIdx = gridCols[tcIdx]!
|
||||
const gridSpan = cell.gridSpan ?? 1
|
||||
if (cell.merged) return
|
||||
const rowSpan = cell.rowSpan ?? 1
|
||||
const x = colX[cIdx] ?? 0
|
||||
const y = rowY[r] ?? 0
|
||||
const w = (colX[Math.min(cIdx + gridSpan, colX.length - 1)] ?? x) - x
|
||||
const h = (rowY[Math.min(r + rowSpan, rowY.length - 1)] ?? y) - y
|
||||
const out: TableCellRender = {
|
||||
x,
|
||||
y,
|
||||
w,
|
||||
h,
|
||||
row: r,
|
||||
col: tcIdx,
|
||||
...(gridSpan > 1 ? { gridSpan } : {}),
|
||||
...(rowSpan > 1 ? { rowSpan } : {}),
|
||||
fill: resolveFill(cell.fill, vp, media),
|
||||
}
|
||||
const borders: NonNullable<TableCellRender['borders']> = {}
|
||||
for (const k of ['l', 'r', 't', 'b'] as const) {
|
||||
const s = resolveStroke(cell.borders?.[k], vp)
|
||||
if (s) borders[k] = s
|
||||
}
|
||||
if (Object.keys(borders).length) out.borders = borders
|
||||
if (cell.text && cell.text.paragraphs.length) {
|
||||
out.text = layoutText({
|
||||
body: cell.text,
|
||||
boxWidthPx: w,
|
||||
boxHeightPx: h,
|
||||
metrics,
|
||||
vp,
|
||||
})
|
||||
}
|
||||
cells.push(out)
|
||||
})
|
||||
})
|
||||
|
||||
return {
|
||||
id: `r_${el.id}`,
|
||||
type: 'table',
|
||||
box,
|
||||
sourceId: el.id,
|
||||
cells,
|
||||
gridX: colX,
|
||||
gridY: rowY,
|
||||
...(el.styleFlags ? { styleFlags: el.styleFlags } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
/** ChartModel → style summary echoed to the Ribbon (kind maps to EditChartOp semantics; horizontal bars count as bar). */
|
||||
function chartStyleInfo(m: ChartElement['chart']): import('./render-tree').ChartStyleInfo {
|
||||
const kind =
|
||||
m.kind === 'bar'
|
||||
? m.series.some((s) => s.plotKind === 'line')
|
||||
? 'comboBarLine'
|
||||
: m.grouping === 'stacked' || m.grouping === 'percentStacked'
|
||||
? 'barStacked'
|
||||
: 'bar'
|
||||
: m.kind === 'pie'
|
||||
? (m.holePct ?? 0) > 0
|
||||
? 'doughnut'
|
||||
: 'pie'
|
||||
: m.kind
|
||||
return {
|
||||
kind,
|
||||
legendPos: m.legendPos == null ? 'none' : m.legendPos === 'tr' ? 'r' : m.legendPos,
|
||||
dataLabels: !!m.dataLabels,
|
||||
gridlines: !!m.valAxis?.gridColor,
|
||||
...(m.title ? { title: m.title } : {}),
|
||||
...(m.catAxis?.title ? { catAxisTitle: m.catAxis.title } : {}),
|
||||
...(m.valAxis?.title ? { valAxisTitle: m.valAxis.title } : {}),
|
||||
...(m.gapWidthPct != null ? { gapWidthPct: m.gapWidthPct } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
function buildChip(el: PassthroughElement, box: PlacedBox): ChipRenderNode {
|
||||
return chipNode(el.id, box, el.kind, CHIP_LABEL[el.kind] ?? el.kind)
|
||||
}
|
||||
|
||||
function chipNode(sourceId: string, box: PlacedBox, kind: string, label: string): ChipRenderNode {
|
||||
return {
|
||||
id: `r_${sourceId}`,
|
||||
type: 'placeholder-chip',
|
||||
box,
|
||||
sourceId,
|
||||
kind,
|
||||
label,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* 2.1 Coordinate system — EMU → px conversion + slide viewport mapping.
|
||||
*
|
||||
* OOXML uses EMU (English Metric Unit): 1 inch = 914400 EMU, 1 px@96dpi = 9525 EMU.
|
||||
* Rendering maps EMU geometry to target canvas pixels; the slide size plus the
|
||||
* target viewport size determine one uniform scale factor, keeping proportions
|
||||
* without stretching.
|
||||
*
|
||||
* Angles: OOXML rot unit = 1/60000 degree; clockwise positive (matching Canvas/CSS).
|
||||
*/
|
||||
import type { EmuRect, Transform, SlideSize } from '@genoffice/pptx-engine'
|
||||
|
||||
export const EMU_PER_INCH = 914400
|
||||
export const EMU_PER_PX_96 = 9525 // 914400 / 96
|
||||
export const EMU_PER_PT = 12700 // 914400 / 72
|
||||
|
||||
/** EMU → px (under the given scale). With scale=1, converts at the 96dpi baseline. */
|
||||
export function emuToPx(emu: number, scale = 1): number {
|
||||
return (emu / EMU_PER_PX_96) * scale
|
||||
}
|
||||
|
||||
/** pt → px (for font sizes), 96dpi: 1pt = 96/72 px. */
|
||||
export function ptToPx(pt: number, scale = 1): number {
|
||||
return ((pt * 96) / 72) * scale
|
||||
}
|
||||
|
||||
/** OOXML rot (1/60000 degree) → degrees. */
|
||||
export function rotToDeg(rot: number): number {
|
||||
return rot / 60000
|
||||
}
|
||||
|
||||
/** OOXML rot (1/60000 degree) → radians. */
|
||||
export function rotToRad(rot: number): number {
|
||||
return (rotToDeg(rot) * Math.PI) / 180
|
||||
}
|
||||
|
||||
export interface Viewport {
|
||||
/** Target canvas width (px) */
|
||||
widthPx: number
|
||||
/** Target canvas height (px) */
|
||||
heightPx: number
|
||||
/** Uniform EMU→px scale factor (96dpi baseline included) */
|
||||
scale: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes a proportional viewport from the slide size + target width.
|
||||
* Pass fitWidthPx: the canvas fills that width proportionally, height follows the slide ratio.
|
||||
*/
|
||||
export function makeViewport(size: SlideSize, fitWidthPx: number): Viewport {
|
||||
const baseWidthPx = size.cx / EMU_PER_PX_96 // the slide's "natural" pixel width at 96dpi
|
||||
const scale = fitWidthPx / baseWidthPx
|
||||
return {
|
||||
widthPx: fitWidthPx,
|
||||
heightPx: (size.cy / EMU_PER_PX_96) * scale,
|
||||
scale,
|
||||
}
|
||||
}
|
||||
|
||||
/** A converted pixel rectangle. */
|
||||
export interface PxRect {
|
||||
x: number
|
||||
y: number
|
||||
w: number
|
||||
h: number
|
||||
}
|
||||
|
||||
/** EMU rect → px rect. */
|
||||
export function rectToPx(r: EmuRect, vp: Viewport): PxRect {
|
||||
return {
|
||||
x: emuToPx(r.x, vp.scale),
|
||||
y: emuToPx(r.y, vp.scale),
|
||||
w: emuToPx(r.cx, vp.scale),
|
||||
h: emuToPx(r.cy, vp.scale),
|
||||
}
|
||||
}
|
||||
|
||||
/** Converted placement info including rotation/flip. Rotation pivots on the rect center. */
|
||||
export interface PlacedBox extends PxRect {
|
||||
/** Rotation angle (degrees, clockwise positive) */
|
||||
rotationDeg: number
|
||||
flipH: boolean
|
||||
flipV: boolean
|
||||
/** Rotation center (px, absolute coordinates) */
|
||||
centerX: number
|
||||
centerY: number
|
||||
}
|
||||
|
||||
/** Parent coordinate mapping for nested groups: converted top-left offset + ext/chExt scaling. */
|
||||
export interface ParentPlacement {
|
||||
x: number
|
||||
y: number
|
||||
/** Group ext/chExt scaling (default 1): baked into child geometry at placement; font sizes don't scale */
|
||||
scaleX?: number
|
||||
scaleY?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Transform (EMU geometry + rotation/flip) → pixel placement box.
|
||||
* parent: for nested groups, the parent's converted top-left offset + group scaling (default none).
|
||||
*/
|
||||
export function placeTransform(
|
||||
t: Transform,
|
||||
vp: Viewport,
|
||||
parent: ParentPlacement = { x: 0, y: 0 },
|
||||
): PlacedBox {
|
||||
const r = rectToPx(t.offset, vp)
|
||||
const sx = parent.scaleX ?? 1
|
||||
const sy = parent.scaleY ?? 1
|
||||
const x = r.x * sx + parent.x
|
||||
const y = r.y * sy + parent.y
|
||||
const w = r.w * sx
|
||||
const h = r.h * sy
|
||||
return {
|
||||
x,
|
||||
y,
|
||||
w,
|
||||
h,
|
||||
rotationDeg: rotToDeg(t.rot),
|
||||
flipH: t.flipH,
|
||||
flipV: t.flipV,
|
||||
centerX: x + w / 2,
|
||||
centerY: y + h / 2,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* 2.2 Fill / stroke resolution — converts pptx-engine Fill/Stroke (final values after
|
||||
* inheritance) into RenderFill/RenderStroke the render layer can consume directly
|
||||
* (px line width, angle in degrees, image dataUrl).
|
||||
*/
|
||||
import type { Fill, Stroke, ShadowEffect } from '@genoffice/pptx-engine'
|
||||
import type { RenderFill, RenderStroke, RenderShadow } from './render-tree'
|
||||
import { emuToPx, EMU_PER_PT, type Viewport } from './coords'
|
||||
|
||||
/** Lookup function for image mediaRef → dataUrl (injected by the caller, may lazy-load). */
|
||||
export type MediaResolver = (mediaRef: string) => string | undefined
|
||||
|
||||
export function resolveFill(
|
||||
fill: Fill | undefined,
|
||||
vp: Viewport,
|
||||
media?: MediaResolver,
|
||||
): RenderFill {
|
||||
if (!fill) return { kind: 'none' }
|
||||
switch (fill.type) {
|
||||
case 'none':
|
||||
return { kind: 'none' }
|
||||
case 'solid':
|
||||
return { kind: 'solid', color: fill.color }
|
||||
case 'gradient':
|
||||
return {
|
||||
kind: 'gradient',
|
||||
stops: fill.stops.map((s) => ({ pos: s.pos, color: s.color })),
|
||||
angleDeg: fill.angle != null ? fill.angle / 60000 : 0,
|
||||
...(fill.path ? { radial: true } : {}),
|
||||
}
|
||||
case 'image':
|
||||
return {
|
||||
kind: 'image',
|
||||
dataUrl: media?.(fill.mediaRef),
|
||||
mode: fill.mode ?? 'stretch',
|
||||
}
|
||||
case 'pattern':
|
||||
// Pattern fills are approximated with the foreground color for now (Phase 2 skips 8x8 tile replication)
|
||||
return { kind: 'solid', color: fill.fg }
|
||||
default:
|
||||
return { kind: 'none' }
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveStroke(stroke: Stroke | undefined, vp: Viewport): RenderStroke | undefined {
|
||||
if (!stroke) return undefined
|
||||
const rf = stroke.fill
|
||||
let color = '#000000'
|
||||
if (rf.type === 'solid') color = rf.color
|
||||
else if (rf.type === 'none') return undefined
|
||||
const widthPx = Math.max(emuToPx(stroke.width || 12700, vp.scale), 0.5)
|
||||
const widthPt = (stroke.width || 12700) / EMU_PER_PT
|
||||
const dash = dashPreset(stroke.dash, widthPx)
|
||||
return {
|
||||
color,
|
||||
widthPx,
|
||||
widthPt,
|
||||
...(dash ? { dash } : {}),
|
||||
...(stroke.dash && stroke.dash !== 'solid' ? { dashPreset: stroke.dash } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
/** Outer shadow EMU/angle → px offsets (OOXML dir is clockwise, y-down, matching canvas). */
|
||||
export function resolveGlow(
|
||||
glow: import('@genoffice/pptx-engine').GlowEffect | undefined,
|
||||
vp: Viewport,
|
||||
): import('./render-tree').RenderGlow | undefined {
|
||||
if (!glow) return undefined
|
||||
return { color: glow.color, blurPx: emuToPx(glow.radius, vp.scale) }
|
||||
}
|
||||
|
||||
export function resolveShadow(
|
||||
shadow: ShadowEffect | undefined,
|
||||
vp: Viewport,
|
||||
): RenderShadow | undefined {
|
||||
if (!shadow) return undefined
|
||||
const distPx = emuToPx(shadow.dist, vp.scale)
|
||||
const rad = (shadow.dirDeg * Math.PI) / 180
|
||||
return {
|
||||
color: shadow.color,
|
||||
blurPx: emuToPx(shadow.blurRad, vp.scale),
|
||||
offsetX: Math.cos(rad) * distPx,
|
||||
offsetY: Math.sin(rad) * distPx,
|
||||
}
|
||||
}
|
||||
|
||||
/** OOXML preset dash name → canvas dash array (relative to line width). */
|
||||
function dashPreset(name: string | undefined, w: number): number[] | undefined {
|
||||
if (!name || name === 'solid') return undefined
|
||||
const u = w
|
||||
switch (name) {
|
||||
case 'dot':
|
||||
case 'sysDot':
|
||||
return [u, u]
|
||||
case 'dash':
|
||||
case 'sysDash':
|
||||
return [4 * u, 3 * u]
|
||||
case 'lgDash':
|
||||
return [8 * u, 3 * u]
|
||||
case 'dashDot':
|
||||
case 'sysDashDot':
|
||||
return [4 * u, 3 * u, u, 3 * u]
|
||||
case 'lgDashDot':
|
||||
return [8 * u, 3 * u, u, 3 * u]
|
||||
case 'lgDashDotDot':
|
||||
return [8 * u, 3 * u, u, 3 * u, u, 3 * u]
|
||||
case 'dashDotDot':
|
||||
case 'sysDashDotDot':
|
||||
return [4 * u, 3 * u, u, 3 * u, u, 3 * u]
|
||||
default:
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* @genoffice/pptx-render — high-fidelity pptx render layer (Phase 2).
|
||||
*
|
||||
* Layering (approach A: data-driven + thin adapters):
|
||||
* coords 2.1 EMU→px coordinate system + viewport
|
||||
* fill 2.2 fill/stroke resolution
|
||||
* metrics 2.3 font metrics (opentype.js exact / heuristic fallback)
|
||||
* text-layout 2.3 text layout (wrapping/line spacing/autofit/vertical alignment)
|
||||
* build-slide aggregation: Slide → RenderTree (fidelity is locked at this layer; unit-testable without canvas)
|
||||
*
|
||||
* The Konva adapter (drawing the RenderTree) is added when apps/slides gets a frontend; not in this package.
|
||||
*/
|
||||
export * from './coords'
|
||||
export * from './render-tree'
|
||||
export * from './fill'
|
||||
export * from './metrics'
|
||||
export * from './text-layout'
|
||||
export * from './build-slide'
|
||||
export * from './build-chart'
|
||||
export * from './preset-geometry'
|
||||
@@ -0,0 +1,203 @@
|
||||
/**
|
||||
* 2.3 Text metrics (fidelity linchpin) — font metrics abstraction layer.
|
||||
*
|
||||
* The key to fidelity is owning the font metrics: don't rely on browser Canvas
|
||||
* measureText (untestable, inconsistent across environments); instead parse real
|
||||
* font files with opentype.js to get exact advance width / ascent / descent, so
|
||||
* any environment (including node unit tests) yields deterministic wrapping and
|
||||
* line-height results.
|
||||
*
|
||||
* Design: FontMetricsProvider interface + two implementations:
|
||||
* 1. OpentypeMetrics — real fonts (opentype.Font), pixel-accurate.
|
||||
* 2. HeuristicMetrics — deterministic fallback without font files (advance
|
||||
* estimated by character class), keeping wrapping logic unit-testable and
|
||||
* cross-environment consistent; once the frontend loads real fonts it
|
||||
* switches to exact metrics automatically.
|
||||
*/
|
||||
|
||||
export interface RunStyle {
|
||||
fontFamily: string
|
||||
fontSizePx: number
|
||||
bold: boolean
|
||||
italic: boolean
|
||||
}
|
||||
|
||||
export interface FontMetrics {
|
||||
/** Ascent at the font size (baseline to top, px) */
|
||||
ascent: number
|
||||
/** Descent at the font size (baseline to bottom, px, positive) */
|
||||
descent: number
|
||||
/** Suggested line height (px) */
|
||||
lineHeight: number
|
||||
}
|
||||
|
||||
export interface FontMetricsProvider {
|
||||
/** Line metrics for this font + size. */
|
||||
metrics(style: RunStyle): FontMetrics
|
||||
/** Advance width of a piece of text under this style (px). */
|
||||
measure(text: string, style: RunStyle): number
|
||||
/**
|
||||
* CSS font family actually used for drawing. When a missing font is substituted
|
||||
* by an installed one, return the substitute name so the renderer draws with the
|
||||
* same font file the metrics used (otherwise baked run x positions drift from the
|
||||
* real widths of the browser's own fallback font → overlap/squeezing).
|
||||
* Unimplemented = use the original name. `text` lets implementations adjust per
|
||||
* script (complex-script runs measure/draw with the same shaping font).
|
||||
*/
|
||||
displayFamily?(style: RunStyle, text?: string): string
|
||||
}
|
||||
|
||||
// ── Grapheme clusters ───────────────────────────────────────────────
|
||||
|
||||
const SEGMENTER: Intl.Segmenter | null =
|
||||
typeof Intl !== 'undefined' && 'Segmenter' in Intl ? new Intl.Segmenter(undefined, { granularity: 'grapheme' }) : null
|
||||
|
||||
/**
|
||||
* Split by grapheme cluster (combining marks / ZWJ emoji / flags / skin-tone
|
||||
* sequences stay intact). Both measurement and line breaking must treat clusters
|
||||
* as the smallest unit — splitting by code point would push Thai combining vowels
|
||||
* to a line start and measure an emoji sequence as N character widths.
|
||||
*/
|
||||
export function graphemes(text: string): string[] {
|
||||
if (!SEGMENTER) return [...text]
|
||||
const out: string[] = []
|
||||
for (const s of SEGMENTER.segment(text)) out.push(s.segment)
|
||||
return out
|
||||
}
|
||||
|
||||
// ── Heuristic fallback (deterministic, unit-testable) ───────────────
|
||||
|
||||
/** Unicode East Asian Width = Wide/Fullwidth ranges (covers all fullwidth scripts at once; don't patch per language). */
|
||||
const WIDE_RANGES: ReadonlyArray<readonly [number, number]> = [
|
||||
[0x1100, 0x115f], // Hangul Jamo (initial consonants)
|
||||
[0x2e80, 0x303e], // CJK radicals / Kangxi radicals / CJK punctuation
|
||||
[0x3041, 0x33ff], // Kana / Bopomofo / compatibility Hangul Jamo / CJK compatibility
|
||||
[0x3400, 0x4dbf], // CJK Extension A
|
||||
[0x4e00, 0x9fff], // CJK basic
|
||||
[0xa000, 0xa4cf], // Yi
|
||||
[0xa960, 0xa97f], // Hangul Jamo Extended-A
|
||||
[0xac00, 0xd7a3], // Hangul syllables
|
||||
[0xf900, 0xfaff], // compatibility ideographs
|
||||
[0xfe30, 0xfe4f], // CJK compatibility forms
|
||||
[0xff00, 0xff60], // fullwidth ASCII
|
||||
[0xffe0, 0xffe6], // fullwidth symbols
|
||||
[0x1b000, 0x1b2ff], // Kana extensions
|
||||
[0x20000, 0x3fffd], // CJK Extension B+
|
||||
]
|
||||
|
||||
/** Whether a code point is EAW fullwidth/wide (word breaking may break per cluster on these). */
|
||||
export function isWideChar(code: number): boolean {
|
||||
for (const [lo, hi] of WIDE_RANGES) {
|
||||
if (code >= lo && code <= hi) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Estimate advance by character class (ratio relative to font size).
|
||||
* EAW fullwidth ≈ 1.0em, general Latin ≈ 0.5em, narrow chars smaller. Bold adds a bit.
|
||||
* These factors are only for the deterministic no-real-font fallback and don't aim
|
||||
* for pixel accuracy; real typesetting is handled by OpentypeMetrics.
|
||||
*/
|
||||
function charAdvanceEm(code: number): number {
|
||||
if (isWideChar(code)) return 1.0
|
||||
// emoji ranges (rough)
|
||||
if (code >= 0x1f000 || (code >= 0x2600 && code <= 0x27bf)) return 1.0
|
||||
// narrow characters
|
||||
if ('iIlj.,:;\'!|'.includes(String.fromCharCode(code))) return 0.28
|
||||
if (' ftr'.includes(String.fromCharCode(code))) return 0.32
|
||||
if ('mwMW'.includes(String.fromCharCode(code))) return 0.82
|
||||
// general Latin / digits
|
||||
return 0.52
|
||||
}
|
||||
|
||||
/** Zero-width code points: non-spacing combining marks (Thai vowels/tones, diacritics) and format chars (ZWJ etc.). */
|
||||
const ZERO_WIDTH_RE = /[\p{Mn}\p{Me}\p{Cf}]/u
|
||||
/** Emoji composition parts: ZWJ (200d) / VS16 (fe0f) / regional indicators (flags) / skin-tone modifiers. */
|
||||
// eslint-disable-next-line no-misleading-character-class -- individual composition code points are matched on purpose
|
||||
const EMOJI_JOIN_RE = /[\u200d\ufe0f\u{1f1e6}-\u{1f1ff}\u{1f3fb}-\u{1f3ff}]/u
|
||||
|
||||
/**
|
||||
* Estimated width of one grapheme cluster: an emoji composition cluster draws as
|
||||
* one glyph at 1em; otherwise sum per code point, counting zero-width marks as 0
|
||||
* (spacing vowel marks Mc, e.g. Devanagari, have real width and use the default factor).
|
||||
*/
|
||||
function clusterAdvanceEm(g: string): number {
|
||||
if (g.length > 1 && EMOJI_JOIN_RE.test(g)) return 1.0
|
||||
let em = 0
|
||||
for (const ch of g) {
|
||||
em += ZERO_WIDTH_RE.test(ch) ? 0 : charAdvanceEm(ch.codePointAt(0) ?? 0)
|
||||
}
|
||||
return em
|
||||
}
|
||||
|
||||
export class HeuristicMetrics implements FontMetricsProvider {
|
||||
metrics(style: RunStyle): FontMetrics {
|
||||
const s = style.fontSizePx
|
||||
// Typical sans-serif ratios: ascent≈0.8em, descent≈0.2em, lineHeight≈1.2em
|
||||
return {
|
||||
ascent: s * 0.8,
|
||||
descent: s * 0.2,
|
||||
lineHeight: s * 1.2,
|
||||
}
|
||||
}
|
||||
|
||||
measure(text: string, style: RunStyle): number {
|
||||
let em = 0
|
||||
for (const g of graphemes(text)) {
|
||||
em += clusterAdvanceEm(g)
|
||||
}
|
||||
const boldFactor = style.bold ? 1.04 : 1
|
||||
return em * style.fontSizePx * boldFactor
|
||||
}
|
||||
}
|
||||
|
||||
// ── Exact metrics via opentype.js ───────────────────────────────────
|
||||
|
||||
/** Minimal interface of opentype.Font (avoids a hard type dependency; the frontend injects the real instance). */
|
||||
export interface OpentypeFontLike {
|
||||
unitsPerEm: number
|
||||
ascender: number
|
||||
descender: number
|
||||
getAdvanceWidth(text: string, fontSize: number): number
|
||||
/** Optional: char → glyph index (0 = missing glyph). Used for the missing-glyph heuristic fallback. */
|
||||
charToGlyphIndex?(char: string): number
|
||||
}
|
||||
|
||||
/**
|
||||
* Exact metrics using fonts already loaded via opentype.js.
|
||||
* fontResolver: returns the font instance for family+bold+italic (undefined if not found → caller falls back).
|
||||
*/
|
||||
export class OpentypeMetrics implements FontMetricsProvider {
|
||||
constructor(
|
||||
private fontResolver: (style: RunStyle) => OpentypeFontLike | undefined,
|
||||
private fallback: FontMetricsProvider = new HeuristicMetrics(),
|
||||
) {}
|
||||
|
||||
metrics(style: RunStyle): FontMetrics {
|
||||
const font = this.fontResolver(style)
|
||||
if (!font) return this.fallback.metrics(style)
|
||||
const scale = style.fontSizePx / font.unitsPerEm
|
||||
const ascent = font.ascender * scale
|
||||
const descent = Math.abs(font.descender) * scale
|
||||
return { ascent, descent, lineHeight: ascent + descent }
|
||||
}
|
||||
|
||||
measure(text: string, style: RunStyle): number {
|
||||
const font = this.fontResolver(style)
|
||||
if (!font) return this.fallback.measure(text, style)
|
||||
try {
|
||||
// Missing-glyph guard: if any character has no glyph (e.g. CJK landing on a Latin
|
||||
// font) → fall back to heuristics for the whole run, so advance=0 doesn't make
|
||||
// line widths badly undersized.
|
||||
if (font.charToGlyphIndex) {
|
||||
for (const ch of text) {
|
||||
if (font.charToGlyphIndex(ch) === 0) return this.fallback.measure(text, style)
|
||||
}
|
||||
}
|
||||
return font.getAdvanceWidth(text, style.fontSizePx)
|
||||
} catch {
|
||||
return this.fallback.measure(text, style)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,960 @@
|
||||
/**
|
||||
* Preset geometry → draw points (local px, relative to the element box top-left).
|
||||
*
|
||||
* OOXML defines ~180 presets; the ~100 common ones are covered here:
|
||||
* - straight-edge polygons → presetPolygon (point list, drawn closed)
|
||||
* - arcs/beziers involved → presetPath (SVG path channel, with fill-only/stroke-only subpaths)
|
||||
* The rest fall back to rectangles (build-slide simply emits no polygonPoints/pathData).
|
||||
* Formulas follow the avLst defaults in ECMA-376 presetShapeDefinitions (some are visual
|
||||
* approximations); adjust unit = 1/1000 % (100000 = 100%), angular adjusts = 1/60000 degree.
|
||||
*/
|
||||
|
||||
/** Connector/line presets (rendered as polylines instead of closed shapes). */
|
||||
const CONNECTOR_RE = /^(line|straightConnector\d?|bentConnector\d|curvedConnector\d)$/
|
||||
|
||||
export function isConnectorPreset(preset: string | undefined): boolean {
|
||||
return !!preset && CONNECTOR_RE.test(preset)
|
||||
}
|
||||
|
||||
/**
|
||||
* Connector points: start/end are decided by flips (xfrm box + flipH/flipV express direction).
|
||||
* Flips are baked directly into the points (the render layer no longer scale-flips this node).
|
||||
*
|
||||
* bentConnector: Manhattan polyline, elbow positions controlled by adj1/adj2.
|
||||
* curvedConnector: S-shaped bezier (same points as bent; the caller smooths via bezier control points).
|
||||
*/
|
||||
export function connectorPoints(
|
||||
preset: string,
|
||||
w: number,
|
||||
h: number,
|
||||
flipH: boolean,
|
||||
flipV: boolean,
|
||||
adjust?: Record<string, number>,
|
||||
): number[] {
|
||||
let pts: number[]
|
||||
if (/^bentConnector|^curvedConnector/.test(preset)) {
|
||||
pts = bentConnectorPts(preset, w, h, adjust)
|
||||
} else {
|
||||
// line / straightConnector: the two ends of a straight line
|
||||
pts = [0, 0, w, h]
|
||||
}
|
||||
if (flipH) for (let i = 0; i < pts.length; i += 2) pts[i] = w - pts[i]!
|
||||
if (flipV) for (let i = 1; i < pts.length; i += 2) pts[i] = h - pts[i]!
|
||||
return pts
|
||||
}
|
||||
|
||||
/**
|
||||
* Elbow computation for bent/curved connectors (no flips; the caller bakes flips in).
|
||||
* Per the OOXML spec:
|
||||
* - bentConnector2: 1 elbow (horizontal→vertical, elbow at the end x)
|
||||
* - bentConnector3: 2 elbows (horizontal→vertical→horizontal, adj1 sets the first segment's end x, default 50%)
|
||||
* - bentConnector4: 3 elbows, adj1 = first-segment x fraction, adj2 = second-segment y fraction (default 50% each)
|
||||
* - bentConnector5: 4 elbows, adj1/adj2/adj3 by analogy
|
||||
*/
|
||||
function bentConnectorPts(preset: string, w: number, h: number, adjust?: Record<string, number>): number[] {
|
||||
const n = parseInt(preset.slice(-1), 10) || 2
|
||||
const clamp = (v: number, lo = -2, hi = 3) => Math.min(Math.max(v, lo), hi)
|
||||
const adj = (name: string, dflt: number) =>
|
||||
adjust?.[name] != null ? clamp(adjust[name]! / 100000) : dflt
|
||||
|
||||
if (n <= 2) {
|
||||
// bentConnector2: (0,0) → (w,0) → (w,h) — one right-angle elbow, not adjustable
|
||||
return [0, 0, w, 0, w, h]
|
||||
} else if (n === 3) {
|
||||
// bentConnector3: adj1 sets which x the first horizontal segment reaches (0..1, default 50%)
|
||||
const a1 = adj('adj1', 0.5)
|
||||
const mx = w * a1
|
||||
return [0, 0, mx, 0, mx, h, w, h]
|
||||
} else if (n === 4) {
|
||||
// bentConnector4: adj1 = first-segment x fraction, adj2 = second-segment y fraction (default 50% each)
|
||||
const a1 = adj('adj1', 0.5)
|
||||
const a2 = adj('adj2', 0.5)
|
||||
const mx = w * a1
|
||||
const my = h * a2
|
||||
return [0, 0, mx, 0, mx, my, w, my, w, h]
|
||||
} else {
|
||||
// bentConnector5: adj1=x1, adj2=y1, adj3=x2 (the two x legs split y into three parts)
|
||||
const a1 = adj('adj1', 0.333)
|
||||
const a2 = adj('adj2', 0.5)
|
||||
const a3 = adj('adj3', 0.667)
|
||||
const x1 = w * a1
|
||||
const y1 = h * a2
|
||||
const x2 = w * a3
|
||||
return [0, 0, x1, 0, x1, y1, x2, y1, x2, h, w, h]
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* SVG bezier control points for curved connectors (each segment: [cp1x,cp1y,cp2x,cp2y,ex,ey]).
|
||||
* Approximates an S-curve from the polyline points — control points shift 1/3 of the
|
||||
* distance along the segment direction near each elbow.
|
||||
* An empty array means no curve (use the polyline points directly).
|
||||
*/
|
||||
export function connectorBezier(pts: number[]): number[] {
|
||||
// At least 3 points are needed to bend (2 points is just a straight line)
|
||||
const nPts = pts.length / 2
|
||||
if (nPts < 3) return []
|
||||
|
||||
const bezier: number[] = []
|
||||
for (let i = 1; i < nPts; i++) {
|
||||
const x0 = pts[(i - 1) * 2]!
|
||||
const y0 = pts[(i - 1) * 2 + 1]!
|
||||
const x1 = pts[i * 2]!
|
||||
const y1 = pts[i * 2 + 1]!
|
||||
// Control points: previous-segment end offset 1/3, next-segment start offset 1/3 (tangent continuity = S curve)
|
||||
const prevX = i > 1 ? pts[(i - 2) * 2]! : x0
|
||||
const prevY = i > 1 ? pts[(i - 2) * 2 + 1]! : y0
|
||||
const nextX = i < nPts - 1 ? pts[(i + 1) * 2]! : x1
|
||||
const nextY = i < nPts - 1 ? pts[(i + 1) * 2 + 1]! : y1
|
||||
const cp1x = x0 + (x1 - prevX) / 6
|
||||
const cp1y = y0 + (y1 - prevY) / 6
|
||||
const cp2x = x1 - (nextX - x0) / 6
|
||||
const cp2y = y1 - (nextY - y0) / 6
|
||||
bezier.push(cp1x, cp1y, cp2x, cp2y, x1, y1)
|
||||
}
|
||||
return bezier
|
||||
}
|
||||
|
||||
/**
|
||||
* Common closed preset geometries → polygon points ([x0,y0,x1,y1,…], closing handled by
|
||||
* the render layer's closed flag). Unsupported presets return null (fall back to a rectangle).
|
||||
*/
|
||||
export function presetPolygon(
|
||||
preset: string | undefined,
|
||||
w: number,
|
||||
h: number,
|
||||
adjust?: Record<string, number>,
|
||||
): number[] | null {
|
||||
if (!preset || w <= 0 || h <= 0) return null
|
||||
const ss = Math.min(w, h) // shortest side (the basis of OOXML formulas)
|
||||
const frac = (name: string, dflt: number) =>
|
||||
Math.min(Math.max((adjust?.[name] ?? dflt) / 100000, 0), 1)
|
||||
|
||||
switch (preset) {
|
||||
case 'triangle': {
|
||||
// Isosceles triangle, apex horizontal position from adj (default 50%)
|
||||
const apex = w * frac('adj', 50000)
|
||||
return [apex, 0, w, h, 0, h]
|
||||
}
|
||||
case 'rtTriangle':
|
||||
return [0, 0, w, h, 0, h]
|
||||
case 'diamond':
|
||||
case 'flowChartDecision':
|
||||
return [w / 2, 0, w, h / 2, w / 2, h, 0, h / 2]
|
||||
case 'parallelogram': {
|
||||
const inset = ss * frac('adj', 25000)
|
||||
return [inset, 0, w, 0, w - inset, h, 0, h]
|
||||
}
|
||||
case 'trapezoid': {
|
||||
const inset = ss * frac('adj', 25000)
|
||||
return [inset, 0, w - inset, 0, w, h, 0, h]
|
||||
}
|
||||
case 'pentagon': {
|
||||
// Regular-pentagon approximation (apex up)
|
||||
return [w / 2, 0, w, h * 0.382, w * 0.809, h, w * 0.191, h, 0, h * 0.382]
|
||||
}
|
||||
case 'hexagon': {
|
||||
const inset = ss * frac('adj', 25000)
|
||||
return [inset, 0, w - inset, 0, w, h / 2, w - inset, h, inset, h, 0, h / 2]
|
||||
}
|
||||
case 'octagon': {
|
||||
const c = ss * frac('adj', 29289)
|
||||
return [c, 0, w - c, 0, w, c, w, h - c, w - c, h, c, h, 0, h - c, 0, c]
|
||||
}
|
||||
case 'mathPlus': {
|
||||
// Math plus glyph: arms span 73.49% of the box and never touch the
|
||||
// edges (unlike 'plus'); adj1 is the arm half-thickness
|
||||
const t = ss * frac('adj1', 23520)
|
||||
const dx = (w * 73490) / 200000
|
||||
const dy = (h * 73490) / 200000
|
||||
const hc = w / 2
|
||||
const vc = h / 2
|
||||
const x1 = hc - dx
|
||||
const x2 = hc - t
|
||||
const x3 = hc + t
|
||||
const x4 = hc + dx
|
||||
const y1 = vc - dy
|
||||
const y2 = vc - t
|
||||
const y3 = vc + t
|
||||
const y4 = vc + dy
|
||||
// prettier-ignore
|
||||
return [x1, y2, x2, y2, x2, y1, x3, y1, x3, y2, x4, y2, x4, y3, x3, y3, x3, y4, x2, y4, x2, y3, x1, y3]
|
||||
}
|
||||
case 'plus': {
|
||||
const a = ss * frac('adj', 25000)
|
||||
const x1 = a
|
||||
const x2 = w - a
|
||||
const y1 = a
|
||||
const y2 = h - a
|
||||
// Cross: vertical arm positioned by height, horizontal arm by width
|
||||
return [x1, 0, x2, 0, x2, y1, w, y1, w, y2, x2, y2, x2, h, x1, h, x1, y2, 0, y2, 0, y1, x1, y1]
|
||||
}
|
||||
case 'rightArrow': {
|
||||
const thick = h * frac('adj1', 50000)
|
||||
const head = Math.min(w, ss * frac('adj2', 50000))
|
||||
const y1 = (h - thick) / 2
|
||||
const y2 = (h + thick) / 2
|
||||
const xh = w - head
|
||||
return [0, y1, xh, y1, xh, 0, w, h / 2, xh, h, xh, y2, 0, y2]
|
||||
}
|
||||
case 'notchedRightArrow': {
|
||||
const thick = h * frac('adj1', 50000)
|
||||
const head = Math.min(w, ss * frac('adj2', 50000))
|
||||
const y1 = (h - thick) / 2
|
||||
const y2 = (h + thick) / 2
|
||||
const xh = w - head
|
||||
// Tail notch depth matches the arrowhead slope
|
||||
const notch = (head * thick) / h
|
||||
return [0, y1, xh, y1, xh, 0, w, h / 2, xh, h, xh, y2, 0, y2, notch, h / 2]
|
||||
}
|
||||
case 'leftArrow': {
|
||||
const thick = h * frac('adj1', 50000)
|
||||
const head = Math.min(w, ss * frac('adj2', 50000))
|
||||
const y1 = (h - thick) / 2
|
||||
const y2 = (h + thick) / 2
|
||||
return [w, y1, head, y1, head, 0, 0, h / 2, head, h, head, y2, w, y2]
|
||||
}
|
||||
case 'upArrow': {
|
||||
const thick = w * frac('adj1', 50000)
|
||||
const head = Math.min(h, ss * frac('adj2', 50000))
|
||||
const x1 = (w - thick) / 2
|
||||
const x2 = (w + thick) / 2
|
||||
return [x1, h, x1, head, 0, head, w / 2, 0, w, head, x2, head, x2, h]
|
||||
}
|
||||
case 'downArrow': {
|
||||
const thick = w * frac('adj1', 50000)
|
||||
const head = Math.min(h, ss * frac('adj2', 50000))
|
||||
const x1 = (w - thick) / 2
|
||||
const x2 = (w + thick) / 2
|
||||
const yh = h - head
|
||||
return [x1, 0, x1, yh, 0, yh, w / 2, h, w, yh, x2, yh, x2, 0]
|
||||
}
|
||||
case 'leftRightArrow': {
|
||||
const thick = h * frac('adj1', 50000)
|
||||
const head = Math.min(w / 2, ss * frac('adj2', 50000))
|
||||
const y1 = (h - thick) / 2
|
||||
const y2 = (h + thick) / 2
|
||||
return [
|
||||
0, h / 2, head, 0, head, y1, w - head, y1, w - head, 0, w, h / 2,
|
||||
w - head, h, w - head, y2, head, y2, head, h,
|
||||
]
|
||||
}
|
||||
case 'upDownArrow': {
|
||||
const thick = w * frac('adj1', 50000)
|
||||
const head = Math.min(h / 2, ss * frac('adj2', 50000))
|
||||
const x1 = (w - thick) / 2
|
||||
const x2 = (w + thick) / 2
|
||||
return [
|
||||
w / 2, 0, w, head, x2, head, x2, h - head, w, h - head, w / 2, h,
|
||||
0, h - head, x1, h - head, x1, head, 0, head,
|
||||
]
|
||||
}
|
||||
case 'chevron': {
|
||||
const d = ss * frac('adj', 50000)
|
||||
return [0, 0, w - d, 0, w, h / 2, w - d, h, 0, h, d, h / 2]
|
||||
}
|
||||
case 'homePlate': {
|
||||
const d = ss * frac('adj', 50000)
|
||||
return [0, 0, w - d, 0, w, h / 2, w - d, h, 0, h]
|
||||
}
|
||||
case 'snip1Rect': {
|
||||
const a = ss * frac('adj', 16667)
|
||||
return [0, 0, w - a, 0, w, a, w, h, 0, h]
|
||||
}
|
||||
case 'snip2SameRect': {
|
||||
const a1 = ss * frac('adj1', 16667)
|
||||
const a2 = ss * frac('adj2', 0)
|
||||
return [a1, 0, w - a1, 0, w, a1, w, h - a2, w - a2, h, a2, h, 0, h - a2, 0, a1]
|
||||
}
|
||||
case 'snip2DiagRect': {
|
||||
const a1 = ss * frac('adj1', 0)
|
||||
const a2 = ss * frac('adj2', 16667)
|
||||
return [a1, 0, w - a2, 0, w, a2, w, h - a1, w - a1, h, a2, h, 0, h - a2, 0, a1]
|
||||
}
|
||||
case 'halfFrame': {
|
||||
const y1 = ss * frac('adj1', 33333)
|
||||
const x1 = ss * frac('adj2', 33333)
|
||||
const x2 = Math.max(w - (y1 * w) / h, x1)
|
||||
const y2 = Math.max(h - (x1 * h) / w, y1)
|
||||
return [0, 0, w, 0, x2, y1, x1, y1, x1, y2, 0, h]
|
||||
}
|
||||
case 'corner': {
|
||||
const y1 = ss * frac('adj1', 50000)
|
||||
const x1 = ss * frac('adj2', 50000)
|
||||
return [0, 0, x1, 0, x1, h - y1, w, h - y1, w, h, 0, h]
|
||||
}
|
||||
case 'diagStripe': {
|
||||
const a = frac('adj', 50000)
|
||||
return [0, h * a, w * a, 0, w, 0, 0, h]
|
||||
}
|
||||
case 'lightningBolt': {
|
||||
// Fixed points from ECMA presetShapeDefinitions (21600 coordinate system)
|
||||
const u = [8472, 0, 12860, 6672, 11050, 6672, 16577, 12007, 14767, 12007,
|
||||
21600, 21600, 10800, 14387, 12377, 14387, 5333, 6667, 7778, 6667]
|
||||
return u.map((v, i) => (v / 21600) * (i % 2 === 0 ? w : h))
|
||||
}
|
||||
case 'flowChartPreparation':
|
||||
return [w * 0.2, 0, w * 0.8, 0, w, h / 2, w * 0.8, h, w * 0.2, h, 0, h / 2]
|
||||
case 'flowChartManualInput':
|
||||
return [0, h / 5, w, 0, w, h, 0, h]
|
||||
case 'flowChartManualOperation':
|
||||
return [0, 0, w, 0, w * 0.8, h, w * 0.2, h]
|
||||
case 'flowChartOffpageConnector':
|
||||
return [0, 0, w, 0, w, h * 0.8, w / 2, h, 0, h * 0.8]
|
||||
case 'flowChartExtract':
|
||||
return [w / 2, 0, w, h, 0, h]
|
||||
case 'flowChartMerge':
|
||||
return [0, 0, w, 0, w / 2, h]
|
||||
case 'flowChartCollate':
|
||||
return [0, 0, w, 0, w / 2, h / 2, w, h, 0, h, w / 2, h / 2]
|
||||
case 'gear6': {
|
||||
// Tooth depth from adj1; tooth shape approximated: 4 points per tooth (two at root, two at tip)
|
||||
const depth = Math.min(frac('adj1', 15000) * 2, 0.6)
|
||||
return gearPoints(6, w, h, 1 - depth)
|
||||
}
|
||||
case 'funnel':
|
||||
return [0, 0, w, 0, w * 0.62, h * 0.62, w * 0.62, h, w * 0.38, h, w * 0.38, h * 0.62]
|
||||
case 'quadArrow': {
|
||||
const sw2 = (ss * frac('adj1', 22500)) / 2
|
||||
const hw = ss * frac('adj2', 22500)
|
||||
const hl = ss * frac('adj3', 22500)
|
||||
const cx = w / 2
|
||||
const cy = h / 2
|
||||
return [
|
||||
cx, 0, cx + hw, hl, cx + sw2, hl, cx + sw2, cy - sw2, w - hl, cy - sw2, w - hl, cy - hw,
|
||||
w, cy, w - hl, cy + hw, w - hl, cy + sw2, cx + sw2, cy + sw2, cx + sw2, h - hl, cx + hw, h - hl,
|
||||
cx, h, cx - hw, h - hl, cx - sw2, h - hl, cx - sw2, cy + sw2, hl, cy + sw2, hl, cy + hw,
|
||||
0, cy, hl, cy - hw, hl, cy - sw2, cx - sw2, cy - sw2, cx - sw2, hl, cx - hw, hl,
|
||||
]
|
||||
}
|
||||
case 'bentArrow': {
|
||||
const t = ss * frac('adj1', 25000)
|
||||
const hw = ss * frac('adj2', 25000)
|
||||
const hl = ss * frac('adj3', 25000)
|
||||
const yc = Math.max(hw, t / 2)
|
||||
return [
|
||||
0, h, 0, yc - t / 2, w - hl, yc - t / 2, w - hl, yc - hw, w, yc,
|
||||
w - hl, yc + hw, w - hl, yc + t / 2, t, yc + t / 2, t, h,
|
||||
]
|
||||
}
|
||||
case 'wedgeRectCallout': {
|
||||
const tipX = w / 2 + w * adjRaw(adjust, 'adj1', -20833)
|
||||
const tipY = h / 2 + h * adjRaw(adjust, 'adj2', 62500)
|
||||
return wedgeCalloutPolygon(w, h, tipX, tipY)
|
||||
}
|
||||
case 'irregularSeal1':
|
||||
return starPoints(11, w, h, 0.3)
|
||||
case 'irregularSeal2':
|
||||
return starPoints(13, w, h, 0.25)
|
||||
case 'star4':
|
||||
return starPoints(4, w, h, frac('adj', 12500))
|
||||
case 'star5':
|
||||
return starPoints(5, w, h, frac('adj', 19098))
|
||||
case 'star6':
|
||||
return starPoints(6, w, h, frac('adj', 28868))
|
||||
case 'star7':
|
||||
return starPoints(7, w, h, frac('adj', 34601))
|
||||
case 'star8':
|
||||
return starPoints(8, w, h, frac('adj', 37500))
|
||||
case 'star10':
|
||||
return starPoints(10, w, h, frac('adj', 42533))
|
||||
case 'star12':
|
||||
return starPoints(12, w, h, frac('adj', 37500))
|
||||
case 'star16':
|
||||
return starPoints(16, w, h, frac('adj', 37500))
|
||||
case 'star24':
|
||||
return starPoints(24, w, h, frac('adj', 37500))
|
||||
case 'star32':
|
||||
return starPoints(32, w, h, frac('adj', 37500))
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** Raw adjust fraction (may be negative for directed offsets like callout tails), clamped to ±2. */
|
||||
function adjRaw(adjust: Record<string, number> | undefined, name: string, dflt: number): number {
|
||||
const v = (adjust?.[name] ?? dflt) / 100000
|
||||
return Math.min(Math.max(v, -2), 2)
|
||||
}
|
||||
|
||||
/** Rectangular bubble + tail triangle (the tail attaches to the edge facing the tip). */
|
||||
function wedgeCalloutPolygon(w: number, h: number, tipX: number, tipY: number): number[] {
|
||||
const g = Math.min(w, h) * 0.1
|
||||
const clamp = (v: number, lo: number, hi: number) => Math.min(Math.max(v, lo), hi)
|
||||
const nx = (tipX - w / 2) / w
|
||||
const ny = (tipY - h / 2) / h
|
||||
if (Math.abs(ny) >= Math.abs(nx)) {
|
||||
const bx = clamp(tipX, 2 * g, w - 2 * g)
|
||||
if (ny >= 0) return [0, 0, w, 0, w, h, bx + g, h, tipX, tipY, bx - g, h, 0, h]
|
||||
return [0, 0, bx - g, 0, tipX, tipY, bx + g, 0, w, 0, w, h, 0, h]
|
||||
}
|
||||
const by = clamp(tipY, 2 * g, h - 2 * g)
|
||||
if (nx >= 0) return [0, 0, w, 0, w, by - g, tipX, tipY, w, by + g, w, h, 0, h]
|
||||
return [0, 0, w, 0, w, h, 0, h, 0, by + g, tipX, tipY, 0, by - g]
|
||||
}
|
||||
|
||||
/** Gear: 4 points per tooth, tip narrower than root; innerR = root radius fraction. */
|
||||
function gearPoints(teeth: number, w: number, h: number, innerR: number): number[] {
|
||||
const cx = w / 2
|
||||
const cy = h / 2
|
||||
const pitch = 360 / teeth
|
||||
const tipHalf = pitch * 0.16
|
||||
const rootHalf = pitch * 0.38
|
||||
const pts: number[] = []
|
||||
for (let i = 0; i < teeth; i++) {
|
||||
const c = -90 + i * pitch
|
||||
for (const [off, r] of [[-rootHalf, innerR], [-tipHalf, 1], [tipHalf, 1], [rootHalf, innerR]] as const) {
|
||||
const a = ((c + off) * Math.PI) / 180
|
||||
pts.push(cx + Math.cos(a) * cx * r, cy + Math.sin(a) * cy * r)
|
||||
}
|
||||
}
|
||||
return pts
|
||||
}
|
||||
|
||||
/** n-point star: outer vertices on the bounding ellipse, inner-vertex radius fraction = innerFrac. */
|
||||
function starPoints(n: number, w: number, h: number, innerFrac: number): number[] {
|
||||
const cx = w / 2
|
||||
const cy = h / 2
|
||||
const pts: number[] = []
|
||||
for (let i = 0; i < n * 2; i++) {
|
||||
const ang = -Math.PI / 2 + (i * Math.PI) / n
|
||||
const f = i % 2 === 0 ? 1 : innerFrac * 2 // adj is relative to half the short side; *2 normalizes to the radius
|
||||
const fr = Math.min(f, 1)
|
||||
pts.push(cx + Math.cos(ang) * cx * fr, cy + Math.sin(ang) * cy * fr)
|
||||
}
|
||||
return pts
|
||||
}
|
||||
|
||||
/** Pill-like rounded-rect presets (rendered with cornerRadius = half the short side). */
|
||||
export function isPillPreset(preset: string | undefined): boolean {
|
||||
return preset === 'flowChartTerminator' || preset === 'flowChartAlternateProcess'
|
||||
}
|
||||
|
||||
// ── SVG path channel (arc/bezier presets) ────────────────────────────
|
||||
|
||||
export interface PresetPathResult {
|
||||
/** Main path, fill + stroke */
|
||||
path?: string
|
||||
/** Fill-only subpath (OOXML path stroke="0", e.g. an arc's pie sector) */
|
||||
fillPath?: string
|
||||
/** Stroke-only subpath (OOXML path fill="none", e.g. arcs/brackets/decorative lines) */
|
||||
strokePath?: string
|
||||
}
|
||||
|
||||
const R2 = (v: number) => Math.round(v * 100) / 100
|
||||
const D2R = Math.PI / 180
|
||||
|
||||
/** SVG path builder (local px); elliptical arcs are split into ≤90° parametric segments as cubics. */
|
||||
class PathB {
|
||||
private parts: string[] = []
|
||||
M(x: number, y: number) { this.parts.push(`M ${R2(x)} ${R2(y)}`); return this }
|
||||
L(x: number, y: number) { this.parts.push(`L ${R2(x)} ${R2(y)}`); return this }
|
||||
Q(x1: number, y1: number, x: number, y: number) {
|
||||
this.parts.push(`Q ${R2(x1)} ${R2(y1)} ${R2(x)} ${R2(y)}`); return this
|
||||
}
|
||||
C(x1: number, y1: number, x2: number, y2: number, x: number, y: number) {
|
||||
this.parts.push(`C ${R2(x1)} ${R2(y1)} ${R2(x2)} ${R2(y2)} ${R2(x)} ${R2(y)}`); return this
|
||||
}
|
||||
Z() { this.parts.push('Z'); return this }
|
||||
/** Parametric angles (degrees, y-down clockwise positive); move says whether to M/L to the arc start first */
|
||||
arc(cx: number, cy: number, rx: number, ry: number, startDeg: number, sweepDeg: number, move?: 'M' | 'L') {
|
||||
const st = startDeg * D2R
|
||||
const sw = sweepDeg * D2R
|
||||
const sx = cx + rx * Math.cos(st)
|
||||
const sy = cy + ry * Math.sin(st)
|
||||
if (move === 'M') this.M(sx, sy)
|
||||
else if (move === 'L') this.L(sx, sy)
|
||||
if (sw === 0) return this
|
||||
const segs = Math.max(1, Math.ceil(Math.abs(sw) / (Math.PI / 2)))
|
||||
const da = sw / segs
|
||||
const k = (4 / 3) * Math.tan(da / 4)
|
||||
for (let i = 0; i < segs; i++) {
|
||||
const a1 = st + i * da
|
||||
const a2 = a1 + da
|
||||
const x1 = cx + rx * Math.cos(a1)
|
||||
const y1 = cy + ry * Math.sin(a1)
|
||||
const x2 = cx + rx * Math.cos(a2)
|
||||
const y2 = cy + ry * Math.sin(a2)
|
||||
this.C(x1 - k * rx * Math.sin(a1), y1 + k * ry * Math.cos(a1),
|
||||
x2 + k * rx * Math.sin(a2), y2 - k * ry * Math.cos(a2), x2, y2)
|
||||
}
|
||||
return this
|
||||
}
|
||||
d() { return this.parts.join(' ') }
|
||||
}
|
||||
|
||||
/** Single-anchor ellipse subpath (full circle). */
|
||||
function ellipseSub(b: PathB, cx: number, cy: number, rx: number, ry: number, ccw = false) {
|
||||
b.arc(cx, cy, rx, ry, 0, ccw ? -360 : 360, 'M').Z()
|
||||
}
|
||||
|
||||
/** Rectangle with mixed round/snip corners (corner order TL/TR/BR/BL). */
|
||||
function mixedCornerRect(w: number, h: number, sizes: number[], kinds: Array<'none' | 'round' | 'snip'>): string {
|
||||
const [tl, tr, br, bl] = sizes as [number, number, number, number]
|
||||
const b = new PathB()
|
||||
b.M(tl, 0).L(w - tr, 0)
|
||||
if (kinds[1] === 'round') b.arc(w - tr, tr, tr, tr, 270, 90)
|
||||
else if (kinds[1] === 'snip') b.L(w, tr)
|
||||
b.L(w, h - br)
|
||||
if (kinds[2] === 'round') b.arc(w - br, h - br, br, br, 0, 90)
|
||||
else if (kinds[2] === 'snip') b.L(w - br, h)
|
||||
b.L(bl, h)
|
||||
if (kinds[3] === 'round') b.arc(bl, h - bl, bl, bl, 90, 90)
|
||||
else if (kinds[3] === 'snip') b.L(0, h - bl)
|
||||
b.L(0, tl)
|
||||
if (kinds[0] === 'round') b.arc(tl, tl, tl, tl, 180, 90)
|
||||
else if (kinds[0] === 'snip') b.L(tl, 0)
|
||||
return b.Z().d()
|
||||
}
|
||||
|
||||
/** Cloud outline (normalized control points × w/h). */
|
||||
function cloudBlob(w: number, h: number): PathB {
|
||||
const b = new PathB()
|
||||
const u: Array<[number, number]> = [
|
||||
[0.2, 0.85], [0.06, 0.86], [0, 0.72], [0.02, 0.59], [0.03, 0.47], [0.11, 0.39], [0.2, 0.42],
|
||||
[0.19, 0.26], [0.29, 0.14], [0.4, 0.2], [0.45, 0.07], [0.6, 0.04], [0.67, 0.14],
|
||||
[0.76, 0.04], [0.91, 0.1], [0.92, 0.26], [0.99, 0.31], [1, 0.46], [0.97, 0.56],
|
||||
[1, 0.69], [0.94, 0.81], [0.85, 0.82], [0.83, 0.94], [0.72, 0.98], [0.65, 0.91],
|
||||
[0.58, 1], [0.45, 1], [0.39, 0.91], [0.33, 0.98], [0.23, 0.95], [0.2, 0.85],
|
||||
]
|
||||
b.M(u[0]![0] * w, u[0]![1] * h)
|
||||
for (let i = 1; i + 2 < u.length + 1; i += 3) {
|
||||
b.C(u[i]![0] * w, u[i]![1] * h, u[i + 1]![0] * w, u[i + 1]![1] * h, u[i + 2]![0] * w, u[i + 2]![1] * h)
|
||||
}
|
||||
return b.Z()
|
||||
}
|
||||
|
||||
/**
|
||||
* Arc/bezier presets → SVG path (local px).
|
||||
* Complements presetPolygon: straight-edge polygons go through the point channel;
|
||||
* only curved shapes are handled here. Unsupported presets return null (fall back to a rectangle).
|
||||
*/
|
||||
export function presetPath(
|
||||
preset: string | undefined,
|
||||
w: number,
|
||||
h: number,
|
||||
adjust?: Record<string, number>,
|
||||
): PresetPathResult | null {
|
||||
if (!preset || w <= 0 || h <= 0) return null
|
||||
const ss = Math.min(w, h)
|
||||
const cx = w / 2
|
||||
const cy = h / 2
|
||||
const frac = (name: string, dflt: number) =>
|
||||
Math.min(Math.max((adjust?.[name] ?? dflt) / 100000, 0), 1)
|
||||
/** Angular adjusts: 1/60000 degree → degrees */
|
||||
const ang = (name: string, dflt: number) => (adjust?.[name] ?? dflt) / 60000
|
||||
const sweepCW = (a1: number, a2: number) => ((a2 - a1) % 360 + 360) % 360
|
||||
|
||||
switch (preset) {
|
||||
case 'arc': {
|
||||
const a1 = ang('adj1', 16200000)
|
||||
const a2 = ang('adj2', 0)
|
||||
const sw = sweepCW(a1, a2) || 90
|
||||
const fill = new PathB().M(cx, cy)
|
||||
fill.arc(cx, cy, cx, cy, a1, sw, 'L').Z()
|
||||
const stroke = new PathB().arc(cx, cy, cx, cy, a1, sw, 'M')
|
||||
return { fillPath: fill.d(), strokePath: stroke.d() }
|
||||
}
|
||||
case 'chord': {
|
||||
const a1 = ang('adj1', 2700000)
|
||||
const a2 = ang('adj2', 16200000)
|
||||
return { path: new PathB().arc(cx, cy, cx, cy, a1, sweepCW(a1, a2) || 180, 'M').Z().d() }
|
||||
}
|
||||
case 'pie': {
|
||||
const a1 = ang('adj1', 0)
|
||||
const a2 = ang('adj2', 16200000)
|
||||
return { path: new PathB().M(cx, cy).arc(cx, cy, cx, cy, a1, sweepCW(a1, a2) || 270, 'L').Z().d() }
|
||||
}
|
||||
case 'blockArc': {
|
||||
const a1 = ang('adj1', 10800000)
|
||||
const a2 = ang('adj2', 0)
|
||||
const sw = sweepCW(a1, a2) || 180
|
||||
const t = ss * frac('adj3', 25000)
|
||||
const rxI = Math.max(cx - t, 0)
|
||||
const ryI = Math.max(cy - t, 0)
|
||||
const b = new PathB().arc(cx, cy, cx, cy, a1, sw, 'M')
|
||||
b.arc(cx, cy, rxI, ryI, a1 + sw, -sw, 'L').Z()
|
||||
return { path: b.d() }
|
||||
}
|
||||
case 'donut': {
|
||||
const t = ss * frac('adj', 25000)
|
||||
const b = new PathB()
|
||||
ellipseSub(b, cx, cy, cx, cy)
|
||||
// Inner ring wound in reverse → nonzero rule punches the hole
|
||||
ellipseSub(b, cx, cy, Math.max(cx - t, 0), Math.max(cy - t, 0), true)
|
||||
return { path: b.d() }
|
||||
}
|
||||
case 'frame': {
|
||||
const t = ss * frac('adj1', 12500)
|
||||
const b = new PathB().M(0, 0).L(w, 0).L(w, h).L(0, h).Z()
|
||||
b.M(t, t).L(t, h - t).L(w - t, h - t).L(w - t, t).Z()
|
||||
return { path: b.d() }
|
||||
}
|
||||
case 'round1Rect': {
|
||||
const r = ss * frac('adj', 16667)
|
||||
return { path: mixedCornerRect(w, h, [0, r, 0, 0], ['none', 'round', 'none', 'none']) }
|
||||
}
|
||||
case 'round2SameRect': {
|
||||
const r1 = ss * frac('adj1', 16667)
|
||||
const r2 = ss * frac('adj2', 0)
|
||||
return { path: mixedCornerRect(w, h, [r1, r1, r2, r2], ['round', 'round', 'round', 'round']) }
|
||||
}
|
||||
case 'round2DiagRect': {
|
||||
const r1 = ss * frac('adj1', 16667)
|
||||
const r2 = ss * frac('adj2', 0)
|
||||
return { path: mixedCornerRect(w, h, [r1, r2, r1, r2], ['round', 'round', 'round', 'round']) }
|
||||
}
|
||||
case 'snipRoundRect': {
|
||||
const r1 = ss * frac('adj1', 16667)
|
||||
const r2 = ss * frac('adj2', 16667)
|
||||
return { path: mixedCornerRect(w, h, [r1, r2, 0, 0], ['round', 'snip', 'none', 'none']) }
|
||||
}
|
||||
case 'heart': {
|
||||
const b = new PathB().M(0.5 * w, 0.3 * h)
|
||||
b.C(0.5 * w, 0.12 * h, 0.36 * w, 0.01 * h, 0.22 * w, 0.01 * h)
|
||||
b.C(0.06 * w, 0.01 * h, 0, 0.15 * h, 0, 0.28 * h)
|
||||
b.C(0, 0.5 * h, 0.2 * w, 0.65 * h, 0.5 * w, h)
|
||||
b.C(0.8 * w, 0.65 * h, w, 0.5 * h, w, 0.28 * h)
|
||||
b.C(w, 0.15 * h, 0.94 * w, 0.01 * h, 0.78 * w, 0.01 * h)
|
||||
b.C(0.64 * w, 0.01 * h, 0.5 * w, 0.12 * h, 0.5 * w, 0.3 * h)
|
||||
return { path: b.Z().d() }
|
||||
}
|
||||
case 'moon': {
|
||||
const g = frac('adj', 50000)
|
||||
const b = new PathB().arc(w, cy, w, cy, 270, -180, 'M')
|
||||
// Inner arc has the same height (cusps close at the top/bottom); its horizontal radius via adj sets crescent thickness
|
||||
b.arc(w, cy, w * (1 - g), cy, 90, 180)
|
||||
return { path: b.Z().d() }
|
||||
}
|
||||
case 'sun': {
|
||||
const g = frac('adj', 25000)
|
||||
const rx = w * g
|
||||
const ry = h * g
|
||||
const b = new PathB()
|
||||
for (let k = 0; k < 8; k++) {
|
||||
const a = k * 45 * D2R
|
||||
const tipX = cx + cx * Math.cos(a)
|
||||
const tipY = cy + cy * Math.sin(a)
|
||||
const br = 1.35
|
||||
const a1 = a - 12 * D2R
|
||||
const a2 = a + 12 * D2R
|
||||
b.M(cx + rx * br * Math.cos(a1), cy + ry * br * Math.sin(a1))
|
||||
.L(tipX, tipY)
|
||||
.L(cx + rx * br * Math.cos(a2), cy + ry * br * Math.sin(a2))
|
||||
.Z()
|
||||
}
|
||||
ellipseSub(b, cx, cy, rx, ry)
|
||||
return { path: b.d() }
|
||||
}
|
||||
case 'cloud':
|
||||
return { path: cloudBlob(w, h).d() }
|
||||
case 'cloudCallout': {
|
||||
const tipX = cx + w * adjRaw(adjust, 'adj1', -20833)
|
||||
const tipY = cy + h * adjRaw(adjust, 'adj2', 62500)
|
||||
const b = cloudBlob(w, h)
|
||||
// Tail: two small bubbles toward the tip
|
||||
for (const [t, r] of [[0.72, 0.075], [0.92, 0.045]] as const) {
|
||||
ellipseSub(b, cx + (tipX - cx) * t, cy + (tipY - cy) * t, ss * r, ss * r)
|
||||
}
|
||||
return { path: b.d() }
|
||||
}
|
||||
case 'teardrop': {
|
||||
const a = Math.min(Math.max((adjust?.adj ?? 100000) / 100000, 0), 2)
|
||||
const tipX = cx + cx * a
|
||||
const tipY = cy - cy * a
|
||||
const b = new PathB().arc(cx, cy, cx, cy, 0, 270, 'M')
|
||||
b.Q(cx + (tipX - cx) / 2, tipY, tipX, tipY).Q(w, (tipY + cy) / 2, w, cy)
|
||||
return { path: b.Z().d() }
|
||||
}
|
||||
case 'plaque': {
|
||||
const r = ss * frac('adj', 16667)
|
||||
const b = new PathB().M(r, 0).L(w - r, 0)
|
||||
b.arc(w, 0, r, r, 180, -90).L(w, h - r)
|
||||
b.arc(w, h, r, r, 270, -90).L(r, h)
|
||||
b.arc(0, h, r, r, 0, -90).L(0, r)
|
||||
b.arc(0, 0, r, r, 90, -90)
|
||||
return { path: b.Z().d() }
|
||||
}
|
||||
case 'cube': {
|
||||
const d = ss * frac('adj', 25000)
|
||||
const path = new PathB().M(0, d).L(d, 0).L(w, 0).L(w, h - d).L(w - d, h).L(0, h).Z().d()
|
||||
const inner = new PathB().M(0, d).L(w - d, d).L(w, 0).M(w - d, d).L(w - d, h).d()
|
||||
return { path, strokePath: inner }
|
||||
}
|
||||
case 'can': {
|
||||
const ry = (h * frac('adj', 25000)) / 2
|
||||
const b = new PathB().M(0, ry).L(0, h - ry)
|
||||
b.arc(cx, h - ry, cx, ry, 180, -180).L(w, ry)
|
||||
b.arc(cx, ry, cx, ry, 0, -180).Z()
|
||||
const rim = new PathB().arc(cx, ry, cx, ry, 180, -180, 'M').d()
|
||||
return { path: b.d(), strokePath: rim }
|
||||
}
|
||||
case 'flowChartMagneticDisk': {
|
||||
const ry = h / 6
|
||||
const b = new PathB().M(0, ry).L(0, h - ry)
|
||||
b.arc(cx, h - ry, cx, ry, 180, -180).L(w, ry)
|
||||
b.arc(cx, ry, cx, ry, 0, -180).Z()
|
||||
const rim = new PathB().arc(cx, ry, cx, ry, 180, -180, 'M').d()
|
||||
return { path: b.d(), strokePath: rim }
|
||||
}
|
||||
case 'flowChartMagneticDrum': {
|
||||
const rx = w / 6
|
||||
const b = new PathB().arc(w - rx, cy, rx, cy, 270, 180, 'M').L(rx, h)
|
||||
b.arc(rx, cy, rx, cy, 90, 180).Z()
|
||||
const rim = new PathB().arc(w - rx, cy, rx, cy, 270, -180, 'M').d()
|
||||
return { path: b.d(), strokePath: rim }
|
||||
}
|
||||
case 'bevel': {
|
||||
const t = ss * frac('adj', 12500)
|
||||
const path = new PathB().M(0, 0).L(w, 0).L(w, h).L(0, h).Z().d()
|
||||
const inner = new PathB()
|
||||
.M(t, t).L(w - t, t).L(w - t, h - t).L(t, h - t).Z()
|
||||
.M(0, 0).L(t, t).M(w, 0).L(w - t, t).M(w, h).L(w - t, h - t).M(0, h).L(t, h - t)
|
||||
return { path, strokePath: inner.d() }
|
||||
}
|
||||
case 'foldedCorner': {
|
||||
const f = ss * frac('adj', 16667)
|
||||
const path = new PathB().M(0, 0).L(w, 0).L(w, h - f).L(w - f, h).L(0, h).Z().d()
|
||||
const fold = new PathB().M(w - f, h).L(w - 0.8 * f, h - 0.8 * f).L(w, h - f).d()
|
||||
return { path, strokePath: fold }
|
||||
}
|
||||
case 'smileyFace': {
|
||||
const b = new PathB()
|
||||
ellipseSub(b, cx, cy, cx, cy)
|
||||
const g = adjRaw(adjust, 'adj', 4653)
|
||||
const face = new PathB()
|
||||
ellipseSub(face, 0.35 * w, 0.37 * h, 0.05 * w, 0.05 * h)
|
||||
ellipseSub(face, 0.65 * w, 0.37 * h, 0.05 * w, 0.05 * h)
|
||||
face.M(0.3 * w, 0.67 * h).Q(cx, h * Math.min(Math.max(0.67 + 4 * g, 0.4), 0.95), 0.7 * w, 0.67 * h)
|
||||
return { path: b.d(), strokePath: face.d() }
|
||||
}
|
||||
case 'noSmoking': {
|
||||
const t = ss * frac('adj', 18750)
|
||||
const b = new PathB()
|
||||
ellipseSub(b, cx, cy, cx, cy)
|
||||
const rxI = Math.max(cx - t, 0)
|
||||
const ryI = Math.max(cy - t, 0)
|
||||
ellipseSub(b, cx, cy, rxI, ryI, true)
|
||||
// 45° slash (line between two inner-circle points, width = ring thickness)
|
||||
const p1x = cx + rxI * Math.cos(225 * D2R)
|
||||
const p1y = cy + ryI * Math.sin(225 * D2R)
|
||||
const p2x = cx + rxI * Math.cos(45 * D2R)
|
||||
const p2y = cy + ryI * Math.sin(45 * D2R)
|
||||
const len = Math.hypot(p2x - p1x, p2y - p1y) || 1
|
||||
const nx = (-(p2y - p1y) / len) * (t / 2)
|
||||
const ny = ((p2x - p1x) / len) * (t / 2)
|
||||
b.M(p1x + nx, p1y + ny).L(p2x + nx, p2y + ny).L(p2x - nx, p2y - ny).L(p1x - nx, p1y - ny).Z()
|
||||
return { path: b.d() }
|
||||
}
|
||||
case 'ribbon': {
|
||||
const b = new PathB()
|
||||
b.M(0, 0.25 * h).L(0.25 * w, 0.25 * h).L(0.25 * w, h).L(0, h).L(0.0833 * w, 0.625 * h).Z()
|
||||
b.M(w, 0.25 * h).L(0.75 * w, 0.25 * h).L(0.75 * w, h).L(w, h).L(0.9167 * w, 0.625 * h).Z()
|
||||
b.M(0.125 * w, 0).L(0.875 * w, 0).L(0.875 * w, 0.75 * h).L(0.125 * w, 0.75 * h).Z()
|
||||
return { path: b.d() }
|
||||
}
|
||||
case 'ribbon2': {
|
||||
const b = new PathB()
|
||||
b.M(0, 0.75 * h).L(0.25 * w, 0.75 * h).L(0.25 * w, 0).L(0, 0).L(0.0833 * w, 0.375 * h).Z()
|
||||
b.M(w, 0.75 * h).L(0.75 * w, 0.75 * h).L(0.75 * w, 0).L(w, 0).L(0.9167 * w, 0.375 * h).Z()
|
||||
b.M(0.125 * w, h).L(0.875 * w, h).L(0.875 * w, 0.25 * h).L(0.125 * w, 0.25 * h).Z()
|
||||
return { path: b.d() }
|
||||
}
|
||||
case 'wave': {
|
||||
const a = h * Math.min(frac('adj1', 12500), 0.25)
|
||||
const b = new PathB().M(0, a)
|
||||
b.C(w / 6, 0, w / 3, 0, w / 2, a).C((2 * w) / 3, 2 * a, (5 * w) / 6, 2 * a, w, a)
|
||||
b.L(w, h - a)
|
||||
b.C((5 * w) / 6, h, (2 * w) / 3, h, w / 2, h - a).C(w / 3, h - 2 * a, w / 6, h - 2 * a, 0, h - a)
|
||||
return { path: b.Z().d() }
|
||||
}
|
||||
case 'doubleWave': {
|
||||
const a = h * Math.min(frac('adj1', 6250), 0.2)
|
||||
const b = new PathB().M(0, a)
|
||||
b.C(w / 12, 0, w / 6, 0, w / 4, a).C(w / 3, 2 * a, (5 * w) / 12, 2 * a, w / 2, a)
|
||||
b.C((7 * w) / 12, 0, (2 * w) / 3, 0, (3 * w) / 4, a).C((5 * w) / 6, 2 * a, (11 * w) / 12, 2 * a, w, a)
|
||||
b.L(w, h - a)
|
||||
b.C((11 * w) / 12, h, (5 * w) / 6, h, (3 * w) / 4, h - a).C((2 * w) / 3, h - 2 * a, (7 * w) / 12, h - 2 * a, w / 2, h - a)
|
||||
b.C((5 * w) / 12, h, w / 3, h, w / 4, h - a).C(w / 6, h - 2 * a, w / 12, h - 2 * a, 0, h - a)
|
||||
return { path: b.Z().d() }
|
||||
}
|
||||
case 'uturnArrow': {
|
||||
const t = ss * frac('adj1', 25000)
|
||||
const hw = 0.75 * t
|
||||
const hl = t
|
||||
const xrc = w - hw
|
||||
const rxO = (xrc + t / 2) / 2
|
||||
const ryO = Math.min(h / 2, rxO)
|
||||
const b = new PathB().M(0, h).L(0, ryO)
|
||||
b.arc(rxO, ryO, rxO, ryO, 180, 180)
|
||||
const yh = h - hl
|
||||
b.L(xrc + t / 2, yh).L(xrc + hw, yh).L(xrc, h).L(xrc - hw, yh).L(xrc - t / 2, yh).L(xrc - t / 2, ryO)
|
||||
b.arc(rxO, ryO, Math.max(rxO - t, 0), Math.max(ryO - t, ryO * 0.2), 0, -180)
|
||||
b.L(t, h).Z()
|
||||
return { path: b.d() }
|
||||
}
|
||||
case 'curvedRightArrow': {
|
||||
const t = ss * frac('adj1', 25000)
|
||||
const b = new PathB().M(0, 0)
|
||||
b.arc(0, cy, w, cy, 270, 90)
|
||||
const bi = Math.max(w - 1.5 * t, 0)
|
||||
b.L((w + bi) / 2, Math.min(h, cy + 1.2 * t)).L(bi, cy).L(w - t, cy)
|
||||
b.arc(0, cy, Math.max(w - t, 0), Math.max(cy - t, 0), 0, -90)
|
||||
b.L(0, 0).Z()
|
||||
return { path: b.d() }
|
||||
}
|
||||
case 'stripedRightArrow': {
|
||||
const thick = h * frac('adj1', 50000)
|
||||
const head = Math.min(w, ss * frac('adj2', 50000))
|
||||
const y1 = (h - thick) / 2
|
||||
const y2 = (h + thick) / 2
|
||||
const xh = w - head
|
||||
const bs = (ss * 5) / 32
|
||||
const b = new PathB()
|
||||
b.M(bs, y1).L(xh, y1).L(xh, 0).L(w, cy).L(xh, h).L(xh, y2).L(bs, y2).Z()
|
||||
b.M(0, y1).L(ss / 32, y1).L(ss / 32, y2).L(0, y2).Z()
|
||||
b.M(ss / 16, y1).L(ss / 8, y1).L(ss / 8, y2).L(ss / 16, y2).Z()
|
||||
return { path: b.d() }
|
||||
}
|
||||
case 'wedgeRoundRectCallout': {
|
||||
const r = ss * frac('adj3', 16667)
|
||||
const tipX = cx + w * adjRaw(adjust, 'adj1', -20833)
|
||||
const tipY = cy + h * adjRaw(adjust, 'adj2', 62500)
|
||||
const b = new PathB()
|
||||
b.M(r, 0).L(w - r, 0).arc(w - r, r, r, r, 270, 90).L(w, h - r)
|
||||
b.arc(w - r, h - r, r, r, 0, 90).L(r, h).arc(r, h - r, r, r, 90, 90).L(0, r)
|
||||
b.arc(r, r, r, r, 180, 90).Z()
|
||||
appendWedgeTail(b, w, h, tipX, tipY)
|
||||
return { path: b.d() }
|
||||
}
|
||||
case 'wedgeEllipseCallout': {
|
||||
const tipX = cx + w * adjRaw(adjust, 'adj1', -20833)
|
||||
const tipY = cy + h * adjRaw(adjust, 'adj2', 62500)
|
||||
const b = new PathB()
|
||||
ellipseSub(b, cx, cy, cx, cy)
|
||||
const th = Math.atan2(tipY - cy, tipX - cx)
|
||||
b.M(cx + cx * Math.cos(th - 0.3), cy + cy * Math.sin(th - 0.3))
|
||||
.L(tipX, tipY)
|
||||
.L(cx + cx * Math.cos(th + 0.3), cy + cy * Math.sin(th + 0.3))
|
||||
.Z()
|
||||
return { path: b.d() }
|
||||
}
|
||||
case 'flowChartPredefinedProcess': {
|
||||
const path = new PathB().M(0, 0).L(w, 0).L(w, h).L(0, h).Z().d()
|
||||
const lines = new PathB().M(w / 8, 0).L(w / 8, h).M((7 * w) / 8, 0).L((7 * w) / 8, h).d()
|
||||
return { path, strokePath: lines }
|
||||
}
|
||||
case 'flowChartInternalStorage': {
|
||||
const path = new PathB().M(0, 0).L(w, 0).L(w, h).L(0, h).Z().d()
|
||||
const lines = new PathB().M(w / 8, 0).L(w / 8, h).M(0, h / 8).L(w, h / 8).d()
|
||||
return { path, strokePath: lines }
|
||||
}
|
||||
case 'flowChartDocument': {
|
||||
const b = new PathB().M(0, 0).L(w, 0).L(w, 0.83 * h)
|
||||
b.C(0.75 * w, 0.72 * h, 0.58 * w, 0.72 * h, 0.5 * w, 0.83 * h)
|
||||
b.C(0.42 * w, 0.94 * h, 0.25 * w, 0.94 * h, 0, 0.83 * h)
|
||||
return { path: b.Z().d() }
|
||||
}
|
||||
case 'flowChartMultidocument': {
|
||||
const b = new PathB().M(0, 0.12 * h).L(0.88 * w, 0.12 * h).L(0.88 * w, 0.85 * h)
|
||||
b.C(0.66 * w, 0.74 * h, 0.51 * w, 0.74 * h, 0.44 * w, 0.85 * h)
|
||||
b.C(0.37 * w, 0.96 * h, 0.22 * w, 0.96 * h, 0, 0.85 * h)
|
||||
b.Z()
|
||||
const backs = new PathB()
|
||||
.M(0.06 * w, 0.12 * h).L(0.06 * w, 0.06 * h).L(0.94 * w, 0.06 * h).L(0.94 * w, 0.6 * h)
|
||||
.M(0.12 * w, 0.06 * h).L(0.12 * w, 0).L(w, 0).L(w, 0.53 * h)
|
||||
return { path: b.d(), strokePath: backs.d() }
|
||||
}
|
||||
case 'flowChartConnector': {
|
||||
const b = new PathB()
|
||||
ellipseSub(b, cx, cy, cx, cy)
|
||||
return { path: b.d() }
|
||||
}
|
||||
case 'flowChartOr': {
|
||||
const b = new PathB()
|
||||
ellipseSub(b, cx, cy, cx, cy)
|
||||
const lines = new PathB().M(cx, 0).L(cx, h).M(0, cy).L(w, cy).d()
|
||||
return { path: b.d(), strokePath: lines }
|
||||
}
|
||||
case 'flowChartSummingJunction': {
|
||||
const b = new PathB()
|
||||
ellipseSub(b, cx, cy, cx, cy)
|
||||
const dx = cx * Math.SQRT1_2
|
||||
const dy = cy * Math.SQRT1_2
|
||||
const lines = new PathB()
|
||||
.M(cx - dx, cy - dy).L(cx + dx, cy + dy).M(cx + dx, cy - dy).L(cx - dx, cy + dy).d()
|
||||
return { path: b.d(), strokePath: lines }
|
||||
}
|
||||
case 'flowChartSort': {
|
||||
const path = new PathB().M(cx, 0).L(w, cy).L(cx, h).L(0, cy).Z().d()
|
||||
return { path, strokePath: new PathB().M(0, cy).L(w, cy).d() }
|
||||
}
|
||||
case 'flowChartDelay': {
|
||||
const b = new PathB().M(0, 0).L(cx, 0)
|
||||
b.arc(cx, cy, cx, cy, 270, 180).L(0, h).Z()
|
||||
return { path: b.d() }
|
||||
}
|
||||
case 'flowChartDisplay': {
|
||||
const b = new PathB().M(0, cy).L(w / 6, 0).L((5 * w) / 6, 0)
|
||||
b.arc((5 * w) / 6, cy, w / 6, cy, 270, 180).L(w / 6, h).Z()
|
||||
return { path: b.d() }
|
||||
}
|
||||
case 'flowChartPunchedTape': {
|
||||
const a = 0.1 * h
|
||||
const b = new PathB().M(0, a)
|
||||
b.C(w / 6, 0, w / 3, 0, w / 2, a).C((2 * w) / 3, 2 * a, (5 * w) / 6, 2 * a, w, a)
|
||||
b.L(w, h - a)
|
||||
b.C((5 * w) / 6, h - 2 * a, (2 * w) / 3, h - 2 * a, w / 2, h - a)
|
||||
b.C(w / 3, h, w / 6, h, 0, h - a)
|
||||
return { path: b.Z().d() }
|
||||
}
|
||||
case 'leftBracket': {
|
||||
const r = Math.min(h / 2, ss * frac('adj', 8333))
|
||||
const b = new PathB().arc(w, r, w, r, 270, -90, 'M').L(0, h - r).arc(w, h - r, w, r, 180, -90)
|
||||
return { strokePath: b.d() }
|
||||
}
|
||||
case 'rightBracket': {
|
||||
const r = Math.min(h / 2, ss * frac('adj', 8333))
|
||||
const b = new PathB().arc(0, r, w, r, 270, 90, 'M').L(w, h - r).arc(0, h - r, w, r, 0, 90)
|
||||
return { strokePath: b.d() }
|
||||
}
|
||||
case 'leftBrace': {
|
||||
const r = Math.min(h / 4, ss * frac('adj1', 8333))
|
||||
const mid = h * frac('adj2', 50000)
|
||||
const xm = w / 2
|
||||
const b = new PathB().arc(w, r, xm, r, 270, -90, 'M').L(xm, mid - r)
|
||||
b.arc(0, mid - r, xm, r, 0, 90).arc(0, mid + r, xm, r, 270, 90).L(xm, h - r)
|
||||
b.arc(w, h - r, xm, r, 180, -90)
|
||||
return { strokePath: b.d() }
|
||||
}
|
||||
case 'rightBrace': {
|
||||
const r = Math.min(h / 4, ss * frac('adj1', 8333))
|
||||
const mid = h * frac('adj2', 50000)
|
||||
const xm = w / 2
|
||||
const b = new PathB().arc(0, r, xm, r, 270, 90, 'M').L(xm, mid - r)
|
||||
b.arc(w, mid - r, xm, r, 180, -90).arc(w, mid + r, xm, r, 270, -90).L(xm, h - r)
|
||||
b.arc(0, h - r, xm, r, 0, 90)
|
||||
return { strokePath: b.d() }
|
||||
}
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** Appends a callout tail triangle to an existing path (same positioning rules as wedgeCalloutPolygon). */
|
||||
function appendWedgeTail(b: PathB, w: number, h: number, tipX: number, tipY: number) {
|
||||
const g = Math.min(w, h) * 0.1
|
||||
const clamp = (v: number, lo: number, hi: number) => Math.min(Math.max(v, lo), hi)
|
||||
const nx = (tipX - w / 2) / w
|
||||
const ny = (tipY - h / 2) / h
|
||||
if (Math.abs(ny) >= Math.abs(nx)) {
|
||||
const bx = clamp(tipX, 2 * g, w - 2 * g)
|
||||
const ey = ny >= 0 ? h : 0
|
||||
b.M(bx - g, ey).L(tipX, tipY).L(bx + g, ey).Z()
|
||||
} else {
|
||||
const by = clamp(tipY, 2 * g, h - 2 * g)
|
||||
const ex = nx >= 0 ? w : 0
|
||||
b.M(ex, by - g).L(tipX, tipY).L(ex, by + g).Z()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,370 @@
|
||||
/**
|
||||
* RenderTree — a data-driven abstract draw list (the render layer's core asset).
|
||||
*
|
||||
* Design intent (plan A): parse the Slide element tree into a pure data structure
|
||||
* of "converted pixel geometry + resolved styles + laid-out text glyph boxes".
|
||||
* Fidelity verification locks onto this layer (coordinates/metrics/wrapping are
|
||||
* unit-testable without a canvas); Konva is just a thin adapter that draws the
|
||||
* RenderTree.
|
||||
*
|
||||
* All geometry units = px (absolute target-canvas coordinates), with viewport
|
||||
* scale and nested group offsets already applied.
|
||||
*/
|
||||
import type { Fill, Stroke } from '@genoffice/pptx-engine'
|
||||
import type { PlacedBox } from './coords'
|
||||
|
||||
export type RenderNodeType =
|
||||
| 'shape' // vector shape (may contain text)
|
||||
| 'picture' // image
|
||||
| 'text' // plain text box
|
||||
| 'group' // group (only carries children; its geometry is for nesting)
|
||||
| 'table' // table (cells positioned relative to the table's top-left)
|
||||
| 'chart' // chart (draw primitives positioned relative to the chart box's top-left)
|
||||
| 'placeholder-chip' // passthrough placeholder chip
|
||||
|
||||
export interface RenderNodeBase {
|
||||
id: string
|
||||
type: RenderNodeType
|
||||
box: PlacedBox
|
||||
/** Source Slide element id, used by the edit layer to locate write-backs */
|
||||
sourceId: string
|
||||
/** master/layout decoration node: read-only display, not selectable/draggable/snappable */
|
||||
decoration?: boolean
|
||||
}
|
||||
|
||||
/** Resolved render fill (RGBA / gradient stops / image dataUrl). */
|
||||
export type RenderFill =
|
||||
| { kind: 'none' }
|
||||
| { kind: 'solid'; color: string }
|
||||
| {
|
||||
kind: 'gradient'
|
||||
stops: Array<{ pos: number; color: string }>
|
||||
angleDeg: number
|
||||
radial?: boolean
|
||||
}
|
||||
| { kind: 'image'; dataUrl?: string; mode: 'stretch' | 'tile' }
|
||||
|
||||
export interface RenderStroke {
|
||||
color: string
|
||||
widthPx: number
|
||||
/** Line width (pt, viewport-independent; for property panel display/editing) */
|
||||
widthPt: number
|
||||
dash?: number[]
|
||||
/** OOXML prstDash preset name (for property panel display/editing) */
|
||||
dashPreset?: string
|
||||
}
|
||||
|
||||
/** Outer shadow converted to px. */
|
||||
/** Glow (approximated in Konva as a shadow without offset) */
|
||||
export interface RenderGlow {
|
||||
color: string
|
||||
blurPx: number
|
||||
}
|
||||
|
||||
export interface RenderShadow {
|
||||
color: string
|
||||
blurPx: number
|
||||
offsetX: number
|
||||
offsetY: number
|
||||
}
|
||||
|
||||
/** A laid-out text glyph block (one contiguous same-format span within a line). */
|
||||
export interface GlyphRun {
|
||||
text: string
|
||||
/** px coordinate relative to the text box top-left (baseline left endpoint) */
|
||||
x: number
|
||||
/** Baseline y (px relative to the text box top-left) */
|
||||
baselineY: number
|
||||
fontFamily: string
|
||||
/** The model run's raw font name (absent when the run has no explicit font — fontFamily is then
|
||||
* a layout default or missing-font substitution product; editors must commit this, never fontFamily,
|
||||
* or the display fallback gets silently written into the file as an explicit font). */
|
||||
srcFontFamily?: string
|
||||
fontSizePx: number
|
||||
color: string
|
||||
bold: boolean
|
||||
italic: boolean
|
||||
underline: boolean
|
||||
/** Strikethrough (<a:rPr strike>) */
|
||||
strike?: boolean
|
||||
/** 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) */
|
||||
widthPx: number
|
||||
/** Logical token order before bidi visual reordering; editable DOM uses this to preserve source text order. */
|
||||
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
|
||||
/** Text outline (<a:rPr><a:ln>, commonly used by WordArt) */
|
||||
outline?: { color: string; widthPx: number }
|
||||
/** Extra per-char spacing spread in by justify alignment (px); draw-only, the editor ignores it and doesn't store it */
|
||||
justifyExtraPx?: number
|
||||
/** Super/subscript baseline shift (px, positive = up; <a:rPr baseline>), already baked into baselineY */
|
||||
baselineShiftPx?: number
|
||||
/** Latin word in vertical text: drawn rotated 90° clockwise (x/baselineY is the rotation anchor) */
|
||||
rotate90?: boolean
|
||||
/** Bullet glyph (non-body content injected by layout; text editors should skip it) */
|
||||
isBullet?: boolean
|
||||
/** RTL direction-level run (Arabic/Hebrew): the renderer must set canvas direction=rtl so punctuation/neutral chars land on the far side */
|
||||
rtl?: boolean
|
||||
/** Source model run index (into Paragraph.runs); the editor uses it to merge fragments and trace back original formatting */
|
||||
srcRunIdx?: number
|
||||
/** Run hyperlink ("slide:N" or url, from TextRun.hyperlink); editor round-trips it, follow actions re-resolve live */
|
||||
link?: string
|
||||
/** The run font's real ascent (px); used by the renderer for baseline→top conversion (falls back to 0.8em) */
|
||||
ascentPx?: number
|
||||
}
|
||||
|
||||
/** A laid-out line of text. */
|
||||
export interface TextLine {
|
||||
runs: GlyphRun[]
|
||||
/** Line top y (px relative to the text box top-left) */
|
||||
top: number
|
||||
height: number
|
||||
/** This line starts a model paragraph (false/absent = auto-wrap continuation of the previous one; the editor splits paragraphs on it) */
|
||||
paraStart?: boolean
|
||||
/** Trailing whitespace swallowed when wrapping (the editor re-adds a space when joining lines; hard breaks/CJK wrapping don't set it) */
|
||||
trailingSpace?: boolean
|
||||
/** The line ends with an <a:br/> soft break; value = the sentinel run's model index (the editor round-trips soft breaks with it) */
|
||||
softBreakAfter?: number
|
||||
/** Paragraph horizontal alignment (editor display) */
|
||||
align?: 'left' | 'center' | 'right' | 'justify'
|
||||
/** Paragraph indent level (editor Tab multi-level list display) */
|
||||
level?: number
|
||||
}
|
||||
|
||||
export interface RenderTextLayout {
|
||||
lines: TextLine[]
|
||||
/** Insets (px) */
|
||||
insets: { l: number; t: number; r: number; b: number }
|
||||
/** Vertical alignment */
|
||||
anchor: 'top' | 'middle' | 'bottom'
|
||||
/** Font scale actually applied by autofit (<1 when shrinking) */
|
||||
fontScale: number
|
||||
/** Line-spacing reduction actually applied by autofit (0-0.2, tied to the fontScale step) */
|
||||
lnSpcReduction?: number
|
||||
/** Total content height after layout (px), used for vertical alignment positioning */
|
||||
contentHeight: number
|
||||
/** bodyPr wrap (false = no wrapping, overflows the box; the editor also doesn't wrap) */
|
||||
wrap: boolean
|
||||
/** bodyPr vert: vertical column layout (lines = columns, right→left); vert/vert270/wordArtVert degrade to eaVert */
|
||||
vert?: 'eaVert' | 'vert' | 'vert270' | 'wordArtVert'
|
||||
}
|
||||
|
||||
/** Connector/line endpoint arrow description (for rendering, sizes converted to px). */
|
||||
export interface ArrowEndRender {
|
||||
/** Arrow type: triangle/stealth/diamond/oval/arrow (line arrow) */
|
||||
type: 'arrow' | 'triangle' | 'stealth' | 'diamond' | 'oval'
|
||||
/** Arrow width (px), the lateral dimension */
|
||||
widthPx: number
|
||||
/** Arrow length/depth (px), the longitudinal dimension */
|
||||
lengthPx: number
|
||||
}
|
||||
|
||||
export interface ShapeRenderNode extends RenderNodeBase {
|
||||
type: 'shape' | 'text'
|
||||
/** Placeholder type (title/ctrTitle/subTitle/body/…); empty placeholders draw hint text on the canvas */
|
||||
placeholder?: string
|
||||
presetGeometry?: string
|
||||
/** Exact corner radius for roundRect-style geometry (px, computed from avLst adj; 50% of the min side = pill) */
|
||||
cornerRadiusPx?: number
|
||||
/** Point list of closed-polygon preset geometry (triangle/diamond/arrow…) (local px, drawn closed) */
|
||||
polygonPoints?: number[]
|
||||
/** SVG path (local px, d format): custGeom / arc-style presets, fill + stroke */
|
||||
pathData?: string
|
||||
/** Fill-only subpath (OOXML path stroke="0", e.g. an arc's pie sector) */
|
||||
fillPathData?: string
|
||||
/** Stroke-only subpath (OOXML path fill="none", e.g. arcs, brackets) */
|
||||
strokePathData?: string
|
||||
/** Connector/straight line: polyline points (local px, flips baked in) + head/tail arrow descriptions */
|
||||
line?: {
|
||||
points: number[]
|
||||
/** Curve control points (bezier, 4 points per segment [cx1,cy1,cx2,cy2,x,y], relative to the polyline start) */
|
||||
bezier?: number[]
|
||||
headEnd?: ArrowEndRender
|
||||
tailEnd?: ArrowEndRender
|
||||
}
|
||||
fill: RenderFill
|
||||
stroke?: RenderStroke
|
||||
shadow?: RenderShadow
|
||||
glow?: RenderGlow
|
||||
text?: RenderTextLayout
|
||||
}
|
||||
|
||||
export interface PictureRenderNode extends RenderNodeBase {
|
||||
type: 'picture'
|
||||
dataUrl?: string
|
||||
/** Picture shape-geometry clip (picture styles): three channels matching shape geometry; clip when any is set */
|
||||
clip?: { cornerRadiusPx?: number; polygonPoints?: number[]; pathData?: string }
|
||||
/** Source image crop ratios (0..1, how much each side is cropped) */
|
||||
srcRect?: { l: number; t: number; r: number; b: number }
|
||||
/** Whole-image opacity (0..1; default 1) */
|
||||
opacity?: number
|
||||
/** Soft-edge feather radius (px) */
|
||||
softEdgePx?: number
|
||||
/** Audio/video (the image is the poster frame): the render layer overlays a play/speaker badge */
|
||||
media?: 'video' | 'audio'
|
||||
stroke?: RenderStroke
|
||||
shadow?: RenderShadow
|
||||
glow?: RenderGlow
|
||||
/** Source element cNvPr name (the edit layer identifies its own elements, e.g. freehand ink) */
|
||||
name?: string
|
||||
/** Source element cNvPr descr payload (freehand ink vector points etc.) */
|
||||
descr?: string
|
||||
}
|
||||
|
||||
export interface GroupRenderNode extends RenderNodeBase {
|
||||
type: 'group'
|
||||
/** children boxes are in group-local coords (relative to the group top-left); ext/chExt scaling is baked into the geometry */
|
||||
children: RenderNode[]
|
||||
/**
|
||||
* ext/chExt scaling (group box size / child coordinate system size). Already baked into
|
||||
* children boxes at build time; the render container must **not** apply it again. Kept only
|
||||
* for the edit pipeline to convert between local px and child EMU.
|
||||
*/
|
||||
childScaleX?: number
|
||||
childScaleY?: number
|
||||
}
|
||||
|
||||
export interface ChipRenderNode extends RenderNodeBase {
|
||||
type: 'placeholder-chip'
|
||||
kind: string // chart/table/smartart/...
|
||||
label: string
|
||||
}
|
||||
|
||||
/** A positioned table cell (coordinates relative to the table top-left, px; merged placeholder cells aren't emitted). */
|
||||
export interface TableCellRender {
|
||||
x: number
|
||||
y: number
|
||||
w: number
|
||||
h: number
|
||||
/** Model coordinates (rows[row][col], col is the tc index, not the logical column), for edit write-backs */
|
||||
row: number
|
||||
col: number
|
||||
/** Merge anchor span (>1 means splittable; default 1) */
|
||||
gridSpan?: number
|
||||
rowSpan?: number
|
||||
fill: RenderFill
|
||||
/** Border lines on the four sides (default none) */
|
||||
borders?: { l?: RenderStroke; r?: RenderStroke; t?: RenderStroke; b?: RenderStroke }
|
||||
text?: RenderTextLayout
|
||||
}
|
||||
|
||||
export interface TableRenderNode extends RenderNodeBase {
|
||||
type: 'table'
|
||||
cells: TableCellRender[]
|
||||
/** Grid line offsets relative to the box (px): gridX has nCols+1 entries, gridY nRows+1 */
|
||||
gridX: number[]
|
||||
gridY: number[]
|
||||
/** tblPr header-row / banded-row toggles (for the Ribbon "Table Design" display) */
|
||||
styleFlags?: { firstRow: boolean; bandRow: boolean }
|
||||
}
|
||||
|
||||
// ── Charts (precomputed draw primitives, coordinates relative to the chart box top-left, px) ──
|
||||
|
||||
export interface ChartLabel {
|
||||
text: string
|
||||
/** Text top-left */
|
||||
x: number
|
||||
y: number
|
||||
fontSizePx: number
|
||||
color: string
|
||||
bold?: boolean
|
||||
/** Rotation angle (e.g. -90 for a value-axis title) */
|
||||
rotationDeg?: number
|
||||
}
|
||||
|
||||
/** Current chart style (for the Ribbon "Chart Design" display; kind aligns with EditChartOp.kind). */
|
||||
export interface ChartStyleInfo {
|
||||
kind:
|
||||
| 'bar'
|
||||
| 'barStacked'
|
||||
| 'line'
|
||||
| 'area'
|
||||
| 'pie'
|
||||
| 'doughnut'
|
||||
| 'scatter'
|
||||
| 'radar'
|
||||
| 'comboBarLine'
|
||||
| 'unknown'
|
||||
legendPos: 'b' | 't' | 'l' | 'r' | 'none'
|
||||
dataLabels: boolean
|
||||
gridlines: boolean
|
||||
title?: string
|
||||
catAxisTitle?: string
|
||||
valAxisTitle?: string
|
||||
gapWidthPct?: number
|
||||
}
|
||||
|
||||
export interface ChartRenderNode extends RenderNodeBase {
|
||||
type: 'chart'
|
||||
/** Inserted by this app (cNvPr descr="aislides-chart"): chart editing enabled; passthrough charts lack this flag */
|
||||
appCreated?: boolean
|
||||
styleInfo?: ChartStyleInfo
|
||||
/** Gridlines / axis lines */
|
||||
gridLines: Array<{
|
||||
x1: number
|
||||
y1: number
|
||||
x2: number
|
||||
y2: number
|
||||
color: string
|
||||
dash?: number[]
|
||||
}>
|
||||
axisLines: Array<{
|
||||
x1: number
|
||||
y1: number
|
||||
x2: number
|
||||
y2: number
|
||||
color: string
|
||||
widthPx: number
|
||||
}>
|
||||
/** Tick / category / legend / axis-title text */
|
||||
labels: ChartLabel[]
|
||||
/** Bars */
|
||||
bars: Array<{ x: number; y: number; w: number; h: number; color: string }>
|
||||
/** Polylines (points is flat [x0,y0,x1,y1,...]); closed+fill for filled radar charts etc. */
|
||||
polylines: Array<{
|
||||
points: number[]
|
||||
color: string
|
||||
widthPx: number
|
||||
smooth?: boolean
|
||||
closed?: boolean
|
||||
fill?: string
|
||||
}>
|
||||
/** Data-point markers (circles) */
|
||||
markers: Array<{ x: number; y: number; r: number; color: string }>
|
||||
/** Legend swatches */
|
||||
swatches: Array<{ x: number; y: number; w: number; h: number; color: string }>
|
||||
/** Pie/doughnut wedges (angles: 12 o'clock = -90°, clockwise, Konva Arc semantics) */
|
||||
wedges?: Array<{
|
||||
cx: number
|
||||
cy: number
|
||||
outerR: number
|
||||
innerR: number
|
||||
startDeg: number
|
||||
sweepDeg: number
|
||||
color: string
|
||||
}>
|
||||
}
|
||||
|
||||
export type RenderNode =
|
||||
| ShapeRenderNode
|
||||
| PictureRenderNode
|
||||
| GroupRenderNode
|
||||
| TableRenderNode
|
||||
| ChartRenderNode
|
||||
| ChipRenderNode
|
||||
|
||||
export interface RenderSlide {
|
||||
widthPx: number
|
||||
heightPx: number
|
||||
/** Viewport scale (fitWidthPx / slide baseline px width) — geometry coordinates already include it */
|
||||
scale: number
|
||||
background: RenderFill
|
||||
nodes: RenderNode[]
|
||||
/** Hidden slide (<p:sld show="0">): thumbnails get a badge, skipped during presentation */
|
||||
hidden?: boolean
|
||||
}
|
||||
|
||||
// Convenience type re-exports (for internal render logic)
|
||||
export type { Fill, Stroke }
|
||||
@@ -0,0 +1,896 @@
|
||||
/**
|
||||
* 2.3 Text layout — replicates PPT text-box layout: wrapping / line spacing /
|
||||
* paragraph spacing / vertical alignment / autofit.
|
||||
*
|
||||
* Input: TextBody (pptx-engine parse result) + text box pixel size + font metrics.
|
||||
* Output: RenderTextLayout (glyph runs per line with exact px coordinates).
|
||||
*
|
||||
* Wrapping rules:
|
||||
* - wrap=true: wrap to the available width; prefer breaking at whitespace, CJK may
|
||||
* break per character, over-long words without whitespace hard-break.
|
||||
* - wrap=false: no wrapping (overflow handled by clipping/autofit).
|
||||
* - autofit=shrink: when content is too tall, shrink font sizes proportionally
|
||||
* (bisection) until it fits or hits the floor.
|
||||
*
|
||||
* Alignment (baked into glyph coordinates; the renderer computes nothing):
|
||||
* - Paragraph align (l/ctr/r/just) → each line offsets horizontally within the
|
||||
* available width; negative offsets allowed on overflow (wrap=none centered
|
||||
* content overflows equally to both sides).
|
||||
* - bodyPr anchor (t/ctr/b) → the overall vertical offset is added to each line's
|
||||
* top/baselineY.
|
||||
*/
|
||||
import type { TextBody, Paragraph, TextRun } from '@genoffice/pptx-engine'
|
||||
import type { RenderTextLayout, TextLine, GlyphRun } from './render-tree'
|
||||
import bidiFactory from 'bidi-js'
|
||||
import { graphemes, isWideChar, type FontMetricsProvider, type RunStyle } from './metrics'
|
||||
import { emuToPx, ptToPx, type Viewport } from './coords'
|
||||
|
||||
const DEFAULT_FONT = 'Arial'
|
||||
const DEFAULT_SIZE_PT = 18
|
||||
|
||||
interface Token {
|
||||
text: string
|
||||
style: RunStyle
|
||||
color: string
|
||||
underline: boolean
|
||||
strike?: boolean
|
||||
/** 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) */
|
||||
ls: number
|
||||
/** Whether a line break is allowed after this token */
|
||||
breakable: boolean
|
||||
/** Whether it is whitespace (trailing whitespace may be swallowed when wrapping) */
|
||||
isSpace: boolean
|
||||
/** Forced line break (<a:br/> soft-break sentinel "\n") */
|
||||
isBreak?: boolean
|
||||
/** Source model run index (index into Paragraph.runs) */
|
||||
srcRun: number
|
||||
/** The model run's raw font name (absent = no explicit font; style.fontFamily is a fallback) */
|
||||
srcFont?: string
|
||||
/** Logical token order before bidi visual reordering (used by editable DOM to restore source order). */
|
||||
logicalOrder?: number
|
||||
/** UAX#9 direction level (odd = RTL); unset for paragraphs without RTL text */
|
||||
level?: number
|
||||
/** Super/subscript baseline shift (px, positive = up; <a:rPr baseline> percentage × font size) */
|
||||
blShift?: number
|
||||
/** Text outline (<a:rPr><a:ln>, commonly used by WordArt) */
|
||||
outline?: { color: string; widthPx: number }
|
||||
/** Run hyperlink (TextRun.hyperlink encoding) */
|
||||
link?: string
|
||||
}
|
||||
|
||||
function runStyle(run: TextRun, scale: number, fontScale: number): RunStyle {
|
||||
const sizePt = run.fontSize ?? DEFAULT_SIZE_PT
|
||||
return {
|
||||
fontFamily: run.fontFamily || DEFAULT_FONT,
|
||||
fontSizePx: ptToPx(sizePt, scale) * fontScale,
|
||||
bold: !!run.bold,
|
||||
italic: !!run.italic,
|
||||
}
|
||||
}
|
||||
|
||||
/** Token width = font advance width + letter spacing × char count (matches canvas letterSpacing: appended after each char) */
|
||||
function tokenWidth(tok: Token, metrics: FontMetricsProvider): number {
|
||||
const w = metrics.measure(tok.text, tok.style)
|
||||
return tok.ls ? w + tok.ls * [...tok.text].length : w
|
||||
}
|
||||
|
||||
/** 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[] = []
|
||||
p.runs.forEach((run, srcRun) => {
|
||||
const style = runStyle(run, scale, fontScale)
|
||||
const color = run.color ?? '#000000'
|
||||
const underline = !!run.underline
|
||||
const ls = run.letterSpacing ? ptToPx(run.letterSpacing, scale) * fontScale : 0
|
||||
// Super/subscript: baseline% (30 = superscript raised 30% of font size, negative = subscript lowered)
|
||||
const blShift = run.baseline ? style.fontSizePx * (run.baseline / 100) : 0
|
||||
const base = {
|
||||
style,
|
||||
color,
|
||||
underline,
|
||||
ls,
|
||||
srcRun,
|
||||
...(run.fontFamily ? { srcFont: run.fontFamily } : {}),
|
||||
...(run.hyperlink ? { link: run.hyperlink } : {}),
|
||||
...(run.strike ? { strike: true } : {}),
|
||||
...(run.baseline ? { blPct: run.baseline } : {}),
|
||||
...(blShift ? { blShift } : {}),
|
||||
...(run.outline
|
||||
? {
|
||||
outline: {
|
||||
color: run.outline.color,
|
||||
widthPx: emuToPx(run.outline.widthEmu, scale) * fontScale,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
}
|
||||
let buf = ''
|
||||
const flushWord = () => {
|
||||
if (!buf) return
|
||||
if (WORD_SEG && SEA_RE.test(buf)) {
|
||||
// Southeast Asian scripts without spaces: ICU dictionary segmentation; word gaps are break opportunities
|
||||
for (const s of WORD_SEG.segment(buf)) {
|
||||
tokens.push({ ...base, text: s.segment, breakable: true, isSpace: false })
|
||||
}
|
||||
} else {
|
||||
tokens.push({ ...base, text: buf, breakable: false, isSpace: false })
|
||||
}
|
||||
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)) {
|
||||
const cp = ch.codePointAt(0) ?? 0
|
||||
if (ch === '\n' || ch === '\v') {
|
||||
flushWord()
|
||||
tokens.push({ ...base, text: '\n', breakable: true, isSpace: false, isBreak: true })
|
||||
} else if (ch === ' ' || ch === '\t') {
|
||||
flushWord()
|
||||
tokens.push({ ...base, text: ch, breakable: true, isSpace: true })
|
||||
} else if (isWideChar(cp)) {
|
||||
flushWord()
|
||||
tokens.push({ ...base, text: ch, breakable: true, isSpace: false })
|
||||
} else {
|
||||
buf += ch
|
||||
}
|
||||
}
|
||||
flushWord()
|
||||
})
|
||||
return tokens
|
||||
}
|
||||
|
||||
/** Southeast Asian scripts without spaces (Thai/Burmese/Khmer/Lao); word boundaries need ICU dictionary segmentation. */
|
||||
const SEA_RE = /[-က-႟ក-]/
|
||||
const WORD_SEG: Intl.Segmenter | null =
|
||||
typeof Intl !== 'undefined' && 'Segmenter' in Intl
|
||||
? new Intl.Segmenter(undefined, { granularity: 'word' })
|
||||
: null
|
||||
|
||||
// ── Bidi (UAX#9) ────────────────────────────────────────────────────
|
||||
|
||||
/** Strong RTL characters (Hebrew/Arabic + presentation forms) — bidi analysis runs only on a match. */
|
||||
const RTL_RE = /[\u0590-\u08ff\ufb1d-\ufdff\ufe70-\ufeff]/
|
||||
let bidiApi: ReturnType<typeof bidiFactory> | null = null
|
||||
|
||||
/**
|
||||
* Runs UAX#9 over the paragraph token stream: tokens crossing direction levels are
|
||||
* split at level boundaries and tagged with their level. Line breaking stays in
|
||||
* logical order (UAX#9 requires wrap first, reorder after); visualOrder reorders
|
||||
* each line once formed.
|
||||
*/
|
||||
function applyBidi(tokens: Token[]): Token[] {
|
||||
const text = tokens.map((t) => t.text).join('')
|
||||
if (!RTL_RE.test(text)) return tokens
|
||||
bidiApi ??= bidiFactory()
|
||||
const { levels } = bidiApi.getEmbeddingLevels(text)
|
||||
const out: Token[] = []
|
||||
let off = 0
|
||||
for (const tok of tokens) {
|
||||
const end = off + tok.text.length
|
||||
let segStart = off
|
||||
for (let i = off + 1; i <= end; i++) {
|
||||
if (i === end || levels[i] !== levels[segStart]) {
|
||||
out.push({ ...tok, text: text.slice(segStart, i), level: levels[segStart] ?? 0 })
|
||||
segStart = i
|
||||
}
|
||||
}
|
||||
off = end
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** UAX#9 L2: reorder line tokens into visual order (from the highest level down to the lowest odd level, reversing contiguous runs per level). */
|
||||
function visualOrder(toks: Token[]): Token[] {
|
||||
let max = 0
|
||||
let minOdd = Infinity
|
||||
for (const t of toks) {
|
||||
const lv = t.level ?? 0
|
||||
if (lv > max) max = lv
|
||||
if (lv % 2 === 1 && lv < minOdd) minOdd = lv
|
||||
}
|
||||
if (minOdd === Infinity) return toks
|
||||
const arr = [...toks]
|
||||
for (let l = max; l >= minOdd; l--) {
|
||||
for (let i = 0; i < arr.length;) {
|
||||
if ((arr[i]!.level ?? 0) >= l) {
|
||||
let j = i
|
||||
while (j < arr.length && (arr[j]!.level ?? 0) >= l) j++
|
||||
for (let a = i, b = j - 1; a < b; a++, b--) {
|
||||
const t = arr[a]!
|
||||
arr[a] = arr[b]!
|
||||
arr[b] = t
|
||||
}
|
||||
i = j
|
||||
} else {
|
||||
i++
|
||||
}
|
||||
}
|
||||
}
|
||||
return arr
|
||||
}
|
||||
|
||||
/** Paragraph base direction: decided by the first strong-direction character (used for the default alignment; RTL paragraphs without explicit alignment align right). */
|
||||
function paraBaseRtl(p: Paragraph): boolean {
|
||||
for (const r of p.runs) {
|
||||
for (const ch of r.text) {
|
||||
if (RTL_RE.test(ch)) return true
|
||||
// eslint-disable-next-line no-misleading-character-class -- broad strong-LTR ranges; combining marks inside are irrelevant for a per-char strong-direction probe
|
||||
if (/[A-Za-z\u00c0-\u058f\u0900-\ud7ff\uf900-\ufdcf]/.test(ch)) return false
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
interface LaidLine {
|
||||
runs: GlyphRun[]
|
||||
height: number
|
||||
ascent: number
|
||||
descent: number
|
||||
/** Single line height (without lnSpc multiplier/reduction; the basis for spcPct paragraph spacing) */
|
||||
singleH: number
|
||||
/** Trailing whitespace was swallowed when wrapping (tells the editor to re-add a space when joining lines) */
|
||||
trailingSpace?: boolean
|
||||
/** The line ends at a soft-break sentinel; value = the sentinel run's model index */
|
||||
softBreakAfter?: number
|
||||
}
|
||||
|
||||
/** Wraps a single paragraph → array of lines (coordinates relative to the x origin; y added uniformly later). */
|
||||
function layoutParagraph(
|
||||
p: Paragraph,
|
||||
availWidth: number,
|
||||
wrap: boolean,
|
||||
metrics: FontMetricsProvider,
|
||||
scale: number,
|
||||
fontScale: number,
|
||||
lnSpcRed = 0,
|
||||
): LaidLine[] {
|
||||
const tokens = applyBidi(tokenizeParagraph(p, scale, fontScale)).map((tok, logicalOrder) => ({
|
||||
...tok,
|
||||
logicalOrder,
|
||||
}))
|
||||
const lines: LaidLine[] = []
|
||||
let cur: Token[] = []
|
||||
let curW = 0
|
||||
|
||||
const pushLine = (toks: Token[]) => {
|
||||
// Strip trailing whitespace (recorded: the editor re-adds a space when joining wrapped lines back into a paragraph)
|
||||
let trailingSpace = false
|
||||
while (toks.length && toks[toks.length - 1]!.isSpace) {
|
||||
toks.pop()
|
||||
trailingSpace = true
|
||||
}
|
||||
if (!toks.length) {
|
||||
// An empty line still occupies one line height. A textless run (the marker
|
||||
// element-level font ops leave on blank cells/paragraphs) styles the line and is
|
||||
// kept as a zero-width glyph run so the editor and ribbon readback see the format.
|
||||
const src = p.runs[0]
|
||||
const st: RunStyle = src
|
||||
? runStyle(src, scale, fontScale)
|
||||
: {
|
||||
fontFamily: DEFAULT_FONT,
|
||||
fontSizePx: ptToPx(DEFAULT_SIZE_PT, scale) * fontScale,
|
||||
bold: false,
|
||||
italic: false,
|
||||
}
|
||||
const m = metrics.metrics(st)
|
||||
lines.push({
|
||||
runs: src
|
||||
? [
|
||||
{
|
||||
text: '',
|
||||
x: 0,
|
||||
baselineY: 0,
|
||||
fontFamily: st.fontFamily,
|
||||
...(src.fontFamily ? { srcFontFamily: src.fontFamily } : {}),
|
||||
fontSizePx: st.fontSizePx,
|
||||
color: src.color ?? '#000000',
|
||||
bold: st.bold,
|
||||
italic: st.italic,
|
||||
underline: !!src.underline,
|
||||
widthPx: 0,
|
||||
srcRunIdx: 0,
|
||||
ascentPx: m.ascent,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
height: lineH(p, m, scale, lnSpcRed),
|
||||
ascent: m.ascent,
|
||||
descent: m.descent,
|
||||
singleH: Math.max(m.lineHeight, m.ascent + m.descent),
|
||||
...(trailingSpace ? { trailingSpace } : {}),
|
||||
})
|
||||
return
|
||||
}
|
||||
const line = buildLine(toks, metrics, p, scale, lnSpcRed)
|
||||
if (trailingSpace) line.trailingSpace = true
|
||||
lines.push(line)
|
||||
}
|
||||
|
||||
for (const tok of tokens) {
|
||||
// <a:br/> forced break: breaks regardless of wrap; record the sentinel run index for editor round-trips
|
||||
if (tok.isBreak) {
|
||||
pushLine(cur)
|
||||
lines[lines.length - 1]!.softBreakAfter = tok.srcRun
|
||||
cur = []
|
||||
curW = 0
|
||||
continue
|
||||
}
|
||||
const w = tokenWidth(tok, metrics)
|
||||
if (wrap && cur.length && curW + w > availWidth && !tok.isSpace) {
|
||||
pushLine(cur)
|
||||
cur = []
|
||||
curW = 0
|
||||
}
|
||||
// Hard-break over-long words (a single token wider than the line)
|
||||
if (wrap && !cur.length && w > availWidth && tok.text.length > 1 && !tok.isSpace) {
|
||||
for (const seg of hardBreak(tok, availWidth, metrics)) {
|
||||
pushLine([seg])
|
||||
}
|
||||
continue
|
||||
}
|
||||
cur.push(tok)
|
||||
curW += w
|
||||
}
|
||||
if (cur.length) pushLine(cur)
|
||||
if (!lines.length) pushLine([])
|
||||
return lines
|
||||
}
|
||||
|
||||
function hardBreak(tok: Token, availWidth: number, metrics: FontMetricsProvider): Token[] {
|
||||
const out: Token[] = []
|
||||
let buf = ''
|
||||
// Hard-cut per grapheme cluster: cut points never land inside combining-mark/ZWJ sequences
|
||||
for (const ch of graphemes(tok.text)) {
|
||||
const test = buf + ch
|
||||
if (buf && tokenWidth({ ...tok, text: test }, metrics) > availWidth) {
|
||||
out.push({ ...tok, text: buf })
|
||||
buf = ch
|
||||
} else {
|
||||
buf = test
|
||||
}
|
||||
}
|
||||
if (buf) out.push({ ...tok, text: buf })
|
||||
return out
|
||||
}
|
||||
|
||||
function buildLine(
|
||||
toks: Token[],
|
||||
metrics: FontMetricsProvider,
|
||||
p: Paragraph,
|
||||
scale: number,
|
||||
lnSpcRed = 0,
|
||||
): LaidLine {
|
||||
let x = 0
|
||||
let ascent = 0
|
||||
let descent = 0
|
||||
let lineHM = 0
|
||||
const runs: GlyphRun[] = []
|
||||
// Lines with RTL levels are reordered into visual order before laying out x (break in logical order → draw in visual order)
|
||||
for (const tok of visualOrder(toks)) {
|
||||
const m = metrics.metrics(tok.style)
|
||||
ascent = Math.max(ascent, m.ascent)
|
||||
descent = Math.max(descent, m.descent)
|
||||
lineHM = Math.max(lineHM, m.lineHeight)
|
||||
const w = tokenWidth(tok, metrics)
|
||||
runs.push({
|
||||
text: tok.text,
|
||||
x,
|
||||
baselineY: 0, // filled in later from the line's ascent
|
||||
// When a missing font is substituted, draw with the substitute name so drawing and measuring use the same font file
|
||||
fontFamily: metrics.displayFamily?.(tok.style, tok.text) ?? tok.style.fontFamily,
|
||||
...(tok.srcFont ? { srcFontFamily: tok.srcFont } : {}),
|
||||
fontSizePx: tok.style.fontSizePx,
|
||||
color: tok.color,
|
||||
bold: tok.style.bold,
|
||||
italic: tok.style.italic,
|
||||
underline: tok.underline,
|
||||
...(tok.strike ? { strike: true } : {}),
|
||||
widthPx: w,
|
||||
...(tok.ls ? { letterSpacingPx: tok.ls } : {}),
|
||||
...(tok.outline ? { outline: tok.outline } : {}),
|
||||
...(tok.blShift ? { baselineShiftPx: tok.blShift } : {}),
|
||||
...(tok.blPct ? { baselinePct: tok.blPct } : {}),
|
||||
...(tok.level != null && tok.level % 2 === 1 ? { rtl: true } : {}),
|
||||
srcRunIdx: tok.srcRun,
|
||||
...(tok.link ? { link: tok.link } : {}),
|
||||
...(tok.logicalOrder != null ? { logicalOrder: tok.logicalOrder } : {}),
|
||||
ascentPx: m.ascent,
|
||||
})
|
||||
x += w
|
||||
}
|
||||
const height = lineH(
|
||||
p,
|
||||
{ ascent, descent, lineHeight: lineHM || ascent + descent },
|
||||
scale,
|
||||
lnSpcRed,
|
||||
)
|
||||
return {
|
||||
runs,
|
||||
height,
|
||||
ascent,
|
||||
descent,
|
||||
singleH: Math.max(lineHM || ascent + descent, ascent + descent),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes line height with the paragraph's line-spacing settings. Single spacing =
|
||||
* the font's suggested line height (opentype: hhea ascent+descent; heuristic: 1.2em)
|
||||
* — with no extra ×1.2 on top (the earlier double scaling made large-size
|
||||
* title spacing ~20% too tall).
|
||||
*/
|
||||
function lineH(
|
||||
p: Paragraph,
|
||||
m: { ascent: number; descent: number; lineHeight: number },
|
||||
scale: number,
|
||||
lnSpcRed = 0,
|
||||
): number {
|
||||
const single = Math.max(m.lineHeight, m.ascent + m.descent)
|
||||
if (p.lineExact != null) return ptToPx(p.lineExact, scale) // exact line spacing is unaffected by autofit spacing reduction
|
||||
const base = p.lineHeight != null ? single * (p.lineHeight / 100) : single
|
||||
return base * (1 - lnSpcRed)
|
||||
}
|
||||
|
||||
export interface TextLayoutInput {
|
||||
body: TextBody
|
||||
boxWidthPx: number
|
||||
boxHeightPx: number
|
||||
metrics: FontMetricsProvider
|
||||
vp: Viewport
|
||||
}
|
||||
|
||||
/** Main entry: TextBody → RenderTextLayout (including autofit shrink stepping). */
|
||||
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),
|
||||
}
|
||||
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,
|
||||
)
|
||||
|
||||
const build = (fontScale: number, lnSpcRed: number) =>
|
||||
layoutAll(body, availWidth, wrap, metrics, vp.scale, fontScale, lnSpcRed)
|
||||
|
||||
// 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
|
||||
// overflows (we edited text / metric differences) do we step further down the
|
||||
// discrete autofit ladder (see SHRINK_STEPS), capped at the stored value
|
||||
const storedScale = body.autofit === 'shrink' ? (body.fontScale ?? 1) : 1
|
||||
const storedRed = body.autofit === 'shrink' ? (body.lnSpcReduction ?? 0) : 0
|
||||
let fontScale = storedScale
|
||||
let lnSpcReduction = storedRed
|
||||
let result = build(fontScale, lnSpcReduction)
|
||||
if (body.autofit === 'shrink' && result.contentHeight > availHeight) {
|
||||
for (const [fs, red] of SHRINK_STEPS) {
|
||||
if (fs >= storedScale - 1e-6) continue
|
||||
const effRed = Math.max(red, storedRed)
|
||||
const r = build(fs, effRed)
|
||||
fontScale = fs
|
||||
lnSpcReduction = effRed
|
||||
result = r
|
||||
if (r.contentHeight <= availHeight) break
|
||||
// Still doesn't fit after all steps → stop at 25% (overflow allowed)
|
||||
}
|
||||
}
|
||||
|
||||
// Vertical anchor: middle/bottom shift everything down (negative offsets allowed
|
||||
// when content is too tall → overflow upward/on both sides),
|
||||
// baked straight into line coordinates so the renderer draws as-is.
|
||||
const anchor = body.anchor ?? 'top'
|
||||
const extraH = availHeight - result.contentHeight
|
||||
const dy = anchor === 'middle' ? extraH / 2 : anchor === 'bottom' ? extraH : 0
|
||||
const lines = dy
|
||||
? result.lines.map((ln) => ({
|
||||
...ln,
|
||||
top: ln.top + dy,
|
||||
runs: ln.runs.map((r) => ({ ...r, baselineY: r.baselineY + dy })),
|
||||
}))
|
||||
: result.lines
|
||||
|
||||
return {
|
||||
lines,
|
||||
insets,
|
||||
anchor,
|
||||
fontScale,
|
||||
...(lnSpcReduction ? { lnSpcReduction } : {}),
|
||||
contentHeight: result.contentHeight,
|
||||
wrap,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* PowerPoint autofit's discrete shrink steps (fontScale in 7.5% increments +
|
||||
* lnSpcReduction in 0/10/20% bands), observed from real files
|
||||
* (92500/0, 85000/10000, 62500/20000…).
|
||||
* Step down and take the first that fits; floor 25%.
|
||||
*/
|
||||
const SHRINK_STEPS: Array<[number, number]> = [
|
||||
[0.925, 0],
|
||||
[0.85, 0.1],
|
||||
[0.775, 0.1],
|
||||
[0.7, 0.2],
|
||||
[0.625, 0.2],
|
||||
[0.55, 0.2],
|
||||
[0.475, 0.2],
|
||||
[0.4, 0.2],
|
||||
[0.325, 0.2],
|
||||
[0.25, 0.2],
|
||||
]
|
||||
|
||||
// ── Vertical text (bodyPr vert) ─────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Vertical column layout: horizontal "lines" become "columns", columns run right
|
||||
* to left, and characters within a column stack top to bottom.
|
||||
* Approximations (v1):
|
||||
* - vert/vert270/wordArtVert should rotate the whole box 90°/270°, but that is too
|
||||
* invasive for rendering/hit-testing/editing overlays, so degrade to the same
|
||||
* column layout as eaVert;
|
||||
* - PowerPoint rotates Latin characters 90° under eaVert; here they stay upright
|
||||
* (one grapheme per cell);
|
||||
* - autofit doesn't self-iterate (only reuses the stored fontScale);
|
||||
* justify/bidi/marL/super-subscript shifts are skipped.
|
||||
* Coordinate conventions match horizontal layout: GlyphRun.x/baselineY are relative
|
||||
* to the content area's (inside insets) top-left, zero renderer changes.
|
||||
* TextLine = one column; paraStart/srcRunIdx semantics unchanged, editor round-trips work.
|
||||
*/
|
||||
function layoutTextVertical(
|
||||
body: TextBody,
|
||||
vert: NonNullable<TextBody['vert']>,
|
||||
availWidth: number,
|
||||
availHeight: number,
|
||||
insets: { l: number; t: number; r: number; b: number },
|
||||
wrap: boolean,
|
||||
metrics: FontMetricsProvider,
|
||||
scale: number,
|
||||
): RenderTextLayout {
|
||||
const fontScale = body.autofit === 'shrink' ? (body.fontScale ?? 1) : 1
|
||||
|
||||
interface Col {
|
||||
runs: GlyphRun[] // baselineY fixed relative to column top; x parked at 0, backfilled by column position in pass two
|
||||
usedH: number
|
||||
colW: number
|
||||
paraStart: boolean
|
||||
align?: Paragraph['align']
|
||||
alignExplicit?: boolean
|
||||
softBreakAfter?: number
|
||||
/** Space-before/after maps to horizontal gaps between columns (carried by a paragraph's first/last column) */
|
||||
gapBefore: number
|
||||
gapAfter: number
|
||||
}
|
||||
const cols: Col[] = []
|
||||
let autoNum = 0
|
||||
|
||||
for (const p of body.paragraphs) {
|
||||
const paraCols: Col[] = []
|
||||
let cur: GlyphRun[] = []
|
||||
let curH = 0
|
||||
let agg = { ascent: 0, descent: 0, lineHeight: 0 }
|
||||
|
||||
const finishCol = (soft?: number) => {
|
||||
let m = agg
|
||||
if (!cur.length) {
|
||||
const st: RunStyle = {
|
||||
fontFamily: DEFAULT_FONT,
|
||||
fontSizePx: ptToPx(DEFAULT_SIZE_PT, scale) * fontScale,
|
||||
bold: false,
|
||||
italic: false,
|
||||
}
|
||||
m = metrics.metrics(st)
|
||||
}
|
||||
paraCols.push({
|
||||
runs: cur,
|
||||
usedH: curH,
|
||||
// Line height maps to column width: the column's max metrics × the paragraph line-spacing setting
|
||||
colW: lineH(p, { ...m, lineHeight: m.lineHeight || m.ascent + m.descent }, scale, 0),
|
||||
paraStart: false,
|
||||
...(soft != null ? { softBreakAfter: soft } : {}),
|
||||
gapBefore: 0,
|
||||
gapAfter: 0,
|
||||
})
|
||||
cur = []
|
||||
curH = 0
|
||||
agg = { ascent: 0, descent: 0, lineHeight: 0 }
|
||||
}
|
||||
|
||||
const pushCell = (tok: Token, g: string, isBullet = false) => {
|
||||
const m = metrics.metrics(tok.style)
|
||||
// Vertical advance = the char style's line box height (CJK ≈ 1em; upright Latin also approximated by the line box)
|
||||
const adv = m.ascent + m.descent + tok.ls
|
||||
if (wrap && cur.length && curH + adv > availHeight) finishCol()
|
||||
agg = {
|
||||
ascent: Math.max(agg.ascent, m.ascent),
|
||||
descent: Math.max(agg.descent, m.descent),
|
||||
lineHeight: Math.max(agg.lineHeight, m.lineHeight),
|
||||
}
|
||||
cur.push({
|
||||
text: g,
|
||||
x: 0,
|
||||
baselineY: curH + m.ascent,
|
||||
fontFamily: metrics.displayFamily?.(tok.style, g) ?? tok.style.fontFamily,
|
||||
...(tok.srcFont ? { srcFontFamily: tok.srcFont } : {}),
|
||||
fontSizePx: tok.style.fontSizePx,
|
||||
color: tok.color,
|
||||
bold: tok.style.bold,
|
||||
italic: tok.style.italic,
|
||||
underline: tok.underline,
|
||||
...(tok.strike ? { strike: true } : {}),
|
||||
...(tok.outline ? { outline: tok.outline } : {}),
|
||||
widthPx: metrics.measure(g, tok.style),
|
||||
...(tok.blPct ? { baselinePct: tok.blPct } : {}),
|
||||
...(isBullet ? { isBullet: true } : { srcRunIdx: tok.srcRun }),
|
||||
...(!isBullet && tok.link ? { link: tok.link } : {}),
|
||||
ascentPx: m.ascent,
|
||||
})
|
||||
curH += adv
|
||||
}
|
||||
|
||||
// Latin words rotate 90° as whole words: vertical advance = word width (vertical length after rotation), column width contribution = line box height
|
||||
const pushRotated = (tok: Token) => {
|
||||
const m = metrics.metrics(tok.style)
|
||||
const adv = tokenWidth(tok, metrics)
|
||||
if (wrap && cur.length && curH + adv > availHeight) finishCol()
|
||||
agg = {
|
||||
ascent: Math.max(agg.ascent, m.ascent),
|
||||
descent: Math.max(agg.descent, m.descent),
|
||||
lineHeight: Math.max(agg.lineHeight, m.lineHeight),
|
||||
}
|
||||
cur.push({
|
||||
text: tok.text,
|
||||
x: 0,
|
||||
baselineY: curH + m.ascent,
|
||||
fontFamily: metrics.displayFamily?.(tok.style, tok.text) ?? tok.style.fontFamily,
|
||||
...(tok.srcFont ? { srcFontFamily: tok.srcFont } : {}),
|
||||
fontSizePx: tok.style.fontSizePx,
|
||||
color: tok.color,
|
||||
bold: tok.style.bold,
|
||||
italic: tok.style.italic,
|
||||
underline: tok.underline,
|
||||
...(tok.strike ? { strike: true } : {}),
|
||||
...(tok.outline ? { outline: tok.outline } : {}),
|
||||
widthPx: adv,
|
||||
rotate90: true,
|
||||
srcRunIdx: tok.srcRun,
|
||||
...(tok.link ? { link: tok.link } : {}),
|
||||
ascentPx: m.ascent,
|
||||
})
|
||||
curH += adv
|
||||
}
|
||||
|
||||
const hasText = p.runs.some((r) => r.text.trim())
|
||||
const bulletType = p.bullet?.type
|
||||
const hasBullet = hasText && (bulletType === 'char' || bulletType === 'number')
|
||||
if (bulletType === 'number' && hasText) autoNum += 1
|
||||
else if (bulletType !== 'number') autoNum = 0
|
||||
if (hasBullet && p.runs[0]) {
|
||||
const base = runStyle(p.runs[0], scale, fontScale)
|
||||
// <a:buSzPct>: bullet glyph size as a percentage of the first run's size
|
||||
const st =
|
||||
p.bullet?.sizePct != null
|
||||
? { ...base, fontSizePx: base.fontSizePx * (p.bullet.sizePct / 100) }
|
||||
: base
|
||||
pushCell(
|
||||
{
|
||||
text: '',
|
||||
style: st,
|
||||
color: p.bullet?.color ?? p.runs[0].color ?? '#000000',
|
||||
underline: false,
|
||||
ls: 0,
|
||||
breakable: false,
|
||||
isSpace: false,
|
||||
srcRun: 0,
|
||||
},
|
||||
bulletType === 'char' ? (p.bullet?.char ?? '•') : `${autoNum}.`,
|
||||
true,
|
||||
)
|
||||
}
|
||||
|
||||
for (const tok of tokenizeParagraph(p, scale, fontScale)) {
|
||||
if (tok.isBreak) {
|
||||
finishCol(tok.srcRun)
|
||||
continue
|
||||
}
|
||||
// Latin/digit words (no wide chars) rotate 90° whole per PowerPoint vertical-writing semantics; CJK stays upright per char
|
||||
const hasWide = [...tok.text].some((ch) => isWideChar(ch.codePointAt(0) ?? 0))
|
||||
if (!hasWide && tok.text.trim()) {
|
||||
pushRotated(tok)
|
||||
continue
|
||||
}
|
||||
for (const g of graphemes(tok.text)) pushCell(tok, g)
|
||||
}
|
||||
if (cur.length || !paraCols.length) finishCol()
|
||||
|
||||
paraCols[0]!.paraStart = true
|
||||
const singleW = paraCols[0]!.colW
|
||||
paraCols[0]!.gapBefore =
|
||||
ptToPx(p.spaceBefore ?? 0, scale) +
|
||||
(p.spaceBeforePct ? singleW * (p.spaceBeforePct / 100) : 0)
|
||||
paraCols[paraCols.length - 1]!.gapAfter =
|
||||
ptToPx(p.spaceAfter ?? 0, scale) + (p.spaceAfterPct ? singleW * (p.spaceAfterPct / 100) : 0)
|
||||
if (p.align) {
|
||||
for (const c of paraCols) {
|
||||
c.align = p.align
|
||||
c.alignExplicit = true
|
||||
}
|
||||
}
|
||||
cols.push(...paraCols)
|
||||
}
|
||||
|
||||
// anchor acts along the text flow (right→left): top starts at the right, middle centers, bottom hugs the left
|
||||
const contentW = cols.reduce((a, c) => a + c.gapBefore + c.colW + c.gapAfter, 0)
|
||||
const anchor = body.anchor ?? 'top'
|
||||
const extraW = availWidth - contentW
|
||||
let xRight = availWidth - (anchor === 'middle' ? extraW / 2 : anchor === 'bottom' ? extraW : 0)
|
||||
let contentHeight = 0
|
||||
const lines: TextLine[] = cols.map((c) => {
|
||||
xRight -= c.gapBefore
|
||||
const colX = xRight - c.colW
|
||||
xRight = colX - c.gapAfter
|
||||
// Paragraph alignment acts vertically within a column: ctr centers, r hugs the bottom (justify treated as left)
|
||||
const dy =
|
||||
c.align === 'center'
|
||||
? (availHeight - c.usedH) / 2
|
||||
: c.align === 'right'
|
||||
? availHeight - c.usedH
|
||||
: 0
|
||||
contentHeight = Math.max(contentHeight, dy + c.usedH)
|
||||
return {
|
||||
runs: c.runs.map((r) => ({
|
||||
...r,
|
||||
// Rotated word anchor = column center shifted right by half the font size (after 90° clockwise the text box lands back on the column center)
|
||||
x: r.rotate90 ? colX + (c.colW + r.fontSizePx) / 2 : colX + (c.colW - r.widthPx) / 2,
|
||||
baselineY: r.baselineY + dy,
|
||||
})),
|
||||
top: dy,
|
||||
height: c.usedH,
|
||||
paraStart: c.paraStart,
|
||||
...(c.softBreakAfter != null ? { softBreakAfter: c.softBreakAfter } : {}),
|
||||
...(c.alignExplicit && c.align ? { align: c.align } : {}),
|
||||
}
|
||||
})
|
||||
|
||||
return { lines, insets, anchor, fontScale, contentHeight, wrap, vert }
|
||||
}
|
||||
|
||||
/** Paragraph horizontal alignment → line x offset (center/right; justify treated as left for now). */
|
||||
function alignOffset(align: Paragraph['align'], availWidth: number, lineWidth: number): number {
|
||||
if (align === 'center') return (availWidth - lineWidth) / 2
|
||||
if (align === 'right') return availWidth - lineWidth
|
||||
return 0
|
||||
}
|
||||
|
||||
function layoutAll(
|
||||
body: TextBody,
|
||||
availWidth: number,
|
||||
wrap: boolean,
|
||||
metrics: FontMetricsProvider,
|
||||
scale: number,
|
||||
fontScale: number,
|
||||
lnSpcRed: number,
|
||||
): { 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) {
|
||||
// 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)
|
||||
const marLPx = emuToPx(p.marL ?? 0, scale)
|
||||
const indentPx = emuToPx(p.indent ?? 0, scale)
|
||||
const hasText = p.runs.some((r) => r.text.trim())
|
||||
const bulletType = p.bullet?.type
|
||||
const hasBullet = hasText && (bulletType === 'char' || bulletType === 'number')
|
||||
if (bulletType === 'number' && hasText) autoNum += 1
|
||||
else if (bulletType !== 'number') autoNum = 0
|
||||
const bulletText = bulletType === 'char' ? (p.bullet?.char ?? '•') : `${autoNum}.`
|
||||
|
||||
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)
|
||||
const laid = layoutParagraph(p, avail, wrap, metrics, scale, fontScale, lnSpcRed)
|
||||
// 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)
|
||||
laid.forEach((ln, li) => {
|
||||
const baseline = y + ln.ascent
|
||||
const lineWidth = ln.runs.reduce((acc, r) => acc + r.widthPx, 0)
|
||||
// Without a bullet the first line adds indent (positive or negative); with a bullet the body always starts at marL
|
||||
const firstShift = !hasBullet && li === 0 ? indentPx : 0
|
||||
// justify: lines filled by wrapping (not paragraph-final, not hard breaks) spread
|
||||
// the remaining width into character spacing; the spread goes through
|
||||
// justifyExtraPx (a draw-only field) so letterSpacing round-trips stay clean
|
||||
let lineRuns = ln.runs
|
||||
if (
|
||||
align === 'justify' &&
|
||||
wrap &&
|
||||
li < laid.length - 1 &&
|
||||
ln.softBreakAfter == null &&
|
||||
ln.runs.length
|
||||
) {
|
||||
const totalChars = ln.runs.reduce((acc, r) => acc + [...r.text].length, 0)
|
||||
const extra = avail - firstShift - lineWidth
|
||||
if (totalChars > 1 && extra > 0) {
|
||||
const per = extra / (totalChars - 1)
|
||||
let consumed = 0
|
||||
lineRuns = ln.runs.map((r) => {
|
||||
const chars = [...r.text].length
|
||||
const jr = {
|
||||
...r,
|
||||
x: r.x + consumed * per,
|
||||
widthPx: r.widthPx + chars * per,
|
||||
justifyExtraPx: per,
|
||||
}
|
||||
consumed += chars
|
||||
return jr
|
||||
})
|
||||
}
|
||||
}
|
||||
const dx = textX + firstShift + alignOffset(align, avail, lineWidth)
|
||||
const runs = lineRuns.map((r) => ({
|
||||
...r,
|
||||
x: r.x + dx,
|
||||
baselineY: baseline - (r.baselineShiftPx ?? 0),
|
||||
}))
|
||||
if (hasBullet && li === 0) {
|
||||
const base = runStyle(p.runs[0]!, scale, fontScale)
|
||||
// <a:buSzPct>: bullet glyph size as a percentage of the first run's size
|
||||
const st =
|
||||
p.bullet?.sizePct != null
|
||||
? { ...base, fontSizePx: base.fontSizePx * (p.bullet.sizePct / 100) }
|
||||
: base
|
||||
const bw = metrics.measure(bulletText, st)
|
||||
const bx = Math.max(marLPx + indentPx, 0) + alignOffset(align, avail, lineWidth)
|
||||
runs.unshift({
|
||||
text: bulletText,
|
||||
x: bx,
|
||||
baselineY: baseline,
|
||||
fontFamily: metrics.displayFamily?.(st, bulletText) ?? st.fontFamily,
|
||||
fontSizePx: st.fontSizePx,
|
||||
color: p.bullet?.color ?? p.runs[0]?.color ?? '#000000',
|
||||
bold: st.bold,
|
||||
italic: false,
|
||||
underline: false,
|
||||
widthPx: bw,
|
||||
isBullet: true,
|
||||
ascentPx: metrics.metrics(st).ascent,
|
||||
})
|
||||
}
|
||||
outLines.push({
|
||||
runs,
|
||||
top: y,
|
||||
height: ln.height,
|
||||
paraStart: li === 0,
|
||||
...(ln.trailingSpace ? { trailingSpace: true } : {}),
|
||||
...(ln.softBreakAfter != null ? { softBreakAfter: ln.softBreakAfter } : {}),
|
||||
...(p.align ? { align: p.align } : {}),
|
||||
...(p.level ? { level: p.level } : {}),
|
||||
})
|
||||
y += ln.height
|
||||
})
|
||||
y +=
|
||||
ptToPx(p.spaceAfter ?? 0, scale) + (p.spaceAfterPct ? singleH * (p.spaceAfterPct / 100) : 0)
|
||||
}
|
||||
return { lines: outLines, contentHeight: y }
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import type { ChartModel } from '@genoffice/pptx-engine'
|
||||
import { buildChartNode } from '../src/build-chart'
|
||||
import { HeuristicMetrics } from '../src/metrics'
|
||||
import { makeViewport } from '../src/coords'
|
||||
|
||||
const vp = makeViewport({ cx: 12192000, cy: 6858000 }, 1280)
|
||||
const metrics = new HeuristicMetrics()
|
||||
const box = {
|
||||
x: 100,
|
||||
y: 100,
|
||||
w: 600,
|
||||
h: 400,
|
||||
centerX: 400,
|
||||
centerY: 300,
|
||||
rotationDeg: 0,
|
||||
flipH: false,
|
||||
flipV: false,
|
||||
}
|
||||
|
||||
const lineModel: ChartModel = {
|
||||
kind: 'line',
|
||||
categories: ['2016', '2017', '2018', '2019'],
|
||||
series: [
|
||||
{ name: 'A', color: '#4CAF50', values: [100, 200, 300, 400], smooth: true, marker: true },
|
||||
{ name: 'B', color: '#2196F3', values: [50, 150, 250, 350], marker: true },
|
||||
],
|
||||
legendPos: 't',
|
||||
valAxis: { gridColor: '#E6E6E6', gridDash: true, labelColor: '#666666', labelSizePt: 10 },
|
||||
}
|
||||
|
||||
describe('buildChartNode', () => {
|
||||
it('builds line chart: polylines within plot, markers, gridlines, legend', () => {
|
||||
const node = buildChartNode('r_1', 'el1', lineModel, box, vp, metrics)!
|
||||
expect(node.type).toBe('chart')
|
||||
expect(node.polylines).toHaveLength(2)
|
||||
expect(node.markers.length).toBe(8)
|
||||
expect(node.gridLines.length).toBeGreaterThan(2)
|
||||
// Legend: 2 swatches + at least 2 texts (more with tick/category labels)
|
||||
expect(node.swatches).toHaveLength(2)
|
||||
// All polyline points are inside the chart box
|
||||
for (const p of node.polylines) {
|
||||
for (let i = 0; i < p.points.length; i += 2) {
|
||||
expect(p.points[i]).toBeGreaterThanOrEqual(0)
|
||||
expect(p.points[i]).toBeLessThanOrEqual(box.w)
|
||||
expect(p.points[i + 1]).toBeGreaterThanOrEqual(0)
|
||||
expect(p.points[i + 1]).toBeLessThanOrEqual(box.h)
|
||||
}
|
||||
}
|
||||
// Larger values have smaller y
|
||||
const a = node.polylines[0]!.points
|
||||
expect(a[1]!).toBeGreaterThan(a[a.length - 1]!)
|
||||
})
|
||||
|
||||
it('builds clustered bars with per-series colors and non-overlapping x', () => {
|
||||
const model: ChartModel = {
|
||||
kind: 'bar',
|
||||
barDir: 'col',
|
||||
grouping: 'clustered',
|
||||
gapWidthPct: 50,
|
||||
categories: ['a', 'b'],
|
||||
series: [
|
||||
{ name: 's1', color: '#111111', values: [10, 20] },
|
||||
{ name: 's2', color: '#222222', values: [15, 5] },
|
||||
],
|
||||
}
|
||||
const node = buildChartNode('r_2', 'el2', model, box, vp, metrics)!
|
||||
expect(node.bars).toHaveLength(4)
|
||||
// Bars of two series within a category don't overlap (bars order = series-major: s1[a,b] then s2[a,b])
|
||||
const s1 = node.bars.filter((b) => b.color === '#111111')
|
||||
const s2 = node.bars.filter((b) => b.color === '#222222')
|
||||
expect(s2[0]!.x).toBeGreaterThanOrEqual(s1[0]!.x + s1[0]!.w - 0.01)
|
||||
// Larger values give taller bars (smaller y)
|
||||
expect(s1[1]!.y).toBeLessThan(s1[0]!.y)
|
||||
})
|
||||
|
||||
it('builds bar+line combo: bar series as bars, line series as overlaid polyline', () => {
|
||||
const model: ChartModel = {
|
||||
kind: 'bar',
|
||||
barDir: 'col',
|
||||
grouping: 'clustered',
|
||||
gapWidthPct: 100,
|
||||
legendPos: 'b',
|
||||
categories: ['Q1', 'Q2', 'Q3'],
|
||||
series: [
|
||||
{ name: 'Sales', color: '#4472C4', values: [10, 20, 30], plotKind: 'bar' },
|
||||
{ name: 'Growth Rate', color: '#ED7D31', values: [5, 8, 12], plotKind: 'line' },
|
||||
],
|
||||
}
|
||||
const node = buildChartNode('r_c', 'elc', model, box, vp, metrics)!
|
||||
// The bar series yields only 3 bars (not 6), the line series yields 1 polyline
|
||||
expect(node.bars).toHaveLength(3)
|
||||
expect(node.bars.every((b) => b.color === '#4472C4')).toBe(true)
|
||||
expect(node.polylines).toHaveLength(1)
|
||||
expect(node.polylines[0]!.color).toBe('#ED7D31')
|
||||
expect(node.polylines[0]!.points).toHaveLength(6)
|
||||
// The legend includes both series
|
||||
expect(node.swatches).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('combo dual axis: line maps to the right secondary value-axis range, right axis line and tick labels drawn', () => {
|
||||
const model: ChartModel = {
|
||||
kind: 'bar',
|
||||
barDir: 'col',
|
||||
grouping: 'clustered',
|
||||
gapWidthPct: 100,
|
||||
categories: ['Q1', 'Q2', 'Q3'],
|
||||
series: [
|
||||
{ name: 'Revenue', color: '#4472C4', values: [120, 180, 240], plotKind: 'bar' },
|
||||
{
|
||||
name: 'Growth',
|
||||
color: '#ED7D31',
|
||||
values: [10, 20, 30],
|
||||
plotKind: 'line',
|
||||
secondaryAxis: true,
|
||||
},
|
||||
],
|
||||
valAxis: { min: 0, max: 250 },
|
||||
valAxis2: { min: 0, max: 30 },
|
||||
}
|
||||
const node = buildChartNode('r_c2', 'elc2', model, box, vp, metrics)!
|
||||
// Three axis lines: bottom x axis + left primary value axis + right secondary value axis (vertical, x = plot-area right edge)
|
||||
expect(node.axisLines).toHaveLength(3)
|
||||
const rightAxis = node.axisLines[2]!
|
||||
expect(rightAxis.x1).toBe(rightAxis.x2)
|
||||
expect(rightAxis.x1).toBeGreaterThan(node.axisLines[1]!.x1)
|
||||
// Secondary tick labels are drawn outside the right axis, including its top value 30 (range 0-30 independent of the left axis 0-250)
|
||||
const secLabels = node.labels.filter((l) => l.x > rightAxis.x1)
|
||||
expect(secLabels.length).toBeGreaterThanOrEqual(2)
|
||||
expect(secLabels.map((l) => l.text)).toContain('30')
|
||||
expect(secLabels.map((l) => l.text)).not.toContain('250')
|
||||
// The line's last value 30 = secondary full scale → y at the plot-area top (misusing the primary 0-250 would land ~88% down)
|
||||
const line = node.polylines[0]!
|
||||
const lastY = line.points[line.points.length - 1]!
|
||||
expect(lastY).toBeCloseTo(rightAxis.y1, 1)
|
||||
// Bars still use the primary range: the tallest bar 240/250 doesn't reach the top
|
||||
expect(Math.min(...node.bars.map((b) => b.y))).toBeGreaterThan(rightAxis.y1)
|
||||
})
|
||||
|
||||
it('returns null for unsupported kinds (falls back to chip upstream)', () => {
|
||||
const unknown: ChartModel = { kind: 'unknown', categories: ['x'], series: [{ values: [1] }] }
|
||||
expect(buildChartNode('r', 's', unknown, box, vp, metrics)).toBeNull()
|
||||
})
|
||||
|
||||
it('builds stacked columns: one bar per category per series, segments cumulative', () => {
|
||||
const model: ChartModel = {
|
||||
kind: 'bar',
|
||||
barDir: 'col',
|
||||
grouping: 'stacked',
|
||||
gapWidthPct: 100,
|
||||
categories: ['a', 'b'],
|
||||
series: [
|
||||
{ name: 's1', color: '#111111', values: [10, 20] },
|
||||
{ name: 's2', color: '#222222', values: [30, 40] },
|
||||
],
|
||||
}
|
||||
const node = buildChartNode('r_3', 'el3', model, box, vp, metrics)!
|
||||
expect(node.bars).toHaveLength(4)
|
||||
// Both segments of a category share the same x (same bar)
|
||||
const catA = node.bars.filter((_b, i) => i % 2 === 0) // the two segments of category a
|
||||
const xs = new Set(node.bars.map((b) => Math.round(b.x)))
|
||||
expect(xs.size).toBe(2) // two categories → two x values
|
||||
// The s2 segment stacks above s1 (smaller y), and s1 bottom = s2 top + s1 height
|
||||
const aSegs = node.bars.filter((b) => Math.round(b.x) === [...xs][0])
|
||||
expect(aSegs).toHaveLength(2)
|
||||
const [seg1, seg2] = aSegs.sort((p, q) => q.y - p.y) // bottom segment first
|
||||
expect(seg2!.y + seg2!.h).toBeCloseTo(seg1!.y, 1)
|
||||
void catA
|
||||
})
|
||||
|
||||
it('percentStacked normalizes each category to 100%', () => {
|
||||
const model: ChartModel = {
|
||||
kind: 'bar',
|
||||
barDir: 'col',
|
||||
grouping: 'percentStacked',
|
||||
categories: ['a'],
|
||||
series: [
|
||||
{ name: 's1', color: '#111111', values: [25] },
|
||||
{ name: 's2', color: '#222222', values: [75] },
|
||||
],
|
||||
}
|
||||
const node = buildChartNode('r_4', 'el4', model, box, vp, metrics)!
|
||||
expect(node.bars).toHaveLength(2)
|
||||
// The two segments' total height = the whole plot-area height (0..100%)
|
||||
const total = node.bars.reduce((a, b) => a + b.h, 0)
|
||||
const top = Math.min(...node.bars.map((b) => b.y))
|
||||
const bottom = Math.max(...node.bars.map((b) => b.y + b.h))
|
||||
expect(total).toBeCloseTo(bottom - top, 1)
|
||||
// 25/75 split
|
||||
const [h1, h2] = node.bars.map((b) => b.h).sort((a, b) => a - b)
|
||||
expect(h2! / h1!).toBeCloseTo(3, 1)
|
||||
})
|
||||
|
||||
it('builds pie wedges summing to 360° with per-point colors', () => {
|
||||
const pie: ChartModel = {
|
||||
kind: 'pie',
|
||||
categories: ['x', 'y', 'z'],
|
||||
series: [{ values: [1, 1, 2], pointColors: ['#AA0000', undefined, '#0000AA'] }],
|
||||
legendPos: 'r',
|
||||
}
|
||||
const node = buildChartNode('r_5', 'el5', pie, box, vp, metrics)!
|
||||
expect(node.wedges).toHaveLength(3)
|
||||
const sweep = node.wedges!.reduce((a, w) => a + w.sweepDeg, 0)
|
||||
expect(sweep).toBeCloseTo(360, 5)
|
||||
expect(node.wedges![2]!.sweepDeg).toBeCloseTo(180, 5)
|
||||
expect(node.wedges![0]!.color).toBe('#AA0000')
|
||||
expect(node.wedges![2]!.color).toBe('#0000AA')
|
||||
// Starts at 12 o'clock (-90°)
|
||||
expect(node.wedges![0]!.startDeg).toBeCloseTo(-90, 5)
|
||||
// Pie has no center hole
|
||||
expect(node.wedges![0]!.innerR).toBe(0)
|
||||
// Legend: 3 category swatches
|
||||
expect(node.swatches).toHaveLength(3)
|
||||
})
|
||||
|
||||
it('doughnut hole uses holePct of outer radius', () => {
|
||||
const dough: ChartModel = {
|
||||
kind: 'pie',
|
||||
holePct: 50,
|
||||
categories: ['x', 'y'],
|
||||
series: [{ values: [1, 1] }],
|
||||
}
|
||||
const node = buildChartNode('r_6', 'el6', dough, box, vp, metrics)!
|
||||
const w = node.wedges![0]!
|
||||
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', () => {
|
||||
const model: ChartModel = {
|
||||
kind: 'bar',
|
||||
barDir: 'bar',
|
||||
grouping: 'clustered',
|
||||
categories: ['Alpha', 'Beta'],
|
||||
series: [{ name: 's1', color: '#111111', values: [10, 30] }],
|
||||
legendPos: 'b',
|
||||
}
|
||||
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)
|
||||
// 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
|
||||
for (const b of node.bars) {
|
||||
expect(b.h).toBeGreaterThan(0)
|
||||
expect(b.x + b.w).toBeLessThanOrEqual(box.w)
|
||||
}
|
||||
})
|
||||
|
||||
it('horizontal bar reversed (orientation maxMin): first category at bottom', () => {
|
||||
const model: ChartModel = {
|
||||
kind: 'bar',
|
||||
barDir: 'bar',
|
||||
categories: ['Alpha', 'Beta'],
|
||||
series: [{ values: [10, 30] }],
|
||||
catAxis: { reversed: true },
|
||||
}
|
||||
const node = buildChartNode('r_h2', 'elh2', model, box, vp, metrics)!
|
||||
const [b1, b2] = node.bars
|
||||
expect(b1!.y).toBeGreaterThan(b2!.y)
|
||||
})
|
||||
|
||||
it('builds scatter: positioned by two value axes, lineMarker draws points and lines by default', () => {
|
||||
const model: ChartModel = {
|
||||
kind: 'scatter',
|
||||
scatterStyle: 'lineMarker',
|
||||
categories: [],
|
||||
series: [{ name: 's', color: '#333333', xValues: [1, 2, 4], values: [10, 20, 15] }],
|
||||
valAxis: { gridColor: '#E6E6E6' },
|
||||
catAxis: { min: 0, max: 5 },
|
||||
}
|
||||
const node = buildChartNode('r_s', 'els', model, box, vp, metrics)!
|
||||
expect(node.markers).toHaveLength(3)
|
||||
expect(node.polylines).toHaveLength(1)
|
||||
// x=1 < x=2 < x=4 map to monotonically increasing pixel x
|
||||
const [m1, m2, m3] = node.markers
|
||||
expect(m1!.x).toBeLessThan(m2!.x)
|
||||
expect(m2!.x).toBeLessThan(m3!.x)
|
||||
// The y=20 point sits above (smaller pixel y) the y=10 point
|
||||
expect(m2!.y).toBeLessThan(m1!.y)
|
||||
})
|
||||
|
||||
it('scatter marker-only style (marker) draws no connecting lines', () => {
|
||||
const model: ChartModel = {
|
||||
kind: 'scatter',
|
||||
scatterStyle: 'marker',
|
||||
categories: [],
|
||||
series: [{ xValues: [1, 2], values: [1, 2] }],
|
||||
}
|
||||
const node = buildChartNode('r_s2', 'els2', model, box, vp, metrics)!
|
||||
expect(node.markers).toHaveLength(2)
|
||||
expect(node.polylines).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('builds radar: one closed polygon per series, filled style has semi-transparent fill', () => {
|
||||
const model: ChartModel = {
|
||||
kind: 'radar',
|
||||
radarStyle: 'filled',
|
||||
categories: ['Listen', 'Speak', 'Read', 'Write'],
|
||||
series: [{ name: 'A', color: '#ED7D31', values: [3, 4, 5, 2] }],
|
||||
legendPos: 'b',
|
||||
}
|
||||
const node = buildChartNode('r_r', 'elr', model, box, vp, metrics)!
|
||||
// Grid rings + 1 series polygon (all closed polylines)
|
||||
const seriesPoly = node.polylines.filter((p) => p.fill)
|
||||
expect(seriesPoly).toHaveLength(1)
|
||||
expect(seriesPoly[0]!.closed).toBe(true)
|
||||
expect(seriesPoly[0]!.points).toHaveLength(8)
|
||||
expect(seriesPoly[0]!.fill).toMatch(/^rgba\(237, 125, 49/)
|
||||
// Spokes = 4 radial grid lines
|
||||
expect(node.gridLines).toHaveLength(4)
|
||||
// All category labels are drawn
|
||||
const catLabels = node.labels.filter((l) =>
|
||||
['Listen', 'Speak', 'Read', 'Write'].includes(l.text),
|
||||
)
|
||||
expect(catLabels).toHaveLength(4)
|
||||
})
|
||||
|
||||
it('radar with fewer than 3 vertices falls back to null (upstream shows a chip)', () => {
|
||||
const model: ChartModel = {
|
||||
kind: 'radar',
|
||||
categories: ['a', 'b'],
|
||||
series: [{ values: [1, 2] }],
|
||||
}
|
||||
expect(buildChartNode('r_r2', 'elr2', model, box, vp, metrics)).toBeNull()
|
||||
})
|
||||
|
||||
it('builds area: solid polygon closed to the baseline', () => {
|
||||
const model: ChartModel = {
|
||||
kind: 'area',
|
||||
categories: ['a', 'b', 'c'],
|
||||
series: [{ name: 's', color: '#70AD47', values: [10, 30, 20] }],
|
||||
}
|
||||
const node = buildChartNode('r_a', 'ela', model, box, vp, metrics)!
|
||||
expect(node.polylines).toHaveLength(1)
|
||||
const p = node.polylines[0]!
|
||||
expect(p.closed).toBe(true)
|
||||
expect(p.fill).toBe('#70AD47')
|
||||
// First and last points land on the same baseline y
|
||||
expect(p.points[1]).toBeCloseTo(p.points[p.points.length - 1]!, 5)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,619 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { openPptx } from '@genoffice/pptx-engine'
|
||||
import { buildRenderSlide } from '../src/index'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const enginePptx = (name: string) =>
|
||||
readFileSync(join(here, '..', '..', 'pptx-engine', 'tests', 'fixtures', name))
|
||||
|
||||
describe('buildRenderSlide (end-to-end on real fixture)', () => {
|
||||
it('builds a RenderSlide with correct viewport + positioned nodes', async () => {
|
||||
const { deck } = await openPptx(enginePptx('01_standard_business.pptx'))
|
||||
const slide = deck.slides[0]!
|
||||
const rs = buildRenderSlide(slide, deck.size, { fitWidthPx: 1280 })
|
||||
|
||||
// 16:9 viewport
|
||||
expect(rs.widthPx).toBe(1280)
|
||||
expect(rs.heightPx).toBeCloseTo(720, 0)
|
||||
expect(rs.nodes.length).toBeGreaterThan(0)
|
||||
|
||||
// Placeholder title/body geometry has been backfilled → render boxes are non-zero and inside the canvas
|
||||
const textNodes = rs.nodes.filter((n) => n.type === 'text' || n.type === 'shape')
|
||||
expect(textNodes.length).toBeGreaterThan(0)
|
||||
for (const n of textNodes) {
|
||||
expect(n.box.w).toBeGreaterThan(0)
|
||||
expect(n.box.h).toBeGreaterThan(0)
|
||||
expect(n.box.x).toBeGreaterThanOrEqual(0)
|
||||
expect(n.box.x).toBeLessThan(rs.widthPx)
|
||||
}
|
||||
})
|
||||
|
||||
it('lays out text for title placeholder into lines with glyph runs', async () => {
|
||||
const { deck } = await openPptx(enginePptx('01_standard_business.pptx'))
|
||||
const rs = buildRenderSlide(deck.slides[0]!, deck.size, { fitWidthPx: 1280 })
|
||||
const withText = rs.nodes.find(
|
||||
(n) => (n.type === 'text' || n.type === 'shape') && (n as any).text?.lines.length,
|
||||
) as any
|
||||
expect(withText).toBeTruthy()
|
||||
expect(withText.text.lines.length).toBeGreaterThan(0)
|
||||
const allRunText = withText.text.lines
|
||||
.flatMap((l: any) => l.runs)
|
||||
.map((r: any) => r.text)
|
||||
.join('')
|
||||
expect(allRunText.trim().length).toBeGreaterThan(0)
|
||||
// Every run has a positive font size and baseline
|
||||
for (const ln of withText.text.lines) {
|
||||
for (const r of ln.runs) {
|
||||
expect(r.fontSizePx).toBeGreaterThan(0)
|
||||
expect(r.baselineY).toBeGreaterThan(0)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('renders CJK/emoji deck without throwing and keeps text', async () => {
|
||||
const { deck } = await openPptx(enginePptx('05_unicode_cjk_emoji.pptx'))
|
||||
let sawText = false
|
||||
for (const slide of deck.slides) {
|
||||
const rs = buildRenderSlide(slide, deck.size, { fitWidthPx: 960 })
|
||||
for (const n of rs.nodes) {
|
||||
if ((n.type === 'text' || n.type === 'shape') && (n as any).text) {
|
||||
const t = (n as any).text.lines
|
||||
.flatMap((l: any) => l.runs)
|
||||
.map((r: any) => r.text)
|
||||
.join('')
|
||||
// eslint-disable-next-line no-control-regex -- ASCII range check is intentional
|
||||
if (/[^\x00-\x7F]/.test(t)) sawText = true
|
||||
}
|
||||
}
|
||||
}
|
||||
expect(sawText).toBe(true)
|
||||
})
|
||||
|
||||
it('roundRect cornerRadiusPx follows avLst adj (50000 → pill = half min edge)', async () => {
|
||||
const { deck } = await openPptx(enginePptx('01_standard_business.pptx'))
|
||||
const slide = deck.slides[0]!
|
||||
// Build a roundRect element (mutating the model directly to avoid depending on fixture content)
|
||||
const el: any = {
|
||||
id: 'sp_test',
|
||||
type: 'shape',
|
||||
anchor: { spIndex: -1, originalXml: '', range: [0, 0] },
|
||||
transform: {
|
||||
offset: { x: 0, y: 0, cx: 914400, cy: 457200 },
|
||||
rot: 0,
|
||||
flipH: false,
|
||||
flipV: false,
|
||||
},
|
||||
presetGeometry: 'roundRect',
|
||||
adjust: { adj: 50000 },
|
||||
fill: { type: 'solid', color: '#00FF00' },
|
||||
}
|
||||
const rs = buildRenderSlide({ ...slide, elements: [el], decorations: [] }, deck.size, {
|
||||
fitWidthPx: 1280,
|
||||
})
|
||||
const n = rs.nodes[0] as any
|
||||
expect(n.cornerRadiusPx).toBeCloseTo(n.box.h / 2, 1) // short side is the height → half height = pill
|
||||
// Without avLst, the default 16.667% applies
|
||||
const el2 = { ...el, adjust: undefined }
|
||||
const rs2 = buildRenderSlide({ ...slide, elements: [el2], decorations: [] }, deck.size, {
|
||||
fitWidthPx: 1280,
|
||||
})
|
||||
const n2 = rs2.nodes[0] as any
|
||||
expect(n2.cornerRadiusPx).toBeCloseTo(Math.min(n2.box.w, n2.box.h) * 0.16667, 1)
|
||||
})
|
||||
|
||||
it('resolves shadow to px offsets (dir 270° → straight up)', async () => {
|
||||
const { deck } = await openPptx(enginePptx('01_standard_business.pptx'))
|
||||
const slide = deck.slides[0]!
|
||||
const el: any = {
|
||||
id: 'sp_shdw',
|
||||
type: 'shape',
|
||||
anchor: { spIndex: -1, originalXml: '', range: [0, 0] },
|
||||
transform: {
|
||||
offset: { x: 0, y: 0, cx: 914400, cy: 914400 },
|
||||
rot: 0,
|
||||
flipH: false,
|
||||
flipV: false,
|
||||
},
|
||||
presetGeometry: 'rect',
|
||||
fill: { type: 'solid', color: '#FFFFFF' },
|
||||
shadow: { color: '#00000033', blurRad: 63500, dist: 25400, dirDeg: 270 },
|
||||
}
|
||||
const rs = buildRenderSlide({ ...slide, elements: [el], decorations: [] }, deck.size, {
|
||||
fitWidthPx: 1280,
|
||||
})
|
||||
const n = rs.nodes[0] as any
|
||||
expect(n.shadow.color).toBe('#00000033')
|
||||
expect(n.shadow.blurPx).toBeGreaterThan(0)
|
||||
expect(n.shadow.offsetX).toBeCloseTo(0, 5)
|
||||
expect(n.shadow.offsetY).toBeLessThan(0) // 270° = upward
|
||||
})
|
||||
|
||||
it('passes picture srcRect through to render node', async () => {
|
||||
const { deck } = await openPptx(enginePptx('01_standard_business.pptx'))
|
||||
const slide = deck.slides[0]!
|
||||
const el: any = {
|
||||
id: 'pic_crop',
|
||||
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: '',
|
||||
srcRect: { l: 0.1, t: 0.2, r: 0.3, b: 0 },
|
||||
}
|
||||
const rs = buildRenderSlide({ ...slide, elements: [el], decorations: [] }, deck.size, {
|
||||
fitWidthPx: 1280,
|
||||
})
|
||||
expect((rs.nodes[0] as any).srcRect).toEqual({ l: 0.1, t: 0.2, r: 0.3, b: 0 })
|
||||
})
|
||||
|
||||
it('picture presetGeometry -> clip three channels (ellipse/roundRect/polygon/unknown fallback)', async () => {
|
||||
const { deck } = await openPptx(enginePptx('01_standard_business.pptx'))
|
||||
const slide = deck.slides[0]!
|
||||
const mk = (presetGeometry?: string, adjust?: Record<string, number>): any => ({
|
||||
id: 'pic_geom',
|
||||
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: '',
|
||||
...(presetGeometry ? { presetGeometry } : {}),
|
||||
...(adjust ? { adjust } : {}),
|
||||
})
|
||||
const build = (el: any) =>
|
||||
buildRenderSlide({ ...slide, elements: [el], decorations: [] }, deck.size, {
|
||||
fitWidthPx: 1280,
|
||||
}).nodes[0] as any
|
||||
|
||||
const ellipse = build(mk('ellipse'))
|
||||
expect(ellipse.clip?.pathData).toMatch(/^M 0 .+ A .+ Z$/)
|
||||
|
||||
const round = build(mk('roundRect', { adj: 50000 }))
|
||||
expect(round.clip?.cornerRadiusPx).toBeCloseTo(build(mk('ellipse')).box.w / 2, 1)
|
||||
|
||||
const hex = build(mk('hexagon'))
|
||||
expect(hex.clip?.polygonPoints?.length).toBeGreaterThanOrEqual(12)
|
||||
|
||||
expect(build(mk()).clip).toBeUndefined()
|
||||
expect(build(mk('rect')).clip).toBeUndefined()
|
||||
expect(build(mk('unknownPreset9')).clip).toBeUndefined()
|
||||
})
|
||||
|
||||
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]!
|
||||
const el: any = {
|
||||
id: 'sp_fld',
|
||||
type: 'text',
|
||||
anchor: { spIndex: -1, originalXml: '', range: [0, 0] },
|
||||
transform: {
|
||||
offset: { x: 0, y: 0, cx: 914400, cy: 914400 },
|
||||
rot: 0,
|
||||
flipH: false,
|
||||
flipV: false,
|
||||
},
|
||||
text: {
|
||||
paragraphs: [
|
||||
{
|
||||
runs: [
|
||||
{ text: 'Pg', fontSize: 12 },
|
||||
{ text: '3', fontSize: 12, field: 'slidenum' },
|
||||
],
|
||||
},
|
||||
],
|
||||
insets: { l: 0, t: 0, r: 0, b: 0 },
|
||||
},
|
||||
}
|
||||
const custom = { ...slide, elements: [el], decorations: [] }
|
||||
const glyphText = (rs: any) =>
|
||||
rs.nodes[0].text.lines
|
||||
.flatMap((l: any) => l.runs)
|
||||
.map((r: any) => r.text)
|
||||
.join('')
|
||||
|
||||
const withNo = buildRenderSlide(custom, deck.size, { fitWidthPx: 1280, slideNo: 5 })
|
||||
expect(glyphText(withNo)).toBe('Pg5')
|
||||
// model run text was not touched
|
||||
expect(el.text.paragraphs[0].runs[1].text).toBe('3')
|
||||
|
||||
const withoutNo = buildRenderSlide(custom, deck.size, { fitWidthPx: 1280 })
|
||||
expect(glyphText(withoutNo)).toBe('Pg3')
|
||||
})
|
||||
|
||||
it('renders tables as table nodes with positioned cells (no more chip)', async () => {
|
||||
const { deck } = await openPptx(enginePptx('01_standard_business.pptx'))
|
||||
let sawTable = false
|
||||
for (const slide of deck.slides) {
|
||||
const rs = buildRenderSlide(slide, deck.size, { fitWidthPx: 960 })
|
||||
for (const n of rs.nodes) {
|
||||
if (n.type === 'table') {
|
||||
sawTable = true
|
||||
const cells = (n as any).cells
|
||||
expect(cells.length).toBeGreaterThan(0)
|
||||
// Cell geometry lies within the table box and cells align with each other
|
||||
for (const c of cells) {
|
||||
expect(c.w).toBeGreaterThan(0)
|
||||
expect(c.h).toBeGreaterThan(0)
|
||||
expect(c.x + c.w).toBeLessThanOrEqual(n.box.w + 0.01)
|
||||
expect(c.y + c.h).toBeLessThanOrEqual(n.box.h + 0.01)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// The fixture contains a table → at least one table node
|
||||
expect(sawTable).toBe(true)
|
||||
})
|
||||
|
||||
it('table cell spans expand across columns and merged cells are skipped', async () => {
|
||||
const { deck } = await openPptx(enginePptx('01_standard_business.pptx'))
|
||||
const slide = deck.slides[0]!
|
||||
const el: any = {
|
||||
id: 'tbl_1',
|
||||
type: 'table',
|
||||
anchor: { spIndex: -1, originalXml: '', range: [0, 0] },
|
||||
transform: {
|
||||
offset: { x: 0, y: 0, cx: 1905000, cy: 952500 },
|
||||
rot: 0,
|
||||
flipH: false,
|
||||
flipV: false,
|
||||
},
|
||||
colWidths: [952500, 952500],
|
||||
rowHeights: [476250, 476250],
|
||||
rows: [
|
||||
[{ gridSpan: 2, text: undefined }, { merged: true }],
|
||||
[{}, {}],
|
||||
],
|
||||
}
|
||||
const rs = buildRenderSlide({ ...slide, elements: [el], decorations: [] }, deck.size, {
|
||||
fitWidthPx: 1280,
|
||||
})
|
||||
const node = rs.nodes[0] as any
|
||||
expect(node.type).toBe('table')
|
||||
// Merged placeholder cells are not emitted: 2 rows × 2 cols - 1 merged = 3
|
||||
expect(node.cells.length).toBe(3)
|
||||
// A cell spanning two columns is as wide as the whole table
|
||||
expect(node.cells[0].w).toBeCloseTo(node.box.w, 1)
|
||||
// The two cells in row 2 each take half
|
||||
expect(node.cells[1].w).toBeCloseTo(node.box.w / 2, 1)
|
||||
})
|
||||
|
||||
it('cells after a mid-row merge keep their grid position (continuation tc is not double-counted)', async () => {
|
||||
const { deck } = await openPptx(enginePptx('01_standard_business.pptx'))
|
||||
const slide = deck.slides[0]!
|
||||
const el: any = {
|
||||
id: 'tbl_1',
|
||||
type: 'table',
|
||||
anchor: { spIndex: -1, originalXml: '', range: [0, 0] },
|
||||
transform: {
|
||||
offset: { x: 0, y: 0, cx: 3810000, cy: 952500 },
|
||||
rot: 0,
|
||||
flipH: false,
|
||||
flipV: false,
|
||||
},
|
||||
colWidths: [952500, 952500, 952500, 952500],
|
||||
rowHeights: [476250, 476250],
|
||||
rows: [
|
||||
[{}, { gridSpan: 2 }, { merged: true }, {}],
|
||||
[{}, {}, {}, {}],
|
||||
],
|
||||
}
|
||||
const rs = buildRenderSlide({ ...slide, elements: [el], decorations: [] }, deck.size, {
|
||||
fitWidthPx: 1280,
|
||||
})
|
||||
const node = rs.nodes[0] as any
|
||||
const colW = node.box.w / 4
|
||||
const row0 = node.cells.filter((c: any) => c.row === 0)
|
||||
// 3 emitted cells: [col0], [col1-2 merged], [col3]
|
||||
expect(row0.length).toBe(3)
|
||||
expect(row0[1].x).toBeCloseTo(colW, 1)
|
||||
expect(row0[1].w).toBeCloseTo(colW * 2, 1)
|
||||
// The cell after the merge sits at column 3, not shifted right off the table
|
||||
expect(row0[2].x).toBeCloseTo(colW * 3, 1)
|
||||
expect(row0[2].w).toBeCloseTo(colW, 1)
|
||||
// Grid lines exposed for the canvas resize grips
|
||||
expect(node.gridX.length).toBe(5)
|
||||
expect(node.gridY.length).toBe(3)
|
||||
expect(node.gridX[4]).toBeCloseTo(node.box.w, 1)
|
||||
})
|
||||
|
||||
it('grows table rows to fit wrapped cell text (row height is a minimum)', async () => {
|
||||
const { deck } = await openPptx(enginePptx('01_standard_business.pptx'))
|
||||
const slide = deck.slides[0]!
|
||||
const longText = {
|
||||
paragraphs: [
|
||||
{
|
||||
runs: [
|
||||
{
|
||||
text: 'a long piece of cell text that definitely wraps across many lines '.repeat(4),
|
||||
fontSize: 14,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
const mkTable = (text?: any): any => ({
|
||||
id: 'tbl_grow',
|
||||
type: 'table',
|
||||
anchor: { spIndex: -1, originalXml: '', range: [0, 0] },
|
||||
// Narrow 2-col table with two short rows
|
||||
transform: {
|
||||
offset: { x: 0, y: 0, cx: 1905000, cy: 952500 },
|
||||
rot: 0,
|
||||
flipH: false,
|
||||
flipV: false,
|
||||
},
|
||||
colWidths: [952500, 952500],
|
||||
rowHeights: [476250, 476250],
|
||||
rows: [
|
||||
[{ text }, {}],
|
||||
[{}, {}],
|
||||
],
|
||||
})
|
||||
const build = (el: any) =>
|
||||
buildRenderSlide({ ...slide, elements: [el], decorations: [] }, deck.size, {
|
||||
fitWidthPx: 1280,
|
||||
}).nodes[0] as any
|
||||
|
||||
const plain = build(mkTable())
|
||||
const grown = build(mkTable(longText))
|
||||
const cellOf = (n: any, r: number, c: number) =>
|
||||
n.cells.find((x: any) => x.row === r && x.col === c)
|
||||
|
||||
// Row 0 grew to fit the wrapped text; row 1 kept its height but moved down
|
||||
expect(cellOf(grown, 0, 0).h).toBeGreaterThan(cellOf(plain, 0, 0).h)
|
||||
const layout = cellOf(grown, 0, 0).text
|
||||
expect(layout.contentHeight + layout.insets.t + layout.insets.b).toBeLessThanOrEqual(
|
||||
cellOf(grown, 0, 0).h + 0.01,
|
||||
)
|
||||
expect(cellOf(grown, 1, 0).h).toBeCloseTo(cellOf(plain, 1, 0).h, 1)
|
||||
expect(cellOf(grown, 1, 0).y).toBeCloseTo(cellOf(grown, 0, 0).h, 1)
|
||||
// The node box grew with the total so nothing is clipped
|
||||
expect(grown.box.h).toBeCloseTo(cellOf(grown, 0, 0).h + cellOf(grown, 1, 0).h, 1)
|
||||
expect(grown.box.h).toBeGreaterThan(plain.box.h)
|
||||
})
|
||||
|
||||
it('maps group children into group-local coords (chOff subtracted, chExt scale baked into child boxes)', async () => {
|
||||
const { deck } = await openPptx(enginePptx('01_standard_business.pptx'))
|
||||
const slide = deck.slides[0]!
|
||||
const anchor = { spIndex: -1, originalXml: '', range: [0, 0] }
|
||||
const group: any = {
|
||||
id: 'grp1',
|
||||
type: 'group',
|
||||
anchor,
|
||||
// Group box 2×1 inch; child coordinate origin at (5,2.5) inch, size 1×0.5 inch → childScale 2
|
||||
transform: {
|
||||
offset: { x: 914400, y: 914400, cx: 1828800, cy: 914400 },
|
||||
rot: 0,
|
||||
flipH: false,
|
||||
flipV: false,
|
||||
},
|
||||
childOffset: { x: 4572000, y: 2286000, cx: 914400, cy: 457200 },
|
||||
children: [
|
||||
{
|
||||
id: 'c1',
|
||||
type: 'shape',
|
||||
anchor,
|
||||
// The child coincides with chOff → local (0,0) within the group
|
||||
transform: {
|
||||
offset: { x: 4572000, y: 2286000, cx: 457200, cy: 228600 },
|
||||
rot: 0,
|
||||
flipH: false,
|
||||
flipV: false,
|
||||
},
|
||||
presetGeometry: 'rect',
|
||||
fill: { type: 'solid', color: '#123456' },
|
||||
},
|
||||
],
|
||||
}
|
||||
const rs = buildRenderSlide({ ...slide, elements: [group], decorations: [] }, deck.size, {
|
||||
fitWidthPx: 1280,
|
||||
})
|
||||
const g = rs.nodes[0] as any
|
||||
expect(g.type).toBe('group')
|
||||
expect(g.children).toHaveLength(1)
|
||||
// ext/chExt = 2x (metadata for edit-pipeline conversion only; render container no longer applies it)
|
||||
expect(g.childScaleX).toBeCloseTo(2, 5)
|
||||
expect(g.childScaleY).toBeCloseTo(2, 5)
|
||||
// child local coords: same point as chOff -> (0,0); width = child EMU x childScale (scaling baked into geometry)
|
||||
const c = g.children[0]
|
||||
expect(c.box.x).toBeCloseTo(0, 3)
|
||||
expect(c.box.y).toBeCloseTo(0, 3)
|
||||
expect(c.box.w).toBeCloseTo(g.box.w / 2, 1) // child cx = half of chExt, childScale already included
|
||||
})
|
||||
|
||||
it('lays out group child text against the scaled box with unscaled font (non-uniform ext/chExt)', async () => {
|
||||
const { deck } = await openPptx(enginePptx('01_standard_business.pptx'))
|
||||
const slide = deck.slides[0]!
|
||||
const anchor = { spIndex: -1, originalXml: '', range: [0, 0] }
|
||||
const mkRun = (text: string) => ({ text, fontSize: 18, fontFamily: 'Arial' })
|
||||
const child = (id: string, offset: { x: number; y: number; cx: number; cy: number }) => ({
|
||||
id,
|
||||
type: 'text',
|
||||
anchor,
|
||||
transform: { offset, rot: 0, flipH: false, flipV: false },
|
||||
presetGeometry: 'rect',
|
||||
fill: { type: 'none' },
|
||||
text: {
|
||||
bodyPr: { wrap: true, anchor: 't', lIns: 0, tIns: 0, rIns: 0, bIns: 0 },
|
||||
paragraphs: [{ runs: [mkRun('word '.repeat(20).trim())], properties: {} }],
|
||||
},
|
||||
})
|
||||
const offset = { x: 0, y: 0, cx: 457200, cy: 457200 }
|
||||
const groupOf = (kids: any[], scaleX: number, scaleY: number): any => ({
|
||||
id: `grp_${scaleX}`,
|
||||
type: 'group',
|
||||
anchor,
|
||||
transform: {
|
||||
offset: { x: 0, y: 0, cx: 914400 * scaleX, cy: 914400 * scaleY },
|
||||
rot: 0,
|
||||
flipH: false,
|
||||
flipV: false,
|
||||
},
|
||||
childOffset: { x: 0, y: 0, cx: 914400, cy: 914400 },
|
||||
children: kids,
|
||||
})
|
||||
// same text: 1x group vs 3x horizontal group -- in the 3x group layout width is x3, fewer wrapped lines; font size unchanged
|
||||
const rs = buildRenderSlide(
|
||||
{
|
||||
...slide,
|
||||
elements: [groupOf([child('t1', offset)], 1, 1), groupOf([child('t2', offset)], 3, 1)],
|
||||
decorations: [],
|
||||
},
|
||||
deck.size,
|
||||
{ fitWidthPx: 1280 },
|
||||
)
|
||||
const [g1, g3] = rs.nodes as any[]
|
||||
const t1 = g1.children[0]
|
||||
const t3 = g3.children[0]
|
||||
expect(t3.box.w).toBeCloseTo(t1.box.w * 3, 1)
|
||||
expect(t3.text.lines.length).toBeLessThan(t1.text.lines.length)
|
||||
// font size does not scale with the group (group scaling only affects geometry)
|
||||
const size1 = t1.text.lines[0].runs[0].fontSizePx
|
||||
const size3 = t3.text.lines[0].runs[0].fontSizePx
|
||||
expect(size3).toBeCloseTo(size1, 3)
|
||||
})
|
||||
|
||||
it('builds connectors as line render nodes with flip baked into points', async () => {
|
||||
const { deck } = await openPptx(enginePptx('01_standard_business.pptx'))
|
||||
const slide = deck.slides[0]!
|
||||
const el: any = {
|
||||
id: 'cxn1',
|
||||
type: 'shape',
|
||||
anchor: { spIndex: -1, originalXml: '', range: [0, 0] },
|
||||
transform: {
|
||||
offset: { x: 0, y: 0, cx: 914400, cy: 457200 },
|
||||
rot: 0,
|
||||
flipH: false,
|
||||
flipV: true,
|
||||
},
|
||||
presetGeometry: 'straightConnector1',
|
||||
fill: { type: 'none' },
|
||||
stroke: {
|
||||
fill: { type: 'solid', color: '#FF0000' },
|
||||
width: 12700,
|
||||
tailEnd: { type: 'triangle' },
|
||||
},
|
||||
}
|
||||
const rs = buildRenderSlide({ ...slide, elements: [el], decorations: [] }, deck.size, {
|
||||
fitWidthPx: 1280,
|
||||
})
|
||||
const n = rs.nodes[0] as any
|
||||
expect(n.line).toBeTruthy()
|
||||
expect(n.line.tailEnd).toBeTruthy()
|
||||
expect(n.line.tailEnd.type).toBe('triangle')
|
||||
expect(n.line.headEnd).toBeUndefined()
|
||||
// flipV is baked into the points: start at bottom-left, end at top-right; the box carries no flip flags anymore
|
||||
expect(n.line.points).toEqual([0, n.box.h, n.box.w, 0])
|
||||
expect(n.box.flipV).toBe(false)
|
||||
})
|
||||
|
||||
it('builds preset polygons (triangle) and renders decorations as flagged nodes', async () => {
|
||||
const { deck } = await openPptx(enginePptx('01_standard_business.pptx'))
|
||||
const slide = deck.slides[0]!
|
||||
const anchor = { spIndex: -1, originalXml: '', range: [0, 0] }
|
||||
const tri: any = {
|
||||
id: 'tri1',
|
||||
type: 'shape',
|
||||
anchor,
|
||||
transform: {
|
||||
offset: { x: 0, y: 0, cx: 914400, cy: 914400 },
|
||||
rot: 0,
|
||||
flipH: false,
|
||||
flipV: false,
|
||||
},
|
||||
presetGeometry: 'triangle',
|
||||
fill: { type: 'solid', color: '#00FF00' },
|
||||
}
|
||||
const deco: any = {
|
||||
id: 'logo1',
|
||||
type: 'shape',
|
||||
anchor,
|
||||
transform: {
|
||||
offset: { x: 0, y: 0, cx: 914400, cy: 100000 },
|
||||
rot: 0,
|
||||
flipH: false,
|
||||
flipV: false,
|
||||
},
|
||||
presetGeometry: 'rect',
|
||||
fill: { type: 'solid', color: '#C43E1C' },
|
||||
}
|
||||
const rs = buildRenderSlide({ ...slide, elements: [tri], decorations: [deco] }, deck.size, {
|
||||
fitWidthPx: 1280,
|
||||
})
|
||||
// The decoration layer comes first and carries the decoration flag
|
||||
expect(rs.nodes[0]!.decoration).toBe(true)
|
||||
expect(rs.nodes[0]!.sourceId).toBe('logo1')
|
||||
const n = rs.nodes[1] as any
|
||||
expect(n.polygonPoints).toBeTruthy()
|
||||
expect(n.polygonPoints.length).toBe(6)
|
||||
expect(n.polygonPoints[0]).toBeCloseTo(n.box.w / 2, 3)
|
||||
})
|
||||
|
||||
it('scales customGeometry unit path to box px (pathData)', async () => {
|
||||
const { deck } = await openPptx(enginePptx('01_standard_business.pptx'))
|
||||
const slide = deck.slides[0]!
|
||||
const el: any = {
|
||||
id: 'cg1',
|
||||
type: 'shape',
|
||||
anchor: { spIndex: -1, originalXml: '', range: [0, 0] },
|
||||
transform: {
|
||||
offset: { x: 0, y: 0, cx: 914400, cy: 457200 },
|
||||
rot: 0,
|
||||
flipH: false,
|
||||
flipV: false,
|
||||
},
|
||||
customGeometry: { path: 'M 0 1 L 0.5 0 L 1 1 Z', strokePath: 'M 0 0 L 1 1' },
|
||||
fill: { type: 'solid', color: '#00FF00' },
|
||||
}
|
||||
const rs = buildRenderSlide({ ...slide, elements: [el], decorations: [] }, deck.size, {
|
||||
fitWidthPx: 1280,
|
||||
})
|
||||
const n = rs.nodes[0] as any
|
||||
const toks = n.pathData.split(' ')
|
||||
expect(toks[0]).toBe('M')
|
||||
expect(Number(toks[1])).toBeCloseTo(0, 2)
|
||||
expect(Number(toks[2])).toBeCloseTo(n.box.h, 1)
|
||||
expect(Number(toks[4])).toBeCloseTo(n.box.w / 2, 1)
|
||||
// strokePath scales along with it
|
||||
expect(n.strokePathData.split(' ').map(Number).filter(Number.isFinite).pop()).toBeCloseTo(
|
||||
n.box.h,
|
||||
1,
|
||||
)
|
||||
expect(n.polygonPoints).toBeUndefined()
|
||||
})
|
||||
|
||||
it('falls back to presetPath channel for curved presets (pie)', async () => {
|
||||
const { deck } = await openPptx(enginePptx('01_standard_business.pptx'))
|
||||
const slide = deck.slides[0]!
|
||||
const el: any = {
|
||||
id: 'pie1',
|
||||
type: 'shape',
|
||||
anchor: { spIndex: -1, originalXml: '', range: [0, 0] },
|
||||
transform: {
|
||||
offset: { x: 0, y: 0, cx: 914400, cy: 914400 },
|
||||
rot: 0,
|
||||
flipH: false,
|
||||
flipV: false,
|
||||
},
|
||||
presetGeometry: 'pie',
|
||||
fill: { type: 'solid', color: '#00FF00' },
|
||||
}
|
||||
const rs = buildRenderSlide({ ...slide, elements: [el], decorations: [] }, deck.size, {
|
||||
fitWidthPx: 1280,
|
||||
})
|
||||
const n = rs.nodes[0] as any
|
||||
expect(n.polygonPoints).toBeUndefined()
|
||||
expect(n.pathData).toMatch(/^M .* C /)
|
||||
expect(n.pathData.endsWith('Z')).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,202 @@
|
||||
/**
|
||||
* Connector geometry tests:
|
||||
* - bent elbow positions (controlled by adj)
|
||||
* - curved bezier control point counts
|
||||
* - ArrowHead size conversion
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { connectorPoints, connectorBezier } from '../src/preset-geometry'
|
||||
import { openPptx } from '@genoffice/pptx-engine'
|
||||
import { buildRenderSlide } from '../src/index'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const enginePptx = (name: string) =>
|
||||
readFileSync(join(here, '..', '..', 'pptx-engine', 'tests', 'fixtures', name))
|
||||
|
||||
// ── bent connector elbows ─────────────────────────────────────────────────
|
||||
|
||||
describe('connectorPoints: bentConnector3 adj controls elbow position', () => {
|
||||
it('adj1=50000 → elbow at horizontal center (default)', () => {
|
||||
const pts = connectorPoints('bentConnector3', 100, 60, false, false, { adj1: 50000 })
|
||||
// Expected: [0,0, 50,0, 50,60, 100,60]
|
||||
expect(pts).toHaveLength(8)
|
||||
expect(pts[2]).toBeCloseTo(50, 3) // second elbow x
|
||||
expect(pts[4]).toBeCloseTo(50, 3) // third elbow x
|
||||
})
|
||||
|
||||
it('adj1=75000 → elbow at 75% of width', () => {
|
||||
const pts = connectorPoints('bentConnector3', 100, 60, false, false, { adj1: 75000 })
|
||||
expect(pts[2]).toBeCloseTo(75, 3)
|
||||
expect(pts[4]).toBeCloseTo(75, 3)
|
||||
})
|
||||
|
||||
it('flipV mirrors y coordinates', () => {
|
||||
const pts = connectorPoints('bentConnector3', 100, 60, false, true, { adj1: 50000 })
|
||||
// flipV: y = h - y, so [0,60, 50,60, 50,0, 100,0]
|
||||
expect(pts[1]).toBeCloseTo(60, 3) // start y
|
||||
expect(pts[7]).toBeCloseTo(0, 3) // end y
|
||||
})
|
||||
|
||||
it('flipH mirrors x coordinates', () => {
|
||||
const pts = connectorPoints('bentConnector3', 100, 60, true, false, { adj1: 50000 })
|
||||
expect(pts[0]).toBeCloseTo(100, 3) // start x = w - 0
|
||||
expect(pts[6]).toBeCloseTo(0, 3) // end x = w - w
|
||||
})
|
||||
})
|
||||
|
||||
describe('connectorPoints: bentConnector2 (single elbow)', () => {
|
||||
it('3 bend points', () => {
|
||||
const pts = connectorPoints('bentConnector2', 100, 60, false, false)
|
||||
expect(pts).toHaveLength(6) // 3 * 2
|
||||
// [0,0, 100,0, 100,60]
|
||||
expect(pts[2]).toBeCloseTo(100, 3)
|
||||
expect(pts[3]).toBeCloseTo(0, 3)
|
||||
expect(pts[4]).toBeCloseTo(100, 3)
|
||||
expect(pts[5]).toBeCloseTo(60, 3)
|
||||
})
|
||||
})
|
||||
|
||||
describe('connectorPoints: line/straightConnector', () => {
|
||||
it('two endpoints', () => {
|
||||
const pts = connectorPoints('line', 100, 60, false, false)
|
||||
expect(pts).toHaveLength(4)
|
||||
expect(pts).toEqual([0, 0, 100, 60])
|
||||
})
|
||||
|
||||
it('correct diagonal after flip', () => {
|
||||
const pts = connectorPoints('straightConnector1', 100, 60, true, true)
|
||||
expect(pts).toEqual([100, 60, 0, 0])
|
||||
})
|
||||
})
|
||||
|
||||
// ── curved connector bezier ───────────────────────────────────────────────
|
||||
|
||||
describe('connectorBezier', () => {
|
||||
it('2 bend points return empty (no curve)', () => {
|
||||
const pts = [0, 0, 100, 60]
|
||||
expect(connectorBezier(pts)).toEqual([])
|
||||
})
|
||||
|
||||
it('3 bend points (bentConnector2) return 2 bezier segments (12 numbers)', () => {
|
||||
const pts = [0, 0, 100, 0, 100, 60]
|
||||
const bz = connectorBezier(pts)
|
||||
expect(bz).toHaveLength(12) // 2 segments × 6
|
||||
})
|
||||
|
||||
it('4 bend points (bentConnector3) return 3 bezier segments (18 numbers)', () => {
|
||||
const pts = [0, 0, 50, 0, 50, 60, 100, 60]
|
||||
const bz = connectorBezier(pts)
|
||||
expect(bz).toHaveLength(18) // 3 segments × 6
|
||||
})
|
||||
|
||||
it('last 2 numbers of each segment equal the polyline bend point', () => {
|
||||
const pts = [0, 0, 50, 0, 50, 60, 100, 60]
|
||||
const bz = connectorBezier(pts)
|
||||
// segment 0 endpoint = pts[1] = (50,0)
|
||||
expect(bz[4]).toBeCloseTo(50, 5)
|
||||
expect(bz[5]).toBeCloseTo(0, 5)
|
||||
// segment 1 endpoint = pts[2] = (50,60)
|
||||
expect(bz[10]).toBeCloseTo(50, 5)
|
||||
expect(bz[11]).toBeCloseTo(60, 5)
|
||||
})
|
||||
})
|
||||
|
||||
// ── build-slide ArrowEnd → ArrowEndRender ─────────────────────────────────
|
||||
|
||||
describe('buildRenderSlide connector → line.tailEnd/headEnd', () => {
|
||||
it('tailEnd triangle → line.tailEnd.type=triangle, sized by med line width', async () => {
|
||||
const { deck } = await openPptx(enginePptx('01_standard_business.pptx'))
|
||||
const slide = deck.slides[0]!
|
||||
const el: any = {
|
||||
id: 'c1',
|
||||
type: 'shape',
|
||||
anchor: { spIndex: -1, originalXml: '', range: [0, 0] },
|
||||
transform: {
|
||||
offset: { x: 0, y: 0, cx: 914400, cy: 457200 },
|
||||
rot: 0,
|
||||
flipH: false,
|
||||
flipV: false,
|
||||
},
|
||||
presetGeometry: 'straightConnector1',
|
||||
fill: { type: 'none' },
|
||||
stroke: {
|
||||
fill: { type: 'solid', color: '#000000' },
|
||||
width: 19050,
|
||||
tailEnd: { type: 'triangle', w: 'med', len: 'med' },
|
||||
},
|
||||
}
|
||||
const rs = buildRenderSlide({ ...slide, elements: [el], decorations: [] }, deck.size, {
|
||||
fitWidthPx: 1280,
|
||||
})
|
||||
const n = rs.nodes[0] as any
|
||||
expect(n.line).toBeTruthy()
|
||||
expect(n.line.tailEnd).toBeTruthy()
|
||||
expect(n.line.tailEnd.type).toBe('triangle')
|
||||
// med x 3 = ~3*lw; lw ~= 19050/9525 * scale(1280/...)
|
||||
expect(n.line.tailEnd.widthPx).toBeGreaterThan(0)
|
||||
expect(n.line.tailEnd.lengthPx).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('both headEnd and tailEnd present', async () => {
|
||||
const { deck } = await openPptx(enginePptx('01_standard_business.pptx'))
|
||||
const slide = deck.slides[0]!
|
||||
const el: any = {
|
||||
id: 'c2',
|
||||
type: 'shape',
|
||||
anchor: { spIndex: -1, originalXml: '', range: [0, 0] },
|
||||
transform: {
|
||||
offset: { x: 0, y: 0, cx: 914400, cy: 914400 },
|
||||
rot: 0,
|
||||
flipH: false,
|
||||
flipV: false,
|
||||
},
|
||||
presetGeometry: 'bentConnector3',
|
||||
adjust: { adj1: 50000 },
|
||||
fill: { type: 'none' },
|
||||
stroke: {
|
||||
fill: { type: 'solid', color: '#FF0000' },
|
||||
width: 12700,
|
||||
headEnd: { type: 'oval' },
|
||||
tailEnd: { type: 'diamond', w: 'lg' },
|
||||
},
|
||||
}
|
||||
const rs = buildRenderSlide({ ...slide, elements: [el], decorations: [] }, deck.size, {
|
||||
fitWidthPx: 1280,
|
||||
})
|
||||
const n = rs.nodes[0] as any
|
||||
expect(n.line.headEnd?.type).toBe('oval')
|
||||
expect(n.line.tailEnd?.type).toBe('diamond')
|
||||
// lg multiplier 5 > med 3
|
||||
expect(n.line.tailEnd.widthPx).toBeGreaterThan(n.line.headEnd.widthPx)
|
||||
})
|
||||
|
||||
it('curved connector produces bezier control points', async () => {
|
||||
const { deck } = await openPptx(enginePptx('01_standard_business.pptx'))
|
||||
const slide = deck.slides[0]!
|
||||
const el: any = {
|
||||
id: 'c3',
|
||||
type: 'shape',
|
||||
anchor: { spIndex: -1, originalXml: '', range: [0, 0] },
|
||||
transform: {
|
||||
offset: { x: 0, y: 0, cx: 914400, cy: 457200 },
|
||||
rot: 0,
|
||||
flipH: false,
|
||||
flipV: false,
|
||||
},
|
||||
presetGeometry: 'curvedConnector3',
|
||||
adjust: { adj1: 50000 },
|
||||
fill: { type: 'none' },
|
||||
stroke: { fill: { type: 'solid', color: '#000000' }, width: 12700 },
|
||||
}
|
||||
const rs = buildRenderSlide({ ...slide, elements: [el], decorations: [] }, deck.size, {
|
||||
fitWidthPx: 1280,
|
||||
})
|
||||
const n = rs.nodes[0] as any
|
||||
expect(n.line).toBeTruthy()
|
||||
expect(n.line.bezier).toBeTruthy()
|
||||
expect(n.line.bezier.length).toBeGreaterThan(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,65 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
emuToPx,
|
||||
ptToPx,
|
||||
rotToDeg,
|
||||
makeViewport,
|
||||
rectToPx,
|
||||
placeTransform,
|
||||
EMU_PER_PX_96,
|
||||
} from '../src/coords'
|
||||
import type { Transform } from '@genoffice/pptx-engine'
|
||||
|
||||
describe('2.1 coordinate system', () => {
|
||||
it('emuToPx: 1px = 9525 EMU at scale 1', () => {
|
||||
expect(emuToPx(9525, 1)).toBeCloseTo(1, 6)
|
||||
expect(emuToPx(EMU_PER_PX_96 * 100, 1)).toBeCloseTo(100, 6)
|
||||
})
|
||||
|
||||
it('ptToPx: 18pt = 24px at 96dpi', () => {
|
||||
expect(ptToPx(18, 1)).toBeCloseTo(24, 6)
|
||||
expect(ptToPx(72, 1)).toBeCloseTo(96, 6)
|
||||
})
|
||||
|
||||
it('rotToDeg: 60000 units = 1 degree', () => {
|
||||
expect(rotToDeg(60000)).toBe(1)
|
||||
expect(rotToDeg(2700000)).toBe(45)
|
||||
})
|
||||
|
||||
it('makeViewport: 16:9 slide maps to correct aspect', () => {
|
||||
// Standard 16:9: 12192000 x 6858000 EMU
|
||||
const vp = makeViewport({ cx: 12192000, cy: 6858000 }, 1280)
|
||||
expect(vp.widthPx).toBe(1280)
|
||||
expect(vp.heightPx).toBeCloseTo(720, 0) // 16:9
|
||||
})
|
||||
|
||||
it('rectToPx: scales geometry by viewport scale', () => {
|
||||
const size = { cx: 9525 * 1000, cy: 9525 * 562 } // natural 1000x562 px
|
||||
const vp = makeViewport(size, 500) // scaled to half
|
||||
const px = rectToPx({ x: 9525 * 100, y: 9525 * 50, cx: 9525 * 200, cy: 9525 * 100 }, vp)
|
||||
expect(px.x).toBeCloseTo(50, 4)
|
||||
expect(px.y).toBeCloseTo(25, 4)
|
||||
expect(px.w).toBeCloseTo(100, 4)
|
||||
expect(px.h).toBeCloseTo(50, 4)
|
||||
})
|
||||
|
||||
it('placeTransform: computes center + rotation + parent offset', () => {
|
||||
const size = { cx: 9525 * 1000, cy: 9525 * 1000 }
|
||||
const vp = makeViewport(size, 1000) // scale 1
|
||||
const t: Transform = {
|
||||
offset: { x: 9525 * 100, y: 9525 * 100, cx: 9525 * 200, cy: 9525 * 80 },
|
||||
rot: 2700000, // 45deg
|
||||
flipH: true,
|
||||
flipV: false,
|
||||
}
|
||||
const box = placeTransform(t, vp, { x: 10, y: 20 })
|
||||
expect(box.x).toBeCloseTo(110, 4)
|
||||
expect(box.y).toBeCloseTo(120, 4)
|
||||
expect(box.w).toBeCloseTo(200, 4)
|
||||
expect(box.h).toBeCloseTo(80, 4)
|
||||
expect(box.rotationDeg).toBe(45)
|
||||
expect(box.flipH).toBe(true)
|
||||
expect(box.centerX).toBeCloseTo(210, 4)
|
||||
expect(box.centerY).toBeCloseTo(160, 4)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,54 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { resolveFill, resolveStroke } from '../src/fill'
|
||||
import { makeViewport } from '../src/coords'
|
||||
import type { Fill, Stroke } from '@genoffice/pptx-engine'
|
||||
|
||||
const vp = makeViewport({ cx: 9525 * 1000, cy: 9525 * 1000 }, 1000) // scale 1
|
||||
|
||||
describe('2.2 fill/stroke resolution', () => {
|
||||
it('solid fill passes color through', () => {
|
||||
const f: Fill = { type: 'solid', color: '#3366CC' }
|
||||
expect(resolveFill(f, vp)).toEqual({ kind: 'solid', color: '#3366CC' })
|
||||
})
|
||||
|
||||
it('none / undefined → none', () => {
|
||||
expect(resolveFill(undefined, vp)).toEqual({ kind: 'none' })
|
||||
expect(resolveFill({ type: 'none' }, vp)).toEqual({ kind: 'none' })
|
||||
})
|
||||
|
||||
it('gradient converts angle from 60000ths to degrees', () => {
|
||||
const f: Fill = {
|
||||
type: 'gradient',
|
||||
stops: [
|
||||
{ pos: 0, color: '#000' },
|
||||
{ pos: 1, color: '#FFF' },
|
||||
],
|
||||
angle: 2700000,
|
||||
}
|
||||
const r = resolveFill(f, vp)
|
||||
expect(r.kind).toBe('gradient')
|
||||
if (r.kind === 'gradient') {
|
||||
expect(r.angleDeg).toBe(45)
|
||||
expect(r.stops.length).toBe(2)
|
||||
}
|
||||
})
|
||||
|
||||
it('image fill resolves dataUrl via media resolver', () => {
|
||||
const f: Fill = { type: 'image', mediaRef: 'ppt/media/image1.png', mode: 'stretch' }
|
||||
const r = resolveFill(f, vp, (ref) => (ref.includes('image1') ? 'data:img' : undefined))
|
||||
expect(r).toEqual({ kind: 'image', dataUrl: 'data:img', mode: 'stretch' })
|
||||
})
|
||||
|
||||
it('stroke converts EMU width to px and maps dash preset', () => {
|
||||
const s: Stroke = { fill: { type: 'solid', color: '#111' }, width: 9525 * 2, dash: 'dash' }
|
||||
const r = resolveStroke(s, vp)
|
||||
expect(r?.color).toBe('#111')
|
||||
expect(r?.widthPx).toBeCloseTo(2, 4)
|
||||
expect(Array.isArray(r?.dash)).toBe(true)
|
||||
})
|
||||
|
||||
it('noFill stroke → undefined', () => {
|
||||
const s: Stroke = { fill: { type: 'none' }, width: 12700 }
|
||||
expect(resolveStroke(s, vp)).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,112 @@
|
||||
/**
|
||||
* Passthrough preview rendering: SmartArt previewShapes → group node,
|
||||
* OLE previewPicture → picture node filling the frame, media images carry a media flag.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import type { PassthroughElement, PictureElement, Slide, SlideDeck } from '@genoffice/pptx-engine'
|
||||
import { buildRenderSlide } from '../src/index'
|
||||
import type { GroupRenderNode, PictureRenderNode } from '../src/render-tree'
|
||||
|
||||
const size: SlideDeck['size'] = { cx: 9525 * 1280, cy: 9525 * 720 }
|
||||
|
||||
const anchor = { spIndex: 0, originalXml: '<p:graphicFrame/>', range: [0, 0] as [number, number] }
|
||||
const transform = (x: number, y: number, cx: number, cy: number) => ({
|
||||
offset: { x, y, cx, cy },
|
||||
rot: 0,
|
||||
flipH: false,
|
||||
flipV: false,
|
||||
})
|
||||
|
||||
const slideOf = (elements: Slide['elements']): Slide => ({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
originalXml: '',
|
||||
bodyPrefix: '',
|
||||
bodySuffix: '',
|
||||
elements,
|
||||
})
|
||||
|
||||
describe('passthrough preview rendering', () => {
|
||||
it('smartart previewShapes → group node (child shapes positioned in diagram canvas space)', () => {
|
||||
const el: PassthroughElement = {
|
||||
id: 'gf1',
|
||||
type: 'passthrough',
|
||||
kind: 'smartart',
|
||||
anchor,
|
||||
transform: transform(9525 * 100, 9525 * 50, 9525 * 400, 9525 * 300),
|
||||
previewShapes: [
|
||||
{
|
||||
id: 'd1',
|
||||
type: 'shape',
|
||||
anchor: { spIndex: -1, originalXml: '', range: [0, 0] },
|
||||
transform: transform(0, 0, 9525 * 200, 9525 * 150),
|
||||
presetGeometry: 'roundRect',
|
||||
fill: { type: 'solid', color: '#4472C4' },
|
||||
},
|
||||
],
|
||||
}
|
||||
const rs = buildRenderSlide(slideOf([el]), size, { fitWidthPx: 1280 })
|
||||
expect(rs.nodes.length).toBe(1)
|
||||
const g = rs.nodes[0] as GroupRenderNode
|
||||
expect(g.type).toBe('group')
|
||||
expect(g.sourceId).toBe('gf1')
|
||||
expect(g.box.x).toBeCloseTo(100, 0)
|
||||
expect(g.children.length).toBe(1)
|
||||
expect(g.children[0]!.type).toBe('shape')
|
||||
expect(g.children[0]!.box.w).toBeCloseTo(200, 0)
|
||||
})
|
||||
|
||||
it('ole previewPicture → picture node fills the frame (ignores the pic own xfrm)', () => {
|
||||
const preview: PictureElement = {
|
||||
id: 'p1',
|
||||
type: 'picture',
|
||||
anchor: { spIndex: -1, originalXml: '', range: [0, 0] },
|
||||
transform: transform(0, 0, 1, 1), // the embedded pic's xfrm should be ignored
|
||||
mediaRef: 'ppt/media/image9.png',
|
||||
}
|
||||
const el: PassthroughElement = {
|
||||
id: 'gf2',
|
||||
type: 'passthrough',
|
||||
kind: 'ole',
|
||||
anchor,
|
||||
transform: transform(0, 0, 9525 * 300, 9525 * 200),
|
||||
previewPicture: preview,
|
||||
}
|
||||
const rs = buildRenderSlide(slideOf([el]), size, {
|
||||
fitWidthPx: 1280,
|
||||
media: (ref) => (ref.includes('image9') ? 'data:img' : undefined),
|
||||
})
|
||||
const n = rs.nodes[0] as PictureRenderNode
|
||||
expect(n.type).toBe('picture')
|
||||
expect(n.sourceId).toBe('gf2')
|
||||
expect(n.dataUrl).toBe('data:img')
|
||||
expect(n.box.w).toBeCloseTo(300, 0)
|
||||
expect(n.box.h).toBeCloseTo(200, 0)
|
||||
})
|
||||
|
||||
it('falls back to placeholder chip when no preview exists', () => {
|
||||
const el: PassthroughElement = {
|
||||
id: 'gf3',
|
||||
type: 'passthrough',
|
||||
kind: 'smartart',
|
||||
anchor,
|
||||
transform: transform(0, 0, 9525 * 100, 9525 * 100),
|
||||
}
|
||||
const rs = buildRenderSlide(slideOf([el]), size, { fitWidthPx: 1280 })
|
||||
expect(rs.nodes[0]!.type).toBe('placeholder-chip')
|
||||
})
|
||||
|
||||
it('audio/video pictures carry the media flag', () => {
|
||||
const el: PictureElement = {
|
||||
id: 'v1',
|
||||
type: 'picture',
|
||||
anchor: { spIndex: 0, originalXml: '<p:pic/>', range: [0, 0] },
|
||||
transform: transform(0, 0, 9525 * 100, 9525 * 100),
|
||||
mediaRef: 'ppt/media/poster.png',
|
||||
media: { kind: 'video', target: 'ppt/media/media1.mp4' },
|
||||
}
|
||||
const rs = buildRenderSlide(slideOf([el]), size, { fitWidthPx: 1280 })
|
||||
const n = rs.nodes[0] as PictureRenderNode
|
||||
expect(n.type).toBe('picture')
|
||||
expect(n.media).toBe('video')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,208 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { isConnectorPreset, connectorPoints, presetPolygon, presetPath, isPillPreset } from '../src/preset-geometry'
|
||||
|
||||
describe('connectorPoints', () => {
|
||||
it('straight connector runs corner to corner; flip mirrors direction', () => {
|
||||
expect(connectorPoints('straightConnector1', 100, 50, false, false)).toEqual([0, 0, 100, 50])
|
||||
expect(connectorPoints('line', 100, 50, true, false)).toEqual([100, 0, 0, 50])
|
||||
expect(connectorPoints('line', 100, 50, false, true)).toEqual([0, 50, 100, 0])
|
||||
})
|
||||
|
||||
it('bentConnector3 has two elbows at adj1 fraction of width', () => {
|
||||
const pts = connectorPoints('bentConnector3', 200, 100, false, false, { adj1: 25000 })
|
||||
expect(pts).toEqual([0, 0, 50, 0, 50, 100, 200, 100])
|
||||
})
|
||||
|
||||
it('bentConnector2 has one elbow', () => {
|
||||
expect(connectorPoints('bentConnector2', 200, 100, false, false)).toEqual([0, 0, 200, 0, 200, 100])
|
||||
})
|
||||
|
||||
it('isConnectorPreset recognizes connector presets only', () => {
|
||||
for (const p of ['line', 'straightConnector1', 'bentConnector3', 'curvedConnector4']) {
|
||||
expect(isConnectorPreset(p)).toBe(true)
|
||||
}
|
||||
for (const p of ['rect', 'ellipse', 'triangle', undefined]) {
|
||||
expect(isConnectorPreset(p)).toBe(false)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('presetPolygon', () => {
|
||||
const inBounds = (pts: number[], w: number, h: number) => {
|
||||
for (let i = 0; i < pts.length; i += 2) {
|
||||
expect(pts[i]!).toBeGreaterThanOrEqual(-0.01)
|
||||
expect(pts[i]!).toBeLessThanOrEqual(w + 0.01)
|
||||
expect(pts[i + 1]!).toBeGreaterThanOrEqual(-0.01)
|
||||
expect(pts[i + 1]!).toBeLessThanOrEqual(h + 0.01)
|
||||
}
|
||||
}
|
||||
|
||||
it('triangle apex follows adj', () => {
|
||||
expect(presetPolygon('triangle', 100, 80)).toEqual([50, 0, 100, 80, 0, 80])
|
||||
expect(presetPolygon('triangle', 100, 80, { adj: 0 })).toEqual([0, 0, 100, 80, 0, 80])
|
||||
})
|
||||
|
||||
it('diamond / flowChartDecision are midpoint quads', () => {
|
||||
expect(presetPolygon('diamond', 100, 60)).toEqual([50, 0, 100, 30, 50, 60, 0, 30])
|
||||
expect(presetPolygon('flowChartDecision', 100, 60)).toEqual(presetPolygon('diamond', 100, 60))
|
||||
})
|
||||
|
||||
it('rightArrow head/shaft follow adj1/adj2 and stay in bounds', () => {
|
||||
const pts = presetPolygon('rightArrow', 200, 100)! // defaults adj1=adj2=50000
|
||||
inBounds(pts, 200, 100)
|
||||
// The arrow tip is at the right-edge midpoint
|
||||
expect(pts).toContain(200)
|
||||
// head length = min(w, ss*0.5) = 50 → head starts at x=150
|
||||
expect(pts[2]).toBe(150)
|
||||
// shaft thickness = h*0.5 → top edge y=25
|
||||
expect(pts[1]).toBe(25)
|
||||
})
|
||||
|
||||
it('chevron / homePlate / hexagon / star5 stay within bounds', () => {
|
||||
for (const p of ['chevron', 'homePlate', 'hexagon', 'star5', 'parallelogram', 'trapezoid', 'octagon', 'plus']) {
|
||||
const pts = presetPolygon(p, 120, 90)
|
||||
expect(pts, p).toBeTruthy()
|
||||
inBounds(pts!, 120, 90)
|
||||
expect(pts!.length).toBeGreaterThanOrEqual(6)
|
||||
}
|
||||
})
|
||||
|
||||
it('unsupported presets return null (rect fallback upstream)', () => {
|
||||
expect(presetPolygon('rect', 100, 100)).toBeNull()
|
||||
expect(presetPolygon('cloudCallout', 100, 100)).toBeNull()
|
||||
expect(presetPolygon(undefined, 100, 100)).toBeNull()
|
||||
})
|
||||
|
||||
it('pill presets flagged for cornerRadius rendering', () => {
|
||||
expect(isPillPreset('flowChartTerminator')).toBe(true)
|
||||
expect(isPillPreset('roundRect')).toBe(false)
|
||||
})
|
||||
|
||||
it('snip1Rect cuts top-right corner by adj fraction of short side', () => {
|
||||
expect(presetPolygon('snip1Rect', 200, 100, { adj: 20000 })).toEqual([0, 0, 180, 0, 200, 20, 200, 100, 0, 100])
|
||||
})
|
||||
|
||||
it('notchedRightArrow has tail notch at mid height', () => {
|
||||
const pts = presetPolygon('notchedRightArrow', 200, 100)!
|
||||
inBounds(pts, 200, 100)
|
||||
// The last point is the notch (x>0, y=h/2)
|
||||
expect(pts[pts.length - 1]).toBe(50)
|
||||
expect(pts[pts.length - 2]).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('new polygon presets stay in bounds and are non-trivial', () => {
|
||||
for (const p of [
|
||||
'snip2SameRect', 'snip2DiagRect', 'halfFrame', 'corner', 'diagStripe', 'lightningBolt',
|
||||
'flowChartPreparation', 'flowChartManualInput', 'flowChartManualOperation',
|
||||
'flowChartOffpageConnector', 'flowChartExtract', 'flowChartMerge', 'flowChartCollate',
|
||||
'gear6', 'funnel', 'quadArrow', 'bentArrow', 'irregularSeal1', 'irregularSeal2',
|
||||
'star7', 'star10', 'star12', 'star16', 'star24', 'star32',
|
||||
]) {
|
||||
const pts = presetPolygon(p, 120, 90)
|
||||
expect(pts, p).toBeTruthy()
|
||||
inBounds(pts!, 120, 90)
|
||||
expect(pts!.length, p).toBeGreaterThanOrEqual(6)
|
||||
}
|
||||
})
|
||||
|
||||
it('star7 has 14 vertices', () => {
|
||||
expect(presetPolygon('star7', 100, 100)!.length).toBe(28)
|
||||
})
|
||||
|
||||
it('wedgeRectCallout default puts tail on bottom edge toward tip', () => {
|
||||
const pts = presetPolygon('wedgeRectCallout', 100, 100)!
|
||||
// tip = (50-20.833, 50+62.5) = (29.17, 112.5): may exceed the box (tail tip)
|
||||
expect(pts).toContain(112.5)
|
||||
expect(pts.length).toBe(14)
|
||||
})
|
||||
})
|
||||
|
||||
describe('presetPath', () => {
|
||||
const nums = (d: string) => d.split(' ').filter((t) => Number.isFinite(Number(t))).map(Number)
|
||||
const inBox = (d: string, w: number, h: number, slack = 0.01) => {
|
||||
const v = nums(d)
|
||||
for (let i = 0; i < v.length; i += 2) {
|
||||
expect(v[i]!).toBeGreaterThanOrEqual(-w * 0.2 - slack)
|
||||
expect(v[i]!).toBeLessThanOrEqual(w * 1.2 + slack)
|
||||
expect(v[i + 1]!).toBeGreaterThanOrEqual(-h * 0.2 - slack)
|
||||
expect(v[i + 1]!).toBeLessThanOrEqual(h * 1.2 + slack)
|
||||
}
|
||||
}
|
||||
|
||||
it('pie default sweeps 0°→270° from center', () => {
|
||||
const r = presetPath('pie', 100, 100)!
|
||||
expect(r.path).toMatch(/^M 50 50 L 100 50 C /)
|
||||
expect(r.path).toMatch(/Z$/)
|
||||
})
|
||||
|
||||
it('arc yields stroke-only arc + fill-only pie', () => {
|
||||
const r = presetPath('arc', 100, 100)!
|
||||
expect(r.strokePath).toMatch(/^M /)
|
||||
expect(r.strokePath).not.toMatch(/Z/)
|
||||
expect(r.fillPath).toMatch(/^M 50 50/)
|
||||
expect(r.fillPath).toMatch(/Z$/)
|
||||
})
|
||||
|
||||
it('donut has two subpaths (outer + reversed hole)', () => {
|
||||
const r = presetPath('donut', 100, 100)!
|
||||
expect(r.path!.match(/M /g)!.length).toBe(2)
|
||||
inBox(r.path!, 100, 100)
|
||||
})
|
||||
|
||||
it('brackets/braces are stroke-only', () => {
|
||||
for (const p of ['leftBracket', 'rightBracket', 'leftBrace', 'rightBrace']) {
|
||||
const r = presetPath(p, 40, 120)!
|
||||
expect(r.path, p).toBeUndefined()
|
||||
expect(r.strokePath, p).toMatch(/^M /)
|
||||
inBox(r.strokePath!, 40, 120)
|
||||
}
|
||||
})
|
||||
|
||||
it('cube/can/bevel/foldedCorner carry decorative strokePath', () => {
|
||||
for (const p of ['cube', 'can', 'bevel', 'foldedCorner', 'smileyFace', 'flowChartPredefinedProcess']) {
|
||||
const r = presetPath(p, 120, 90)!
|
||||
expect(r.path, p).toMatch(/^M /)
|
||||
expect(r.strokePath, p).toMatch(/^M /)
|
||||
inBox(r.path!, 120, 90)
|
||||
}
|
||||
})
|
||||
|
||||
it('curved/blob presets stay near box', () => {
|
||||
for (const p of [
|
||||
'heart', 'moon', 'sun', 'cloud', 'teardrop', 'plaque', 'noSmoking', 'ribbon', 'ribbon2',
|
||||
'wave', 'doubleWave', 'uturnArrow', 'curvedRightArrow', 'stripedRightArrow', 'chord', 'blockArc',
|
||||
'frame', 'round1Rect', 'round2SameRect', 'round2DiagRect', 'snipRoundRect',
|
||||
'flowChartDocument', 'flowChartMultidocument', 'flowChartConnector', 'flowChartOr',
|
||||
'flowChartSummingJunction', 'flowChartSort', 'flowChartDelay', 'flowChartDisplay',
|
||||
'flowChartPunchedTape', 'flowChartMagneticDisk', 'flowChartMagneticDrum', 'flowChartInternalStorage',
|
||||
]) {
|
||||
const r = presetPath(p, 120, 90)
|
||||
expect(r, p).toBeTruthy()
|
||||
const d = r!.path ?? r!.strokePath!
|
||||
expect(d, p).toMatch(/^M /)
|
||||
inBox(d, 120, 90)
|
||||
}
|
||||
})
|
||||
|
||||
it('callout paths include tail toward tip', () => {
|
||||
for (const p of ['wedgeRoundRectCallout', 'wedgeEllipseCallout', 'cloudCallout']) {
|
||||
const r = presetPath(p, 100, 100)!
|
||||
expect(r.path, p).toMatch(/^M /)
|
||||
// Default tip is below the box → some point has y>h
|
||||
expect(Math.max(...nums(r.path!).filter((_, i) => i % 2 === 1)), p).toBeGreaterThan(100)
|
||||
}
|
||||
})
|
||||
|
||||
it('blockArc respects inner radius adj3', () => {
|
||||
const r = presetPath('blockArc', 100, 100, { adj1: 10800000, adj2: 0, adj3: 50000 })!
|
||||
const v = nums(r.path!)
|
||||
// inner arc radius = 50-50 = 0 → all points converge within the centerline
|
||||
for (let i = 0; i < v.length; i += 2) expect(v[i + 1]!).toBeLessThanOrEqual(50.01)
|
||||
})
|
||||
|
||||
it('unknown presets return null', () => {
|
||||
expect(presetPath('rect', 100, 100)).toBeNull()
|
||||
expect(presetPath('ellipse', 100, 100)).toBeNull()
|
||||
expect(presetPath(undefined, 100, 100)).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,722 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { HeuristicMetrics, OpentypeMetrics, type OpentypeFontLike } from '../src/metrics'
|
||||
import { layoutText } from '../src/text-layout'
|
||||
import { makeViewport } from '../src/coords'
|
||||
import type { TextBody } from '@genoffice/pptx-engine'
|
||||
|
||||
const vp = makeViewport({ cx: 9525 * 1000, cy: 9525 * 1000 }, 1000) // scale 1
|
||||
|
||||
function body(partial: Partial<TextBody> & Pick<TextBody, 'paragraphs'>): TextBody {
|
||||
return {
|
||||
anchor: 'top',
|
||||
insets: { l: 0, t: 0, r: 0, b: 0 },
|
||||
autofit: 'none',
|
||||
wrap: true,
|
||||
...partial,
|
||||
}
|
||||
}
|
||||
|
||||
describe('2.3 metrics', () => {
|
||||
const m = new HeuristicMetrics()
|
||||
|
||||
it('CJK advances ~1em, latin narrower', () => {
|
||||
const style = { fontFamily: 'Arial', fontSizePx: 100, bold: false, italic: false }
|
||||
const cjk = m.measure('中文', style)
|
||||
const latin = m.measure('ab', style)
|
||||
expect(cjk).toBeCloseTo(200, 0) // 2 * 1em * 100px
|
||||
expect(latin).toBeLessThan(cjk)
|
||||
})
|
||||
|
||||
it('opentype metrics falls back to heuristic when glyph missing (CJK in latin font)', () => {
|
||||
const latinOnly: OpentypeFontLike = {
|
||||
unitsPerEm: 1000,
|
||||
ascender: 800,
|
||||
descender: -200,
|
||||
getAdvanceWidth: () => 0, // opentype gives 0/notdef width for missing glyphs
|
||||
charToGlyphIndex: (ch) => (ch.codePointAt(0)! < 0x2e80 ? 1 : 0),
|
||||
}
|
||||
const om = new OpentypeMetrics(() => latinOnly)
|
||||
const style = { fontFamily: 'Latin', fontSizePx: 100, bold: false, italic: false }
|
||||
// CJK → falls back to the heuristic (≈1em per char) instead of 0
|
||||
expect(om.measure('中文', style)).toBeCloseTo(200, 0)
|
||||
})
|
||||
|
||||
it('opentype metrics uses real font when available, else fallback', () => {
|
||||
const fakeFont: OpentypeFontLike = {
|
||||
unitsPerEm: 1000,
|
||||
ascender: 800,
|
||||
descender: -200,
|
||||
getAdvanceWidth: (t, s) => t.length * s * 0.5,
|
||||
}
|
||||
const om = new OpentypeMetrics((st) => (st.fontFamily === 'Real' ? fakeFont : undefined))
|
||||
const real = { fontFamily: 'Real', fontSizePx: 100, bold: false, italic: false }
|
||||
expect(om.measure('abcd', real)).toBeCloseTo(200, 4) // 4 * 100 * 0.5
|
||||
const met = om.metrics(real)
|
||||
expect(met.ascent).toBeCloseTo(80, 4)
|
||||
expect(met.descent).toBeCloseTo(20, 4)
|
||||
// Unknown fonts fall back to the heuristic (no throw)
|
||||
const unknown = { fontFamily: 'Nope', fontSizePx: 100, bold: false, italic: false }
|
||||
expect(om.measure('ab', unknown)).toBeGreaterThan(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('2.3 text layout', () => {
|
||||
it('single short line stays one line', () => {
|
||||
const layout = layoutText({
|
||||
body: body({ paragraphs: [{ runs: [{ text: 'Hi', fontSize: 18 }] }] }),
|
||||
boxWidthPx: 400,
|
||||
boxHeightPx: 200,
|
||||
metrics: new HeuristicMetrics(),
|
||||
vp,
|
||||
})
|
||||
expect(layout.lines.length).toBe(1)
|
||||
expect(layout.lines[0]!.runs.map((r) => r.text).join('')).toBe('Hi')
|
||||
})
|
||||
|
||||
it('wraps long text into multiple lines at word boundaries', () => {
|
||||
const long = 'word '.repeat(40).trim()
|
||||
const layout = layoutText({
|
||||
body: body({ paragraphs: [{ runs: [{ text: long, fontSize: 18 }] }] }),
|
||||
boxWidthPx: 200,
|
||||
boxHeightPx: 2000,
|
||||
metrics: new HeuristicMetrics(),
|
||||
vp,
|
||||
})
|
||||
expect(layout.lines.length).toBeGreaterThan(1)
|
||||
// No line is wider than the available width
|
||||
for (const ln of layout.lines) {
|
||||
const w = ln.runs.reduce((a, r) => a + r.widthPx, 0)
|
||||
expect(w).toBeLessThanOrEqual(200 + 1)
|
||||
}
|
||||
})
|
||||
|
||||
it('empty paragraph with a textless marker run keeps its style (line height + readback)', () => {
|
||||
const marked = layoutText({
|
||||
body: body({ paragraphs: [{ runs: [{ text: '', fontSize: 32 }] }] }),
|
||||
boxWidthPx: 400,
|
||||
boxHeightPx: 200,
|
||||
metrics: new HeuristicMetrics(),
|
||||
vp,
|
||||
})
|
||||
const plain = layoutText({
|
||||
body: body({ paragraphs: [{ runs: [] }] }),
|
||||
boxWidthPx: 400,
|
||||
boxHeightPx: 200,
|
||||
metrics: new HeuristicMetrics(),
|
||||
vp,
|
||||
})
|
||||
// The marker styles the empty line: taller than the default-styled empty paragraph,
|
||||
// and exposed as a zero-width run so the editor/ribbon can read the format back
|
||||
expect(marked.lines[0]!.height).toBeGreaterThan(plain.lines[0]!.height)
|
||||
expect(plain.lines[0]!.runs.length).toBe(0)
|
||||
const run = marked.lines[0]!.runs[0]!
|
||||
expect(run.text).toBe('')
|
||||
expect(run.widthPx).toBe(0)
|
||||
expect(run.fontSizePx).toBeCloseTo((32 * 96) / 72, 1)
|
||||
})
|
||||
|
||||
it('wrap=false keeps single line even if overflowing', () => {
|
||||
const long = 'word '.repeat(40).trim()
|
||||
const layout = layoutText({
|
||||
body: body({ wrap: false, paragraphs: [{ runs: [{ text: long, fontSize: 18 }] }] }),
|
||||
boxWidthPx: 200,
|
||||
boxHeightPx: 2000,
|
||||
metrics: new HeuristicMetrics(),
|
||||
vp,
|
||||
})
|
||||
expect(layout.lines.length).toBe(1)
|
||||
})
|
||||
|
||||
it('CJK wraps per-character', () => {
|
||||
const cjk = '中文换行测试内容比较长需要折行的一段文字'.repeat(3)
|
||||
const layout = layoutText({
|
||||
body: body({ paragraphs: [{ runs: [{ text: cjk, fontSize: 24 }] }] }),
|
||||
boxWidthPx: 150,
|
||||
boxHeightPx: 3000,
|
||||
metrics: new HeuristicMetrics(),
|
||||
vp,
|
||||
})
|
||||
expect(layout.lines.length).toBeGreaterThan(1)
|
||||
})
|
||||
|
||||
it('autofit=shrink reduces font scale when content overflows height', () => {
|
||||
const many = Array.from({ length: 30 }, (_, i) => ({
|
||||
runs: [{ text: `Line ${i} of text`, fontSize: 40 }],
|
||||
}))
|
||||
const layout = layoutText({
|
||||
body: body({ autofit: 'shrink', paragraphs: many }),
|
||||
boxWidthPx: 400,
|
||||
boxHeightPx: 200,
|
||||
metrics: new HeuristicMetrics(),
|
||||
vp,
|
||||
})
|
||||
expect(layout.fontScale).toBeLessThan(1)
|
||||
// Step floor 25%: with very heavy content, stop at 25% and allow overflow
|
||||
expect(layout.fontScale).toBeGreaterThanOrEqual(0.25)
|
||||
})
|
||||
|
||||
it('"\\n" sentinel (from <a:br/>) forces a line break even without wrap', () => {
|
||||
const layout = layoutText({
|
||||
body: body({ wrap: false, paragraphs: [{ runs: [{ text: 'A\nB', fontSize: 18 }] }] }),
|
||||
boxWidthPx: 400,
|
||||
boxHeightPx: 200,
|
||||
metrics: new HeuristicMetrics(),
|
||||
vp,
|
||||
})
|
||||
expect(layout.lines.length).toBe(2)
|
||||
expect(layout.lines[0]!.runs.map((r) => r.text).join('')).toBe('A')
|
||||
expect(layout.lines[1]!.runs.map((r) => r.text).join('')).toBe('B')
|
||||
})
|
||||
|
||||
it('lineHeight % and spaceBefore/spaceAfter affect vertical metrics', () => {
|
||||
const single = layoutText({
|
||||
body: body({ paragraphs: [{ runs: [{ text: 'x', fontSize: 20 }] }] }),
|
||||
boxWidthPx: 400,
|
||||
boxHeightPx: 400,
|
||||
metrics: new HeuristicMetrics(),
|
||||
vp,
|
||||
})
|
||||
const spaced = layoutText({
|
||||
body: body({
|
||||
paragraphs: [
|
||||
{ runs: [{ text: 'x', fontSize: 20 }], lineHeight: 200, spaceBefore: 12, spaceAfter: 6 },
|
||||
],
|
||||
}),
|
||||
boxWidthPx: 400,
|
||||
boxHeightPx: 400,
|
||||
metrics: new HeuristicMetrics(),
|
||||
vp,
|
||||
})
|
||||
expect(spaced.contentHeight).toBeGreaterThan(single.contentHeight)
|
||||
// Double line spacing + 12pt before + 6pt after
|
||||
expect(spaced.lines[0]!.top).toBeGreaterThan(0) // spaceBefore pushed the line start down
|
||||
})
|
||||
|
||||
it('align=center centers each line horizontally (baked into run x)', () => {
|
||||
const m = new HeuristicMetrics()
|
||||
const layout = layoutText({
|
||||
body: body({ paragraphs: [{ runs: [{ text: '中文', fontSize: 18 }], align: 'center' }] }),
|
||||
boxWidthPx: 400,
|
||||
boxHeightPx: 100,
|
||||
metrics: m,
|
||||
vp,
|
||||
})
|
||||
const runs = layout.lines[0]!.runs
|
||||
const lineW = runs.reduce((a, r) => a + r.widthPx, 0)
|
||||
expect(runs[0]!.x).toBeCloseTo((400 - lineW) / 2, 1)
|
||||
})
|
||||
|
||||
it('align=right flushes line to the right edge', () => {
|
||||
const layout = layoutText({
|
||||
body: body({ paragraphs: [{ runs: [{ text: 'ab', fontSize: 18 }], align: 'right' }] }),
|
||||
boxWidthPx: 400,
|
||||
boxHeightPx: 100,
|
||||
metrics: new HeuristicMetrics(),
|
||||
vp,
|
||||
})
|
||||
const runs = layout.lines[0]!.runs
|
||||
const lineW = runs.reduce((a, r) => a + r.widthPx, 0)
|
||||
expect(runs[runs.length - 1]!.x + runs[runs.length - 1]!.widthPx).toBeCloseTo(400, 1)
|
||||
expect(runs[0]!.x).toBeCloseTo(400 - lineW, 1)
|
||||
})
|
||||
|
||||
it('anchor=middle bakes vertical offset into line top/baseline', () => {
|
||||
const layout = layoutText({
|
||||
body: body({ anchor: 'middle', paragraphs: [{ runs: [{ text: 'Hi', fontSize: 18 }] }] }),
|
||||
boxWidthPx: 400,
|
||||
boxHeightPx: 200,
|
||||
metrics: new HeuristicMetrics(),
|
||||
vp,
|
||||
})
|
||||
const line = layout.lines[0]!
|
||||
const expectedTop = (200 - layout.contentHeight) / 2
|
||||
expect(line.top).toBeCloseTo(expectedTop, 1)
|
||||
expect(line.runs[0]!.baselineY).toBeGreaterThan(expectedTop)
|
||||
})
|
||||
|
||||
it('anchor=top keeps lines at top (no offset)', () => {
|
||||
const layout = layoutText({
|
||||
body: body({ anchor: 'top', paragraphs: [{ runs: [{ text: 'Hi', fontSize: 18 }] }] }),
|
||||
boxWidthPx: 400,
|
||||
boxHeightPx: 200,
|
||||
metrics: new HeuristicMetrics(),
|
||||
vp,
|
||||
})
|
||||
expect(layout.lines[0]!.top).toBe(0)
|
||||
})
|
||||
|
||||
it('preserves vertical anchor and multi-run color/bold', () => {
|
||||
const layout = layoutText({
|
||||
body: body({
|
||||
anchor: 'middle',
|
||||
paragraphs: [
|
||||
{
|
||||
runs: [
|
||||
{ text: 'A', fontSize: 18, bold: true, color: '#FF0000' },
|
||||
{ text: 'B', fontSize: 18, italic: true, color: '#00FF00' },
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
boxWidthPx: 400,
|
||||
boxHeightPx: 200,
|
||||
metrics: new HeuristicMetrics(),
|
||||
vp,
|
||||
})
|
||||
expect(layout.anchor).toBe('middle')
|
||||
const runs = layout.lines[0]!.runs
|
||||
expect(runs.find((r) => r.text === 'A')?.bold).toBe(true)
|
||||
expect(runs.find((r) => r.text === 'A')?.color).toBe('#FF0000')
|
||||
expect(runs.find((r) => r.text === 'B')?.italic).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('bullets and indentation (bullet / marL / indent)', () => {
|
||||
const m = new HeuristicMetrics()
|
||||
const run = (text: string) => ({ text, fontSize: 10, color: '#111111' })
|
||||
|
||||
it('buChar: first line prefixed with bullet glyph, body starts at marL (hanging indent)', () => {
|
||||
const lay = layoutText({
|
||||
body: body({
|
||||
paragraphs: [
|
||||
{
|
||||
runs: [run('item one')],
|
||||
bullet: { type: 'char', char: '•' },
|
||||
marL: 127000, // ≈13.3px
|
||||
indent: -127000,
|
||||
},
|
||||
],
|
||||
}),
|
||||
boxWidthPx: 400,
|
||||
boxHeightPx: 100,
|
||||
metrics: m,
|
||||
vp,
|
||||
})
|
||||
const runs = lay.lines[0]!.runs
|
||||
expect(runs[0]!.text).toBe('•')
|
||||
expect(runs[0]!.x).toBeCloseTo(0, 5) // marL+indent = 0
|
||||
const textStart = runs[1]!
|
||||
expect(textStart.x).toBeCloseTo(127000 / 9525, 1) // body line start = marL
|
||||
})
|
||||
|
||||
it('buAutoNum: consecutive paragraphs numbered 1. 2., reset after a non-numbered paragraph', () => {
|
||||
const paragraphs = [
|
||||
{ runs: [run('a')], bullet: { type: 'number' as const }, marL: 127000, indent: -127000 },
|
||||
{ runs: [run('b')], bullet: { type: 'number' as const }, marL: 127000, indent: -127000 },
|
||||
{ runs: [run('plain')] },
|
||||
{ runs: [run('c')], bullet: { type: 'number' as const }, marL: 127000, indent: -127000 },
|
||||
]
|
||||
const lay = layoutText({
|
||||
body: body({ paragraphs }),
|
||||
boxWidthPx: 400,
|
||||
boxHeightPx: 200,
|
||||
metrics: m,
|
||||
vp,
|
||||
})
|
||||
expect(lay.lines[0]!.runs[0]!.text).toBe('1.')
|
||||
expect(lay.lines[1]!.runs[0]!.text).toBe('2.')
|
||||
expect(lay.lines[2]!.runs[0]!.text).toBe('plain')
|
||||
expect(lay.lines[3]!.runs[0]!.text).toBe('1.') // reset
|
||||
})
|
||||
|
||||
it('buSzPct/buClr: bullet glyph drawn scaled and in its own color', () => {
|
||||
const lay = layoutText({
|
||||
body: body({
|
||||
paragraphs: [
|
||||
{
|
||||
runs: [run('item')],
|
||||
bullet: { type: 'char', char: '•', sizePct: 75, color: '#C00000' },
|
||||
marL: 127000,
|
||||
indent: -127000,
|
||||
},
|
||||
],
|
||||
}),
|
||||
boxWidthPx: 400,
|
||||
boxHeightPx: 100,
|
||||
metrics: m,
|
||||
vp,
|
||||
})
|
||||
const runs = lay.lines[0]!.runs
|
||||
expect(runs[0]!.text).toBe('•')
|
||||
expect(runs[0]!.color).toBe('#C00000')
|
||||
expect(runs[0]!.fontSizePx).toBeCloseTo(runs[1]!.fontSizePx * 0.75, 5)
|
||||
})
|
||||
|
||||
it('buNone/no bullet: no symbol added; positive indent applies to the first line only', () => {
|
||||
const lay = layoutText({
|
||||
body: body({
|
||||
paragraphs: [
|
||||
{
|
||||
runs: [run('中文正文换行测试中文正文换行测试中文正文换行测试')],
|
||||
bullet: { type: 'none' },
|
||||
marL: 95250, // 10px
|
||||
indent: 47625, // first line +5px
|
||||
},
|
||||
],
|
||||
}),
|
||||
boxWidthPx: 120,
|
||||
boxHeightPx: 200,
|
||||
metrics: m,
|
||||
vp,
|
||||
})
|
||||
expect(lay.lines.length).toBeGreaterThan(1)
|
||||
expect(lay.lines[0]!.runs[0]!.text).not.toBe('•')
|
||||
expect(lay.lines[0]!.runs[0]!.x).toBeCloseTo(15, 0) // marL + indent
|
||||
expect(lay.lines[1]!.runs[0]!.x).toBeCloseTo(10, 0) // marL
|
||||
})
|
||||
})
|
||||
|
||||
describe('text outline (rPr a:ln) passthrough to GlyphRun', () => {
|
||||
const m = new HeuristicMetrics()
|
||||
|
||||
it('outline color + EMU width converted to px; runs without outline omit the field', () => {
|
||||
const t = layoutText({
|
||||
body: body({
|
||||
paragraphs: [
|
||||
{
|
||||
runs: [
|
||||
{
|
||||
text: 'Art',
|
||||
fontFamily: 'Arial',
|
||||
fontSize: 40,
|
||||
outline: { color: '#FF0000', widthEmu: 12700 },
|
||||
},
|
||||
{ text: 'plain', fontFamily: 'Arial', fontSize: 40 },
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
boxWidthPx: 10000,
|
||||
boxHeightPx: 1000,
|
||||
metrics: m,
|
||||
vp,
|
||||
})
|
||||
const runs = t.lines[0]!.runs
|
||||
expect(runs[0]!.outline?.color).toBe('#FF0000')
|
||||
// 12700 EMU = 1pt, scale=1 -> 96/72 px
|
||||
expect(runs[0]!.outline?.widthPx).toBeCloseTo(96 / 72, 3)
|
||||
expect(runs[1]!.outline).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('2.3 letter-spacing (rPr spc) and substitute family for missing fonts', () => {
|
||||
const m = new HeuristicMetrics()
|
||||
|
||||
it('letterSpacing counts into run width and the next run x (appended after each character)', () => {
|
||||
// Two runs: "abcd" with 2pt letter spacing + a following "x"; the latter's x = the former's width
|
||||
const t = layoutText({
|
||||
body: body({
|
||||
paragraphs: [
|
||||
{
|
||||
runs: [
|
||||
{ text: 'abcd', fontFamily: 'Arial', fontSize: 75, letterSpacing: 2 },
|
||||
{ text: 'x', fontFamily: 'Arial', fontSize: 75 },
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
boxWidthPx: 10000,
|
||||
boxHeightPx: 1000,
|
||||
metrics: m,
|
||||
vp,
|
||||
})
|
||||
const runs = t.lines[0]!.runs
|
||||
expect(runs).toHaveLength(2)
|
||||
const plain = m.measure('abcd', {
|
||||
fontFamily: 'Arial',
|
||||
fontSizePx: 100,
|
||||
bold: false,
|
||||
italic: false,
|
||||
})
|
||||
const lsPx = (2 * 100) / 75 // 2pt → px (at scale=1, 1pt=4/3px)
|
||||
expect(runs[0]!.letterSpacingPx).toBeCloseTo(lsPx, 3)
|
||||
expect(runs[0]!.widthPx).toBeCloseTo(plain + 4 * lsPx, 3)
|
||||
expect(runs[1]!.x).toBeCloseTo(runs[0]!.x + runs[0]!.widthPx, 3)
|
||||
expect(runs[1]!.letterSpacingPx).toBeUndefined()
|
||||
})
|
||||
|
||||
it('displayFamily substitute name written into GlyphRun.fontFamily (measurement and drawing share the source)', () => {
|
||||
const withSub = {
|
||||
metrics: (s: any) => m.metrics(s),
|
||||
measure: (t: string, s: any) => m.measure(t, s),
|
||||
displayFamily: (s: any) => (s.fontFamily === 'Playfair Display' ? 'Georgia' : s.fontFamily),
|
||||
}
|
||||
const t = layoutText({
|
||||
body: body({
|
||||
paragraphs: [{ runs: [{ text: 'Hi', fontFamily: 'Playfair Display', fontSize: 20 }] }],
|
||||
}),
|
||||
boxWidthPx: 10000,
|
||||
boxHeightPx: 1000,
|
||||
metrics: withSub,
|
||||
vp,
|
||||
})
|
||||
expect(t.lines[0]!.runs[0]!.fontFamily).toBe('Georgia')
|
||||
})
|
||||
})
|
||||
|
||||
describe('spcPct paragraph spacing + justify alignment', () => {
|
||||
// Heuristic: 18pt → 24px, line height 1.2em = 28.8px
|
||||
it('spaceBeforePct=100 adds one single line height before the paragraph', () => {
|
||||
const layout = layoutText({
|
||||
body: body({
|
||||
paragraphs: [
|
||||
{ runs: [{ text: 'a', fontSize: 18 }] },
|
||||
{ runs: [{ text: 'b', fontSize: 18 }], spaceBeforePct: 100 },
|
||||
],
|
||||
}),
|
||||
boxWidthPx: 400,
|
||||
boxHeightPx: 400,
|
||||
metrics: new HeuristicMetrics(),
|
||||
vp,
|
||||
})
|
||||
expect(layout.lines[1]!.top).toBeCloseTo(28.8 + 28.8, 1)
|
||||
})
|
||||
|
||||
it('spaceAfterPct=50 appends half a single line height', () => {
|
||||
const layout = layoutText({
|
||||
body: body({
|
||||
paragraphs: [
|
||||
{ runs: [{ text: 'a', fontSize: 18 }], spaceAfterPct: 50 },
|
||||
{ runs: [{ text: 'b', fontSize: 18 }] },
|
||||
],
|
||||
}),
|
||||
boxWidthPx: 400,
|
||||
boxHeightPx: 400,
|
||||
metrics: new HeuristicMetrics(),
|
||||
vp,
|
||||
})
|
||||
expect(layout.lines[1]!.top).toBeCloseTo(28.8 + 14.4, 1)
|
||||
})
|
||||
|
||||
it('justify: wrapped lines fill the available width, the last line of a paragraph stays left-aligned', () => {
|
||||
const long = 'word '.repeat(20).trim()
|
||||
const layout = layoutText({
|
||||
body: body({ paragraphs: [{ runs: [{ text: long, fontSize: 18 }], align: 'justify' }] }),
|
||||
boxWidthPx: 200,
|
||||
boxHeightPx: 2000,
|
||||
metrics: new HeuristicMetrics(),
|
||||
vp,
|
||||
})
|
||||
expect(layout.lines.length).toBeGreaterThan(1)
|
||||
for (let i = 0; i < layout.lines.length; i++) {
|
||||
const ln = layout.lines[i]!
|
||||
const last = ln.runs[ln.runs.length - 1]!
|
||||
const per = last.justifyExtraPx ?? 0
|
||||
// Last glyph's right edge = x + width - the extra trailing letter-space
|
||||
const rightEdge = last.x + last.widthPx - per * (per ? 1 : 0)
|
||||
if (i < layout.lines.length - 1) {
|
||||
expect(per).toBeGreaterThan(0)
|
||||
expect(rightEdge).toBeCloseTo(200, 0)
|
||||
} else {
|
||||
expect(per).toBe(0)
|
||||
expect(rightEdge).toBeLessThan(200)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('justify does not affect lines ended by a soft break', () => {
|
||||
const layout = layoutText({
|
||||
body: body({
|
||||
paragraphs: [
|
||||
{
|
||||
runs: [
|
||||
{ text: 'short', fontSize: 18 },
|
||||
{ text: '\n', fontSize: 18 },
|
||||
{ text: 'more text here', fontSize: 18 },
|
||||
],
|
||||
align: 'justify',
|
||||
},
|
||||
],
|
||||
}),
|
||||
boxWidthPx: 400,
|
||||
boxHeightPx: 400,
|
||||
metrics: new HeuristicMetrics(),
|
||||
vp,
|
||||
})
|
||||
// Soft-wrapped lines are not justified
|
||||
expect(layout.lines[0]!.runs.every((r) => !r.justifyExtraPx)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('shrink discrete steps + superscript/subscript baseline', () => {
|
||||
it('shrink scale lands on a PowerPoint step (7.5% increments), lnSpcReduction follows', () => {
|
||||
const many = Array.from({ length: 8 }, (_, i) => ({
|
||||
runs: [{ text: `Row ${i}`, fontSize: 20 }],
|
||||
}))
|
||||
// 8 lines × 20pt (26.7px×1.2=32px) = 256px, box height 210 → needs ≤82% → step 0.775/0.1
|
||||
const layout = layoutText({
|
||||
body: body({ autofit: 'shrink', paragraphs: many }),
|
||||
boxWidthPx: 400,
|
||||
boxHeightPx: 210,
|
||||
metrics: new HeuristicMetrics(),
|
||||
vp,
|
||||
})
|
||||
const STEPS = [0.925, 0.85, 0.775, 0.7, 0.625, 0.55, 0.475, 0.4, 0.325, 0.25]
|
||||
expect(STEPS.some((s) => Math.abs(s - layout.fontScale) < 1e-9)).toBe(true)
|
||||
expect(layout.contentHeight).toBeLessThanOrEqual(210)
|
||||
// Step pairing: below 85% comes with line-spacing reduction
|
||||
if (layout.fontScale <= 0.85) expect(layout.lnSpcReduction).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('existing scale caps the ceiling: only steps smaller than it are used', () => {
|
||||
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,
|
||||
})
|
||||
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)
|
||||
})
|
||||
|
||||
it('superscript baseline=30 → baseline rises 30% of font size, subscript goes the other way', () => {
|
||||
const layout = layoutText({
|
||||
body: body({
|
||||
paragraphs: [
|
||||
{
|
||||
runs: [
|
||||
{ text: 'x', fontSize: 18 },
|
||||
{ text: '2', fontSize: 18, baseline: 30 },
|
||||
{ text: 'n', fontSize: 18, baseline: -25 },
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
boxWidthPx: 400,
|
||||
boxHeightPx: 200,
|
||||
metrics: new HeuristicMetrics(),
|
||||
vp,
|
||||
})
|
||||
const [base, sup, sub] = layout.lines[0]!.runs
|
||||
// 18pt = 24px; raised by 24×0.3 = 7.2px
|
||||
expect(base!.baselineY - sup!.baselineY).toBeCloseTo(7.2, 1)
|
||||
expect(sub!.baselineY - base!.baselineY).toBeCloseTo(6, 1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('vertical text (bodyPr vert) column layout', () => {
|
||||
const m = new HeuristicMetrics()
|
||||
const layoutV = (b: TextBody, w = 200, h = 300) =>
|
||||
layoutText({ body: b, boxWidthPx: w, boxHeightPx: h, metrics: m, vp })
|
||||
|
||||
it('eaVert: two CJK paragraphs → two columns, right-to-left, chars flow downward within a column, all inside the box', () => {
|
||||
const layout = layoutV(
|
||||
body({
|
||||
vert: 'eaVert',
|
||||
paragraphs: [
|
||||
{ runs: [{ text: '縦書き', fontSize: 18 }] },
|
||||
{ runs: [{ text: '二列目', fontSize: 18 }] },
|
||||
],
|
||||
}),
|
||||
)
|
||||
expect(layout.vert).toBe('eaVert')
|
||||
expect(layout.lines).toHaveLength(2)
|
||||
const [c1, c2] = layout.lines
|
||||
// One run per char per column; the second column (second paragraph) has a smaller x than the first
|
||||
expect(c1!.runs.map((r) => r.text)).toEqual(['縦', '書', 'き'])
|
||||
expect(c2!.runs[0]!.x).toBeLessThan(c1!.runs[0]!.x)
|
||||
// anchor=top → the first column starts flush with the right edge
|
||||
const right = Math.max(...c1!.runs.map((r) => r.x + r.widthPx))
|
||||
expect(right).toBeLessThanOrEqual(200)
|
||||
expect(right).toBeGreaterThan(200 - 30)
|
||||
// baselineY strictly increases within a column
|
||||
for (const col of layout.lines) {
|
||||
for (let i = 1; i < col.runs.length; i++) {
|
||||
expect(col.runs[i]!.baselineY).toBeGreaterThan(col.runs[i - 1]!.baselineY)
|
||||
}
|
||||
for (const r of col.runs) {
|
||||
expect(r.x).toBeGreaterThanOrEqual(0)
|
||||
expect(r.x + r.widthPx).toBeLessThanOrEqual(200)
|
||||
expect(r.baselineY).toBeLessThanOrEqual(300)
|
||||
}
|
||||
}
|
||||
// Paragraph identity preserved (the editor splits paragraphs by paraStart)
|
||||
expect(c1!.paraStart).toBe(true)
|
||||
expect(c2!.paraStart).toBe(true)
|
||||
})
|
||||
|
||||
it('eaVert: overflowing text wraps to new columns, continuation columns have paraStart=false and stay right-to-left', () => {
|
||||
const layout = layoutV(
|
||||
body({
|
||||
vert: 'eaVert',
|
||||
paragraphs: [{ runs: [{ text: '縦書きテスト'.repeat(5), fontSize: 18 }] }],
|
||||
}),
|
||||
300,
|
||||
100,
|
||||
)
|
||||
expect(layout.lines.length).toBeGreaterThan(1)
|
||||
expect(layout.lines[0]!.paraStart).toBe(true)
|
||||
expect(layout.lines.slice(1).every((l) => l.paraStart === false)).toBe(true)
|
||||
for (const col of layout.lines) expect(col.height).toBeLessThanOrEqual(100)
|
||||
const xs = layout.lines.map((l) => l.runs[0]!.x)
|
||||
for (let i = 1; i < xs.length; i++) expect(xs[i]!).toBeLessThan(xs[i - 1]!)
|
||||
// Text is lossless (reassembled column by column)
|
||||
expect(layout.lines.flatMap((l) => l.runs.map((r) => r.text)).join('')).toBe(
|
||||
'縦書きテスト'.repeat(5),
|
||||
)
|
||||
})
|
||||
|
||||
it('vert/vert270/wordArtVert degrade to the same column layout as eaVert (vert flag preserved)', () => {
|
||||
const mk = (vert: TextBody['vert']) =>
|
||||
layoutV(body({ vert, paragraphs: [{ runs: [{ text: '縦書', fontSize: 18 }] }] }))
|
||||
const coords = (l: ReturnType<typeof mk>) =>
|
||||
l.lines.map((ln) => ln.runs.map((r) => [r.text, r.x, r.baselineY]))
|
||||
const ea = mk('eaVert')
|
||||
for (const v of ['vert', 'vert270', 'wordArtVert'] as const) {
|
||||
const l = mk(v)
|
||||
expect(l.vert).toBe(v)
|
||||
expect(coords(l)).toEqual(coords(ea))
|
||||
}
|
||||
})
|
||||
|
||||
it('anchor acts along the text flow: bottom hugs the left, middle centers', () => {
|
||||
const paras = [{ runs: [{ text: '縦', fontSize: 18 }] }]
|
||||
const left = (a: TextBody['anchor']) =>
|
||||
Math.min(
|
||||
...layoutV(body({ vert: 'eaVert', anchor: a, paragraphs: paras })).lines[0]!.runs.map(
|
||||
(r) => r.x,
|
||||
),
|
||||
)
|
||||
const top = left('top')
|
||||
const mid = left('middle')
|
||||
const bot = left('bottom')
|
||||
expect(bot).toBeLessThan(mid)
|
||||
expect(mid).toBeLessThan(top)
|
||||
expect(bot).toBeGreaterThanOrEqual(0)
|
||||
expect(bot).toBeLessThan(6) // column width 28.8, glyph width 24 → centered offset 2.4
|
||||
})
|
||||
})
|
||||
|
||||
describe('vertical layout latin word rotation', () => {
|
||||
it('in eaVert latin words rotate 90° as whole words, CJK stays upright char by char', async () => {
|
||||
const { layoutText } = await import('../src/text-layout')
|
||||
const { HeuristicMetrics } = await import('../src/metrics')
|
||||
const { makeViewport } = await import('../src/coords')
|
||||
const vp = makeViewport({ cx: 9525 * 1000, cy: 9525 * 1000 }, 1000) // scale 1
|
||||
const out = layoutText({
|
||||
body: {
|
||||
vert: 'eaVert',
|
||||
paragraphs: [{ runs: [{ text: '縦書きABC組版' }] }],
|
||||
} as never,
|
||||
boxWidthPx: 300,
|
||||
boxHeightPx: 200,
|
||||
metrics: new HeuristicMetrics(),
|
||||
vp,
|
||||
})
|
||||
const runs = out.lines.flatMap((l) => l.runs).filter((r) => !r.isBullet)
|
||||
const rotated = runs.filter((r) => r.rotate90)
|
||||
const upright = runs.filter((r) => !r.rotate90)
|
||||
expect(rotated.length).toBe(1)
|
||||
expect(rotated[0]!.text).toBe('ABC')
|
||||
// CJK stays upright char by char
|
||||
expect(upright.map((r) => r.text).join('')).toBe('縦書き組版')
|
||||
// Rotated word anchors stay within the column (not outside the content area)
|
||||
expect(rotated[0]!.x).toBeGreaterThan(0)
|
||||
expect(rotated[0]!.x).toBeLessThanOrEqual(300)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node"],
|
||||
// Pin resolution to this repo's workspace sources (avoids stale types when node_modules links point elsewhere)
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@genoffice/pptx-engine": ["../pptx-engine/src/index.ts"],
|
||||
"@genoffice/pptx-engine/table-grid": ["../pptx-engine/src/table-grid.ts"]
|
||||
}
|
||||
},
|
||||
"include": ["src", "tests"]
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { dirname, resolve } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { defineConfig } from 'vitest/config'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
|
||||
export default defineConfig({
|
||||
// Always resolve to this repo's workspace sources (consistent with tsconfig paths)
|
||||
resolve: {
|
||||
alias: {
|
||||
// Subpath before the bare name: string aliases are prefix replacements
|
||||
'@genoffice/pptx-engine/table-grid': resolve(here, '../pptx-engine/src/table-grid.ts'),
|
||||
'@genoffice/pptx-engine': resolve(here, '../pptx-engine/src/index.ts'),
|
||||
},
|
||||
},
|
||||
test: {
|
||||
include: ['tests/**/*.test.ts'],
|
||||
},
|
||||
})
|
||||
Reference in New Issue
Block a user