AI-native design editor. Open-source Figma alternative.
fix: draw a fixed-size text's lines past its box, as Figma does (#1574)
Danila Poyarkov70c2d86e02ba
diff --git a/changes/1574/fixed.md b/changes/1574/fixed.mdnew file mode 100644index 000000000..398316de5--- /dev/null+++ b/changes/1574/fixed.md@@ -0,0 +1 @@+- A fixed-size text grown past its box draws its other lines below it, as in Figma, instead of being cut off at the box.diff --git a/packages/core/src/canvas/renderer/visual-bounds.ts b/packages/core/src/canvas/renderer/visual-bounds.tsindex 1c04224da..51e63e073 100644--- a/packages/core/src/canvas/renderer/visual-bounds.ts+++ b/packages/core/src/canvas/renderer/visual-bounds.ts@@ -9,6 +9,7 @@ import {type VisualBounds} from '@open-pencil/scene-graph/geometry'import Matrix, { type Mat3 } from '@open-pencil/scene-graph/matrix'+import { textLinesOverflow } from '@open-pencil/scene-graph/text'import { projectedNode, type RotationPreview } from '#core/geometry'@@ -41,13 +42,14 @@ export function worldNodeVisualBounds(graph: SceneGraph, node: SceneNode): VisuaminX: -stroke - effects.left,minY: -stroke - effects.top,maxX: node.width + stroke + effects.right,- maxY: node.height + stroke + effects.bottom+ maxY: node.height + textLinesOverflow(node) + stroke + effects.bottom})}/*** What a node draws itself, in its own axes before position, rotation, and flips: the box grown- * by strokes and effects, its path geometry, and text decoration. Children are not included.+ * by strokes and effects, its path geometry, and text lines and decoration. Children are not+ * included.*/function localVisualBounds(node: SceneNode): VisualBounds {const stroke = strokeOverflow(node.strokes, node.strokeCap, node.vectorNetwork, node)@@ -56,7 +58,8 @@ function localVisualBounds(node: SceneNode): VisualBounds {minX: -stroke - effects.left,minY: -stroke - effects.top,maxX: node.width + stroke + effects.right,- maxY: node.height + stroke + effects.bottom + textDecorationOverflow(node)+ maxY:+ node.height + textLinesOverflow(node) + stroke + effects.bottom + textDecorationOverflow(node)}const hasNonInsideStroke = node.strokes.some((stroke) => stroke.visible && stroke.align !== 'INSIDE'diff --git a/packages/core/src/canvas/scene.ts b/packages/core/src/canvas/scene.tsindex c7f6eb5f0..27c3938e9 100644--- a/packages/core/src/canvas/scene.ts+++ b/packages/core/src/canvas/scene.ts@@ -10,6 +10,7 @@ import {} from '@open-pencil/scene-graph/arrow-caps'import Matrix from '@open-pencil/scene-graph/matrix'import type { Color } from '@open-pencil/scene-graph/primitives'+import { textLinesOverflow } from '@open-pencil/scene-graph/text'import { createSceneGeometry, nodeOrientationMatrix, projectedNode } from '#core/geometry'import { shownText } from '#core/text/case'@@ -97,9 +98,12 @@ function isCulled(((node.type === 'FRAME' || node.type === 'COMPONENT' || node.type === 'INSTANCE') &&node.clipsContent)if (!canCull || hasOverflowPathTextPaint(node)) return false+ // Text lines past a fixed-size box still draw, as in Figma.+ const linesOverflow = textLinesOverflow(node)const vp = r.worldViewportif (hasTransformedAncestor) {+ if (linesOverflow > 0) return falseconst bounds = createSceneGeometry(graph, preview).bounds(node)return (bounds.x > vp.x + vp.w ||@@ -109,7 +113,7 @@ function isCulled()}const bw = node.width- const bh = node.height+ const bh = node.height + linesOverflowif (projectedNode(node, preview).rotation !== 0) {const diag = Math.hypot(bw, bh)const { x: cx, y: cy } = createSceneGeometry(graph, preview).toWorld(node, {@@ -957,13 +961,6 @@ function drawPaintedText(r: SkiaRenderer, canvas: Canvas, node: SceneNode): bool)}-function shouldClipTextToLayoutBox(node: SceneNode): boolean {- return (- !hasOverflowPathTextPaint(node) &&- (node.textAutoResize === 'NONE' || node.textAutoResize === 'TRUNCATE')- )-}-function drawResolvedPathText(r: SkiaRenderer,canvas: Canvas,@@ -987,16 +984,13 @@ function drawsLaidOutText(r: SkiaRenderer, node: SceneNode): boolean {}/**- * The emoji of a text, once whatever fills it has, clipped as its glyphs are: over its saved- * glyphs' placeholder squares, or over the blank squares the editor's layout gives them.+ * The emoji of a text, once whatever fills it has: over its saved glyphs' placeholder squares, or+ * over the blank squares the editor's layout gives them.*/function drawTextEmoji(r: SkiaRenderer, canvas: Canvas, node: SceneNode): void {const saved = drawsSavedText(node)if (!saved && !drawsLaidOutText(r, node)) returncanvas.save()- if (shouldClipTextToLayoutBox(node)) {- canvas.clipRect(r.ck.LTRBRect(0, 0, node.width, node.height), r.ck.ClipOp.Intersect, false)- }if (saved) drawSavedEmoji(r, canvas, node)else {withTextParagraph(r, node, r.ck.BLACK, { halfLeading: true }, (paragraph) =>@@ -1015,9 +1009,6 @@ export function renderText(r: SkiaRenderer, canvas: Canvas, node: SceneNode, filif (!text) returncanvas.save()- if (shouldClipTextToLayoutBox(node)) {- canvas.clipRect(r.ck.LTRBRect(0, 0, node.width, node.height), r.ck.ClipOp.Intersect, false)- }if (drawSavedText(r, canvas, node, fill)) {canvas.restore()diff --git a/packages/core/src/figma-api/render-bounds.ts b/packages/core/src/figma-api/render-bounds.tsindex c3376d7e9..23f515380 100644--- a/packages/core/src/figma-api/render-bounds.ts+++ b/packages/core/src/figma-api/render-bounds.ts@@ -9,6 +9,7 @@ import {} from '@open-pencil/scene-graph/geometry'import Matrix from '@open-pencil/scene-graph/matrix'import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'+import { textLinesOverflow } from '@open-pencil/scene-graph/text'const INTRINSIC_CONTAINER_TYPES = new Set(['FRAME',@@ -85,7 +86,9 @@ function translatedBounds(bounds: VisualBounds, offset: Vector, overflow: numberfunction ownRenderBounds(node: SceneNode, graph: SceneGraph): VisualBounds | null {if (!hasRenderableGeometry(node)) return null- const base = transformedRect(node, graph, 0, 0, node.width, node.height)+ // Text lines past a fixed-size box draw, and cast their shadow, as in Figma.+ const linesOverflow = textLinesOverflow(node)+ const base = transformedRect(node, graph, 0, 0, node.width, node.height + linesOverflow)const stroke = strokeOverflow(node.strokes, node.strokeCap, node.vectorNetwork, node)let bounds = transformedRect(node,@@ -111,6 +114,8 @@ function ownRenderBounds(node: SceneNode, graph: SceneGraph): VisualBounds | nul) ?? bounds}+ if (linesOverflow > 0) bounds = unionVisualBounds(bounds, base) ?? bounds+for (const effect of node.effects) {if (!effect.visible) continueif (effect.type === 'DROP_SHADOW') {diff --git a/packages/core/src/layout/text-auto-resize.ts b/packages/core/src/layout/text-auto-resize.tsindex 98d307017..c6ea16838 100644--- a/packages/core/src/layout/text-auto-resize.ts+++ b/packages/core/src/layout/text-auto-resize.ts@@ -3,15 +3,23 @@ import { TEXT_METRIC_FIELDS } from '@open-pencil/scene-graph/fields'import { measureTextForLayout } from './text-measurement'+/** Case and direction change what the lines hold, so how wide they are and where they break. */+const TEXT_CONTENT_FIELDS = ['textCase', 'textDirection'] as const+export const TEXT_AUTO_RESIZE_KEYS = new Set<keyof SceneNode>([...TEXT_METRIC_FIELDS,+ ...TEXT_CONTENT_FIELDS,'lineHeight','textAutoResize','width','maxLines'])-const TEXT_AUTO_WIDTH_KEYS = new Set<keyof SceneNode>([...TEXT_METRIC_FIELDS, 'textAutoResize'])+const TEXT_AUTO_WIDTH_KEYS = new Set<keyof SceneNode>([+ ...TEXT_METRIC_FIELDS,+ ...TEXT_CONTENT_FIELDS,+ 'textAutoResize'+])export function hasTextAutoResizeChange(changes: Partial<SceneNode>): boolean {return Object.keys(changes).some((key) => TEXT_AUTO_RESIZE_KEYS.has(key as keyof SceneNode))@@ -21,10 +29,14 @@ function hasTextAutoWidthChange(changes: Partial<SceneNode>): boolean {return Object.keys(changes).some((key) => TEXT_AUTO_WIDTH_KEYS.has(key as keyof SceneNode))}+type TextSizeChanges = Partial<+ Pick<SceneNode, 'width' | 'height' | 'derivedLayout' | 'derivedTextGlyphs' | 'derivedTextHeight'>+>+export function textAutoResizeChanges(node: SceneNode | undefined,changes: Partial<SceneNode>-): Partial<Pick<SceneNode, 'width' | 'height' | 'derivedLayout' | 'derivedTextGlyphs'>> {+): TextSizeChanges {if (node?.type !== 'TEXT' || !hasTextAutoResizeChange(changes)) return {}// Path text is laid out along its path (derivedTextGlyphs on textPathBox),// not by paragraph auto-resize. Running the measurement here would null the@@ -36,13 +48,17 @@ export function textAutoResizeChanges(const next = { ...node, ...changes }const mode = next.textAutoResize- if (mode !== 'HEIGHT' && mode !== 'WIDTH_AND_HEIGHT') return {}+ // A fixed-size box keeps its size; its lines are measured at its width, since they draw past it.+ if (mode !== 'HEIGHT' && mode !== 'WIDTH_AND_HEIGHT')+ return { derivedTextHeight: measureTextForLayout(next, next.width).height || null }const maxWidth = mode === 'HEIGHT' ? next.width : undefinedconst measured = measureTextForLayout(next, maxWidth)- const resized: Partial<- Pick<SceneNode, 'width' | 'height' | 'derivedLayout' | 'derivedTextGlyphs'>- > = { derivedLayout: null, derivedTextGlyphs: null }+ const resized: TextSizeChanges = {+ derivedLayout: null,+ derivedTextGlyphs: null,+ derivedTextHeight: null+ }if (mode === 'WIDTH_AND_HEIGHT' && hasTextAutoWidthChange(changes) && measured.width > 0)resized.width = measured.width@@ -76,9 +92,12 @@ export function sizeAutoResizingText(const resized =(changes.width !== undefined && changes.width !== node.width) ||(changes.height !== undefined && changes.height !== node.height)- if (!resized) continue- graph.updateNode(id, changes)- changed = true+ // A fixed-size box only learns how far its lines reach, which needs no layout.+ const measured =+ changes.derivedTextHeight !== undefined &&+ changes.derivedTextHeight !== node.derivedTextHeight+ if (resized || measured) graph.updateNode(id, changes)+ changed ||= resized}return changed}diff --git a/packages/core/tests/canvas/text/overflow.test.ts b/packages/core/tests/canvas/text/overflow.test.tsnew file mode 100644index 000000000..de7ec4885--- /dev/null+++ b/packages/core/tests/canvas/text/overflow.test.ts@@ -0,0 +1,87 @@+import { beforeAll, expect, test } from 'bun:test'++import { expectDefined } from '#core-tests/helpers/assert'++import { SceneGraph } from '@open-pencil/scene-graph'++import { SkiaRenderer } from '#core/canvas/renderer'+import { getCanvasKit } from '#core/canvaskit'+import { renderNodesToImage } from '#core/io/formats/raster/render'++let ck: Awaited<ReturnType<typeof getCanvasKit>>++beforeAll(async () => {+ ck = await getCanvasKit()+})++/** A unit square outline in the glyph commands blob format, drawn up from the baseline. */+function squareCommandsBlob(): Uint8Array {+ const corners = [+ [1, 0, 0],+ [2, 1, 0],+ [2, 1, 1],+ [2, 0, 1]+ ] as const+ const blob = new Uint8Array(1 + corners.length * 9)+ const view = new DataView(blob.buffer)+ corners.forEach(([command, x, y], index) => {+ blob[index * 9] = command+ view.setFloat32(index * 9 + 1, x, true)+ view.setFloat32(index * 9 + 5, y, true)+ })+ return blob+}++// Figma 126 draws a fixed-size text's lines past its box: only frames clip.+test('a fixed-size text draws its lines past its box', () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const glyph = (y: number) => ({+ commandsBlob: squareCommandsBlob(),+ x: 0,+ y,+ fontSize: 20,+ firstCharacter: 0,+ advance: 20+ })+ const text = graph.createNode('TEXT', page.id, {+ width: 40,+ height: 30,+ text: 'ab',+ fontFamily: '__MissingFont__',+ textAutoResize: 'NONE',+ fills: [{ type: 'SOLID', color: { r: 0, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }],+ derivedTextGlyphs: [glyph(25), glyph(55)],+ derivedTextHeight: 60+ })+ const surface = expectDefined(ck.MakeSurface(1, 1), 'surface')+ const renderer = new SkiaRenderer(ck, surface)+ // The font is missing, so the saved glyphs are what draws the text.+ renderer.nodeFontReadiness = () => 'exhausted'++ try {+ const png = expectDefined(+ renderNodesToImage(ck, renderer, graph, page.id, [text.id], { scale: 1, format: 'PNG' }),+ 'png'+ )+ const image = expectDefined(ck.MakeImageFromEncoded(png), 'image')+ const pixels = expectDefined(+ image.readPixels(0, 0, {+ alphaType: ck.AlphaType.Unpremul,+ colorType: ck.ColorType.RGBA_8888,+ colorSpace: ck.ColorSpace.SRGB,+ width: image.width(),+ height: image.height()+ }),+ 'pixels'+ )+ const alpha = (x: number, y: number) => pixels[(y * image.width() + x) * 4 + 3]+ // The export reaches the second line, whose glyph fills rows 35 to 55 below the 30 px box.+ expect(image.height()).toBe(60)+ expect(alpha(10, 15)).toBeGreaterThan(0)+ expect(alpha(10, 45)).toBeGreaterThan(0)+ image.delete()+ } finally {+ surface.delete()+ }+})diff --git a/packages/core/tests/editor/text/auto-resize.test.ts b/packages/core/tests/editor/text/auto-resize.test.tsindex 86c8a87fc..1abc15150 100644--- a/packages/core/tests/editor/text/auto-resize.test.ts+++ b/packages/core/tests/editor/text/auto-resize.test.ts@@ -123,4 +123,102 @@ describe('editor text auto-resize updates', () => {expect(getNodeOrThrow(editor.graph, text.id).width).toBe(64)expect(getNodeOrThrow(editor.graph, text.id).height).toBe(32)})++ test('auto-width text takes the width its case gives it', () => {+ setTextMeasurer((node) => ({+ width: (node.text?.length ?? 0) * (node.textCase === 'UPPER' ? 20 : 10),+ height: 20+ }))+ const editor = createEditor()+ const text = editor.graph.createNode('TEXT', editor.state.currentPageId, {+ text: 'ten chars!',+ textAutoResize: 'WIDTH_AND_HEIGHT',+ width: 100,+ height: 20+ })++ editor.updateNode(text.id, { textCase: 'UPPER' })++ expect(getNodeOrThrow(editor.graph, text.id).width).toBe(200)+ })++ test('auto-width text takes the width its direction gives it', () => {+ setTextMeasurer((node) => ({+ width: (node.text?.length ?? 0) * (node.textDirection === 'RTL' ? 20 : 10),+ height: 20+ }))+ const editor = createEditor()+ const text = editor.graph.createNode('TEXT', editor.state.currentPageId, {+ text: 'ten chars!',+ textAutoResize: 'WIDTH_AND_HEIGHT',+ width: 100,+ height: 20+ })++ editor.updateNode(text.id, { textDirection: 'RTL' })++ expect(getNodeOrThrow(editor.graph, text.id).width).toBe(200)+ })+})++// Figma 126 draws a fixed-size text's lines past its box, so they are measured even though the+// box keeps its size.+describe('fixed-size text', () => {+ test('keeps its box and measures how far its lines reach', () => {+ setTextMeasurer((node, maxWidth) => {+ const width = (node.text?.length ?? 0) * node.fontSize * 0.5+ const lines = maxWidth ? Math.ceil(width / maxWidth) : 1+ return { width: Math.min(width, maxWidth ?? width), height: lines * node.fontSize * 1.2 }+ })+ const editor = createEditor()+ const text = editor.graph.createNode('TEXT', editor.state.currentPageId, {+ text: 'dssdds',+ textAutoResize: 'NONE',+ width: 110,+ height: 40,+ fontSize: 14+ })++ editor.updateNode(text.id, { fontSize: 64 })++ const node = getNodeOrThrow(editor.graph, text.id)+ expect([node.width, node.height]).toEqual([110, 40])+ expect(node.derivedTextHeight).toBeCloseTo(2 * 64 * 1.2)+ })++ test('auto-sized text has no lines past its box', () => {+ setTextMeasurer((node) => ({ width: 100, height: node.fontSize * 1.2 }))+ const editor = createEditor()+ const text = editor.graph.createNode('TEXT', editor.state.currentPageId, {+ text: 'Hello',+ textAutoResize: 'NONE',+ width: 50,+ height: 10,+ derivedTextHeight: 80+ })++ editor.updateNode(text.id, { textAutoResize: 'WIDTH_AND_HEIGHT' })++ expect(getNodeOrThrow(editor.graph, text.id).derivedTextHeight).toBeNull()+ })++ test('measures its lines again when their case changes', () => {+ // Upper case takes more room here, so the same text wraps onto more lines.+ setTextMeasurer((node, maxWidth) => {+ const width = (node.text?.length ?? 0) * (node.textCase === 'UPPER' ? 20 : 10)+ const lines = maxWidth ? Math.ceil(width / maxWidth) : 1+ return { width: Math.min(width, maxWidth ?? width), height: lines * 20 }+ })+ const editor = createEditor()+ const text = editor.graph.createNode('TEXT', editor.state.currentPageId, {+ text: 'ten chars!',+ textAutoResize: 'NONE',+ width: 100,+ height: 20+ })++ editor.updateNode(text.id, { textCase: 'UPPER' })++ expect(getNodeOrThrow(editor.graph, text.id).derivedTextHeight).toBe(40)+ })})diff --git a/packages/core/tests/figma-api/render-bounds.test.ts b/packages/core/tests/figma-api/render-bounds.test.tsindex 929cd9110..984962ea6 100644--- a/packages/core/tests/figma-api/render-bounds.test.ts+++ b/packages/core/tests/figma-api/render-bounds.test.ts@@ -38,6 +38,31 @@ describe('absoluteRenderBounds', () => {expect(emptyVector.absoluteRenderBounds).toBeNull()})+ // Figma 126 draws a fixed-size text's lines past its box, and their shadow with them.+ test('absoluteRenderBounds reaches text lines past a fixed-size box and their shadow', () => {+ const graph = new SceneGraph()+ const api = new FigmaAPI(graph)+ const text = api.createText()+ text.characters = 'Lines'+ text.fills = [solidFill({ r: 0, g: 0, b: 0, a: 1 })]+ text.textAutoResize = 'NONE'+ text.resize(110, 40)+ graph.updateNode(text.id, { derivedTextHeight: 150 })+ text.effects = [+ {+ type: 'DROP_SHADOW',+ color: { r: 0, g: 0, b: 0, a: 1 },+ offset: { x: 0, y: 10 },+ radius: 0,+ spread: 0,+ visible: true,+ blendMode: 'NORMAL'+ }+ ]++ expect(text.absoluteRenderBounds).toEqual({ x: 0, y: 0, width: 110, height: 160 })+ })+test('absoluteRenderBounds is clipped by ancestor frames', () => {const api = new FigmaAPI(new SceneGraph())const frame = api.createFrame()diff --git a/packages/fig/src/node-change/convert.ts b/packages/fig/src/node-change/convert.tsindex 4a807ead3..0c7c4e69f 100644--- a/packages/fig/src/node-change/convert.ts+++ b/packages/fig/src/node-change/convert.ts@@ -486,10 +486,11 @@ function convertTextProps(nc: NodeChange, blobs: Uint8Array[]): TextProps {function convertDerivedText(nc: NodeChange,blobs: Uint8Array[]-): Pick<SceneNode, 'derivedLayout' | 'derivedTextGlyphs'> {+): Pick<SceneNode, 'derivedLayout' | 'derivedTextGlyphs' | 'derivedTextHeight'> {const layoutSize = nc.derivedTextData?.layoutSizereturn {derivedLayout: layoutSize ? { width: layoutSize.x, height: layoutSize.y } : null,+ derivedTextHeight: savedLinesHeight(nc),derivedTextGlyphs: convertFigmaDerivedTextGlyphs(nc.derivedTextData,blobs,@@ -498,6 +499,17 @@ function convertDerivedText(}}+/**+ * How far the lines Figma saved reach: the bottom of the last one. Figma's layout size is the box+ * of a fixed-size text even when its lines draw past it, so the lines themselves tell.+ */+function savedLinesHeight(nc: NodeChange): number | null {+ const bottoms = (nc.derivedTextData?.baselines ?? []).map(+ (line) => (line.lineY ?? line.position.y - line.lineAscent) + line.lineHeight+ )+ return bottoms.length > 0 ? Math.max(...bottoms) : null+}+function convertLayoutPadding(nc: NodeChange): Pick<SceneNode, 'paddingTop' | 'paddingBottom' | 'paddingLeft' | 'paddingRight'> {diff --git a/packages/fig/tests/node-change/index.test.ts b/packages/fig/tests/node-change/index.test.tsindex ba4fec3ae..7d58ecfa2 100644--- a/packages/fig/tests/node-change/index.test.ts+++ b/packages/fig/tests/node-change/index.test.ts@@ -106,6 +106,31 @@ describe('@open-pencil/fig NodeChange policy', () => {for (const [i, value] of expected.entries()) expect(actual[i]).toBeCloseTo(value)})+ // Figma's layout size is a fixed-size text's box even when its lines draw past it.+ test('reads how far a text’s saved lines reach', () => {+ const line = (lineY: number) => ({+ firstCharacter: 0,+ endCharacter: 3,+ position: { x: 0, y: lineY + 58 },+ width: 100,+ lineY,+ lineHeight: 77,+ lineAscent: 58+ })+ const props = nodeChangeToProps(+ {+ type: 'TEXT',+ size: { x: 110, y: 40 },+ textAutoResize: 'NONE',+ derivedTextData: { layoutSize: { x: 110, y: 40 }, baselines: [line(0), line(77)] }+ },+ []+ )++ expect(props.derivedLayout).toEqual({ width: 110, height: 40 })+ expect(props.derivedTextHeight).toBe(154)+ })+test('converts normalized text values', () => {// A percent stays one, and Figma's RAW multiplier is a percent too.expect(convertLineHeight({ value: 120, units: 'PERCENT' })).toEqual(percentLength(120))diff --git a/packages/scene-graph/src/geometry.ts b/packages/scene-graph/src/geometry.tsindex 771088c01..b761ecf7a 100644--- a/packages/scene-graph/src/geometry.ts+++ b/packages/scene-graph/src/geometry.ts@@ -1,5 +1,6 @@import { arrowCapOverflow } from './arrow-caps'import type { Rect, Vector } from './primitives'+import { textLinesOverflow } from './text/overflow'import type { Effect, Stroke, StrokeCap, StrokeJoin, VectorNetwork } from './types'export function degToRad(degrees: number): number {@@ -296,6 +297,7 @@ export interface VisualBoundsNode {textDecoration?: stringtextUnderlineOffset?: number | nulltextDecorationThickness?: number | null+ derivedTextHeight?: number | null}export function unionVisualBounds(@@ -409,6 +411,12 @@ export function nodeVisualBounds(bounds = unionVisualBounds(bounds, transformedLocalBounds(node, localGeometry, abs)) ?? bounds}+ const linesOverflow = textLinesOverflow(node)+ if (linesOverflow > 0) {+ const lines = { x: 0, y: 0, width: node.width, height: node.height + linesOverflow }+ bounds = unionVisualBounds(bounds, transformedLocalBounds(node, lines, abs)) ?? bounds+ }+bounds.maxY += textDecorationOverflow(node)return boundsdiff --git a/packages/scene-graph/src/node-defaults.ts b/packages/scene-graph/src/node-defaults.tsindex d01015acb..57b4b659d 100644--- a/packages/scene-graph/src/node-defaults.ts+++ b/packages/scene-graph/src/node-defaults.ts@@ -223,6 +223,7 @@ export function createDefaultNode(flipY: false,textPicture: null,derivedTextGlyphs: null,+ derivedTextHeight: null,textPathData: null,textPathBox: null,booleanOperation: undefined,diff --git a/packages/scene-graph/src/text/index.ts b/packages/scene-graph/src/text/index.tsindex 8de0a312d..4242efd16 100644--- a/packages/scene-graph/src/text/index.ts+++ b/packages/scene-graph/src/text/index.ts@@ -2,4 +2,5 @@ export * from './lists'export * from './paragraphs'export * from './references'export * from './lengths'+export * from './overflow'export * from './schema'diff --git a/packages/scene-graph/src/text/overflow.ts b/packages/scene-graph/src/text/overflow.tsnew file mode 100644index 000000000..4ba4796c2--- /dev/null+++ b/packages/scene-graph/src/text/overflow.ts@@ -0,0 +1,12 @@+import type { VisualBoundsNode } from '../geometry'++type TextBoundsNode = Pick<VisualBoundsNode, 'type' | 'height' | 'derivedTextHeight'>++/**+ * How far a text's lines reach below its box: a fixed-size box does not clip them, as in Figma,+ * and the renderer starts them at its top.+ */+export function textLinesOverflow(node: TextBoundsNode): number {+ if (node.type !== 'TEXT' || !node.derivedTextHeight) return 0+ return Math.max(0, node.derivedTextHeight - node.height)+}diff --git a/packages/scene-graph/src/types.ts b/packages/scene-graph/src/types.tsindex 938e5ecd3..a63f73d4c 100644--- a/packages/scene-graph/src/types.ts+++ b/packages/scene-graph/src/types.ts@@ -847,6 +847,12 @@ export interface SceneNode {textPicture: Uint8Array | nullderivedTextGlyphs: DerivedTextGlyph[] | null+ /**+ * How far a text's lines reach down from its top: measured at its width when its text or width+ * changes, or read from the lines a file saved, and never saved itself. A fixed-size box does not+ * clip them, as in Figma, so its visual bounds reach this far. Null when not known.+ */+ derivedTextHeight: number | null/** Format-neutral layout path for text-on-path nodes. */textPathData: TextPathData | null/** Node-local box that maps textPathData into the node coordinate space. */diff --git a/packages/scene-graph/tests/geometry.test.ts b/packages/scene-graph/tests/geometry.test.tsnew file mode 100644index 000000000..2d0f1c735--- /dev/null+++ b/packages/scene-graph/tests/geometry.test.ts@@ -0,0 +1,31 @@+import { describe, expect, test } from 'bun:test'++import { nodeVisualBounds, type VisualBoundsNode } from '@open-pencil/scene-graph/geometry'++const at = () => ({ x: 10, y: 20 })++function text(props: Partial<VisualBoundsNode>): VisualBoundsNode {+ return { id: 'text', type: 'TEXT', visible: true, width: 110, height: 40, ...props }+}++// Figma 126 draws a fixed-size text's lines past its box.+describe('text lines past a fixed-size box', () => {+ test('reach the visual bounds', () => {+ expect(nodeVisualBounds(text({ derivedTextHeight: 154 }), at)).toEqual({+ minX: 10,+ minY: 20,+ maxX: 120,+ maxY: 174+ })+ })++ test('turn with the text', () => {+ const bounds = nodeVisualBounds(text({ derivedTextHeight: 154, rotation: 90 }), at)+ expect(bounds.maxX - bounds.minX).toBeCloseTo(154)+ expect(bounds.maxY - bounds.minY).toBeCloseTo(110)+ })++ test('within the box leave it as it is', () => {+ expect(nodeVisualBounds(text({ derivedTextHeight: 30 }), at).maxY).toBe(60)+ })+})diff --git a/tests/e2e/canvas/text/overflow-visual.spec.ts b/tests/e2e/canvas/text/overflow-visual.spec.tsnew file mode 100644index 000000000..88815ad5e--- /dev/null+++ b/tests/e2e/canvas/text/overflow-visual.spec.ts@@ -0,0 +1,17 @@+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'+import { textOverflowDriver } from '#tests/helpers/canvas/text-overflow-driver'++const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')+const texts = textOverflowDriver(() => editor.page)++// Figma 126 never clips a text layer to its box: a fixed-size box grown past by its text draws+// the rest below it, and only a frame that clips its content cuts the text off.+test('draws a fixed-size text past its box, and a clipping frame still cuts it', async () => {+ for (const { height, linesHeight } of await texts.show()) {+ expect(height).toBe(40)+ expect(linesHeight).toBeGreaterThan(100)+ }+ await editor.canvas.waitForRender()+ editor.canvas.assertNoErrors()+ expect(await editor.canvas.screenshotCanvasRegion()).toMatchSnapshot('text-overflow.png')+})diff --git a/tests/e2e/canvas/text/overflow-visual.spec.ts-snapshots/text-overflow-openpencil-darwin.png b/tests/e2e/canvas/text/overflow-visual.spec.ts-snapshots/text-overflow-openpencil-darwin.pngnew file mode 100644index 000000000..0ba74c22aBinary files /dev/null and b/tests/e2e/canvas/text/overflow-visual.spec.ts-snapshots/text-overflow-openpencil-darwin.png differdiff --git a/tests/helpers/canvas/text-overflow-driver.ts b/tests/helpers/canvas/text-overflow-driver.tsnew file mode 100644index 000000000..0839acbce--- /dev/null+++ b/tests/helpers/canvas/text-overflow-driver.ts@@ -0,0 +1,72 @@+import type { Page } from '@playwright/test'++/** A fixed-size text's box height and how far its lines reach below its top. */+export interface TextOverflowState {+ height: number+ linesHeight: number | null+}++/**+ * Fixed-size texts grown past their boxes: one on the page over a rectangle showing its box, and+ * one in a frame that clips its content. The font size goes through the editor, which measures+ * the lines, as the panel's does.+ */+export function textOverflowDriver(page: () => Page) {+ return {+ show(): Promise<TextOverflowState[]> {+ return page().evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const pageId = store.state.currentPageId+ const boxFill = [+ {+ type: 'SOLID' as const,+ color: { r: 0.86, g: 0.91, b: 0.98, a: 1 },+ opacity: 1,+ visible: true+ }+ ]+ const frame = store.graph.createNode('FRAME', pageId, {+ name: 'Clips its content',+ x: 300,+ y: 40,+ width: 160,+ height: 120,+ clipsContent: true,+ fills: boxFill+ })+ store.graph.createNode('RECTANGLE', pageId, {+ name: 'Box',+ x: 40,+ y: 40,+ width: 110,+ height: 40,+ fills: boxFill+ })+ const ids = [+ { parent: pageId, x: 40, y: 40 },+ { parent: frame.id, x: 20, y: 20 }+ ].map(({ parent, x, y }) => {+ const text = store.graph.createNode('TEXT', parent, {+ x,+ y,+ width: 110,+ height: 40,+ text: 'dssdds grows',+ fontSize: 14,+ textAutoResize: 'NONE'+ })+ store.updateNode(text.id, { fontSize: 48 })+ return text.id+ })+ store.clearSelection()+ store.requestRender()+ return ids.map((id) => {+ const node = store.graph.getNode(id)+ if (!node) throw new Error(`Missing text ${id}`)+ return { height: node.height, linesHeight: node.derivedTextHeight }+ })+ })+ }+ }+}