Skip to content

AI-native design editor. Open-source Figma alternative.

feat(pdf): embed fonts and keep wrapped text lines in PDF export (#1220)

LarryBambelle7c5067b1ee58
diff --git a/changes/1220/added.md b/changes/1220/added.md
new file mode 100644
index 000000000..89c9e9732
--- /dev/null
+++ b/changes/1220/added.md
@@ -0,0 +1 @@
+- `export_pdf` keeps the line breaks of wrapped text, and `embed_fonts` embeds the TrueType fonts the text uses and reports any face that falls back to a standard PDF font.
diff --git a/changes/1220/fixed.md b/changes/1220/fixed.md
new file mode 100644
index 000000000..ac4904b4a
--- /dev/null
+++ b/changes/1220/fixed.md
@@ -0,0 +1,3 @@
+- `open-pencil export --node` checks the fonts of a text layer exported on its own: `--font-policy strict` and `warn` used to find no fonts to check and let a substituted face through.
+- SVG export no longer adds a space where a text changes style, such as between a regular and a bold part of a word.
+- SVG and PDF export write text in the case it is set to show (upper, lower, or title case), as the canvas draws it.
diff --git a/packages/core/src/canvas/text/shape.ts b/packages/core/src/canvas/text/shape.ts
index c2bdbb69e..e2048ecd8 100644
--- a/packages/core/src/canvas/text/shape.ts
+++ b/packages/core/src/canvas/text/shape.ts
@@ -190,29 +190,47 @@ function needsShaping(graph: SceneGraph): boolean {
return false
}
+/** How many shaping calls share each provider made for them; the last one to finish deletes it. */
+const shaperProviderUsers = new Map<TypefaceFontProvider, number>()
+
/**
- * Run a `.fig` or Figma clipboard write with text shaping. Unless the attached font provider
- * belongs to this CanvasKit, the loaded fonts are registered in one that lives for this write only.
+ * Run `use` with text shaped as the canvas lays it out. Unless the attached font provider belongs
+ * to this CanvasKit, the loaded fonts are registered in one made for shaping, which calls that
+ * overlap share and the last of them deletes.
*/
+export async function withTextShaper<T>(
+ canvasKit: CanvasKit,
+ use: (shape: (node: SceneNode) => ShapedText | null) => Promise<T>
+): Promise<T> {
+ const attached = fontManager.providerFor(canvasKit)
+ const provider = attached ?? canvasKit.TypefaceFontProvider.Make()
+ if (!attached) fontManager.attachProvider(canvasKit, provider)
+ const shared = !attached || shaperProviderUsers.has(provider)
+ if (shared) shaperProviderUsers.set(provider, (shaperProviderUsers.get(provider) ?? 0) + 1)
+ try {
+ return await use((node) => shapeText(canvasKit, provider, node))
+ } finally {
+ if (shared) {
+ const users = (shaperProviderUsers.get(provider) ?? 1) - 1
+ if (users > 0) {
+ shaperProviderUsers.set(provider, users)
+ } else {
+ shaperProviderUsers.delete(provider)
+ fontManager.detachProvider(provider)
+ provider.delete()
+ }
+ }
+ }
+}
+
+/** Run a `.fig` or Figma clipboard write with text shaping. */
export async function withFigExportRuntime<T>(
graph: SceneGraph,
ck: CanvasKit | undefined,
write: (runtime: FigNodeChangeExportRuntime) => Promise<T>
): Promise<T> {
if (!needsShaping(graph)) return write({ ...EMPTY_EXPORT_RUNTIME, textDecorations })
- const canvasKit = ck ?? (await getCanvasKit())
- const reusable = fontManager.providerFor(canvasKit)
- const provider = reusable ?? canvasKit.TypefaceFontProvider.Make()
- if (!reusable) fontManager.attachProvider(canvasKit, provider)
- try {
- return await write({
- shapeText: (node) => shapeText(canvasKit, provider, node),
- textDecorations
- })
- } finally {
- if (!reusable) {
- fontManager.detachProvider(provider)
- provider.delete()
- }
- }
+ return withTextShaper(ck ?? (await getCanvasKit()), (shapeText) =>
+ write({ shapeText, textDecorations })
+ )
}
diff --git a/packages/core/src/io/formats/pdf/export.ts b/packages/core/src/io/formats/pdf/export.ts
index 5f5c942ac..8cca1ae96 100644
--- a/packages/core/src/io/formats/pdf/export.ts
+++ b/packages/core/src/io/formats/pdf/export.ts
@@ -1,34 +1,95 @@
import type { SceneGraph } from '@open-pencil/scene-graph'
import { computeContentBounds } from '#core/io/formats/raster'
-import { renderNodesToSVG } from '#core/io/formats/svg'
+import { renderNodesToSVG, type SVGExportOptions, type SVGTextLayout } from '#core/io/formats/svg'
+
+import {
+ embeddedFontAlias,
+ planFontEmbedding,
+ registerEmbeddedFonts,
+ type PDFFontFace,
+ type PDFFontReport
+} from './fonts'
+import type { PDFPageSpec } from './plan'
export interface PDFExportOptions {
title?: string
+ /** The faces the text uses, to embed their files; without them text uses standard PDF fonts. */
+ fonts?: readonly PDFFontFace[]
+ /** Line breaks of text nodes as the editor laid them out, so paragraphs stay wrapped. */
+ textLayout?: SVGTextLayout
}
-export async function renderNodesToPDF(
+export interface PDFExportResult {
+ data: Uint8Array
+ /** The pages written, in order. Pages with nothing visible are skipped. */
+ pages: Array<{ label?: string; width: number; height: number }>
+ /** Embedded and fallback faces, when `fonts` was given. */
+ fonts?: PDFFontReport
+}
+
+interface PreparedPage {
+ spec: PDFPageSpec
+ svgElement: Element
+ width: number
+ height: number
+}
+
+type PageSVGOptions = Pick<SVGExportOptions, 'textLayout' | 'fontAlias'>
+
+function preparePage(
graph: SceneGraph,
- pageId: string,
- nodeIds: string[],
- options: PDFExportOptions = {}
-): Promise<Uint8Array | null> {
- const svg = renderNodesToSVG(graph, pageId, nodeIds, { xmlDeclaration: false })
+ spec: PDFPageSpec,
+ svgOptions: PageSVGOptions
+): PreparedPage | null {
+ const svg = renderNodesToSVG(graph, spec.pageId, spec.nodeIds, {
+ xmlDeclaration: false,
+ ...svgOptions
+ })
if (!svg) return null
- const bounds = computeContentBounds(graph, nodeIds)
+ const bounds = computeContentBounds(graph, spec.nodeIds)
if (!bounds) return null
const width = bounds.maxX - bounds.minX
const height = bounds.maxY - bounds.minY
if (width <= 0 || height <= 0) return null
+ const svgDoc = new DOMParser().parseFromString(svg, 'image/svg+xml')
+ if (svgDoc.querySelector('parsererror')) return null
+
+ return { spec, svgElement: svgDoc.documentElement, width, height }
+}
+
+const orientationOf = (page: PreparedPage) => (page.width > page.height ? 'landscape' : 'portrait')
+
+/**
+ * A PDF with one page per spec, each sized to its content. Null when no page has anything visible.
+ */
+export async function renderPagesToPDFDetailed(
+ graph: SceneGraph,
+ specs: readonly PDFPageSpec[],
+ options: PDFExportOptions = {}
+): Promise<PDFExportResult | null> {
+ const embedding = options.fonts ? planFontEmbedding(options.fonts) : null
+ const svgOptions: PageSVGOptions = {
+ textLayout: options.textLayout,
+ fontAlias: embedding ? embeddedFontAlias(embedding) : undefined
+ }
+ const preparePages = () =>
+ specs
+ .map((spec) => preparePage(graph, spec, svgOptions))
+ .filter((page): page is PreparedPage => page !== null)
+ let prepared = preparePages()
+ if (prepared.length === 0) return null
+ const first = prepared[0]
+
const [{ jsPDF }, { svg2pdf }] = await Promise.all([import('jspdf'), import('svg2pdf.js')])
const doc = new jsPDF({
- orientation: width > height ? 'landscape' : 'portrait',
+ orientation: orientationOf(first),
unit: 'pt',
- format: [width, height],
+ format: [first.width, first.height],
compress: true
})
@@ -36,15 +97,33 @@ export async function renderNodesToPDF(
doc.setProperties({ title: options.title })
}
- const parser = new DOMParser()
- const svgDoc = parser.parseFromString(svg, 'image/svg+xml')
- const svgElement = svgDoc.documentElement
+ // jsPDF reads a font file when it is registered, so a face it refuses is only known now: the
+ // pages are written again without that face's name.
+ if (embedding && !registerEmbeddedFonts(doc, embedding)) prepared = preparePages()
- const parseError = svgDoc.querySelector('parsererror')
- if (parseError) return null
+ for (const [index, page] of prepared.entries()) {
+ if (index > 0) doc.addPage([page.width, page.height], orientationOf(page))
+ await svg2pdf(page.svgElement, doc, { x: 0, y: 0, width: page.width, height: page.height })
+ }
- await svg2pdf(svgElement, doc, { x: 0, y: 0, width, height })
+ return {
+ data: new Uint8Array(doc.output('arraybuffer')),
+ pages: prepared.map((page) => ({
+ label: page.spec.label,
+ width: page.width,
+ height: page.height
+ })),
+ ...(embedding ? { fonts: embedding.report } : {})
+ }
+}
- const buffer = doc.output('arraybuffer')
- return new Uint8Array(buffer)
+/** One PDF page holding all `nodeIds`. */
+export async function renderNodesToPDF(
+ graph: SceneGraph,
+ pageId: string,
+ nodeIds: string[],
+ options: PDFExportOptions = {}
+): Promise<Uint8Array | null> {
+ const result = await renderPagesToPDFDetailed(graph, [{ pageId, nodeIds }], options)
+ return result?.data ?? null
}
diff --git a/packages/core/src/io/formats/pdf/fonts.ts b/packages/core/src/io/formats/pdf/fonts.ts
new file mode 100644
index 000000000..4ba0627e0
--- /dev/null
+++ b/packages/core/src/io/formats/pdf/fonts.ts
@@ -0,0 +1,104 @@
+import { fromUint8Array } from 'js-base64'
+
+import type { SVGFontAlias } from '#core/io/formats/svg'
+import { hasTrueTypeOutlines, isVariableFont } from '#core/text/font/variation'
+
+/**
+ * jsPDF draws text in its standard fonts and in the files registered with it, and keeps only a
+ * normal and a bold face per family. Every embedded face is therefore registered under a family
+ * name of its own, and the SVG handed to svg2pdf names the face by it.
+ */
+
+/** A face the text uses, with the file the canvas draws it from, or why there is none. */
+export interface PDFFontFace {
+ family: string
+ style: string
+ data: ArrayBuffer | null
+ /** Why there is no file, when `data` is null. */
+ missing?: string
+}
+
+/** The jsPDF calls that register a font file. */
+export interface PDFFontTarget {
+ addFileToVFS(fileName: string, data: string): unknown
+ addFont(fileName: string, family: string, style: string): unknown
+}
+
+export interface PDFFontReport {
+ /** Faces embedded in the file, such as `Inter Bold Italic`. */
+ embedded: string[]
+ /** Faces drawn in a standard PDF font instead, with the reason. */
+ fallback: Array<{ face: string; reason: string }>
+}
+
+interface EmbeddedFace {
+ alias: string
+ data: ArrayBuffer
+ label: string
+}
+
+/** The faces to embed, by family and style, and what happened to each face. */
+export interface PDFFontEmbedding {
+ faces: Map<string, EmbeddedFace>
+ report: PDFFontReport
+}
+
+const faceKey = (family: string, style: string) => `${family}\0${style}`
+
+/** Why jsPDF cannot embed a font file, or null when it can. */
+function unsupportedReason(data: ArrayBuffer): string | null {
+ if (!hasTrueTypeOutlines(data)) return 'not a TrueType font file'
+ // jsPDF would draw every weight of a variable font in its default instance.
+ if (isVariableFont(data)) return 'variable font'
+ return null
+}
+
+/** Picks the faces jsPDF can embed, each under a family name of its own. */
+export function planFontEmbedding(faces: readonly PDFFontFace[]): PDFFontEmbedding {
+ const embedding: PDFFontEmbedding = { faces: new Map(), report: { embedded: [], fallback: [] } }
+ for (const face of faces) {
+ const label = `${face.family} ${face.style}`
+ if (!face.data) {
+ embedding.report.fallback.push({
+ face: label,
+ reason: face.missing ?? 'font file not available'
+ })
+ continue
+ }
+ const reason = unsupportedReason(face.data)
+ if (reason) {
+ embedding.report.fallback.push({ face: label, reason })
+ continue
+ }
+ // jsPDF reads family names as CSS: letters and digits only keep them unambiguous.
+ const alias = `EmbeddedFont${embedding.faces.size}`
+ embedding.faces.set(faceKey(face.family, face.style), { alias, data: face.data, label })
+ }
+ return embedding
+}
+
+/** The family the SVG names each embedded face by. */
+export function embeddedFontAlias(embedding: PDFFontEmbedding): SVGFontAlias {
+ return (family, style) => embedding.faces.get(faceKey(family, style))?.alias ?? null
+}
+
+/**
+ * Registers each planned face's file with jsPDF. A face jsPDF refuses is dropped from the
+ * embedding and reported as a fallback; returns false when any was.
+ */
+export function registerEmbeddedFonts(doc: PDFFontTarget, embedding: PDFFontEmbedding): boolean {
+ let registered = true
+ for (const [key, { alias, data, label }] of embedding.faces) {
+ try {
+ doc.addFileToVFS(`${alias}.ttf`, fromUint8Array(new Uint8Array(data)))
+ doc.addFont(`${alias}.ttf`, alias, 'normal')
+ embedding.report.embedded.push(label)
+ } catch (error) {
+ embedding.faces.delete(key)
+ const reason = error instanceof Error ? error.message : String(error)
+ embedding.report.fallback.push({ face: label, reason })
+ registered = false
+ }
+ }
+ return registered
+}
diff --git a/packages/core/src/io/formats/pdf/index.ts b/packages/core/src/io/formats/pdf/index.ts
index 18398e30d..49c418e83 100644
--- a/packages/core/src/io/formats/pdf/index.ts
+++ b/packages/core/src/io/formats/pdf/index.ts
@@ -1,2 +1,5 @@
-export { renderNodesToPDF } from './export'
-export type { PDFExportOptions } from './export'
+export { renderNodesToPDF, renderPagesToPDFDetailed } from './export'
+export type { PDFExportOptions, PDFExportResult } from './export'
+export type { PDFFontFace, PDFFontReport } from './fonts'
+export { MAX_PDF_PAGES, PDF_MODES, PDFPlanError, planPDFPages } from './plan'
+export type { PDFMode, PDFPageSpec, PDFPlanInput } from './plan'
diff --git a/packages/core/src/io/formats/pdf/plan.ts b/packages/core/src/io/formats/pdf/plan.ts
new file mode 100644
index 000000000..111e40b81
--- /dev/null
+++ b/packages/core/src/io/formats/pdf/plan.ts
@@ -0,0 +1,92 @@
+import type { SceneGraph } from '@open-pencil/scene-graph'
+
+export const PDF_MODES = ['single', 'frames', 'pages'] as const
+export type PDFMode = (typeof PDF_MODES)[number]
+
+/** Most pages one PDF may hold. */
+export const MAX_PDF_PAGES = 200
+
+/** One PDF page: these nodes of this design page, sized to their bounds. */
+export interface PDFPageSpec {
+ pageId: string
+ nodeIds: string[]
+ /** Name of the frame or design page the PDF page comes from. */
+ label?: string
+}
+
+export interface PDFPlanInput {
+ mode: PDFMode
+ /** `single`: the nodes on the one PDF page. `frames`: one PDF page for each. */
+ ids?: readonly string[]
+ /** `pages`: the design pages to export, in order. */
+ pageIds?: readonly string[]
+ currentPageId: string
+}
+
+export class PDFPlanError extends Error {
+ constructor(message: string) {
+ super(message)
+ this.name = 'PDFPlanError'
+ }
+}
+
+function pageIdOfNode(graph: SceneGraph, nodeId: string): string | null {
+ let node = graph.getNode(nodeId)
+ while (node && node.type !== 'CANVAS') {
+ node = node.parentId ? graph.getNode(node.parentId) : undefined
+ }
+ return node?.id ?? null
+}
+
+function visibleChildren(graph: SceneGraph, pageId: string): string[] {
+ const page = graph.getNode(pageId)
+ if (!page) return []
+ return page.childIds.filter((id) => graph.getNode(id)?.visible !== false)
+}
+
+/**
+ * Decides which PDF pages an export makes. Pure over the scene graph, so it needs neither jsPDF
+ * nor a DOM. Throws PDFPlanError when the request names something missing or exports nothing.
+ */
+export function planPDFPages(graph: SceneGraph, input: PDFPlanInput): PDFPageSpec[] {
+ const specs: PDFPageSpec[] = []
+
+ if (input.mode === 'single') {
+ const ids = input.ids?.length ? [...input.ids] : visibleChildren(graph, input.currentPageId)
+ specs.push({ pageId: input.currentPageId, nodeIds: ids })
+ } else if (input.mode === 'frames') {
+ const ids = input.ids?.length ? [...input.ids] : visibleChildren(graph, input.currentPageId)
+ for (const id of ids) {
+ const node = graph.getNode(id)
+ if (!node) throw new PDFPlanError(`Node "${id}" not found`)
+ specs.push({
+ pageId: pageIdOfNode(graph, id) ?? input.currentPageId,
+ nodeIds: [id],
+ label: node.name
+ })
+ }
+ } else {
+ const designPages = graph.getPages()
+ const selected = input.pageIds?.length
+ ? input.pageIds.map((id) => {
+ const page = designPages.find((candidate) => candidate.id === id)
+ if (!page) throw new PDFPlanError(`Page "${id}" not found`)
+ return page
+ })
+ : designPages
+ for (const page of selected) {
+ const ids = visibleChildren(graph, page.id)
+ if (ids.length > 0) specs.push({ pageId: page.id, nodeIds: ids, label: page.name })
+ }
+ }
+
+ if (specs.every((spec) => spec.nodeIds.length === 0)) {
+ throw new PDFPlanError('No visible nodes to export')
+ }
+ if (specs.length > MAX_PDF_PAGES) {
+ throw new PDFPlanError(
+ `${specs.length} PDF pages requested, the limit is ${MAX_PDF_PAGES}. Export fewer frames or pages.`
+ )
+ }
+ return specs
+}
diff --git a/packages/core/src/io/formats/pdf/prepare.ts b/packages/core/src/io/formats/pdf/prepare.ts
new file mode 100644
index 000000000..7eb3d0e6c
--- /dev/null
+++ b/packages/core/src/io/formats/pdf/prepare.ts
@@ -0,0 +1,113 @@
+import type { ShapedTextGlyph } from '@open-pencil/fig/node-change'
+import type { SceneGraph } from '@open-pencil/scene-graph'
+
+import { withTextShaper } from '#core/canvas/text/shape'
+import { getCanvasKit } from '#core/canvaskit'
+import { populateFigPage } from '#core/io/formats/fig'
+import type { SVGCharacterEdges, SVGTextLayout } from '#core/io/formats/svg'
+import { computeAllLayouts } from '#core/layout'
+import { shownText } from '#core/text/case'
+import type { DocumentFontStatus } from '#core/text/font/status'
+import { fontManager } from '#core/text/fonts'
+import { prepareGraphFonts } from '#core/text/prepare'
+
+import type { PDFFontFace } from './fonts'
+import type { PDFPageSpec } from './plan'
+
+/**
+ * Loads every font the text of these pages draws with, as the canvas does: the faces, the
+ * characters remote fonts must cover, and the script and emoji fallbacks.
+ */
+export function preparePDFFonts(
+ graph: SceneGraph,
+ specs: readonly PDFPageSpec[]
+): Promise<DocumentFontStatus> {
+ return prepareGraphFonts(
+ graph,
+ specs.flatMap((spec) => spec.nodeIds)
+ )
+}
+
+/**
+ * Design pages other than the open one may still be unread, since `.fig` pages load on demand.
+ * Reads the pages a `pages` export asks for, or every page, so planning sees their layers.
+ */
+export function readPDFPages(graph: SceneGraph, pageIds?: readonly string[]): void {
+ // No ids, or an empty list, exports every page, as planPDFPages reads them.
+ const ids = pageIds?.length ? pageIds : graph.getPages().map((page) => page.id)
+ for (const pageId of ids) {
+ populateFigPage(graph, pageId)
+ }
+}
+
+/**
+ * Loads the fonts the text of pages read by {@link readPDFPages} needs and lays them out, since
+ * pages other than the open one have no layout yet, so every PDF page is complete.
+ */
+export async function preparePagesForPDF(
+ graph: SceneGraph,
+ specs: readonly PDFPageSpec[]
+): Promise<DocumentFontStatus> {
+ const status = await preparePDFFonts(graph, specs)
+ for (const spec of specs) computeAllLayouts(graph, spec.pageId)
+ return status
+}
+
+/** The faces the pages' text uses, with the files the canvas draws them from. */
+export function pdfFontFaces(status: DocumentFontStatus): PDFFontFace[] {
+ return status.faces.map((face) => {
+ const data =
+ face.status === 'available' ? fontManager.loadedData(face.family, face.style) : null
+ if (data) return { family: face.family, style: face.style, data }
+ const missing =
+ face.reason === 'unsupported-format' ? 'unsupported font format' : 'font file not available'
+ return { family: face.family, style: face.style, data, missing }
+ })
+}
+
+/**
+ * Runs `render` with the line breaks the canvas gives each text node (same paragraph builder and
+ * fonts), so a wrapped paragraph stays wrapped in the PDF. Without CanvasKit, `render` gets no
+ * layout and each text node is exported on one line.
+ */
+export async function withPDFTextLayout<T>(
+ render: (textLayout: SVGTextLayout | undefined) => Promise<T>
+): Promise<T> {
+ const ck = await getCanvasKit().catch(() => null)
+ if (!ck) return render(undefined)
+ return withTextShaper(ck, (shape) =>
+ render((node) => {
+ // Shaped lines are cut by character index, which the text's case must keep.
+ if (shownText(node).length !== node.text.length) return null
+ const shaped = shape(node)
+ if (!shaped?.baselines.length) return null
+ const characters = characterEdges(shaped.glyphs)
+ return shaped.baselines.map((line) => ({
+ start: line.firstCharacter,
+ end: line.endCharacter,
+ x: line.position.x,
+ y: line.position.y,
+ width: line.width,
+ characters
+ }))
+ })
+ )
+}
+
+/** The left and right edges of the glyphs each character is drawn with. */
+function characterEdges(glyphs: readonly ShapedTextGlyph[]): Map<number, SVGCharacterEdges> {
+ const edges = new Map<number, SVGCharacterEdges>()
+ for (const glyph of glyphs) {
+ if (glyph.firstCharacter === undefined) continue
+ const left = glyph.x
+ const right = glyph.x + glyph.advance
+ const known = edges.get(glyph.firstCharacter)
+ edges.set(
+ glyph.firstCharacter,
+ known
+ ? { left: Math.min(known.left, left), right: Math.max(known.right, right) }
+ : { left, right }
+ )
+ }
+ return edges
+}
diff --git a/packages/core/src/io/formats/svg/defs.ts b/packages/core/src/io/formats/svg/defs.ts
index c6cd2772f..2bb6d0296 100644
--- a/packages/core/src/io/formats/svg/defs.ts
+++ b/packages/core/src/io/formats/svg/defs.ts
@@ -22,6 +22,10 @@ import type { Color } from '@open-pencil/scene-graph/primitives'
import { svg, type SVGNode } from './node'
import { round } from './paths'
+import type { SVGTextLayout } from './text/lines'
+
+/** The family to name a font face by instead of its own, or null to keep the face. */
+export type SVGFontAlias = (family: string, style: string) => string | null
export interface SVGExportContext {
defs: SVGNode[]
@@ -32,6 +36,9 @@ export interface SVGExportContext {
idPrefix?: string
/** Paints drawn in `currentColor`, such as an icon's tinted paths, so CSS `color` sets them. */
tint?: (node: SceneNode) => readonly ('fill' | 'stroke')[]
+ /** Line breaks of text nodes; without them each text node is drawn on one line. */
+ textLayout?: SVGTextLayout
+ fontAlias?: SVGFontAlias
}
export function nextDefId(ctx: SVGExportContext, prefix: string): string {
diff --git a/packages/core/src/io/formats/svg/export.ts b/packages/core/src/io/formats/svg/export.ts
index 698def3b2..aea618485 100644
--- a/packages/core/src/io/formats/svg/export.ts
+++ b/packages/core/src/io/formats/svg/export.ts
@@ -1,6 +1,5 @@
import { lineStrokeEnds } from '@open-pencil/scene-graph/arrow-caps'
import type { RenderColorSpace } from '@open-pencil/scene-graph/color'
-import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text-direction'
import { normalizeDashPattern } from '#core/canvas/strokes'
import { fittedDashPattern } from '#core/canvas/strokes/sides'
@@ -33,17 +32,13 @@ export {
type OutlineNode
} from './paths'
-import type {
- SceneGraph,
- SceneNode,
- Fill,
- Stroke,
- CharacterStyleOverride
-} from '@open-pencil/scene-graph'
+import type { SceneGraph, SceneNode, Fill, Stroke } from '@open-pencil/scene-graph'
-import type { SVGExportContext } from './defs'
+import type { SVGExportContext, SVGFontAlias } from './defs'
import { svg, renderSVGNode } from './node'
import type { SVGNode } from './node'
+import { renderTextNode } from './text/export'
+import type { SVGTextLayout } from './text/lines'
// --- Node rendering ---
@@ -200,91 +195,6 @@ function nodeShapeElements(
}
}
-function styleOverrideToTspanAttrs(
- style: CharacterStyleOverride,
- colorSpace: 'srgb' | 'display-p3'
-): Record<string, string | number | undefined> {
- const attrs: Record<string, string | number | undefined> = {}
- if (style.fontFamily) attrs['font-family'] = style.fontFamily
- if (style.fontSize) attrs['font-size'] = style.fontSize
- if (style.fontWeight) attrs['font-weight'] = style.fontWeight
- if (style.italic) attrs['font-style'] = 'italic'
- if (style.letterSpacing) attrs['letter-spacing'] = round(style.letterSpacing)
- if (style.textDecoration === 'UNDERLINE') attrs['text-decoration'] = 'underline'
- if (style.textDecoration === 'STRIKETHROUGH') attrs['text-decoration'] = 'line-through'
- if (style.fills) {
- const visibleFill = style.fills.find((f) => f.visible && f.type === 'SOLID')
- if (visibleFill) {
- attrs.fill = formatColor(visibleFill.color, visibleFill.opacity, colorSpace)
- }
- }
- return attrs
-}
-
-function isLogicalTextEnd(node: SceneNode, direction: 'LTR' | 'RTL'): boolean {
- return (
- (direction === 'LTR' && node.textAlignHorizontal === 'RIGHT') ||
- (direction === 'RTL' && node.textAlignHorizontal === 'LEFT')
- )
-}
-
-function textAnchorForNode(
- node: SceneNode,
- direction: 'LTR' | 'RTL'
-): 'middle' | 'end' | undefined {
- if (node.textAlignHorizontal === 'CENTER') return 'middle'
- if (isLogicalTextEnd(node, direction)) return 'end'
- return undefined
-}
-
-function textXForNode(node: SceneNode, direction: 'LTR' | 'RTL'): number {
- if (node.textAlignHorizontal === 'CENTER') return round(node.width / 2)
- if (isLogicalTextEnd(node, direction)) return round(node.width)
- return 0
-}
-
-function renderTextNode(
- node: SceneNode,
- fillAttr: string | null,
- colorSpace: 'srgb' | 'display-p3'
-): SVGNode {
- const direction = resolveNodeTextDirection(node)
- const textAnchor = textAnchorForNode(node, direction)
-
- let textDecoration: 'underline' | 'line-through' | undefined
- if (node.textDecoration === 'UNDERLINE') textDecoration = 'underline'
- else if (node.textDecoration === 'STRIKETHROUGH') textDecoration = 'line-through'
-
- const attrs: Record<string, string | number | undefined> = {
- 'font-family': node.fontFamily || undefined,
- 'font-size': node.fontSize || undefined,
- 'font-weight': node.fontWeight !== 400 ? node.fontWeight : undefined,
- 'font-style': node.italic ? 'italic' : undefined,
- fill: fillAttr ?? undefined,
- direction: direction === 'RTL' ? 'rtl' : undefined,
- 'text-anchor': textAnchor,
- 'text-decoration': textDecoration,
- 'letter-spacing': node.letterSpacing ? round(node.letterSpacing) : undefined
- }
-
- const x = textXForNode(node, direction)
- const y = node.fontSize || 14
-
- if (node.styleRuns.length > 0) {
- const spans: SVGNode[] = []
- let pos = 0
- for (const run of node.styleRuns) {
- const text = node.text.slice(pos, pos + run.length)
- pos += run.length
- spans.push(svg('tspan', styleOverrideToTspanAttrs(run.style, colorSpace), text))
- }
-
- return svg('text', { x, y, ...attrs }, ...spans)
- }
-
- return svg('text', { x, y, ...attrs }, node.text)
-}
-
// --- Main recursive renderer ---
function buildTransformAttr(node: SceneNode): string | undefined {
@@ -424,7 +334,7 @@ function renderNode(node: SceneNode, ctx: SVGExportContext): SVGNode | null {
if (node.type === 'TEXT') {
const firstFill = node.fills.find((f) => f.visible)
const fillAttr = firstFill ? resolveFill(firstFill, node, ctx) : null
- const textEl = renderTextNode(node, fillAttr, ctx.colorSpace)
+ const textEl = renderTextNode(node, fillAttr, ctx)
return svg('g', groupAttrs, textEl)
}
@@ -488,6 +398,16 @@ export interface SVGExportOptions {
xmlDeclaration?: boolean
/** Target export color space (default: srgb) */
colorSpace?: 'srgb' | 'display-p3'
+ /**
+ * Line breaks of text nodes as the editor laid them out. Without them each text node is one
+ * line of SVG text, which renderers that do not wrap SVG text (such as PDF) keep on one line.
+ */
+ textLayout?: SVGTextLayout
+ /**
+ * A family to name a font face by instead of its own, such as the one a PDF embeds the face's
+ * file under. Text in an aliased face is written in that family at normal weight and style.
+ */
+ fontAlias?: SVGFontAlias
}
export function renderNodesToSVG(
@@ -507,7 +427,9 @@ export function renderNodesToSVG(
defs: [],
defIdCounter: 0,
graph,
- colorSpace: options.colorSpace ?? 'srgb'
+ colorSpace: options.colorSpace ?? 'srgb',
+ textLayout: options.textLayout,
+ fontAlias: options.fontAlias
}
const contentNodes: SVGNode[] = []
diff --git a/packages/core/src/io/formats/svg/import.ts b/packages/core/src/io/formats/svg/import.ts
index 79951ea9c..51be9917e 100644
--- a/packages/core/src/io/formats/svg/import.ts
+++ b/packages/core/src/io/formats/svg/import.ts
@@ -21,7 +21,7 @@ import {
import { parseSVGDocument } from './document'
import { parseSVGSize, svgRootId } from './metadata'
-import { createSVGText } from './text'
+import { createSVGText } from './text/import'
export type SVGImportData = SVGVectorizeResult &
Size & {
diff --git a/packages/core/src/io/formats/svg/index.ts b/packages/core/src/io/formats/svg/index.ts
index 3311a7f7b..9fd26ce26 100644
--- a/packages/core/src/io/formats/svg/index.ts
+++ b/packages/core/src/io/formats/svg/index.ts
@@ -1,5 +1,6 @@
export {
renderNodesToSVG,
+ type SVGExportOptions,
geometryBlobToSVGPath,
nodeOutlinePath,
vectorNetworkToSVGPaths,
@@ -13,4 +14,6 @@ export {
type SVGImportOptions
} from './import'
export { isSVGMarkup } from './metadata'
-export { svgImportFonts } from './text'
+export type { SVGFontAlias } from './defs'
+export type { SVGCharacterEdges, SVGTextLayout, SVGTextLine } from './text/lines'
+export { svgImportFonts } from './text/import'
diff --git a/packages/core/src/io/formats/svg/node.ts b/packages/core/src/io/formats/svg/node.ts
index aeaf013b1..3a4d71f6b 100644
--- a/packages/core/src/io/formats/svg/node.ts
+++ b/packages/core/src/io/formats/svg/node.ts
@@ -36,6 +36,9 @@ function renderAttrs(attrs: Record<string, string | number>): string {
return parts.length > 0 ? ' ' + parts.join(' ') : ''
}
+/** Elements whose whitespace is text: indenting their children would draw it as spaces. */
+const TEXT_CONTENT_TAGS = new Set(['text', 'tspan', 'textPath'])
+
export function renderSVGNode(node: SVGNode, indent = 0): string {
const pad = ' '.repeat(indent)
const attrsStr = renderAttrs(node.attrs)
@@ -44,6 +47,13 @@ export function renderSVGNode(node: SVGNode, indent = 0): string {
return `${pad}<${node.tag}${attrsStr}/>`
}
+ if (TEXT_CONTENT_TAGS.has(node.tag)) {
+ const content = node.children
+ .map((child) => (typeof child === 'string' ? escapeText(child) : renderSVGNode(child)))
+ .join('')
+ return `${pad}<${node.tag}${attrsStr}>${content}</${node.tag}>`
+ }
+
const hasOnlyText = node.children.length === 1 && typeof node.children[0] === 'string'
if (hasOnlyText) {
return `${pad}<${node.tag}${attrsStr}>${escapeText(node.children[0] as string)}</${node.tag}>`
diff --git a/packages/core/src/io/formats/svg/text/export.ts b/packages/core/src/io/formats/svg/text/export.ts
new file mode 100644
index 000000000..5dd2fc43b
--- /dev/null
+++ b/packages/core/src/io/formats/svg/text/export.ts
@@ -0,0 +1,129 @@
+import type { CharacterStyleOverride, SceneNode } from '@open-pencil/scene-graph'
+import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text-direction'
+
+import { formatColor, type SVGExportContext, type SVGFontAlias } from '#core/io/formats/svg/defs'
+import { svg, type SVGNode } from '#core/io/formats/svg/node'
+import { round } from '#core/io/formats/svg/paths'
+import { laidOutTextSpans } from '#core/io/formats/svg/text/lines'
+import { shownText, shownTextSlice } from '#core/text/case'
+import type { FontFaceRef } from '#core/text/face'
+import { textFontFace } from '#core/text/requirements'
+
+function styleOverrideToTspanAttrs(
+ style: CharacterStyleOverride,
+ colorSpace: 'srgb' | 'display-p3'
+): Record<string, string | number | undefined> {
+ const attrs: Record<string, string | number | undefined> = {}
+ if (style.fontFamily) attrs['font-family'] = style.fontFamily
+ if (style.fontSize) attrs['font-size'] = style.fontSize
+ if (style.fontWeight) attrs['font-weight'] = style.fontWeight
+ if (style.italic) attrs['font-style'] = 'italic'
+ if (style.letterSpacing) attrs['letter-spacing'] = round(style.letterSpacing)
+ if (style.textDecoration === 'UNDERLINE') attrs['text-decoration'] = 'underline'
+ if (style.textDecoration === 'STRIKETHROUGH') attrs['text-decoration'] = 'line-through'
+ if (style.fills) {
+ const visibleFill = style.fills.find((f) => f.visible && f.type === 'SOLID')
+ if (visibleFill) {
+ attrs.fill = formatColor(visibleFill.color, visibleFill.opacity, colorSpace)
+ }
+ }
+ return attrs
+}
+
+/**
+ * Font attributes naming a face's alias, such as the family a PDF embeds its file under, or else
+ * the face itself, so text inside an aliased parent does not inherit the alias.
+ */
+function aliasedFontAttrs(
+ face: FontFaceRef,
+ fontAlias: SVGFontAlias
+): Record<string, string | number> {
+ const alias = fontAlias(face.family, face.style)
+ if (alias) return { 'font-family': alias, 'font-weight': 'normal', 'font-style': 'normal' }
+ return {
+ 'font-family': face.family,
+ 'font-weight': face.weight,
+ 'font-style': face.italic ? 'italic' : 'normal'
+ }
+}
+
+function isLogicalTextEnd(node: SceneNode, direction: 'LTR' | 'RTL'): boolean {
+ return (
+ (direction === 'LTR' && node.textAlignHorizontal === 'RIGHT') ||
+ (direction === 'RTL' && node.textAlignHorizontal === 'LEFT')
+ )
+}
+
+function textAnchorForNode(
+ node: SceneNode,
+ direction: 'LTR' | 'RTL'
+): 'middle' | 'end' | undefined {
+ if (node.textAlignHorizontal === 'CENTER') return 'middle'
+ if (isLogicalTextEnd(node, direction)) return 'end'
+ return undefined
+}
+
+function textXForNode(node: SceneNode, direction: 'LTR' | 'RTL'): number {
+ if (node.textAlignHorizontal === 'CENTER') return round(node.width / 2)
+ if (isLogicalTextEnd(node, direction)) return round(node.width)
+ return 0
+}
+
+export function renderTextNode(
+ node: SceneNode,
+ fillAttr: string | null,
+ ctx: SVGExportContext
+): SVGNode {
+ const { colorSpace, textLayout, fontAlias } = ctx
+ const direction = resolveNodeTextDirection(node)
+ const lines = textLayout ? textLayout(node) : null
+ const laidOut = lines && lines.length > 0 ? lines : null
+
+ let textDecoration: 'underline' | 'line-through' | undefined
+ if (node.textDecoration === 'UNDERLINE') textDecoration = 'underline'
+ else if (node.textDecoration === 'STRIKETHROUGH') textDecoration = 'line-through'
+
+ const attrs: Record<string, string | number | undefined> = {
+ 'font-family': node.fontFamily || undefined,
+ 'font-size': node.fontSize || undefined,
+ 'font-weight': node.fontWeight !== 400 ? node.fontWeight : undefined,
+ 'font-style': node.italic ? 'italic' : undefined,
+ fill: fillAttr ?? undefined,
+ // Laid-out spans each start at their own left edge, so they take no direction or anchor.
+ direction: direction === 'RTL' && !laidOut ? 'rtl' : undefined,
+ 'text-anchor': laidOut ? undefined : textAnchorForNode(node, direction),
+ 'text-decoration': textDecoration,
+ 'letter-spacing': node.letterSpacing ? round(node.letterSpacing) : undefined,
+ ...(fontAlias ? aliasedFontAttrs(textFontFace(node), fontAlias) : {})
+ }
+ const spanAttrs = (style: CharacterStyleOverride) => ({
+ ...styleOverrideToTspanAttrs(style, colorSpace),
+ ...(fontAlias ? aliasedFontAttrs(textFontFace(node, style), fontAlias) : {})
+ })
+
+ if (laidOut) {
+ // Laid-out spans sit where the editor draws them, which keeps every space it draws.
+ return svg(
+ 'text',
+ { ...attrs, 'xml:space': 'preserve' },
+ ...laidOutTextSpans(node, laidOut, spanAttrs)
+ )
+ }
+
+ const x = textXForNode(node, direction)
+ const y = node.fontSize || 14
+
+ if (node.styleRuns.length > 0) {
+ const spans: SVGNode[] = []
+ let pos = 0
+ for (const run of node.styleRuns) {
+ const text = shownTextSlice(node, pos, pos + run.length)
+ pos += run.length
+ spans.push(svg('tspan', spanAttrs(run.style), text))
+ }
+
+ return svg('text', { x, y, ...attrs }, ...spans)
+ }
+
+ return svg('text', { x, y, ...attrs }, shownText(node))
+}
diff --git a/packages/core/src/io/formats/svg/text.ts b/packages/core/src/io/formats/svg/text/import.ts
similarity index 100%
rename from packages/core/src/io/formats/svg/text.ts
rename to packages/core/src/io/formats/svg/text/import.ts
diff --git a/packages/core/src/io/formats/svg/text/lines.ts b/packages/core/src/io/formats/svg/text/lines.ts
new file mode 100644
index 000000000..dda7c1448
--- /dev/null
+++ b/packages/core/src/io/formats/svg/text/lines.ts
@@ -0,0 +1,107 @@
+import type { CharacterStyleOverride, SceneNode } from '@open-pencil/scene-graph'
+
+import { svg, type SVGNode } from '#core/io/formats/svg/node'
+import { round } from '#core/io/formats/svg/paths'
+import { shownTextSlice } from '#core/text/case'
+
+/**
+ * One line of a text node as the editor laid it out: the characters of `node.text` it holds
+ * (`end` is exclusive and may include the newline that ends the line) and where its baseline
+ * starts, in the node's own coordinates.
+ */
+export interface SVGTextLine {
+ start: number
+ end: number
+ x: number
+ y: number
+ width: number
+ /**
+ * Where the characters are drawn, by index in `node.text`: the left and right edges of their
+ * glyphs in the node. With them every span is placed where the editor draws it, instead of
+ * after the span before it, which a renderer measures in fonts of its own.
+ */
+ characters?: ReadonlyMap<number, SVGCharacterEdges>
+}
+
+export interface SVGCharacterEdges {
+ left: number
+ right: number
+}
+
+/** The lines of a text node from the host's text layout, or null to keep the text on one line. */
+export type SVGTextLayout = (node: SceneNode) => readonly SVGTextLine[] | null
+
+type SpanAttrs = (style: CharacterStyleOverride) => Record<string, string | number | undefined>
+
+interface TextPiece {
+ from: number
+ to: number
+ style: CharacterStyleOverride | null
+}
+
+/** The text cut at its style runs; characters no run covers keep the node's own style. */
+function textPieces(node: SceneNode): TextPiece[] {
+ const pieces: TextPiece[] = []
+ let cursor = 0
+ for (const run of node.styleRuns.toSorted((a, b) => a.start - b.start)) {
+ if (run.start > cursor) pieces.push({ from: cursor, to: run.start, style: null })
+ const from = Math.max(cursor, run.start)
+ const to = Math.min(run.start + run.length, node.text.length)
+ if (to > from) pieces.push({ from, to, style: run.style })
+ cursor = Math.max(cursor, to)
+ }
+ if (cursor < node.text.length) pieces.push({ from: cursor, to: node.text.length, style: null })
+ return pieces
+}
+
+/** The left and right edges of the characters from `from` to `to` that have glyphs. */
+function spanEdges(line: SVGTextLine, from: number, to: number): SVGCharacterEdges | null {
+ let left = Infinity
+ let right = -Infinity
+ for (let index = from; index < to; index++) {
+ const edges = line.characters?.get(index)
+ if (!edges) continue
+ left = Math.min(left, edges.left)
+ right = Math.max(right, edges.right)
+ }
+ return left <= right ? { left, right } : null
+}
+
+function lineSpans(
+ node: SceneNode,
+ pieces: readonly TextPiece[],
+ line: SVGTextLine,
+ spanAttrs: SpanAttrs
+): SVGNode[] {
+ // The newline that ends a line is not drawn.
+ const end = node.text[line.end - 1] === '\n' ? line.end - 1 : line.end
+ const y = round(line.y)
+ const spans: SVGNode[] = []
+ for (const piece of pieces) {
+ const from = Math.max(piece.from, line.start)
+ const to = Math.min(piece.to, end)
+ if (to <= from) continue
+ const attrs = piece.style ? spanAttrs(piece.style) : {}
+ // Every span starts at its left edge, in either direction, since renderers disagree on
+ // which side `text-anchor` and `direction` place. Without character edges the first span of
+ // a line starts at the line's left edge, and the rest follow on from it.
+ const left = spanEdges(line, from, to)?.left ?? (spans.length === 0 ? line.x : null)
+ const position = left === null ? {} : { x: round(left), y }
+ spans.push(svg('tspan', { ...position, ...attrs }, shownTextSlice(node, from, to)))
+ }
+ return spans
+}
+
+/**
+ * One `tspan` per style run on each laid-out line, the first of a line at its own baseline, so a
+ * wrapped paragraph keeps the editor's line breaks in renderers that do not wrap SVG text. Each
+ * span holds its characters in the case they are shown in.
+ */
+export function laidOutTextSpans(
+ node: SceneNode,
+ lines: readonly SVGTextLine[],
+ spanAttrs: SpanAttrs
+): SVGNode[] {
+ const pieces = textPieces(node)
+ return lines.flatMap((line) => lineSpans(node, pieces, line, spanAttrs))
+}
diff --git a/packages/core/src/text/font/status.ts b/packages/core/src/text/font/status.ts
index 276dd54b4..e4bd842cd 100644
--- a/packages/core/src/text/font/status.ts
+++ b/packages/core/src/text/font/status.ts
@@ -36,10 +36,14 @@ function faceKey(family: string, style: string): string {
return `${family}\0${style}`
}
+/** The text nodes under each root, and each root that is itself text. */
function rootTextNodes(graph: SceneGraph, rootIds: readonly string[]): SceneNode[] {
- return rootIds.flatMap((rootId) =>
- graph.flattenTree(rootId).flatMap(({ node }) => (node.type === 'TEXT' ? [node] : []))
- )
+ return rootIds.flatMap((rootId) => {
+ const root = graph.getNode(rootId)
+ if (!root) return []
+ const nodes = [root, ...graph.flattenTree(rootId).map(({ node }) => node)]
+ return nodes.filter((node) => node.type === 'TEXT')
+ })
}
function collectFaceUses(graph: SceneGraph, rootIds: readonly string[]): MutableFontFaceUse[] {
diff --git a/packages/core/src/text/font/variation.ts b/packages/core/src/text/font/variation.ts
index b1d0b7d2e..3b0afd855 100644
--- a/packages/core/src/text/font/variation.ts
+++ b/packages/core/src/text/font/variation.ts
@@ -34,6 +34,14 @@ export function isVariableFont(data: ArrayBuffer): boolean {
return sfntTable(new DataView(data), 'fvar') !== null
}
+/** The sfnt versions of a font with TrueType outlines: 1.0, and Apple's `true`. */
+const TRUETYPE_VERSIONS = new Set([0x00010000, 0x74727565])
+
+/** Whether the file is a single font with TrueType outlines, not CFF (`OTTO`), WOFF, or a collection. */
+export function hasTrueTypeOutlines(data: ArrayBuffer): boolean {
+ return data.byteLength >= 12 && TRUETYPE_VERSIONS.has(new DataView(data).getUint32(0))
+}
+
function fixed(view: DataView, offset: number): number {
return view.getInt32(offset) / 65536
}
diff --git a/packages/core/src/text/requirements.ts b/packages/core/src/text/requirements.ts
index bd771b51a..db4c8cf1e 100644
--- a/packages/core/src/text/requirements.ts
+++ b/packages/core/src/text/requirements.ts
@@ -1,25 +1,32 @@
-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import { uniqBy } from 'es-toolkit/array'
+
+import type { CharacterStyleOverride, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { DEFAULT_FONT_FAMILY } from '#core/constants'
import { shownCharacters } from '#core/text/case'
+import type { FontFaceRef } from '#core/text/face'
import { cjkFallbackScriptForLanguage, type FontFallbackScript } from '#core/text/fallbacks'
import { weightToStyle } from '#core/text/font/style'
+/** The face a text draws in, or the face a style run over it draws in. */
+export function textFontFace(node: SceneNode, style: CharacterStyleOverride = {}): FontFaceRef {
+ const weight = style.fontWeight ?? (node.fontWeight || 400)
+ const italic = style.italic ?? node.italic
+ return {
+ family: style.fontFamily ?? (node.fontFamily || DEFAULT_FONT_FAMILY),
+ style: weightToStyle(weight, italic),
+ weight,
+ italic
+ }
+}
+
export function collectNodeFontFaces(node: SceneNode): Array<{ family: string; style: string }> {
if (node.type !== 'TEXT') return []
- const family = node.fontFamily || DEFAULT_FONT_FAMILY
- const faces = new Map<string, { family: string; style: string }>()
- const add = (faceFamily: string, style: string) => {
- faces.set(`${faceFamily}\0${style}`, { family: faceFamily, style })
- }
- add(family, weightToStyle(node.fontWeight || 400, node.italic))
- for (const run of node.styleRuns) {
- const runFamily = run.style.fontFamily ?? family
- const weight = run.style.fontWeight ?? node.fontWeight
- const italic = run.style.italic ?? node.italic
- add(runFamily, weightToStyle(weight, italic))
- }
- return [...faces.values()]
+ const faces = [textFontFace(node), ...node.styleRuns.map((run) => textFontFace(node, run.style))]
+ return uniqBy(faces, (face) => `${face.family}\0${face.style}`).map(({ family, style }) => ({
+ family,
+ style
+ }))
}
export function collectGraphFontKeys(
diff --git a/packages/core/src/tools/vector/export.ts b/packages/core/src/tools/vector/export.ts
index 90b16f58e..68ea7f684 100644
--- a/packages/core/src/tools/vector/export.ts
+++ b/packages/core/src/tools/vector/export.ts
@@ -1,6 +1,7 @@
import { fromUint8Array } from 'js-base64'
import * as v from 'valibot'
+import { PDF_MODES, PDFPlanError, planPDFPages } from '#core/io/formats/pdf/plan'
import type { RasterExportFormat } from '#core/io/formats/raster'
import { toolNumber } from '#core/tools/input'
import { defineTool } from '#core/tools/schema'
@@ -84,19 +85,77 @@ export const exportSVG = defineTool({
export const exportPDF = defineTool({
name: 'export_pdf',
description:
- 'Export nodes as a vector PDF document. Text remains selectable, paths stay sharp at any zoom. Returns base64-encoded PDF data.',
+ 'Export nodes as a vector PDF document. Text remains selectable and keeps its line breaks, paths stay sharp at any zoom. Returns base64-encoded PDF data and the size of each PDF page. ' +
+ 'mode "single" (default) puts all ids on one PDF page; "frames" makes one PDF page per id (or per top-level frame of the current page); "pages" makes one PDF page per design page (all pages, or page_ids). ' +
+ 'embed_fonts embeds the TrueType file of each font face the text uses and reports which faces were embedded and which fell back to a standard PDF font.',
execution: { kind: 'async', mutation: 'none' },
exposure: { webmcp: false },
- input: v.strictObject({ ...exportInputs }),
+ input: v.strictObject({
+ ...exportInputs,
+ mode: v.optional(
+ v.pipe(
+ v.picklist(PDF_MODES),
+ v.description(
+ '"single" (default): one PDF page for all ids. "frames": one PDF page per id or top-level frame. "pages": one PDF page per design page.'
+ )
+ ),
+ 'single'
+ ),
+ page_ids: v.optional(
+ v.pipe(
+ v.array(v.string()),
+ v.description('mode "pages": the design pages to export, in order (default: all pages)')
+ )
+ ),
+ embed_fonts: v.optional(
+ v.pipe(
+ v.boolean(),
+ v.description(
+ 'Embed the fonts the text uses (default false: standard PDF fonts). Makes the file larger.'
+ )
+ ),
+ false
+ )
+ }),
execute: async (figma, args) => {
- const { renderNodesToPDF } = await import('#core/io/formats/pdf')
- const pageId = figma.currentPageId
- const ids =
- args.ids && args.ids.length > 0 ? args.ids : figma.currentPage.children.map((node) => node.id)
- const data = await renderNodesToPDF(figma.graph, pageId, ids)
- if (!data || data.length === 0) return { error: 'No visible nodes to export' }
- const base64 = fromUint8Array(data)
- return { mimeType: 'application/pdf', base64, byteLength: data.length }
+ const [{ renderPagesToPDFDetailed }, pdfPrepare] = await Promise.all([
+ import('#core/io/formats/pdf'),
+ import('#core/io/formats/pdf/prepare')
+ ])
+ try {
+ if (args.mode === 'pages') pdfPrepare.readPDFPages(figma.graph, args.page_ids)
+ const specs = planPDFPages(figma.graph, {
+ mode: args.mode,
+ ids: args.ids,
+ pageIds: args.page_ids,
+ currentPageId: figma.currentPageId
+ })
+ const fontStatus =
+ args.mode === 'pages'
+ ? await pdfPrepare.preparePagesForPDF(figma.graph, specs)
+ : await pdfPrepare.preparePDFFonts(figma.graph, specs)
+ const fonts = args.embed_fonts ? pdfPrepare.pdfFontFaces(fontStatus) : undefined
+ const result = await pdfPrepare.withPDFTextLayout((textLayout) =>
+ renderPagesToPDFDetailed(figma.graph, specs, { fonts, textLayout })
+ )
+ if (!result || result.data.length === 0) return { error: 'No visible nodes to export' }
+ return {
+ mimeType: 'application/pdf',
+ base64: fromUint8Array(result.data),
+ byteLength: result.data.length,
+ pageCount: result.pages.length,
+ pages: result.pages.map((page, index) => ({
+ page: index + 1,
+ ...(page.label ? { name: page.label } : {}),
+ width: Math.round(page.width),
+ height: Math.round(page.height)
+ })),
+ ...(result.fonts ? { fonts: result.fonts } : {})
+ }
+ } catch (error) {
+ if (error instanceof PDFPlanError) return { error: error.message }
+ throw error
+ }
}
})
diff --git a/packages/core/tests/canvas/text/shape.test.ts b/packages/core/tests/canvas/text/shape.test.ts
index eaf386719..9cad68d1d 100644
--- a/packages/core/tests/canvas/text/shape.test.ts
+++ b/packages/core/tests/canvas/text/shape.test.ts
@@ -1,15 +1,15 @@
import { beforeAll, describe, expect, test } from 'bun:test'
-
import { join } from 'node:path'
import { expectDefined } from '#core-tests/helpers/assert'
import { FIXTURES } from '#core-tests/helpers/paths'
+import type { TypefaceFontProvider } from 'canvaskit-wasm'
import type { ShapedText } from '@open-pencil/fig/node-change'
import { SceneGraph } from '@open-pencil/scene-graph'
import type { SceneNode } from '@open-pencil/scene-graph'
-import { withFigExportRuntime } from '#core/canvas/text/shape'
+import { withFigExportRuntime, withTextShaper } from '#core/canvas/text/shape'
import { getCanvasKit } from '#core/canvaskit'
import { EMOJI_METRICS_FAMILY } from '#core/text/emoji'
import { fontManager } from '#core/text/fonts'
@@ -371,3 +371,41 @@ describe('text shaping for saved glyphs', () => {
expect(width(bold)).toBeGreaterThan(width(regular) * 1.2)
})
})
+
+test('overlapping shaping calls share their provider until the last one finishes', async () => {
+ const ck = await getCanvasKit()
+ // Providers other tests left attached are set aside, so the calls make one of their own.
+ const setAside: TypefaceFontProvider[] = []
+ for (
+ let provider = fontManager.providerFor(ck);
+ provider;
+ provider = fontManager.providerFor(ck)
+ ) {
+ setAside.push(provider)
+ fontManager.detachProvider(provider)
+ }
+ try {
+ const graph = new SceneGraph()
+ const node = graph.createNode('TEXT', graph.getPages()[0].id, {
+ text: 'Shaped',
+ fontFamily: 'Inter',
+ fontSize: 13
+ })
+ const firstHeld = Promise.withResolvers<undefined>()
+ const secondHeld = Promise.withResolvers<undefined>()
+
+ const first = withTextShaper(ck, () => firstHeld.promise)
+ const second = withTextShaper(ck, async (shape) => {
+ await secondHeld.promise
+ return shape(node)
+ })
+ firstHeld.resolve(undefined)
+ await first
+ secondHeld.resolve(undefined)
+
+ expect((await second)?.baselines).toHaveLength(1)
+ expect(fontManager.providerFor(ck)).toBeNull()
+ } finally {
+ for (const provider of setAside.toReversed()) fontManager.attachProvider(ck, provider)
+ }
+})
diff --git a/packages/core/tests/io/formats/pdf/fonts.test.ts b/packages/core/tests/io/formats/pdf/fonts.test.ts
new file mode 100644
index 000000000..1168c4f88
--- /dev/null
+++ b/packages/core/tests/io/formats/pdf/fonts.test.ts
@@ -0,0 +1,104 @@
+import { beforeAll, describe, expect, test } from 'bun:test'
+import { readFile } from 'node:fs/promises'
+import { join } from 'node:path'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+import { FIXTURES } from '#core-tests/helpers/paths'
+
+import {
+ embeddedFontAlias,
+ planFontEmbedding,
+ registerEmbeddedFonts,
+ type PDFFontTarget
+} from '#core/io/formats/pdf/fonts'
+import { fontManager } from '#core/text/fonts'
+
+/** Records what jsPDF would be asked to register. */
+function pdfDoc() {
+ const fonts: Array<{ file: string; family: string; style: string }> = []
+ const files = new Map<string, string>()
+ const doc: PDFFontTarget = {
+ addFileToVFS: (file, data) => files.set(file, data),
+ addFont: (file, family, style) => fonts.push({ file, family, style })
+ }
+ return { doc, fonts, files }
+}
+
+const fixture = async (name: string) => {
+ const data = await readFile(join(FIXTURES, 'fonts', name))
+ return data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength)
+}
+
+let inter: ArrayBuffer
+let interVariable: ArrayBuffer
+let cff: ArrayBuffer
+
+beforeAll(async () => {
+ inter = expectDefined(await fontManager.fetchBundledFont('/Inter-Regular.ttf'), 'Inter')
+ interVariable = await fixture('InterVariable-Latin.ttf')
+ cff = await fixture('NotoSansCJK-Test.otf')
+})
+
+describe('PDF font embedding', () => {
+ test('registers each face under a family name of its own', () => {
+ const { doc, fonts, files } = pdfDoc()
+ const embedding = planFontEmbedding([
+ { family: 'Inter', style: 'Regular', data: inter },
+ { family: 'Inter', style: 'Bold', data: inter }
+ ])
+ const alias = embeddedFontAlias(embedding)
+
+ expect(registerEmbeddedFonts(doc, embedding)).toBe(true)
+ expect(embedding.report).toEqual({ embedded: ['Inter Regular', 'Inter Bold'], fallback: [] })
+ expect(files.size).toBe(2)
+ expect(fonts.every((font) => font.style === 'normal')).toBe(true)
+ const regular = expectDefined(alias('Inter', 'Regular'), 'Regular alias')
+ const bold = expectDefined(alias('Inter', 'Bold'), 'Bold alias')
+ expect(regular).toMatch(/^[A-Za-z0-9]+$/)
+ expect(bold).not.toBe(regular)
+ expect(fonts.map((font) => font.family)).toEqual([regular, bold])
+ expect(alias('Inter', 'Italic')).toBeNull()
+ })
+
+ test('falls back to a standard font when a face cannot be embedded, and says why', () => {
+ const { doc, fonts } = pdfDoc()
+ const embedding = planFontEmbedding([
+ { family: 'Missing', style: 'Italic', data: null },
+ { family: 'Unsupported', style: 'Regular', data: null, missing: 'unsupported font format' },
+ { family: 'Variable', style: 'Italic', data: interVariable },
+ { family: 'Cff', style: 'Italic', data: cff }
+ ])
+
+ expect(registerEmbeddedFonts(doc, embedding)).toBe(true)
+ expect(fonts).toEqual([])
+ expect(embedding.report).toEqual({
+ embedded: [],
+ fallback: [
+ { face: 'Missing Italic', reason: 'font file not available' },
+ { face: 'Unsupported Regular', reason: 'unsupported font format' },
+ { face: 'Variable Italic', reason: 'variable font' },
+ { face: 'Cff Italic', reason: 'not a TrueType font file' }
+ ]
+ })
+ expect(embeddedFontAlias(embedding)('Variable', 'Italic')).toBeNull()
+ })
+
+ test('a face jsPDF rejects is dropped and reported as a fallback', () => {
+ const doc: PDFFontTarget = {
+ addFileToVFS: () => undefined,
+ addFont: () => {
+ throw new Error('Unsupported font')
+ }
+ }
+ const embedding = planFontEmbedding([{ family: 'Inter', style: 'Regular', data: inter }])
+ const alias = embeddedFontAlias(embedding)
+ expect(alias('Inter', 'Regular')).not.toBeNull()
+
+ expect(registerEmbeddedFonts(doc, embedding)).toBe(false)
+ expect(embedding.report).toEqual({
+ embedded: [],
+ fallback: [{ face: 'Inter Regular', reason: 'Unsupported font' }]
+ })
+ expect(alias('Inter', 'Regular')).toBeNull()
+ })
+})
diff --git a/packages/core/tests/io/formats/pdf/plan.test.ts b/packages/core/tests/io/formats/pdf/plan.test.ts
new file mode 100644
index 000000000..f10a5f696
--- /dev/null
+++ b/packages/core/tests/io/formats/pdf/plan.test.ts
@@ -0,0 +1,116 @@
+import { describe, expect, test } from 'bun:test'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { FigmaAPI } from '#core/figma-api'
+import { MAX_PDF_PAGES, PDFPlanError, planPDFPages } from '#core/io/formats/pdf/plan'
+
+/** Page "Cards" (Front, Back, hidden Draft), page "Posters" (Poster), empty page "Blank". */
+function document() {
+ const graph = new SceneGraph()
+ const figma = new FigmaAPI(graph)
+ const cards = figma.currentPage
+ cards.name = 'Cards'
+ const front = figma.createFrame()
+ front.name = 'Front'
+ const back = figma.createFrame()
+ back.name = 'Back'
+ const draft = figma.createFrame()
+ draft.name = 'Draft'
+ draft.visible = false
+ const posters = figma.createPage()
+ posters.name = 'Posters'
+ figma.currentPage = posters
+ const poster = figma.createFrame()
+ poster.name = 'Poster'
+ const blank = figma.createPage()
+ blank.name = 'Blank'
+ figma.currentPage = cards
+ return { graph, figma, cards, posters, blank, front, back, draft, poster }
+}
+
+describe('planPDFPages', () => {
+ test('single puts every visible top-level node on one page, or just the ids given', () => {
+ const { graph, cards, front, back } = document()
+ const all = planPDFPages(graph, { mode: 'single', currentPageId: cards.id })
+ expect(all).toEqual([{ pageId: cards.id, nodeIds: [front.id, back.id] }])
+
+ const some = planPDFPages(graph, { mode: 'single', ids: [back.id], currentPageId: cards.id })
+ expect(some).toEqual([{ pageId: cards.id, nodeIds: [back.id] }])
+ })
+
+ test('frames makes one page per frame, named after it', () => {
+ const { graph, cards, front, back } = document()
+ const specs = planPDFPages(graph, { mode: 'frames', currentPageId: cards.id })
+ expect(specs.map((spec) => [spec.label, spec.nodeIds])).toEqual([
+ ['Front', [front.id]],
+ ['Back', [back.id]]
+ ])
+ })
+
+ test('frames follows the order of the ids and finds the design page of each', () => {
+ const { graph, cards, posters, front, poster } = document()
+ const specs = planPDFPages(graph, {
+ mode: 'frames',
+ ids: [poster.id, front.id],
+ currentPageId: cards.id
+ })
+ expect(specs.map((spec) => spec.pageId)).toEqual([posters.id, cards.id])
+ })
+
+ test('frames finds the design page of a nested node', () => {
+ const { graph, figma, cards, front } = document()
+ const inner = figma.createFrame()
+ inner.name = 'Inner'
+ front.appendChild(inner)
+ const [spec] = planPDFPages(graph, { mode: 'frames', ids: [inner.id], currentPageId: cards.id })
+ expect(spec).toEqual({ pageId: cards.id, nodeIds: [inner.id], label: 'Inner' })
+ })
+
+ test('pages makes one page per design page and skips empty ones', () => {
+ const { graph, cards, front, back, poster } = document()
+ const specs = planPDFPages(graph, { mode: 'pages', currentPageId: cards.id })
+ expect(specs.map((spec) => [spec.label, spec.nodeIds])).toEqual([
+ ['Cards', [front.id, back.id]],
+ ['Posters', [poster.id]]
+ ])
+ })
+
+ test('pages follows page_ids in the order given', () => {
+ const { graph, cards, posters } = document()
+ const specs = planPDFPages(graph, {
+ mode: 'pages',
+ pageIds: [posters.id, cards.id],
+ currentPageId: cards.id
+ })
+ expect(specs.map((spec) => spec.label)).toEqual(['Posters', 'Cards'])
+ })
+
+ test('names a missing node or page', () => {
+ const { graph, cards } = document()
+ expect(() =>
+ planPDFPages(graph, { mode: 'frames', ids: ['9:9'], currentPageId: cards.id })
+ ).toThrow('Node "9:9" not found')
+ expect(() =>
+ planPDFPages(graph, { mode: 'pages', pageIds: ['9:9'], currentPageId: cards.id })
+ ).toThrow('Page "9:9" not found')
+ })
+
+ test('rejects a request that exports nothing', () => {
+ const { graph, blank, cards } = document()
+ expect(() =>
+ planPDFPages(graph, { mode: 'pages', pageIds: [blank.id], currentPageId: cards.id })
+ ).toThrow(PDFPlanError)
+ expect(() => planPDFPages(graph, { mode: 'single', currentPageId: blank.id })).toThrow(
+ 'No visible nodes to export'
+ )
+ })
+
+ test('rejects more pages than a PDF may hold', () => {
+ const { graph, figma, cards } = document()
+ for (let i = 0; i < MAX_PDF_PAGES; i++) figma.createFrame()
+ expect(() => planPDFPages(graph, { mode: 'frames', currentPageId: cards.id })).toThrow(
+ /limit is 200/
+ )
+ })
+})
diff --git a/packages/core/tests/io/formats/pdf/prepare.test.ts b/packages/core/tests/io/formats/pdf/prepare.test.ts
new file mode 100644
index 000000000..622c090d1
--- /dev/null
+++ b/packages/core/tests/io/formats/pdf/prepare.test.ts
@@ -0,0 +1,50 @@
+import { expect, test } from 'bun:test'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { exportFigFile, parseFigFile } from '#core/io'
+import { planPDFPages } from '#core/io/formats/pdf/plan'
+import { readPDFPages } from '#core/io/formats/pdf/prepare'
+import { initCodec } from '#core/kiwi'
+
+/** A `.fig` opened as the editor opens one: only its first page read. */
+async function openedFig() {
+ await initCodec()
+ const source = new SceneGraph()
+ source.createNode('RECTANGLE', source.getPages()[0].id, { name: 'First', width: 10, height: 10 })
+ for (const name of ['Second', 'Third']) {
+ source.createNode('RECTANGLE', source.addPage(name).id, { name, width: 10, height: 10 })
+ }
+ const bytes = await exportFigFile(source)
+ return parseFigFile(bytes.buffer as ArrayBuffer, { populate: 'first-page' })
+}
+
+test('pages not read yet are read before a pages export is planned', async () => {
+ const graph = await openedFig()
+ const [first, second, third] = graph.getPages()
+ const plan = () => planPDFPages(graph, { mode: 'pages', currentPageId: first.id })
+
+ expect(plan().map((spec) => spec.pageId)).toEqual([first.id])
+ readPDFPages(graph)
+ expect(plan().map((spec) => spec.pageId)).toEqual([first.id, second.id, third.id])
+})
+
+test('an empty page list reads every page, as it exports every page', async () => {
+ const graph = await openedFig()
+ const [first, second, third] = graph.getPages()
+
+ readPDFPages(graph, [])
+
+ const planned = planPDFPages(graph, { mode: 'pages', pageIds: [], currentPageId: first.id })
+ expect(planned.map((spec) => spec.pageId)).toEqual([first.id, second.id, third.id])
+})
+
+test('only the pages a pages export asks for are read', async () => {
+ const graph = await openedFig()
+ const [, second, third] = graph.getPages()
+
+ readPDFPages(graph, [second.id])
+
+ expect(graph.getChildren(second.id)).toHaveLength(1)
+ expect(graph.getChildren(third.id)).toHaveLength(0)
+})
diff --git a/packages/core/tests/io/formats/pdf/text-layout.test.ts b/packages/core/tests/io/formats/pdf/text-layout.test.ts
new file mode 100644
index 000000000..82cc7db0d
--- /dev/null
+++ b/packages/core/tests/io/formats/pdf/text-layout.test.ts
@@ -0,0 +1,88 @@
+import { beforeAll, expect, test } from 'bun:test'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { withPDFTextLayout } from '#core/io/formats/pdf/prepare'
+import { renderNodesToSVG } from '#core/io/formats/svg'
+import { fontManager } from '#core/text/fonts'
+
+const SENTENCE = 'A sentence long enough that it has to wrap onto a second line.'
+
+beforeAll(async () => {
+ const inter = expectDefined(await fontManager.fetchBundledFont('/Inter-Regular.ttf'), 'Inter')
+ fontManager.markLoaded('Inter', 'Regular', inter)
+})
+
+test('a paragraph wrapped on the canvas keeps its lines in the SVG drawn into a PDF', async () => {
+ const graph = new SceneGraph()
+ const pageId = graph.getPages()[0].id
+ const node = graph.createNode('TEXT', pageId, {
+ text: SENTENCE,
+ fontFamily: 'Inter',
+ fontSize: 13,
+ lineHeight: 16,
+ width: 230,
+ height: 32,
+ textAutoResize: 'HEIGHT'
+ })
+
+ const svg = await withPDFTextLayout(async (textLayout) => {
+ const lines = expectDefined(textLayout?.(node), 'text lines')
+ expect(lines).toHaveLength(2)
+ expect(lines[1].start).toBe(lines[0].end)
+ expect(lines[1].end).toBe(SENTENCE.length)
+ expect(lines[1].y - lines[0].y).toBe(16)
+ return renderNodesToSVG(graph, pageId, [node.id], { xmlDeclaration: false, textLayout })
+ })
+
+ const spans = expectDefined(svg, 'SVG').match(/<tspan [^>]*>[^<]*<\/tspan>/g) ?? []
+ expect(spans).toHaveLength(2)
+ expect(spans.map((span) => span.replace(/<[^>]+>/g, '')).join('')).toBe(SENTENCE)
+})
+
+test('a style run that starts mid-word is placed where the canvas draws its first letter', async () => {
+ const graph = new SceneGraph()
+ const pageId = graph.getPages()[0].id
+ const node = graph.createNode('TEXT', pageId, {
+ text: 'Bold',
+ fontFamily: 'Inter',
+ fontSize: 20,
+ width: 200,
+ height: 24,
+ styleRuns: [{ start: 1, length: 3, style: { letterSpacing: 4 } }]
+ })
+
+ const svg = await withPDFTextLayout(async (textLayout) => {
+ const [line] = expectDefined(textLayout?.(node), 'text lines')
+ const o = expectDefined(line.characters?.get(1), 'edges of "o"')
+ const b = expectDefined(line.characters?.get(0), 'edges of "B"')
+ expect(o.left).toBeCloseTo(b.right, 3)
+ return renderNodesToSVG(graph, pageId, [node.id], { xmlDeclaration: false, textLayout })
+ })
+
+ const spans = expectDefined(svg, 'SVG').match(/<tspan [^>]*>/g) ?? []
+ expect(spans).toHaveLength(2)
+ expect(spans.every((span) => / x="[\d.]+"/.test(span))).toBe(true)
+})
+
+test('text whose case changes its length is kept on one line, in that case', async () => {
+ const graph = new SceneGraph()
+ const pageId = graph.getPages()[0].id
+ const node = graph.createNode('TEXT', pageId, {
+ text: 'Straße',
+ textCase: 'UPPER',
+ fontFamily: 'Inter',
+ fontSize: 20,
+ width: 200,
+ height: 24
+ })
+
+ const svg = await withPDFTextLayout(async (textLayout) => {
+ expect(textLayout?.(node)).toBeNull()
+ return renderNodesToSVG(graph, pageId, [node.id], { xmlDeclaration: false, textLayout })
+ })
+
+ expect(expectDefined(svg, 'SVG')).toContain('>STRASSE</text>')
+})
diff --git a/packages/core/tests/io/formats/svg/font-alias.test.ts b/packages/core/tests/io/formats/svg/font-alias.test.ts
new file mode 100644
index 000000000..895e8c701
--- /dev/null
+++ b/packages/core/tests/io/formats/svg/font-alias.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, test } from 'bun:test'
+
+import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
+
+import { renderNodesToSVG, type SVGTextLine } from '#core/io/formats/svg'
+
+const ALIASES: Record<string, string> = {
+ 'Inter\0Regular': 'EmbeddedFont0',
+ 'Roboto\0Bold Italic': 'EmbeddedFont1'
+}
+
+function exportText(props: Partial<SceneNode>, lines?: SVGTextLine[]): string {
+ const graph = new SceneGraph()
+ const pageId = graph.getPages()[0].id
+ const node = graph.createNode('TEXT', pageId, { width: 200, height: 60, fontSize: 20, ...props })
+ const svg = renderNodesToSVG(graph, pageId, [node.id], {
+ xmlDeclaration: false,
+ textLayout: lines ? () => lines : undefined,
+ fontAlias: (family, style) => ALIASES[`${family}\0${style}`] ?? null
+ })
+ if (!svg) throw new Error('nothing exported')
+ return svg
+}
+
+const textTag = (svg: string) => svg.match(/<text [^>]*>/)?.[0] ?? ''
+const spanTags = (svg: string) => svg.match(/<tspan [^>]*>/g) ?? []
+
+describe('SVG text with font aliases', () => {
+ test('text in an aliased face names the alias at normal weight and style', () => {
+ const tag = textTag(exportText({ text: 'Hello', fontFamily: 'Inter' }))
+ expect(tag).toContain('font-family="EmbeddedFont0"')
+ expect(tag).toContain('font-weight="normal"')
+ expect(tag).toContain('font-style="normal"')
+ })
+
+ test('text without a family is aliased as the default family it is drawn in', () => {
+ expect(textTag(exportText({ text: 'Hello', fontFamily: '' }))).toContain(
+ 'font-family="EmbeddedFont0"'
+ )
+ })
+
+ test('a style run names its own face, so it does not inherit the alias of the text', () => {
+ const svg = exportText({
+ text: 'Plain bold styled',
+ fontFamily: 'Inter',
+ styleRuns: [
+ { start: 0, length: 6, style: {} },
+ { start: 6, length: 5, style: { fontWeight: 700 } },
+ { start: 11, length: 6, style: { fontFamily: 'Roboto', fontWeight: 700, italic: true } }
+ ]
+ })
+ const [plain, bold, styled] = spanTags(svg)
+ expect(plain).toContain('font-family="EmbeddedFont0"')
+ expect(bold).toContain('font-family="Inter"')
+ expect(bold).toContain('font-weight="700"')
+ expect(bold).toContain('font-style="normal"')
+ expect(styled).toContain('font-family="EmbeddedFont1"')
+ expect(styled).toContain('font-style="normal"')
+ })
+
+ test('laid-out lines name the face of each styled span', () => {
+ const svg = exportText(
+ {
+ text: 'One two',
+ fontFamily: 'Inter',
+ styleRuns: [{ start: 4, length: 3, style: { fontWeight: 700 } }]
+ },
+ [{ start: 0, end: 7, x: 0, y: 20, width: 100 }]
+ )
+ expect(textTag(svg)).toContain('font-family="EmbeddedFont0"')
+ expect(spanTags(svg)[1]).toContain('font-family="Inter"')
+ })
+})
diff --git a/packages/core/tests/io/formats/svg/node.test.ts b/packages/core/tests/io/formats/svg/node.test.ts
new file mode 100644
index 000000000..c14762903
--- /dev/null
+++ b/packages/core/tests/io/formats/svg/node.test.ts
@@ -0,0 +1,23 @@
+import { expect, test } from 'bun:test'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { renderNodesToSVG } from '#core/io/formats/svg'
+
+test('styled text runs are written together, with no whitespace drawn between them', () => {
+ const graph = new SceneGraph()
+ const pageId = graph.getPages()[0].id
+ const node = graph.createNode('TEXT', pageId, {
+ text: 'Bold',
+ width: 100,
+ height: 20,
+ styleRuns: [
+ { start: 0, length: 1, style: {} },
+ { start: 1, length: 3, style: { fontWeight: 700 } }
+ ]
+ })
+
+ const svg = renderNodesToSVG(graph, pageId, [node.id], { xmlDeclaration: false })
+
+ expect(svg).toMatch(/<text [^>]*><tspan>B<\/tspan><tspan font-weight="700">old<\/tspan><\/text>/)
+})
diff --git a/packages/core/tests/io/formats/svg/text/lines.test.ts b/packages/core/tests/io/formats/svg/text/lines.test.ts
new file mode 100644
index 000000000..9dfbbc9d8
--- /dev/null
+++ b/packages/core/tests/io/formats/svg/text/lines.test.ts
@@ -0,0 +1,155 @@
+import { describe, expect, test } from 'bun:test'
+
+import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
+
+import { renderNodesToSVG, type SVGTextLine } from '#core/io/formats/svg'
+
+function exportText(props: Partial<SceneNode>, lines?: SVGTextLine[] | null): string {
+ const graph = new SceneGraph()
+ const pageId = graph.getPages()[0].id
+ const node = graph.createNode('TEXT', pageId, {
+ width: 200,
+ height: 60,
+ fontSize: 20,
+ ...props
+ })
+ const svg = renderNodesToSVG(graph, pageId, [node.id], {
+ xmlDeclaration: false,
+ textLayout: lines === undefined ? undefined : () => lines
+ })
+ if (!svg) throw new Error('nothing exported')
+ return svg
+}
+
+describe('SVG text with laid-out lines', () => {
+ test('without a layout, or with none for the node, the text stays on one line', () => {
+ for (const lines of [undefined, null, []]) {
+ const svg = exportText({ text: 'First line\nSecond line' }, lines)
+ expect(svg).not.toContain('<tspan')
+ expect(svg).toContain('y="20"')
+ }
+ })
+
+ test('each line is placed at its own baseline and the newline is not drawn', () => {
+ const text = 'First line\nSecond line'
+ const svg = exportText({ text }, [
+ { start: 0, end: 11, x: 0, y: 18, width: 80 },
+ { start: 11, end: text.length, x: 0, y: 42, width: 96 }
+ ])
+ expect(svg).toContain('<tspan x="0" y="18">First line</tspan>')
+ expect(svg).toContain('<tspan x="0" y="42">Second line</tspan>')
+ })
+
+ test('style runs are cut at line breaks and keep their own attributes', () => {
+ const svg = exportText(
+ {
+ text: 'abcdef ghij',
+ styleRuns: [{ start: 0, length: 3, style: { fontWeight: 700 } }]
+ },
+ [
+ { start: 0, end: 7, x: 0, y: 18, width: 70 },
+ { start: 7, end: 11, x: 0, y: 42, width: 40 }
+ ]
+ )
+ expect(svg).toContain('<tspan x="0" y="18" font-weight="700">abc</tspan>')
+ expect(svg).toContain('<tspan>def </tspan>')
+ expect(svg).toContain('<tspan x="0" y="42">ghij</tspan>')
+ })
+
+ test('lines take their x from the layout instead of the alignment anchor', () => {
+ const svg = exportText({ text: 'Centered', textAlignHorizontal: 'CENTER' }, [
+ { start: 0, end: 8, x: 61.5, y: 18, width: 77 }
+ ])
+ expect(svg).not.toContain('text-anchor')
+ expect(svg).toContain('<tspan x="61.5" y="18">Centered</tspan>')
+ })
+
+ test('a right-to-left line starts at its left edge, with no direction or anchor', () => {
+ const svg = exportText({ text: 'مرحبا', textDirection: 'RTL' }, [
+ { start: 0, end: 5, x: 120, y: 18, width: 50 }
+ ])
+ expect(svg).not.toContain('text-anchor')
+ expect(svg).not.toContain('direction')
+ expect(svg).toContain('<tspan x="120" y="18">مرحبا</tspan>')
+ })
+
+ test('with character edges every span is placed where its characters are drawn', () => {
+ const edges = (from: number, widths: number[]) =>
+ new Map(
+ widths.map((width, index) => [
+ from + index,
+ { left: index * 10, right: index * 10 + width }
+ ])
+ )
+ const svg = exportText(
+ {
+ text: 'Bold',
+ styleRuns: [{ start: 1, length: 3, style: { fontWeight: 700 } }]
+ },
+ [{ start: 0, end: 4, x: 0, y: 18, width: 40, characters: edges(0, [10, 10, 10, 10]) }]
+ )
+ expect(svg).toContain('xml:space="preserve"')
+ expect(svg).toContain(
+ '<tspan x="0" y="18">B</tspan><tspan x="10" y="18" font-weight="700">old</tspan>'
+ )
+ })
+
+ test('a right-to-left span starts at the left edge of its characters', () => {
+ const svg = exportText(
+ {
+ text: 'אבג',
+ textDirection: 'RTL',
+ styleRuns: [{ start: 1, length: 2, style: { fontWeight: 700 } }]
+ },
+ [
+ {
+ start: 0,
+ end: 3,
+ x: 70,
+ y: 18,
+ width: 30,
+ characters: new Map([
+ [0, { left: 90, right: 100 }],
+ [1, { left: 80, right: 90 }],
+ [2, { left: 70, right: 80 }]
+ ])
+ }
+ ]
+ )
+ expect(svg).toContain(
+ '<tspan x="90" y="18">א</tspan><tspan x="70" y="18" font-weight="700">בג</tspan>'
+ )
+ })
+
+ test('laid-out lines hold the text in the case it is shown in', () => {
+ const svg = exportText(
+ {
+ text: 'quiet loud',
+ textCase: 'TITLE',
+ styleRuns: [{ start: 6, length: 4, style: { textCase: 'UPPER' } }]
+ },
+ [
+ { start: 0, end: 6, x: 0, y: 18, width: 50 },
+ { start: 6, end: 10, x: 0, y: 42, width: 50 }
+ ]
+ )
+ expect(svg).toContain('>Quiet </tspan>')
+ expect(svg).toContain('>LOUD</tspan>')
+ })
+})
+
+describe('SVG text case', () => {
+ test('text on one line is written in the case it is shown in', () => {
+ expect(exportText({ text: 'Mixed Case', textCase: 'UPPER' })).toContain('>MIXED CASE</text>')
+ const runs = exportText({
+ text: 'Mixed Case',
+ textCase: 'UPPER',
+ styleRuns: [
+ { start: 0, length: 6, style: {} },
+ { start: 6, length: 4, style: { textCase: 'LOWER' } }
+ ]
+ })
+ expect(runs).toContain('>MIXED </tspan>')
+ expect(runs).toContain('>case</tspan>')
+ })
+})
diff --git a/packages/core/tests/tools/vector/export-pdf.test.ts b/packages/core/tests/tools/vector/export-pdf.test.ts
new file mode 100644
index 000000000..73ab68464
--- /dev/null
+++ b/packages/core/tests/tools/vector/export-pdf.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, test } from 'bun:test'
+
+import * as v from 'valibot'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { FigmaAPI } from '#core/figma-api'
+import { ALL_TOOLS } from '#core/tools'
+
+const exportPDF = ALL_TOOLS.find((tool) => tool.name === 'export_pdf')
+if (!exportPDF) throw new Error('export_pdf tool missing')
+
+describe('export_pdf', () => {
+ test('mode defaults to single and accepts frames and pages', () => {
+ expect(v.parse(exportPDF.input, {}).mode).toBe('single')
+ for (const mode of ['frames', 'pages']) {
+ expect(v.parse(exportPDF.input, { mode, page_ids: ['0:1'] }).mode).toBe(mode)
+ }
+ expect(v.safeParse(exportPDF.input, { mode: 'spread' }).success).toBe(false)
+ })
+
+ test('embeds fonts only on request', () => {
+ expect(v.parse(exportPDF.input, {}).embed_fonts).toBe(false)
+ expect(v.parse(exportPDF.input, { embed_fonts: true }).embed_fonts).toBe(true)
+ expect(v.safeParse(exportPDF.input, { embed_fonts: 'yes' }).success).toBe(false)
+ })
+
+ test('reports a problem with the request as an error result', async () => {
+ const figma = new FigmaAPI(new SceneGraph())
+ expect(await exportPDF.execute(figma, { mode: 'single' })).toEqual({
+ error: 'No visible nodes to export'
+ })
+ expect(await exportPDF.execute(figma, { mode: 'pages', page_ids: ['9:9'] })).toEqual({
+ error: 'Page "9:9" not found'
+ })
+ })
+})
diff --git a/tests/engine/text/fonts/status.test.ts b/tests/engine/text/fonts/status.test.ts
index 62852ae5a..a8ae03667 100644
--- a/tests/engine/text/fonts/status.test.ts
+++ b/tests/engine/text/fonts/status.test.ts
@@ -37,6 +37,22 @@ describe('documentFontStatus', () => {
})
})
+ test('counts a root that is itself a text node', () => {
+ const graph = new SceneGraph()
+ const manager = new FontManager()
+ manager.markLoaded('Inter', 'Regular', new ArrayBuffer(8), 'bundled')
+ const node = graph.createNode('TEXT', pageId(graph), {
+ text: 'Hello',
+ fontFamily: 'Inter',
+ fontWeight: 400
+ })
+
+ const status = documentFontStatus(graph, [node.id], manager)
+ expect(status.faces.map((face) => [face.family, face.style, face.status])).toEqual([
+ ['Inter', 'Regular', 'available']
+ ])
+ })
+
test('reports the active default-family substitution for missing faces', () => {
const graph = new SceneGraph()
const manager = new FontManager()