AI-native design editor. Open-source Figma alternative.
fix(text): count truncation by laid-out line heights (#1241)
Danny Ward2a8a9e157879
diff --git a/changes/1241/fixed.md b/changes/1241/fixed.mdnew file mode 100644index 000000000..ad4a3b483--- /dev/null+++ b/changes/1241/fixed.md@@ -0,0 +1 @@+- Text truncation to a fixed height now counts actual laid-out line heights, including mixed-size text.diff --git a/packages/core/src/canvas/text/layout/build.ts b/packages/core/src/canvas/text/layout/build.tsindex 23dc547ab..bafd9446e 100644--- a/packages/core/src/canvas/text/layout/build.ts+++ b/packages/core/src/canvas/text/layout/build.ts@@ -100,7 +100,7 @@ function paragraphLines(// Lines are cut by character index, which the text's case must keep.if (shownText(node).length !== node.text.length) return undefinedconst lead = firstLineIndent > 0 ? 1 : 0- const ellipsis = buildTruncateOpts(node, node.fontSize || DEFAULT_FONT_SIZE).ellipsis+ const ellipsis = buildTruncateOpts(node).ellipsis// A justified line is stretched only with text after it: lines are laid out with the rest// of the paragraph and cut, as truncated last lines are.const justified = node.textAlignHorizontal === 'JUSTIFIED'@@ -216,7 +216,7 @@ function buildBlocks()const digits = topLevelNumberDigits([...items.values()])const rtl = resolveNodeTextDirection(node) === 'RTL'- const truncation = buildTruncateOpts(node, node.fontSize || DEFAULT_FONT_SIZE)+ const truncation = buildTruncateOpts(node)const maxLines = truncation.maxLines// Each paragraph starts one byte, its newline, after the one before it ends.const utf8Starts: number[] = []@@ -344,14 +344,13 @@ function buildMarker(}}-/** Lay a text node out as the renderer draws it, at its own width. */-export function buildParagraph(+function createTextLayout(r: TextRenderer,node: ParagraphNode,- color?: Float32Array,- options: ParagraphBuildOptions = {}+ color: Float32Array | undefined,+ options: ParagraphBuildOptions): TextLayout {- const layout = needsParagraphLayout(node)+ return needsParagraphLayout(node)? buildBlocks(r, node, color, options): TextLayout.ofParagraph(r.ck,@@ -359,11 +358,38 @@ export function buildParagraph(shownText(node).length,paragraphLines(r, node, color, options))+}++/** How many laid-out line boxes fit the fixed height, preserving the first line. */+function linesWithinHeight(layout: TextLayout, height: number): number {+ const lines = layout.getLineMetrics()+ const firstOverflow = lines.findIndex((line) => line.baseline + line.descent > height)+ return Math.max(1, firstOverflow === -1 ? lines.length : firstOverflow)+}++/** Lay a text node out as the renderer draws it, at its own width. */+export function buildParagraph(+ r: TextRenderer,+ node: ParagraphNode,+ color?: Float32Array,+ options: ParagraphBuildOptions = {}+): TextLayout {+ const layout = createTextLayout(r, node, color, options)+ const heightTruncation =+ node.textTruncation === 'ENDING' &&+ node.height > 0 &&+ (node.maxLines == null || node.maxLines <= 0)+ let fittingLines: number | undefinedtry {layoutForNode(layout, node)- return layout+ if (heightTruncation) fittingLines = linesWithinHeight(layout, node.height)} catch (error) {layout.delete()throw error}+ if (fittingLines !== undefined && fittingLines < layout.getLineMetrics().length) {+ layout.delete()+ return buildParagraph(r, { ...node, maxLines: fittingLines }, color, options)+ }+ return layout}diff --git a/packages/core/src/canvas/text/paragraph/index.ts b/packages/core/src/canvas/text/paragraph/index.tsindex 5b0850b16..e64961585 100644--- a/packages/core/src/canvas/text/paragraph/index.ts+++ b/packages/core/src/canvas/text/paragraph/index.ts@@ -41,18 +41,12 @@ export function resolveParagraphLayoutWidth(node: ParagraphNode, maxWidth?: numbreturn node.width || 1e6}-export function buildTruncateOpts(- node: ParagraphNode,- baseFontSize: number-): { maxLines?: number; ellipsis?: string } {+export function buildTruncateOpts(node: ParagraphNode): { maxLines?: number; ellipsis?: string } {if (node.textTruncation !== 'ENDING') return {}const opts: { maxLines?: number; ellipsis: string } = { ellipsis: ELLIPSIS }if (node.maxLines != null && node.maxLines > 0) {opts.maxLines = node.maxLines- } else if (node.height > 0) {- const lineH = lineHeightPixels(node.lineHeight, baseFontSize) || baseFontSize * 1.2- opts.maxLines = Math.max(1, Math.floor(node.height / lineH))}return opts}@@ -282,7 +276,7 @@ export function buildSkParagraph(const arabicFallbacks = fontManager.getArabicFallbackFamilies()const textDirection = resolveNodeTextDirection(node)- const truncateOpts = block.truncation ?? buildTruncateOpts(node, baseFontSize)+ const truncateOpts = block.truncation ?? buildTruncateOpts(node)const fontFamilies = (primary: string, weight: number, italic = false) =>resolveParagraphFontFamilies(diff --git a/packages/core/tests/canvas/text/lines.test.ts b/packages/core/tests/canvas/text/lines.test.tsindex 0364736c2..423bcb87c 100644--- a/packages/core/tests/canvas/text/lines.test.ts+++ b/packages/core/tests/canvas/text/lines.test.ts@@ -205,4 +205,27 @@ describe('lines of mixed sizes', () => {}}})++ test('fits the number of lines whose individual heights fit the box', () => {+ const smaller = layOut({+ text: 'small\nsmall\nsmall',+ fontSize: 40,+ height: 34,+ textAutoResize: 'NONE',+ textTruncation: 'ENDING',+ styleRuns: [run(0, 17, { fontSize: 12 })]+ })+ expect(smaller.getLineMetrics()).toHaveLength(2)+ expect(smaller.didExceedMaxLines()).toBe(true)++ const larger = layOut({+ text: 'small\nLARGE\nsmall',+ height: 70,+ textAutoResize: 'NONE',+ textTruncation: 'ENDING',+ styleRuns: [run(6, 5, { fontSize: 40 })]+ })+ expect(larger.getLineMetrics()).toHaveLength(1)+ expect(larger.didExceedMaxLines()).toBe(true)+ })})diff --git a/tests/e2e/canvas/text/lines-visual.spec.ts b/tests/e2e/canvas/text/lines-visual.spec.tsindex c703d2a50..25a796596 100644--- a/tests/e2e/canvas/text/lines-visual.spec.ts+++ b/tests/e2e/canvas/text/lines-visual.spec.ts@@ -2,12 +2,33 @@ import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')-test('places lines of mixed sizes as Figma does', async () => {+test('places and truncates lines of mixed sizes as Figma does', async () => {await editor.page.evaluate(() => {const store = window.openPencil?.getStore?.()if (!store) throw new Error('Missing editor')const big = (start: number, length: number) => ({ start, length, style: { fontSize: 36 } })const wrapping = 'Small words LARGE then wraps onto more lines'+ const truncationFill = [+ {+ type: 'SOLID' as const,+ color: { r: 0.86, g: 0.91, b: 0.98, a: 1 },+ opacity: 1,+ visible: true+ }+ ]+ for (const [name, y, height] of [+ ['Two small lines fit', 40, 34],+ ['Tall second line overflows', 220, 70]+ ] as const) {+ store.graph.createNode('RECTANGLE', store.state.currentPageId, {+ name,+ x: 732,+ y,+ width: 150,+ height,+ fills: truncationFill+ })+ }const texts = [{ x: 40, y: 40, text: wrapping, styleRuns: [big(12, 5)] },{ x: 280, y: 40, text: wrapping, styleRuns: [big(12, 5)], textAlignHorizontal: 'CENTER' },@@ -58,13 +79,37 @@ test('places lines of mixed sizes as Figma does', async () => {textParagraphs: 'textParagraphs' in props ? [...props.textParagraphs] : []})}+ store.graph.createNode('TEXT', store.state.currentPageId, {+ name: 'Small mixed-size lines fit the fixed height',+ x: 740,+ y: 40,+ width: 134,+ height: 34,+ text: 'small\nsmall\nsmall',+ fontSize: 40,+ textAutoResize: 'NONE',+ textTruncation: 'ENDING',+ styleRuns: [{ start: 0, length: 17, style: { fontSize: 12 } }]+ })+ store.graph.createNode('TEXT', store.state.currentPageId, {+ name: 'Tall mixed-size line exceeds the fixed height',+ x: 740,+ y: 220,+ width: 134,+ height: 70,+ text: 'small\nLARGE\nsmall',+ fontSize: 16,+ textAutoResize: 'NONE',+ textTruncation: 'ENDING',+ styleRuns: [{ start: 6, length: 5, style: { fontSize: 40 } }]+ })store.requestRender()})await editor.page.waitForFunction(() => {const store = window.openPencil?.getStore?.()return (store?.graph.getChildren(store.state.currentPageId).filter((node) => node.type === 'TEXT')- .length === 6+ .length === 8)})await editor.page.evaluate(diff --git a/tests/e2e/canvas/text/lines-visual.spec.ts-snapshots/text-lines-openpencil-darwin.png b/tests/e2e/canvas/text/lines-visual.spec.ts-snapshots/text-lines-openpencil-darwin.pngindex a7e636b3d..1cce6ec7d 100644Binary files a/tests/e2e/canvas/text/lines-visual.spec.ts-snapshots/text-lines-openpencil-darwin.png and b/tests/e2e/canvas/text/lines-visual.spec.ts-snapshots/text-lines-openpencil-darwin.png differ