AI-native design editor. Open-source Figma alternative.
fix(svg): put each explicit line of multiline text on its own baseline (#1439)
Mark David Pradodce0c56b3a1a
diff --git a/changes/1439/fixed.md b/changes/1439/fixed.mdnew file mode 100644index 000000000..748065a1e--- /dev/null+++ b/changes/1439/fixed.md@@ -0,0 +1 @@+- SVG export places each explicit line of multiline text on its own baseline.diff --git a/packages/core/src/io/formats/pdf/prepare.ts b/packages/core/src/io/formats/pdf/prepare.tsindex 7eb3d0e6c..0e380cdd6 100644--- a/packages/core/src/io/formats/pdf/prepare.ts+++ b/packages/core/src/io/formats/pdf/prepare.ts@@ -68,7 +68,7 @@ export function pdfFontFaces(status: DocumentFontStatus): PDFFontFace[] {/*** 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.+ * layout and only explicit newlines start a new line.*/export async function withPDFTextLayout<T>(render: (textLayout: SVGTextLayout | undefined) => Promise<T>diff --git a/packages/core/src/io/formats/svg/defs.ts b/packages/core/src/io/formats/svg/defs.tsindex c37972420..fcacb67b7 100644--- a/packages/core/src/io/formats/svg/defs.ts+++ b/packages/core/src/io/formats/svg/defs.ts@@ -31,7 +31,7 @@ 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. */+ /** Measured line breaks. Without them, only explicit newlines start a new baseline. */textLayout?: SVGTextLayoutfontAlias?: SVGFontAlias}diff --git a/packages/core/src/io/formats/svg/export.ts b/packages/core/src/io/formats/svg/export.tsindex aea618485..c0e44cad9 100644--- a/packages/core/src/io/formats/svg/export.ts+++ b/packages/core/src/io/formats/svg/export.ts@@ -399,8 +399,8 @@ export interface SVGExportOptions {/** 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.+ * Line breaks of text nodes as the editor laid them out, wraps included. Without them, only+ * explicit newlines start a new baseline, which renderers that do not wrap SVG text keep.*/textLayout?: SVGTextLayout/**diff --git a/packages/core/src/io/formats/svg/text/export.ts b/packages/core/src/io/formats/svg/text/export.tsindex 3a7adef81..b1aa3749a 100644--- a/packages/core/src/io/formats/svg/text/export.ts+++ b/packages/core/src/io/formats/svg/text/export.ts@@ -4,7 +4,12 @@ import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text/directioimport { 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, textStyleSpans } from '#core/io/formats/svg/text/lines'+import {+ explicitNewlineLines,+ laidOutTextSpans,+ textStyleSpans,+ type SpanAttrs+} from '#core/io/formats/svg/text/lines'import { shownText } from '#core/text/case'import type { FontFaceRef } from '#core/text/face'import { textFontFace } from '#core/text/requirements'@@ -69,6 +74,36 @@ function textXForNode(node: SceneNode, direction: 'LTR' | 'RTL'): number {return 0}+/** Text with no measured layout: explicit newlines on their own baselines, otherwise one line. */+function renderUnmeasuredText(+ node: SceneNode,+ attrs: Record<string, string | number | undefined>,+ spanAttrs: SpanAttrs,+ direction: 'LTR' | 'RTL'+): SVGNode {+ const x = textXForNode(node, direction)+ const y = node.fontSize || 14+ // No measured wraps: an explicit newline still starts a line, on the same anchor as one line.+ const newlineLines = explicitNewlineLines(node, x, y)+ if (newlineLines) {+ return svg(+ 'text',+ { ...attrs, 'xml:space': 'preserve' },+ ...laidOutTextSpans(node, newlineLines, spanAttrs)+ )+ }++ if (node.styleRuns.length > 0) {+ return svg(+ 'text',+ { x, y, ...attrs, 'xml:space': 'preserve' },+ ...textStyleSpans(node, spanAttrs)+ )+ }++ return svg('text', { x, y, ...attrs }, shownText(node))+}+export function renderTextNode(node: SceneNode,fillAttr: string | null,@@ -110,16 +145,5 @@ export function renderTextNode()}- const x = textXForNode(node, direction)- const y = node.fontSize || 14-- if (node.styleRuns.length > 0) {- return svg(- 'text',- { x, y, ...attrs, 'xml:space': 'preserve' },- ...textStyleSpans(node, spanAttrs)- )- }-- return svg('text', { x, y, ...attrs }, shownText(node))+ return renderUnmeasuredText(node, attrs, spanAttrs, direction)}diff --git a/packages/core/src/io/formats/svg/text/lines.ts b/packages/core/src/io/formats/svg/text/lines.tsindex 5190d13e5..3814ddd49 100644--- a/packages/core/src/io/formats/svg/text/lines.ts+++ b/packages/core/src/io/formats/svg/text/lines.ts@@ -28,10 +28,15 @@ export interface SVGCharacterEdges {right: number}-/** The lines of a text node from the host's text layout, or null to keep the text on one line. */+/**+ * Measured lines of a text node, or null when this node has none. Export then keeps only the+ * text's explicit newlines, each on its own baseline.+ */export type SVGTextLayout = (node: SceneNode) => readonly SVGTextLine[] | null-type SpanAttrs = (style: CharacterStyleOverride) => Record<string, string | number | undefined>+export type SpanAttrs = (+ style: CharacterStyleOverride+) => Record<string, string | number | undefined>interface TextPiece {from: number@@ -84,8 +89,13 @@ function lineSpans(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+ // The newline that ends a line is not drawn. A CR is dropped only with that LF, so a+ // literal trailing CR stays.+ let end = line.end+ if (end > line.start && node.text[end - 1] === '\n') {+ end -= 1+ if (end > line.start && node.text[end - 1] === '\r') end -= 1+ }const y = round(line.y)const spans: SVGNode[] = []for (const piece of pieces) {@@ -103,6 +113,90 @@ function lineSpans(return spans}+/**+ * Baseline-to-baseline distance with no measured layout. A line height is pixels — a percent is+ * already that fraction of the font size — and automatic (`null` or `0`) is 1.2 times the font+ * size, the estimate text layout uses when it has no font metrics.+ */+function resolvedLineHeight(fontSize: number, lineHeight: number | null): number {+ return lineHeight || fontSize * 1.2+}++/** The line height a run contributes: its own when it sets one, otherwise the node's. */+function runLineHeight(node: SceneNode, style: CharacterStyleOverride | null): number {+ const fontSize = style?.fontSize ?? node.fontSize+ const lineHeight = style?.lineHeight !== undefined ? style.lineHeight : node.lineHeight+ return resolvedLineHeight(fontSize, lineHeight)+}++/**+ * The characters that set a line's height. Text excludes the LF that ends the line and the CR+ * of that CRLF, as the canvas does. An empty line is the newline that makes it.+ */+function lineHeightSpan(text: string, start: number, end: number): { from: number; to: number } {+ if (end > start && text[end - 1] === '\n') {+ let contentEnd = end - 1+ if (contentEnd > start && text[contentEnd - 1] === '\r') contentEnd -= 1+ if (contentEnd > start) return { from: start, to: contentEnd }+ return { from: end - 1, to: end }+ }+ if (end > start) return { from: start, to: end }+ // A trailing empty line has no characters of its own; the newline that opened it does.+ return { from: Math.max(0, start - 1), to: start }+}++/**+ * How far this line's baseline stands below the one before it. The line is as tall as the+ * tallest line height on it, and an empty line is as tall as the newline that makes it.+ */+function explicitLineHeight(+ node: SceneNode,+ pieces: readonly TextPiece[],+ start: number,+ end: number+): number {+ const { from, to } = lineHeightSpan(node.text, start, end)+ let height = 0+ let covered = false+ for (const piece of pieces) {+ const pieceFrom = Math.max(piece.from, from)+ const pieceTo = Math.min(piece.to, to)+ if (pieceTo <= pieceFrom) continue+ covered = true+ height = Math.max(height, runLineHeight(node, piece.style))+ }+ return covered ? height : resolvedLineHeight(node.fontSize, node.lineHeight)+}++/**+ * One line per explicit newline, for text exported without a measured layout. `x` is the+ * alignment anchor and `firstBaseline` the first line's baseline, both as the single-line+ * fallback computes them. Each later baseline stands the height of that line below the one+ * before it, as the canvas lays lines out. `null` when the text has no newline, so a single+ * line stays one `<text>`.+ */+export function explicitNewlineLines(+ node: SceneNode,+ x: number,+ firstBaseline: number+): SVGTextLine[] | null {+ if (!node.text.includes('\n')) return null+ const pieces = textPieces(node)+ const parts = node.text.split('\n')+ const lines: SVGTextLine[] = []+ let start = 0+ let y = firstBaseline+ for (const [index, part] of parts.entries()) {+ // The newline that ends a line stays inside the range, as a measured line's `end` does.+ const endsWithBreak = index < parts.length - 1+ const end = start + part.length + (endsWithBreak ? 1 : 0)+ if (index > 0) y += explicitLineHeight(node, pieces, start, end)+ lines.push({ start, end, x, y, width: node.width })+ start = end+ }+ return lines+}+/*** 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. Eachdiff --git a/packages/core/tests/io/formats/svg/text/lines.test.ts b/packages/core/tests/io/formats/svg/text/lines.test.tsindex e82038f1a..b83fa5d3e 100644--- a/packages/core/tests/io/formats/svg/text/lines.test.ts+++ b/packages/core/tests/io/formats/svg/text/lines.test.ts@@ -21,12 +21,23 @@ function exportText(props: Partial<SceneNode>, lines?: SVGTextLine[] | null): streturn svg}+function textElement(svg: string): string {+ const text = svg.match(/<text\b[^>]*>[\s\S]*?<\/text>/)?.[0]+ if (!text) throw new Error('no text element')+ return text+}+describe('SVG text with laid-out lines', () => {- test('without a layout, or with none for the node, the text stays on one line', () => {+ test('without a measured layout, each explicit newline keeps its own baseline', () => {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"')+ const svg = exportText(+ { text: 'First line\nSecond line', fontSize: 16, lineHeight: 24, width: 100 },+ lines+ )+ const text = textElement(svg)+ expect(text).toContain('<tspan x="0" y="16">First line</tspan>')+ expect(text).toContain('<tspan x="0" y="40">Second line</tspan>')+ expect(text).not.toContain('\n')}})@@ -138,6 +149,239 @@ describe('SVG text with laid-out lines', () => {})})+describe('SVG text lines without a measured layout', () => {+ test('a single line stays one text element', () => {+ const svg = exportText({ text: 'First line', fontSize: 16, lineHeight: 24, width: 100 })+ expect(textElement(svg)).toBe(+ '<text x="0" y="16" font-family="Inter" font-size="16" fill="#000000">First line</text>'+ )+ })++ test('an automatic line height spaces baselines by 1.2 times the font size', () => {+ const svg = exportText({+ text: 'First line\nSecond line',+ fontSize: 16,+ lineHeight: null,+ width: 100+ })+ const text = textElement(svg)+ expect(text).toContain('<tspan x="0" y="16">First line</tspan>')+ expect(text).toContain('<tspan x="0" y="35.2">Second line</tspan>')+ })++ test('an automatic line height steps by the font size of the line it reaches', () => {+ const below = exportText({+ text: 'Aa\nBc',+ fontSize: 16,+ lineHeight: null,+ width: 100,+ // Only "B" is larger, so the line takes the tallest font on it: 40 * 1.2.+ styleRuns: [{ start: 3, length: 1, style: { fontSize: 40 } }]+ })+ const belowText = textElement(below)+ expect(belowText).toContain('<tspan x="0" y="16">Aa</tspan>')+ expect(belowText).toContain('<tspan x="0" y="64" font-size="40">B</tspan>')+ expect(belowText).toContain('<tspan>c</tspan>')++ const above = exportText({+ text: 'Aa\nBb',+ fontSize: 16,+ lineHeight: null,+ width: 100,+ styleRuns: [{ start: 0, length: 2, style: { fontSize: 40 } }]+ })+ const aboveText = textElement(above)+ expect(aboveText).toContain('<tspan x="0" y="16" font-size="40">Aa</tspan>')+ expect(aboveText).toContain('<tspan x="0" y="35.2">Bb</tspan>')+ })++ test('an explicit line height does not follow a run font size', () => {+ const svg = exportText({+ text: 'Aa\nBb',+ fontSize: 16,+ lineHeight: 24,+ width: 100,+ styleRuns: [{ start: 3, length: 2, style: { fontSize: 40 } }]+ })+ const text = textElement(svg)+ expect(text).toContain('<tspan x="0" y="16">Aa</tspan>')+ expect(text).toContain('<tspan x="0" y="40" font-size="40">Bb</tspan>')+ })++ test("a run's line height sets the step of the line it is on", () => {+ const svg = exportText({+ text: 'one\ntwo\nthree',+ fontSize: 16,+ lineHeight: null,+ width: 100,+ styleRuns: [{ start: 4, length: 3, style: { lineHeight: 50 } }]+ })+ const text = textElement(svg)+ expect(text).toContain('<tspan x="0" y="16">one</tspan>')+ expect(text).toContain('<tspan x="0" y="66">two</tspan>')+ expect(text).toContain('<tspan x="0" y="85.2">three</tspan>')+ })++ test('a blank line is as tall as the newline that makes it', () => {+ const svg = exportText({+ text: 'A\n\nC',+ fontSize: 16,+ lineHeight: null,+ width: 100,+ styleRuns: [{ start: 2, length: 1, style: { fontSize: 40 } }]+ })+ const text = textElement(svg)+ expect(text).toContain('<tspan x="0" y="16">A</tspan>')+ expect(text).toContain('<tspan x="0" y="83.2">C</tspan>')+ })++ test('a newline styled apart from its line does not set that line', () => {+ const svg = exportText({+ text: 'A\nB\nC',+ fontSize: 16,+ lineHeight: null,+ width: 100,+ // The break before C, and C itself. The break must not size "B".+ styleRuns: [{ start: 3, length: 2, style: { fontSize: 40 } }]+ })+ const text = textElement(svg)+ expect(text).toContain('<tspan x="0" y="16">A</tspan>')+ expect(text).toContain('<tspan x="0" y="35.2">B</tspan>')+ expect(text).toContain('<tspan x="0" y="83.2" font-size="40">C</tspan>')++ const crlf = exportText({+ text: 'A\nB\r\nC',+ fontSize: 16,+ lineHeight: null,+ width: 100,+ styleRuns: [{ start: 3, length: 2, style: { fontSize: 40 } }]+ })+ const crlfText = textElement(crlf)+ expect(crlfText).toContain('<tspan x="0" y="16">A</tspan>')+ expect(crlfText).toContain('<tspan x="0" y="35.2">B</tspan>')+ expect(crlfText).toContain('<tspan x="0" y="54.4">C</tspan>')+ })++ test('a line shorter than the node steps by its own font size', () => {+ const svg = exportText({+ text: 'A\nBb\nC',+ fontSize: 40,+ lineHeight: null,+ width: 100,+ styleRuns: [{ start: 2, length: 2, style: { fontSize: 10 } }]+ })+ const text = textElement(svg)+ expect(text).toContain('<tspan x="0" y="40">A</tspan>')+ expect(text).toContain('<tspan x="0" y="52" font-size="10">Bb</tspan>')+ expect(text).toContain('<tspan x="0" y="100">C</tspan>')+ })++ test('a percent line height spaces by the pixel length stored on the node', () => {+ const svg = exportText({+ text: 'First line\nSecond line',+ fontSize: 10,+ // 120% of 10px is stored on the node as 12px.+ lineHeight: 12,+ width: 100+ })+ const text = textElement(svg)+ expect(text).toContain('<tspan x="0" y="10">First line</tspan>')+ expect(text).toContain('<tspan x="0" y="22">Second line</tspan>')+ })++ test('centered and right-aligned lines share the single-line anchor', () => {+ const center = exportText({+ text: 'First line\nSecond line',+ fontSize: 16,+ lineHeight: 24,+ width: 100,+ textAlignHorizontal: 'CENTER'+ })+ expect(center).toContain('text-anchor="middle"')+ expect(center).toContain('<tspan x="50" y="16">First line</tspan>')+ expect(center).toContain('<tspan x="50" y="40">Second line</tspan>')++ const right = exportText({+ text: 'First line\nSecond line',+ fontSize: 16,+ lineHeight: 24,+ width: 100,+ textAlignHorizontal: 'RIGHT'+ })+ expect(right).toContain('text-anchor="end"')+ expect(right).toContain('<tspan x="100" y="16">First line</tspan>')+ expect(right).toContain('<tspan x="100" y="40">Second line</tspan>')+ })++ test('a right-to-left paragraph keeps the logical anchor on every line', () => {+ const svg = exportText({+ text: 'أول\nثان',+ fontSize: 16,+ lineHeight: 24,+ width: 180,+ textDirection: 'RTL',+ textAlignHorizontal: 'LEFT'+ })+ expect(svg).toContain('direction="rtl"')+ expect(svg).toContain('text-anchor="end"')+ expect(svg).toContain('<tspan x="180" y="16">أول</tspan>')+ expect(svg).toContain('<tspan x="180" y="40">ثان</tspan>')+ })++ test('style runs are cut at newlines and a blank line still advances the baseline', () => {+ const styled = exportText({+ text: 'abcd\nefgh',+ fontSize: 16,+ lineHeight: 24,+ width: 100,+ styleRuns: [{ start: 2, length: 4, style: { fontWeight: 700 } }]+ })+ expect(textElement(styled)).toContain(+ '<tspan x="0" y="16">ab</tspan><tspan font-weight="700">cd</tspan><tspan x="0" y="40" font-weight="700">e</tspan><tspan>fgh</tspan>'+ )++ const blank = exportText({ text: 'A\n\nC', fontSize: 16, lineHeight: 24, width: 100 })+ const text = textElement(blank)+ expect(text).toContain('<tspan x="0" y="16">A</tspan>')+ expect(text).toContain('<tspan x="0" y="64">C</tspan>')+ expect(text).not.toContain('\n')+ })++ test('a carriage return is dropped only when it belongs to a CRLF', () => {+ const crlf = textElement(+ exportText({ text: 'A\r\nB', fontSize: 16, lineHeight: 24, width: 100 })+ )+ expect(crlf).toContain('<tspan x="0" y="16">A</tspan>')+ expect(crlf).toContain('<tspan x="0" y="40">B</tspan>')+ expect(crlf).not.toContain('\r')++ const trailing = textElement(+ exportText({ text: 'A\nB\r', fontSize: 16, lineHeight: 24, width: 100 })+ )+ expect(trailing).toContain('<tspan x="0" y="16">A</tspan>')+ expect(trailing).toContain('>B\r</tspan>')++ const middle = textElement(+ exportText({ text: 'A\rB\nC', fontSize: 16, lineHeight: 24, width: 100 })+ )+ expect(middle).toContain('>A\rB</tspan>')+ expect(middle).toContain('<tspan x="0" y="40">C</tspan>')+ })++ test('spaces at the ends of a line are kept', () => {+ const svg = exportText({+ text: ' First\nSecond ',+ fontSize: 16,+ lineHeight: 24,+ width: 100+ })+ const text = textElement(svg)+ expect(text).toContain('xml:space="preserve"')+ expect(text).toContain('> First</tspan>')+ expect(text).toContain('>Second </tspan>')+ })+})+describe('SVG text case', () => {test('keeps text before and after a style run on one line', () => {const svg = exportText({@@ -146,7 +390,22 @@ describe('SVG text case', () => {})expect(svg).toContain('xml:space="preserve"')- expect(svg).toContain('<tspan>Hello </tspan><tspan font-weight="700">bold</tspan><tspan> world</tspan>')+ expect(svg).toContain(+ '<tspan>Hello </tspan><tspan font-weight="700">bold</tspan><tspan> world</tspan>'+ )+ })++ test('each explicit line is written in the case it is shown in', () => {+ const svg = exportText({+ text: 'straße\nnext',+ textCase: 'UPPER',+ fontSize: 16,+ lineHeight: 24,+ width: 100+ })+ const text = textElement(svg)+ expect(text).toContain('<tspan x="0" y="16">STRASSE</tspan>')+ expect(text).toContain('<tspan x="0" y="40">NEXT</tspan>')})test('text on one line is written in the case it is shown in', () => {