AI-native design editor. Open-source Figma alternative.
fix: fit shapes with text to their label as FigJam does (#1337)
Danila Poyarkov9d9ff464c52b
diff --git a/changes/1239/added.md b/changes/1239/added.mdindex e3ce79f04..40638f0c0 100644--- a/changes/1239/added.md+++ b/changes/1239/added.md@@ -1 +1 @@-- FigJam shapes with text open from `.fig` files and paste from FigJam with their kind, colour, corners, and label, grow to fit their label as FigJam does, save back as FigJam shapes, and are written and read as `<Shape>` in design JSX. A Shape tool, shown from Customize toolbar, picks any of FigJam's 30 kinds from a searchable grid and places it as FigJam does, with its label ready to type; the Design panel switches a selected shape's kind and styles it with FigJam's palette, fill and line modes, text sizes, and typefaces, and the Layers panel shows each kind's outline. Sticky notes take FigJam's typefaces too (#1114).+- FigJam shapes with text open from `.fig` files and paste from FigJam with their kind, colour, corners, and label, grow taller to fit their label or, once their height is set, keep it and end the label with "…", as FigJam does, save back as FigJam shapes, and are written and read as `<Shape>` in design JSX. A Shape tool, shown from Customize toolbar, picks any of FigJam's 30 kinds from a searchable grid and places it as FigJam does, with its label ready to type; the Design panel switches a selected shape's kind and styles it with FigJam's palette, fill and line modes, text sizes, and typefaces, and sets its corner radius and its label's typography as Figma's Design panel does, and the Layers panel shows each kind's outline. Sticky notes take FigJam's typefaces too (#1114).diff --git a/packages/core/src/canvas/labels/paragraph-cache.ts b/packages/core/src/canvas/labels/paragraph-cache.tsindex fa28465ca..527b9c3c4 100644--- a/packages/core/src/canvas/labels/paragraph-cache.ts+++ b/packages/core/src/canvas/labels/paragraph-cache.ts@@ -14,6 +14,7 @@ import { ResourceCache } from '#core/cache/resource'import { resolveParagraphFontFamilies } from '#core/canvas/text/font-families'import { DEFAULT_FONT_FAMILY, SECTION_TITLE_FONT_FAMILY } from '#core/constants'import { textHasFallbackScript } from '#core/text/coverage'+import { ELLIPSIS } from '#core/text/ellipsis'import { weightToStyle } from '#core/text/fonts'import { missingGlyphOccurrences, type MissingGlyphOccurrence } from '#core/text/resolver'@@ -71,7 +72,7 @@ function buildEntry(): LabelParagraphEntry {const style = new ck.ParagraphStyle({maxLines: 1,- ellipsis: '…',+ ellipsis: ELLIPSIS,textDirection:detectTextDirection(text) === 'RTL' ? ck.TextDirection.RTL : ck.TextDirection.LTR,textAlign: ck.TextAlign.Left,diff --git a/packages/core/src/canvas/labels/text.ts b/packages/core/src/canvas/labels/text.tsindex 1eddb671e..3cd62325f 100644--- a/packages/core/src/canvas/labels/text.ts+++ b/packages/core/src/canvas/labels/text.ts@@ -1,5 +1,7 @@import type { Font } from 'canvaskit-wasm'+import { ELLIPSIS } from '#core/text/ellipsis'+export function measureLabelText(font: Font, text: string): number {const glyphIds = font.getGlyphIDs(text)const widths = font.getGlyphWidths(glyphIds)@@ -12,9 +14,8 @@ export function ellipsizeLabelText(font: Font, text: string, maxWidth: number):if (maxWidth <= 0) return ''if (measureLabelText(font, text) <= maxWidth) return text- const ellipsis = '…'- const ellipsisWidth = measureLabelText(font, ellipsis)- if (maxWidth <= ellipsisWidth) return ellipsis+ const ellipsisWidth = measureLabelText(font, ELLIPSIS)+ if (maxWidth <= ellipsisWidth) return ELLIPSISlet width = 0let end = 0@@ -25,5 +26,5 @@ export function ellipsizeLabelText(font: Font, text: string, maxWidth: number):width += widths[index]end = index + 1}- return text.slice(0, end) + ellipsis+ return text.slice(0, end) + ELLIPSIS}diff --git a/packages/core/src/canvas/text/paragraph/index.ts b/packages/core/src/canvas/text/paragraph/index.tsindex 99a0bd49f..87bf49f8d 100644--- a/packages/core/src/canvas/text/paragraph/index.ts+++ b/packages/core/src/canvas/text/paragraph/index.ts@@ -24,6 +24,7 @@ import {import type { TextRenderer } from '#core/canvas/text/renderer'import { DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE } from '#core/constants'import { shownTextSlice } from '#core/text/case'+import { ELLIPSIS } from '#core/text/ellipsis'import { fontManager, weightToStyle } from '#core/text/fonts'import type { ParagraphNode } from './inputs'@@ -40,7 +41,7 @@ export function buildTruncateOpts(): { maxLines?: number; ellipsis?: string } {if (node.textTruncation !== 'ENDING') return {}- const opts: { maxLines?: number; ellipsis: string } = { ellipsis: '…' }+ const opts: { maxLines?: number; ellipsis: string } = { ellipsis: ELLIPSIS }if (node.maxLines != null && node.maxLines > 0) {opts.maxLines = node.maxLines} else if (node.height > 0) {diff --git a/packages/core/src/canvas/text/placed.ts b/packages/core/src/canvas/text/placed.tsindex 9190ffaf1..1777767f1 100644--- a/packages/core/src/canvas/text/placed.ts+++ b/packages/core/src/canvas/text/placed.ts@@ -9,6 +9,7 @@ import type { TextLayout, TextLayoutMarker } from '#core/canvas/text/layout'import { textFontVariations } from '#core/canvas/text/paragraph'import { utf16IndicesByUtf8 } from '#core/canvas/text/utf8'import { DEFAULT_FONT_FAMILY } from '#core/constants'+import { ELLIPSIS } from '#core/text/ellipsis'import { fontManager, weightToStyle } from '#core/text/fonts'import { glyphOutlineSourceSync, type GlyphOutlineSource } from '#core/text/opentype'@@ -164,9 +165,6 @@ function runOutlineSource(return null}-/** What truncated text ends in, as the paragraph builds it. */-const ELLIPSIS = '…'-/*** The font of the ellipsis that ends truncated text, when the run is that ellipsis: the* paragraph adds it after the last characters shown, from the first font that maps it.diff --git a/packages/core/src/editor/selection/colors.ts b/packages/core/src/editor/selection/colors.tsindex b366fe9bd..fcecf2cf0 100644--- a/packages/core/src/editor/selection/colors.ts+++ b/packages/core/src/editor/selection/colors.ts@@ -1,8 +1,10 @@+import { stickySublayers } from '@open-pencil/scene-graph'import type { Color, Fill, SceneGraph, SceneNode } from '@open-pencil/scene-graph'/*** Figma's Selection colors: every solid fill and stroke colour of the selected layers and their- * descendants, most used first. Effect colours and colours bound to a variable are left out.+ * descendants, most used first. Effect colours, colours bound to a variable and a sticky note's+ * author line are left out.*/export interface SelectionColor {@@ -43,7 +45,9 @@ function eachNode(graph: SceneGraph, ids: readonly string[], visit: (node: Sceneconst node = graph.getNode(id)if (!node) returnvisit(node)- for (const childId of node.childIds) walk(childId)+ // Figma lists a note's body and colour, not the author line it writes itself.+ const author = node.type === 'STICKY' ? stickySublayers(graph, node)?.author : undefined+ for (const childId of node.childIds) if (childId !== author?.id) walk(childId)}for (const id of ids) walk(id)}diff --git a/packages/core/src/layout/shape-with-text.ts b/packages/core/src/layout/shape-with-text.tsindex 3ee26fd15..37fa089bd 100644--- a/packages/core/src/layout/shape-with-text.ts+++ b/packages/core/src/layout/shape-with-text.ts@@ -1,61 +1,73 @@-import { compact } from 'es-toolkit'--import { shapeWithTextFrameFields, shapeWithTextLabel } from '@open-pencil/scene-graph'+import {+ SHAPE_WITH_TEXT_LABEL_LAYOUT,+ shapeWithTextFrameFields,+ shapeWithTextLabel+} from '@open-pencil/scene-graph'import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'-import { fitShapeWithText } from '@open-pencil/scene-graph/shape-with-text'+import {+ fitShapeWithTextHeight,+ shapeWithTextLabelBox+} from '@open-pencil/scene-graph/shape-with-text'import { measureTextForLayout } from './text-measurement'-/** The size a shape with text was given: what a user or script last set, else its own. */-function givenSize(shape: SceneNode): { width: number; height: number } {- return {- width: shape.shapeUserWidth > 0 ? shape.shapeUserWidth : shape.width,- height: shape.shapeUserHeight > 0 ? shape.shapeUserHeight : shape.height- }+/** The height a shape with text was given: what a user or script last set, else its own. */+function givenHeight(shape: SceneNode): number {+ return shape.shapeUserHeight > 0 ? shape.shapeUserHeight : shape.height}/**- * The size and padding a shape with text takes for its label, as FigJam fits it (see- * fitShapeWithText): its given size while the label fits, grown just enough when it does not.+ * The height and padding a shape with text takes for its label, as FigJam fits it (see+ * fitShapeWithTextHeight). A shape whose height was set keeps it (`shapeTruncates`).*/export function shapeWithTextFit(graph: SceneGraph, shape: SceneNode): Partial<SceneNode> {- const given = givenSize(shape)const label = shapeWithTextLabel(graph, shape)- let size = given- if (label?.text) {- const wrapping: SceneNode = { ...label, textAutoResize: 'HEIGHT' }- const words = compact(label.text.split(/\s+/))- const longestWord = Math.max(- 0,- // A word is measured on one line, unwrapped, so its width is never capped by the label's.- ...words.map(- (word) =>- measureTextForLayout({- ...label,- text: word,- styleRuns: [],- textAutoResize: 'WIDTH_AND_HEIGHT'- }).width- )+ let height = shape.shapeTruncates ? shape.height : givenHeight(shape)+ if (label?.text && !shape.shapeTruncates) {+ height = fitShapeWithTextHeight(shape.shapeWithTextType, shape.width, height, (maxWidth) =>+ measureTextForLayout(wholeText(label, maxWidth), maxWidth))- size = fitShapeWithText(shape.shapeWithTextType, {- ...given,- longestWord,- measure: (maxWidth) => measureTextForLayout({ ...wrapping, width: maxWidth }, maxWidth)- })}+ return { height, ...shapeWithTextFrameFields(shape.shapeWithTextType, shape.width, height) }+}++/** A label's whole text wrapped at `width`, not cut short by a truncation it already has. */+function wholeText(label: SceneNode, width: number): SceneNode {return {- ...size,- ...shapeWithTextFrameFields(shape.shapeWithTextType, size.width, size.height)+ ...label,+ ...SHAPE_WITH_TEXT_LABEL_LAYOUT,+ textTruncation: 'DISABLED',+ maxLines: null,+ width}}-/** Fits a shape with text to its label before its auto layout places the label. */+/**+ * How a shape's label sits in its label box: as tall as its text, or, in a shape that keeps its+ * height, cut to the box with "…" when the text runs past it, as FigJam truncates it.+ */+function labelFit(shape: SceneNode, label: SceneNode): Partial<SceneNode> {+ const whole = { ...SHAPE_WITH_TEXT_LABEL_LAYOUT, textTruncation: 'DISABLED' } as const+ if (!shape.shapeTruncates || !label.text) return whole+ const box = shapeWithTextLabelBox(shape.shapeWithTextType, shape.width, shape.height)+ if (measureTextForLayout(wholeText(label, box.width), box.width).height <= box.height)+ return whole+ return { textAutoResize: 'NONE', height: box.height, textTruncation: 'ENDING' }+}++/** Fits a shape with text and its label before its auto layout places the label. */export function fitShapeWithTextFrame(graph: SceneGraph, shape: SceneNode): void {if (shape.type !== 'SHAPE_WITH_TEXT') return- const fit = shapeWithTextFit(graph, shape)+ updateChanged(graph, shape, shapeWithTextFit(graph, shape))+ const fitted = graph.getNode(shape.id)+ const label = fitted && shapeWithTextLabel(graph, fitted)+ if (fitted && label) updateChanged(graph, label, labelFit(fitted, label))+}++/** Writes only the fields that differ, so a shape that already fits records no change. */+function updateChanged(graph: SceneGraph, node: SceneNode, fields: Partial<SceneNode>): void {const changes = Object.fromEntries(- Object.entries(fit).filter(([key, value]) => Reflect.get(shape, key) !== value)+ Object.entries(fields).filter(([key, value]) => Reflect.get(node, key) !== value))- if (Object.keys(changes).length > 0) graph.updateNode(shape.id, changes)+ if (Object.keys(changes).length > 0) graph.updateNode(node.id, changes)}diff --git a/packages/core/src/rpc/read-commands.ts b/packages/core/src/rpc/read-commands.tsindex 29195a5b9..630aad9df 100644--- a/packages/core/src/rpc/read-commands.ts+++ b/packages/core/src/rpc/read-commands.ts@@ -2,6 +2,7 @@ import { sumBy } from 'es-toolkit'import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import { ELLIPSIS } from '#core/text/ellipsis'import type { DocumentFontStatus } from '#core/text/font/status'import { prepareGraphFonts } from '#core/text/prepare'import { queryByXPath } from '#core/xpath'@@ -337,7 +338,7 @@ export const nodeCommand: RPCCommand<NodeArgs, NodeResult | { error: string }> =textDirection: node.textDirection,text: (() => {if (!node.text.length) return null- if (node.text.length > 200) return node.text.slice(0, 200) + '…'+ if (node.text.length > 200) return node.text.slice(0, 200) + ELLIPSISreturn node.text})(),parent: parent ? { id: parent.id, name: parent.name, type: parent.type } : null,diff --git a/packages/core/src/text/ellipsis.ts b/packages/core/src/text/ellipsis.tsnew file mode 100644index 000000000..cab5c72cd--- /dev/null+++ b/packages/core/src/text/ellipsis.ts@@ -0,0 +1,5 @@+/**+ * The character that ends text cut short: a truncated text layer, which Figma saves with its glyph,+ * and the editor's own labels.+ */+export const ELLIPSIS = '…'diff --git a/packages/core/tests/design-jsx/shapes-with-text.test.ts b/packages/core/tests/design-jsx/shapes-with-text.test.tsindex 92422c75b..340d72982 100644--- a/packages/core/tests/design-jsx/shapes-with-text.test.ts+++ b/packages/core/tests/design-jsx/shapes-with-text.test.ts@@ -33,8 +33,8 @@ describe('shapes with text in design JSX', () => {autoRename: false,width: 240,height: 160,- shapeUserWidth: 240,shapeUserHeight: 160,+ shapeTruncates: false,cornerRadius: 0})})@@ -57,10 +57,24 @@ describe('shapes with text in design JSX', () => {const label = 'A label long enough to need more lines than a small square holds'const [result] = await renderJSX(graph, `<Shape w={120} h={120}>${label}</Shape>`)const shape = getNodeOrThrow(graph, result.id)+ expect([shape.width, shape.height]).toEqual([120, expect.any(Number)])expect(shape.height).toBeGreaterThan(120)expect(sceneNodeToJSX(result.id, graph)).toContain('w={120} h={120}')})+ test('truncate keeps the height and cuts the label off, and writes back', async () => {+ const graph = new SceneGraph()+ const label = 'A label long enough to need more lines than a small square holds'+ const [result] = await renderJSX(graph, `<Shape w={120} h={120} truncate>${label}</Shape>`)+ const shape = getNodeOrThrow(graph, result.id)+ expect(shape).toMatchObject({ height: 120, shapeTruncates: true })+ expect(shapeWithTextLabel(graph, shape)?.textTruncation).toBe('ENDING')+ expect(sceneNodeToJSX(result.id, graph)).toContain('w={120} h={120} truncate')+ // The height it keeps is written, even where the height it was given differs, as a file can.+ graph.updateNode(shape.id, { shapeUserHeight: 90 })+ expect(sceneNodeToJSX(result.id, graph)).toContain('w={120} h={120} truncate')+ })+test('a prop of the wrong kind warns and is left out', async () => {const graph = new SceneGraph()const [result] = await renderJSX(graph, '<Shape kind="blob" w={0}>Hi</Shape>')diff --git a/packages/core/tests/editor/selection/colors.test.ts b/packages/core/tests/editor/selection/colors.test.tsindex 15e14faf0..51a8583cf 100644--- a/packages/core/tests/editor/selection/colors.test.ts+++ b/packages/core/tests/editor/selection/colors.test.ts@@ -6,6 +6,7 @@ import {selectionColors,selectionColorsShown} from '@open-pencil/core/editor'+import { createSticky, stickySublayers } from '@open-pencil/scene-graph'import type { Color, Fill } from '@open-pencil/scene-graph'const RED = { r: 1, g: 0.3, b: 0.2, a: 1 }@@ -92,4 +93,20 @@ describe('selection colors', () => {expect(selectionColorsShown(graph, [rectA, ellipse])).toBe(true)expect(selectionColorsShown(graph, [frame])).toBe(true)})++ test("a sticky note lists its body and colour, not its author line, as in Figma", () => {+ const editor = createEditor()+ const { graph } = editor+ const note = createSticky(graph, graph.getPages()[0].id, { text: 'Hi' })+ const author = stickySublayers(graph, note)?.author+ expect(author?.fills.length).toBeGreaterThan(0)+ const listed = selectionColors(graph, [note.id]).map(({ opacity }) => opacity)+ // The body's black at 80% and the note colour; the author's black at 50% is left out.+ expect(listed).toHaveLength(2)+ expect(listed).toContain(0.8)+ // The author line listed on its own, before or after its note, is walked all the same.+ const authorId = author?.id ?? ''+ expect(selectionColors(graph, [authorId, note.id])).toHaveLength(3)+ expect(selectionColors(graph, [note.id, authorId])).toHaveLength(3)+ })})diff --git a/packages/core/tests/layout/generated/shape-with-text.test.ts b/packages/core/tests/layout/generated/shape-with-text.test.tsindex 433a8f384..0aa04d62a 100644--- a/packages/core/tests/layout/generated/shape-with-text.test.ts+++ b/packages/core/tests/layout/generated/shape-with-text.test.ts@@ -54,4 +54,52 @@ describe('shape with text size', () => {computeAllLayouts(graph, id)expect(getNodeOrThrow(graph, id).height).toBe(176)})++ test('a long label grows the shape taller only, as FigJam grows it', () => {+ const graph = new SceneGraph()+ const id = drawnShape(graph, 'Internationalisation in a label')+ // The 372 px line is wider than the 144 px label box, so it wraps, and the shape stays 176 wide.+ expect(getNodeOrThrow(graph, id).width).toBe(176)+ })++ test('a shape whose height was set keeps it and cuts its label off', () => {+ const graph = new SceneGraph()+ const id = drawnShape(graph)+ graph.updateNode(id, { height: 120 })+ const label = shapeWithTextLabel(graph, getNodeOrThrow(graph, id))+ if (!label) throw new Error('shape has no label')+ graph.updateNode(label.id, { text: Array.from({ length: 8 }, () => 'line').join('\n') })+ computeAllLayouts(graph, id)+ expect(getNodeOrThrow(graph, id)).toMatchObject({ height: 120, shapeTruncates: true })+ // Cut to the 88 px label box, which the renderer fills with whole lines and "…".+ expect(getNodeOrThrow(graph, label.id)).toMatchObject({+ textTruncation: 'ENDING',+ height: 88+ })+ graph.updateNode(label.id, { text: 'Hi' })+ computeAllLayouts(graph, id)+ expect(getNodeOrThrow(graph, label.id)).toMatchObject({+ textTruncation: 'DISABLED',+ textAutoResize: 'HEIGHT'+ })+ })++ test('a truncated label stays truncated however often layout runs', () => {+ // As CanvasKit measures, a truncated label measures only the lines it shows.+ setTextMeasurer((node) => {+ const lines = node.text.split('\n').length+ const shown = node.textTruncation === 'ENDING' ? Math.floor(node.height / 36) : lines+ return { width: 40, height: Math.min(lines, shown) * 36 }+ })+ const graph = new SceneGraph()+ const id = drawnShape(graph)+ graph.updateNode(id, { height: 120 })+ const label = shapeWithTextLabel(graph, getNodeOrThrow(graph, id))+ if (!label) throw new Error('shape has no label')+ graph.updateNode(label.id, { text: Array.from({ length: 8 }, () => 'line').join('\n') })+ for (let pass = 0; pass < 3; pass++) {+ computeAllLayouts(graph, id)+ expect(getNodeOrThrow(graph, label.id).textTruncation).toBe('ENDING')+ }+ })})diff --git a/packages/design-jsx/src/reference/authoring.md b/packages/design-jsx/src/reference/authoring.mdindex 36343d4f9..d8a382143 100644--- a/packages/design-jsx/src/reference/authoring.md+++ b/packages/design-jsx/src/reference/authoring.md@@ -26,7 +26,7 @@ This reference describes scene creation, not React DOM output. Use the `render`- `Span` styles some characters of a `Text` with `Text`'s own prop names: `size`, `font`, `weight`, `italic`, `color`, `fills`, `lineHeight`, `letterSpacing`, `textDecoration`, the decoration details, and `textCase`. `href` links its characters to a URL without changing how they look. Spans nest; the inner one wins. `Paragraph` writes one paragraph: `list="ordered"` or `list="unordered"` makes it a list item nested at `level` 1–5, and `spacing`, `listSpacing`, and `indent` override the `Text`'s `paragraphSpacing`, `listSpacing`, and `paragraphIndent` for it; `hangingList` on the `Text` hangs list markers outside the text box. A `Text` holds only `Paragraph`s or none; without them, a line break in its text still starts a paragraph.- `Icon` uses an Iconify name, size, and color. Prefer icons to emoji when reliable vector output is needed. Image fills belong on appropriate leaf shapes, not containers whose children must remain visible.- `Sticky` makes a FigJam sticky note whose text is its body: `<Sticky color="yellow" author="Ada">Ship it</Sticky>`. `color` takes a FigJam palette name (`white`, `gray`, `red`, `orange`, `yellow`, `green`, `teal`, `blue`, `violet`, `pink`) or any colour, `author` signs it (`authorVisible={false}` hides the line), `wide` makes it 416 wide instead of 240, `textSize` is `small`, `medium`, `large`, `extraLarge`, or `huge`, `typeface` is `simple`, `bookish`, `technical`, or `scribbled`, and `scale` scales the whole note. A note sizes itself; it takes no `w`, `h`, fills, or layout props.-- `Shape` makes a FigJam shape with text whose text is its label: `<Shape kind="diamond" bg="#FFC943">Valid?</Shape>`. `kind` is `square` (default), `ellipse`, `diamond`, `rounded_rectangle`, `parallelogram_right`, `eng_database`, or another FigJam shape, written in lowercase. `w` and `h` are the size it is given (176 by default); it grows past them to fit its label, and never splits a word. `bg`, `stroke`, `strokeWidth`, `rounded` (6 by default), and `rotate` style it as any layer; the label is centred in the shape and takes the same `textSize` and `typeface` as `Sticky`.+- `Shape` makes a FigJam shape with text whose text is its label: `<Shape kind="diamond" bg="#FFC943">Valid?</Shape>`. `kind` is `square` (default), `ellipse`, `diamond`, `rounded_rectangle`, `parallelogram_right`, `eng_database`, or another FigJam shape, written in lowercase. `w` and `h` are the size it is given (176 by default); it grows taller to fit its label, never wider, so a word too long for it breaks. `truncate` keeps its height and cuts the label off with "…" instead, as FigJam does once a shape's height is set. `bg`, `stroke`, `strokeWidth`, `rounded` (6 by default), and `rotate` style it as any layer; the label is centred in the shape and takes the same `textSize` and `typeface` as `Sticky`.- `Connector` draws a FigJam connector that follows the layers it joins: `<Connector from="Start" to="Done">Next</Connector>`. `from` and `to` name layers of the same JSX, take a `ref()` a layer is marked with (`const card = ref()`, then `<Frame ref={card}>` and `from={card}`), or give `{ x, y }` points in the connector's parent; `fromSide`/`toSide` (`top`, `right`, `bottom`, `left`) fix the side it attaches by, `line` is `elbowed` (default), `straight`, or `curved`, and `startCap`/`endCap` take the same caps as `strokeCap`: `none`, `round`, `square`, `arrow_lines`, `arrow_equilateral`, `triangle_filled`, `diamond_filled`, or `circle_filled` (it starts with none and ends with `arrow_lines`). Its text is the label; `stroke`, `strokeWidth`, and `dashPattern` style the line. When layers share a name, join them by `ref()`; a name more than one layer has joins the first, with a warning.- Design JSX props are the portable authoring interface. Some CSS-style aliases are supported, but this is not a browser CSS engine; do not assume arbitrary HTML, classes, or styles work.diff --git a/packages/design-jsx/src/shapes-with-text.ts b/packages/design-jsx/src/shapes-with-text.tsindex f74f2fe5d..e8cf43e7c 100644--- a/packages/design-jsx/src/shapes-with-text.ts+++ b/packages/design-jsx/src/shapes-with-text.ts@@ -57,9 +57,13 @@ export const ShapeLayerProps = v.object({dashPattern: v.optional(Dash)})-/** The props `<Shape>` takes: its kind, and the layer props a shape has. */+/**+ * The props `<Shape>` takes: its kind, whether it keeps its height and truncates its label as a+ * resized FigJam shape does, and the layer props a shape has.+ */export const ShapeProps = v.object({kind: v.optional(enumProp(SHAPE_KIND)),+ truncate: v.optional(v.boolean()),textSize: v.optional(enumProp(FIGJAM_TEXT_SIZE)),typeface: v.optional(enumProp(FIGJAM_TYPEFACE)),...ShapeLayerProps.entries@@ -84,7 +88,8 @@ export function renderShapeNode(...layer,name: layer.name ?? (text.trim() || 'Shape with text'),autoRename: !layer.name,- shapeWithTextType: props.kind ?? 'SQUARE'+ shapeWithTextType: props.kind ?? 'SQUARE',+ shapeTruncates: props.truncate ?? false},{ text })@@ -94,8 +99,8 @@ export function renderShapeNode(}/**- * A shape's own props as `<Shape>` writes them, after its name and position: the size it was- * given rather than the size its label grew it to, so it grows the same way when read back.+ * A shape's own props as `<Shape>` writes them, after its name and position: the height it was+ * given rather than the height its label grew it to, so it grows the same way when read back.*/export function shapeWithTextProps(graph: SceneGraph, node: SceneNode): JSXProp[] {const props: JSXProp[] = []@@ -104,10 +109,12 @@ export function shapeWithTextProps(graph: SceneGraph, node: SceneNode): JSXProp[}const label = shapeWithTextLabel(graph, node)if (label) props.push(...figJamTextProps(label))- const width = node.shapeUserWidth > 0 ? node.shapeUserWidth : node.width- const height = node.shapeUserHeight > 0 ? node.shapeUserHeight : node.height- if (width !== SHAPE_WITH_TEXT_SIZE) props.push(['w', width])+ // A truncating shape keeps the height it has; any other grows from the height it was given.+ const height =+ !node.shapeTruncates && node.shapeUserHeight > 0 ? node.shapeUserHeight : node.height+ if (node.width !== SHAPE_WITH_TEXT_SIZE) props.push(['w', node.width])if (height !== SHAPE_WITH_TEXT_SIZE) props.push(['h', height])+ if (node.shapeTruncates) props.push(['truncate', true])if (node.rotation !== 0) props.push(['rotate', Math.round(node.rotation * 100) / 100])collectFillProps(node, props)collectStrokeProps(node, props)diff --git a/packages/docs/reference/design-authoring.md b/packages/docs/reference/design-authoring.mdindex 3cd2f50b4..660625276 100644--- a/packages/docs/reference/design-authoring.md+++ b/packages/docs/reference/design-authoring.md@@ -28,7 +28,7 @@ This reference describes scene creation, not React DOM output. Use the `render`- `Span` styles some characters of a `Text` with `Text`'s own prop names: `size`, `font`, `weight`, `italic`, `color`, `fills`, `lineHeight`, `letterSpacing`, `textDecoration`, the decoration details, and `textCase`. `href` links its characters to a URL without changing how they look. Spans nest; the inner one wins. `Paragraph` writes one paragraph: `list="ordered"` or `list="unordered"` makes it a list item nested at `level` 1–5, and `spacing`, `listSpacing`, and `indent` override the `Text`'s `paragraphSpacing`, `listSpacing`, and `paragraphIndent` for it; `hangingList` on the `Text` hangs list markers outside the text box. A `Text` holds only `Paragraph`s or none; without them, a line break in its text still starts a paragraph.- `Icon` uses an Iconify name, size, and color. Prefer icons to emoji when reliable vector output is needed. Image fills belong on appropriate leaf shapes, not containers whose children must remain visible.- `Sticky` makes a FigJam sticky note whose text is its body: `<Sticky color="yellow" author="Ada">Ship it</Sticky>`. `color` takes a FigJam palette name (`white`, `gray`, `red`, `orange`, `yellow`, `green`, `teal`, `blue`, `violet`, `pink`) or any colour, `author` signs it (`authorVisible={false}` hides the line), `wide` makes it 416 wide instead of 240, `textSize` is `small`, `medium`, `large`, `extraLarge`, or `huge`, `typeface` is `simple`, `bookish`, `technical`, or `scribbled`, and `scale` scales the whole note. A note sizes itself; it takes no `w`, `h`, fills, or layout props.-- `Shape` makes a FigJam shape with text whose text is its label: `<Shape kind="diamond" bg="#FFC943">Valid?</Shape>`. `kind` is `square` (default), `ellipse`, `diamond`, `rounded_rectangle`, `parallelogram_right`, `eng_database`, or another FigJam shape, written in lowercase. `w` and `h` are the size it is given (176 by default); it grows past them to fit its label, and never splits a word. `bg`, `stroke`, `strokeWidth`, `rounded` (6 by default), and `rotate` style it as any layer; the label is centred in the shape and takes the same `textSize` and `typeface` as `Sticky`.+- `Shape` makes a FigJam shape with text whose text is its label: `<Shape kind="diamond" bg="#FFC943">Valid?</Shape>`. `kind` is `square` (default), `ellipse`, `diamond`, `rounded_rectangle`, `parallelogram_right`, `eng_database`, or another FigJam shape, written in lowercase. `w` and `h` are the size it is given (176 by default); it grows taller to fit its label, never wider, so a word too long for it breaks. `truncate` keeps its height and cuts the label off with "…" instead, as FigJam does once a shape's height is set. `bg`, `stroke`, `strokeWidth`, `rounded` (6 by default), and `rotate` style it as any layer; the label is centred in the shape and takes the same `textSize` and `typeface` as `Sticky`.- `Connector` draws a FigJam connector that follows the layers it joins: `<Connector from="Start" to="Done">Next</Connector>`. `from` and `to` name layers of the same JSX, take a `ref()` a layer is marked with (`const card = ref()`, then `<Frame ref={card}>` and `from={card}`), or give `{ x, y }` points in the connector's parent; `fromSide`/`toSide` (`top`, `right`, `bottom`, `left`) fix the side it attaches by, `line` is `elbowed` (default), `straight`, or `curved`, and `startCap`/`endCap` take the same caps as `strokeCap`: `none`, `round`, `square`, `arrow_lines`, `arrow_equilateral`, `triangle_filled`, `diamond_filled`, or `circle_filled` (it starts with none and ends with `arrow_lines`). Its text is the label; `stroke`, `strokeWidth`, and `dashPattern` style the line. When layers share a name, join them by `ref()`; a name more than one layer has joins the first, with a warning.- Design JSX props are the portable authoring interface. Some CSS-style aliases are supported, but this is not a browser CSS engine; do not assume arbitrary HTML, classes, or styles work.diff --git a/packages/fig/src/node-change/convert.ts b/packages/fig/src/node-change/convert.tsindex e0f5cf347..c23947fb2 100644--- a/packages/fig/src/node-change/convert.ts+++ b/packages/fig/src/node-change/convert.ts@@ -416,18 +416,18 @@ function givenSize(value: unknown): number {}/**- * A FigJam shape with text's kind and the size it was given; its label is read as a sublayer.- * FigJam keeps the given height; OpenPencil keeps the given width too, in its plugin data.+ * A FigJam shape with text's kind, the height it was given and whether it keeps that height; its+ * label is read as a sublayer.*/function convertShapeWithTextProps(nc: NodeChange-): Partial<Pick<SceneNode, 'shapeWithTextType' | 'shapeUserHeight' | 'shapeUserWidth'>> {+): Partial<Pick<SceneNode, 'shapeWithTextType' | 'shapeUserHeight' | 'shapeTruncates'>> {if (nc.type !== 'SHAPE_WITH_TEXT') return {}const kind = isShapeWithTextType(nc.shapeWithTextType) ? nc.shapeWithTextType : 'SQUARE'return {shapeWithTextType: kind,shapeUserHeight: givenSize(nc.shapeUserHeight),- shapeUserWidth: givenSize(readNodeChangePluginData(nc, OPEN_PENCIL_PLUGIN_DATA.shapeUserWidth))+ shapeTruncates: nc.shapeTruncates === true}}diff --git a/packages/fig/src/node-change/export/node.ts b/packages/fig/src/node-change/export/node.tsindex 25ea85191..0435bf18a 100644--- a/packages/fig/src/node-change/export/node.ts+++ b/packages/fig/src/node-change/export/node.ts@@ -917,13 +917,6 @@ function applyNodeVisualProps(if (!node.autoRename) nc.autoRename = false}-/** The width a shape with text was given, which FigJam's record has no field for. */-function applyShapeUserWidthPluginData(node: SceneNode): void {- const width =- node.type === 'SHAPE_WITH_TEXT' && node.shapeUserWidth > 0 ? node.shapeUserWidth : undefined- node.pluginData = withPluginData(node.pluginData, OPEN_PENCIL_PLUGIN_DATA.shapeUserWidth, width)-}-/*** Import maps TEXT_PATH → TEXT. Re-emit Kiwi type 41 only while path fidelity* remains (materialized path data + baked glyphs). After an edit that cannot@@ -1064,7 +1057,6 @@ export function sceneNodeToKiwiWithContext(applyExportSettingsPluginData(node)applyLibrarySourcePluginData(node)serializeNodeStatus(node, nc)- applyShapeUserWidthPluginData(node)applyTextPathBoxPluginData(node, savedInFigmaBox(node))const pluginData = mergePluginData(node.pluginData)if (pluginData.length > 0) nc.pluginData = pluginDatadiff --git a/packages/fig/src/node-change/generated/shape-with-text.ts b/packages/fig/src/node-change/generated/shape-with-text.tsindex 01dcc8f17..e5c91560c 100644--- a/packages/fig/src/node-change/generated/shape-with-text.ts+++ b/packages/fig/src/node-change/generated/shape-with-text.ts@@ -1,4 +1,4 @@-import { pick } from 'es-toolkit'+import { omit, pick } from 'es-toolkit'import type { NodeChange } from '@open-pencil/kiwi/fig/codec'import {@@ -48,6 +48,9 @@ const SHAPE_WITH_TEXT_RECORD_FIELDS = ['pluginRelaunchData'] as const+/** The label's sizing, which layout sets from the shape and FigJam's label record leaves out. */+const LABEL_LAYOUT_FIELDS = ['textAutoResize', 'textTruncation', 'maxLines'] as const+/** What a shape with text's background keeps: the shape's own paint, corners and effects. */const SHAPE_WITH_TEXT_BACKGROUND_FIELDS = ['fillPaints',@@ -113,7 +116,6 @@ function readShapeWithText(const overrides = generationOverridesOf(record)graph.updateNode(shape.id, {...backgroundProps(overrides.get(background), blobs),- shapeUserWidth: shape.shapeUserWidth > 0 ? shape.shapeUserWidth : shape.width,shapeUserHeight: shape.shapeUserHeight > 0 ? shape.shapeUserHeight : shape.height,...shapeWithTextFrameFields(shape.shapeWithTextType, shape.width, shape.height)})@@ -135,6 +137,7 @@ function writeShapeWithText(const record: KiwiNodeChange = pick(nc, SHAPE_WITH_TEXT_RECORD_FIELDS)record.shapeWithTextType = node.shapeWithTextTypeif (node.shapeUserHeight > 0) record.shapeUserHeight = node.shapeUserHeight+ if (node.shapeTruncates) record.shapeTruncates = trueconst slots = SHAPE_WITH_TEXT_SLOTSconst background: GeneratedEntry = {guidPath: generatedSlotPath(slots.background),@@ -143,7 +146,8 @@ function writeShapeWithText(}const text = textSublayer(context, slots.label, label)record.nodeGenerationData = {- overrides: [background, text.entry],+ // FigJam sizes and truncates the label from the shape itself, so its own sizing stays out.+ overrides: [background, omit(text.entry, LABEL_LAYOUT_FIELDS)],useFineGrainedSyncing: false,diffOnlyRemovals: []}diff --git a/packages/fig/tests/node-change/generated/shape-with-text.test.ts b/packages/fig/tests/node-change/generated/shape-with-text.test.tsindex 1f0fea178..237fa1ec0 100644--- a/packages/fig/tests/node-change/generated/shape-with-text.test.ts+++ b/packages/fig/tests/node-change/generated/shape-with-text.test.ts@@ -141,18 +141,21 @@ describe('shapes with text', () => {expect(shapeWithTextLabel(reread, copy)?.text).toBe('Orders')})- test('a shape widened for a long word reopens with the width it was given', () => {+ test('a shape that keeps its height reopens truncating, its label without sizing fields', () => {const { graph } = importShape(decision)const page = graph.getPages()[0]const shape = createShapeWithText(graph,page.id,- { width: 180, height: 120, shapeUserWidth: 120, shapeUserHeight: 100 },- { text: 'Internationalisation' }+ { width: 180, height: 120, shapeUserHeight: 120, shapeTruncates: true },+ { text: 'A label longer than the shape', textTruncation: 'ENDING', textAutoResize: 'NONE' })const [record] = sceneNodeToKiwi(shape, guid(1), 0, { value: 10 }, graph, [])+ expect(record).toMatchObject({ shapeUserHeight: 120, shapeTruncates: true })+ const label = generationOverridesOf(record).get(1)+ expect([label?.textAutoResize, label?.textTruncation]).toEqual([undefined, undefined])const { shape: copy } = importShape({ ...record, guid: guid(6) })- expect([copy.width, copy.shapeUserWidth, copy.shapeUserHeight]).toEqual([180, 120, 100])+ expect([copy.height, copy.shapeUserHeight, copy.shapeTruncates]).toEqual([120, 120, true])})test('a given height that is not a finite positive number is unset', () => {diff --git a/packages/scene-graph/src/generated/index.ts b/packages/scene-graph/src/generated/index.tsindex 9cf3727f4..6cc9c5e58 100644--- a/packages/scene-graph/src/generated/index.ts+++ b/packages/scene-graph/src/generated/index.ts@@ -53,12 +53,12 @@ export function generatedFrameText(graph: SceneGraph, node: SceneNode): SceneNod* (`GeneratedFrameKind.sized`); fields `changes` sets itself, such as an undo restoring them, win.*/export function withGeneratedFrameSize(- node: Pick<SceneNode, 'type'>,+ node: SceneNode,changes: Partial<SceneNode>): Partial<SceneNode> {const kind = generatedFrameKind(node)if (!kind?.sized || (changes.width === undefined && changes.height === undefined)) return changes- return { ...kind.sized(changes), ...changes }+ return { ...kind.sized(changes, node), ...changes }}/** Whether a layer turns: any layer but a generated frame that stays upright. */diff --git a/packages/scene-graph/src/generated/kind.ts b/packages/scene-graph/src/generated/kind.tsindex 82f4dd43c..2e9afb40a 100644--- a/packages/scene-graph/src/generated/kind.ts+++ b/packages/scene-graph/src/generated/kind.ts@@ -19,8 +19,8 @@ export interface GeneratedFrameKind {/** Whether it takes its name from its text until the user names it, as a sticky note does. */namedByText: boolean/**- * What a width or height set from outside layout also sets on the frame, such as the size a- * shape with text was given, which layout grows it from.+ * What a width or height set on `frame` from outside layout also sets on it, such as the height+ * a shape with text was given, which layout grows it from.*/- sized?(changes: Partial<SceneNode>): Partial<SceneNode>+ sized?(changes: Partial<SceneNode>, frame: SceneNode): Partial<SceneNode>}diff --git a/packages/scene-graph/src/generated/shape-with-text.ts b/packages/scene-graph/src/generated/shape-with-text.tsindex 9f0802aae..ea4e44ebe 100644--- a/packages/scene-graph/src/generated/shape-with-text.ts+++ b/packages/scene-graph/src/generated/shape-with-text.ts@@ -70,8 +70,9 @@ export function shapeWithTextLabel(graph: SceneGraph, shape: SceneNode): SceneNo/*** A shape with text edits its label in place, turns and resizes freely, and, as in FigJam, takes- * its name from its label until it is named. A width or height set on it by a resize, a field or- * a script is the size it was given, which layout grows it from when its label needs more room.+ * its name from its label until it is named. A height set on it by a resize, a field or a script+ * is the height it was given, which layout grows it from when its label needs more room; once+ * that height changes, FigJam keeps it and truncates the label instead.*/export const SHAPE_WITH_TEXT_KIND: GeneratedFrameKind = {complete: (graph, frame) => shapeWithTextLabel(graph, frame) !== null,@@ -80,10 +81,10 @@ export const SHAPE_WITH_TEXT_KIND: GeneratedFrameKind = {resizes: true,strokesAndEffects: true,namedByText: true,- sized: ({ width, height }) => ({- ...(width !== undefined && { shapeUserWidth: width }),- ...(height !== undefined && { shapeUserHeight: height })- })+ sized: ({ height }, shape) =>+ height === undefined || height === shape.height+ ? {}+ : { shapeUserHeight: height, shapeTruncates: true }}/** Adds the label to a SHAPE_WITH_TEXT the caller created, styled as FigJam generates it. */@@ -122,7 +123,6 @@ export function createShapeWithText(shapeWithTextType: kind,width,height,- shapeUserWidth: props.shapeUserWidth ?? width,shapeUserHeight: props.shapeUserHeight ?? height,...shapeWithTextFrameFields(kind, width, height)})diff --git a/packages/scene-graph/src/instances/fields.ts b/packages/scene-graph/src/instances/fields.tsindex 984c211aa..ee053b8a9 100644--- a/packages/scene-graph/src/instances/fields.ts+++ b/packages/scene-graph/src/instances/fields.ts@@ -48,7 +48,7 @@ export const INSTANCE_FOLLOWED_FIELDS = ['starInnerRadius','shapeWithTextType','shapeUserHeight',- 'shapeUserWidth'+ 'shapeTruncates'] as const/** Fields a component's layer gives its copies unless an instance overrides them. */diff --git a/packages/scene-graph/src/node-defaults.ts b/packages/scene-graph/src/node-defaults.tsindex e9784adc0..751ea5816 100644--- a/packages/scene-graph/src/node-defaults.ts+++ b/packages/scene-graph/src/node-defaults.ts@@ -184,7 +184,7 @@ export function createDefaultNode(starInnerRadius: 0.38,shapeWithTextType: 'SQUARE',shapeUserHeight: 0,- shapeUserWidth: 0,+ shapeTruncates: false,componentId: null,instanceOverrides: createInstanceOverrideState(),componentPropertyDefinitions: [],diff --git a/packages/scene-graph/src/plugin-data/fields.ts b/packages/scene-graph/src/plugin-data/fields.tsindex b7f4c6c50..47759a65f 100644--- a/packages/scene-graph/src/plugin-data/fields.ts+++ b/packages/scene-graph/src/plugin-data/fields.ts@@ -233,15 +233,6 @@ export const OPEN_PENCIL_PLUGIN_DATA = {okhcl: jsonPluginDataField('okhcl', 'content', okhcl),/** How a main component or component set behaves as a control in preview. */behaviour: jsonPluginDataField('behaviour', 'content', behaviourSchema),- /**- * The width a shape with text was given, which it grows past only for a word too wide.- * FigJam keeps the height it was given (`shapeUserHeight`) but not the width.- */- shapeUserWidth: jsonPluginDataField(- 'shapeUserWidth',- 'format',- v.pipe(v.number(), v.finite(), v.minValue(0))- ),/** The icon a frame draws, such as `lucide:home`, on the frame its paths are in. */icon: jsonPluginDataField('icon', 'content', iconSchema),/** Which of an icon path's paints its icon's color sets, on each path the source drew in it. */diff --git a/packages/scene-graph/src/shape-with-text/fit.ts b/packages/scene-graph/src/shape-with-text/fit.tsindex 5250d2950..76a946c42 100644--- a/packages/scene-graph/src/shape-with-text/fit.ts+++ b/packages/scene-graph/src/shape-with-text/fit.ts@@ -12,69 +12,80 @@ export interface LabelBox {height: number}-/** Fractions of the box, left/top/right/bottom, left free around the label so it stays inside the shape. */-const LABEL_INSET: Partial<Record<ShapeWithTextType, readonly [number, number, number, number]>> = {- ELLIPSE: [0.15, 0.15, 0.15, 0.15],- SUMMING_JUNCTION: [0.15, 0.15, 0.15, 0.15],- OR: [0.15, 0.15, 0.15, 0.15],- TRIANGLE_UP: [0.25, 0.45, 0.25, 0.05],- TRIANGLE_DOWN: [0.25, 0.05, 0.25, 0.45],- TRAPEZOID: [0.2, 0, 0.2, 0],- ENG_QUEUE: [0.15, 0, 0.3, 0],- ENG_FOLDER: [0, 0.18, 0, 0],- PREDEFINED_PROCESS: [0.1, 0, 0.1, 0],- SHIELD: [0.1, 0, 0.1, 0.25],- DOCUMENT_SINGLE: [0, 0, 0, 0.15],- DOCUMENT_MULTIPLE: [0, 0.12, 0.12, 0.15],- MANUAL_INPUT: [0, 0.25, 0, 0],- HEXAGON: [0.2, 0, 0.2, 0],- CHEVRON: [0.25, 0, 0.25, 0],- PENTAGON: [0.15, 0.3, 0.15, 0],- OCTAGON: [0.1, 0.1, 0.1, 0.1],- STAR: [0.3, 0.35, 0.3, 0.25],- PLUS: [0.33, 0.33, 0.33, 0.33],- ARROW_LEFT: [0.3, 0.25, 0, 0.25],- ARROW_RIGHT: [0, 0.25, 0.3, 0.25],- SPEECH_BUBBLE: [0, 0, 0, 0.2],- INTERNAL_STORAGE: [0.15, 0.15, 0, 0]+type Insets = readonly [left: number, top: number, right: number, bottom: number]++/** The 16 px FigJam leaves around a label, 8 px on a shape less than 100 px on a side. */+function labelPadding(width: number, height: number): number {+ return Math.min(width, height) < 100 ? 8 : 16}-/** Padding FigJam leaves around a label, 16 px, less on small shapes. */-function labelPadding(size: number): number {- return Math.min(16, size * 0.1)+/** FigJam doubles some kinds' insets on a shape 300 px wide or more. */+function wide(width: number): boolean {+ return width >= 300}-/** Left, top, right and bottom insets of the label, in px, for kinds FigJam was measured on. */-function measuredInsets(- type: ShapeWithTextType,- width: number,- height: number-): readonly [number, number, number, number] | null {- const padX = labelPadding(width)- const padY = labelPadding(height)- switch (type) {- case 'SQUARE':- case 'ROUNDED_RECTANGLE':- return [padX, padY, padX, padY]- case 'DIAMOND': {- // The middle half, 4 px in from it.- const x = width * 0.25 + Math.min(4, width * 0.02)- const y = height * 0.25 + Math.min(4, height * 0.02)- return [x, y, x, y]- }- case 'PARALLELOGRAM_RIGHT':- case 'PARALLELOGRAM_LEFT': {- const x = Math.min(height * 0.35 + padX, width * 0.4)- return [x, padY, x, padY]- }- case 'ENG_DATABASE': {- // Below the cap and its rim, above the bottom curve.- const cap = databaseCap(width, height)- return [padX, cap * 2 + padY, padX, cap]- }- default:- return null- }+type InsetRule = (width: number, height: number, padding: number) => Insets++/** A triangle's label sits under its middle, 4 px in from its sides; returns its top and bottom. */+function triangleInsets(width: number, height: number): readonly [apex: number, base: number] {+ const lean = (4 * height) / width+ return [height / 2 + lean, 8 + lean]+}++/** The rectangle inscribed in an ellipse, its width rounded to a whole pixel. */+const ellipseInsets: InsetRule = (width, height) => {+ const label = Math.round(width / Math.SQRT2)+ const x = (width - label) / 2+ const y = (height - height * Math.sqrt(1 - (label / width) ** 2)) / 2+ return [x, y, x, y]+}++/**+ * The px FigJam leaves free on each side of a label in each kind, measured from its saved label+ * layouts. Insets that scale do so with the side they lie along.+ */+const LABEL_INSETS: Record<ShapeWithTextType, InsetRule> = {+ SQUARE: (_w, _h, p) => [p, p, p, p],+ ROUNDED_RECTANGLE: (w, _h, p) => {+ const inset = wide(w) ? p * 2 : p+ return [inset, inset, inset, inset]+ },+ ELLIPSE: ellipseInsets,+ SUMMING_JUNCTION: ellipseInsets,+ OR: ellipseInsets,+ DIAMOND: (w, h) => [w / 4 + 4, h / 4 + 4, w / 4 + 4, h / 4 + 4],+ TRIANGLE_UP: (w, h) => {+ const [apex, base] = triangleInsets(w, h)+ return [w / 4, apex, w / 4, base]+ },+ TRIANGLE_DOWN: (w, h) => {+ const [apex, base] = triangleInsets(w, h)+ return [w / 4, base, w / 4, apex]+ },+ PARALLELOGRAM_RIGHT: (w, _h, p) => [(13 * w) / 62 + 6, p, (13 * w) / 62 + 6, p],+ PARALLELOGRAM_LEFT: (w, _h, p) => [(13 * w) / 62 + 6, p, (13 * w) / 62 + 6, p],+ // Below the cap and its rim, above the bottom curve.+ ENG_DATABASE: (w, h, p) => [p, databaseCap(w, h) * 2 + p, p, databaseCap(w, h)],+ ENG_QUEUE: (_w, _h, p) => [24, p, 64, p],+ ENG_FILE: (_w, _h, p) => [p, 64, p, 64],+ ENG_FOLDER: (_w, _h, p) => [p, 60, p, p],+ TRAPEZOID: (w, _h, p) => [(16 * w) / 121, p, (16 * w) / 121, p],+ HEXAGON: (w, _h, p) => [(8 * w) / 121, p, (8 * w) / 121, p],+ PREDEFINED_PROCESS: (w) => (wide(w) ? [48, 24, 48, 24] : [32, 16, 32, 16]),+ INTERNAL_STORAGE: (w) => (wide(w) ? [40, 40, 24, 24] : [24, 24, 16, 16]),+ SHIELD: (_w, h, p) => [p, h * 0.075, p, h * 0.1977],+ DOCUMENT_SINGLE: (_w, _h, p) => [p, p, p, 28],+ DOCUMENT_MULTIPLE: (_w, _h, p) => [32, p, p, 28],+ MANUAL_INPUT: (_w, _h, p) => [p, 24, p, p],+ CHEVRON: (_w, _h, p) => [43, p, 43, p],+ PENTAGON: (w, h) => [w * 0.115, h * 0.27403, w * 0.115, h * 0.08454],+ OCTAGON: (w, h) => [w * 0.11466, h * 0.1193, w * 0.11466, h * 0.1193],+ STAR: (w, h) => [w * 0.19531, h * 0.3028, w * 0.19531, h * 0.109],+ PLUS: (_w, h, p) => [p, (h * 5) / 18, p, (h * 5) / 18],+ ARROW_LEFT: (_w, h, p) => [54, h * 0.25465, p, h * 0.25465],+ ARROW_RIGHT: (_w, h, p) => [p, h * 0.25465, 54, h * 0.25465],+ // Above the tail, an eighth of the shape and at most 32 px tall.+ SPEECH_BUBBLE: (w, h, p) => [p, p, p, p + Math.min(32, Math.min(w, h) / 8)]}/** Where a shape's label sits inside its `width` × `height` box. */@@ -83,15 +94,9 @@ export function shapeWithTextLabelBox(width: number,height: number): LabelBox {- const measured = measuredInsets(type, width, height)- const [left, top, right, bottom] =- measured ??- (LABEL_INSET[type] ?? [0, 0, 0, 0]).map((free, side) => {- const size = side % 2 === 0 ? width : height- return size * free + labelPadding(size)- })- const x = Math.min(left, width / 2)- const y = Math.min(top, height / 2)+ const [left, top, right, bottom] = LABEL_INSETS[type](width, height, labelPadding(width, height))+ const x = insetWithin(left, right, width)+ const y = insetWithin(top, bottom, height)return {x,y,@@ -100,76 +105,50 @@ export function shapeWithTextLabelBox(}}-/** Kinds whose label area shrinks towards their corners; they grow in both directions to stay in shape. */-const GROWS_IN_PROPORTION = new Set<ShapeWithTextType>([- 'ELLIPSE',- 'DIAMOND',- 'TRIANGLE_UP',- 'TRIANGLE_DOWN',- 'HEXAGON',- 'PENTAGON',- 'OCTAGON',- 'STAR',- 'PLUS',- 'SUMMING_JUNCTION',- 'OR'-])+/** The inset before a label, its share of `size` when both insets do not fit in it. */+function insetWithin(before: number, after: number, size: number): number {+ return before + after <= size ? before : (size * before) / (before + after)+}/** Measures a label wrapped at `maxWidth`; its height is what the wrapped lines take. */export type LabelMeasure = (maxWidth: number) => { width: number; height: number }-export interface ShapeWithTextFit {- /** The size the shape was given. */- width: number- height: number- /** The width of the label's longest word, which is never split. */- longestWord: number- measure: LabelMeasure-}-const LARGEST = 100_000-/** The smallest `value` from `from` up for which `fits` holds, found by doubling then halving. */-function smallestFitting(from: number, fits: (value: number) => boolean): number {- if (fits(from)) return from- let low = from- let high = Math.max(from * 2, from + 16)+/** Whether a kind grows for its label; FigJam keeps summing junctions and ors round. */+export function shapeWithTextGrows(type: ShapeWithTextType): boolean {+ return type !== 'SUMMING_JUNCTION' && type !== 'OR'+}++/**+ * The height a `width`-wide shape of `type` takes for its label, as FigJam fits it: the height it+ * was given while the label fits its label box, else the smallest whole height whose label box+ * holds the label. FigJam never widens a shape for its label; a word too long for it breaks.+ */+export function fitShapeWithTextHeight(+ type: ShapeWithTextType,+ width: number,+ height: number,+ measure: LabelMeasure+): number {+ const fits = (h: number) => {+ const box = shapeWithTextLabelBox(type, width, h)+ return measure(box.width).height <= box.height+ }+ if (width <= 0 || height <= 0 || !shapeWithTextGrows(type) || fits(height)) return height+ let low = height+ let high = Math.max(height * 2, height + 16)while (!fits(high)) {low = highhigh *= 2if (high > LARGEST) return LARGEST}- while (high - low > 0.5) {- const middle = (low + high) / 2+ // The smallest whole height that fits, above a height that does not.+ low = Math.floor(low)+ while (high - low > 1) {+ const middle = Math.floor((low + high) / 2)if (fits(middle)) high = middleelse low = middle}return Math.ceil(high)}--/**- * The size a shape of `type` takes for its label, as FigJam fits it: it keeps the size it was- * given while the label fits, never splits a word (a word too wide widens the shape just enough),- * and otherwise grows taller. Kinds whose label area narrows at their corners, such as ellipses and- * diamonds, grow in both directions instead, so they keep their proportions.- */-export function fitShapeWithText(- type: ShapeWithTextType,- { width, height, longestWord, measure }: ShapeWithTextFit-): { width: number; height: number } {- const wordFits = (w: number, h: number) => shapeWithTextLabelBox(type, w, h).width >= longestWord- const fits = (w: number, h: number) => {- const box = shapeWithTextLabelBox(type, w, h)- return box.width >= longestWord && measure(box.width).height <= box.height- }- if (width <= 0 || height <= 0 || fits(width, height)) return { width, height }- if (GROWS_IN_PROPORTION.has(type)) {- // Searched in pixels of width, not as a scale, so it grows as little as the label needs.- const ratio = height / width- const fittedWidth = smallestFitting(width, (w) => fits(w, w * ratio) || w >= LARGEST)- return { width: fittedWidth, height: Math.ceil(fittedWidth * ratio) }- }- const fittedWidth = smallestFitting(width, (w) => wordFits(w, height) || w >= LARGEST)- const fittedHeight = smallestFitting(height, (h) => fits(fittedWidth, h) || h >= LARGEST)- return { width: fittedWidth, height: fittedHeight }-}diff --git a/packages/scene-graph/src/shape-with-text/index.ts b/packages/scene-graph/src/shape-with-text/index.tsindex b3761c332..51edd0d34 100644--- a/packages/scene-graph/src/shape-with-text/index.ts+++ b/packages/scene-graph/src/shape-with-text/index.ts@@ -2,9 +2,9 @@ export * from './kinds'export * from './geometry'export {databaseCap,- fitShapeWithText,+ fitShapeWithTextHeight,+ shapeWithTextGrows,shapeWithTextLabelBox,type LabelBox,- type LabelMeasure,- type ShapeWithTextFit+ type LabelMeasure} from './fit'diff --git a/packages/scene-graph/src/types.ts b/packages/scene-graph/src/types.tsindex b5f31fc7a..a8b85fb47 100644--- a/packages/scene-graph/src/types.ts+++ b/packages/scene-graph/src/types.ts@@ -741,8 +741,11 @@ export interface SceneNode {shapeWithTextType: ShapeWithTextType/** The height a shape with text was given; it grows past it to fit its label. 0 is unset. */shapeUserHeight: number- /** The width a shape with text was given; it widens past it only for a word too wide. 0 is unset. */- shapeUserWidth: number+ /**+ * Whether a shape with text keeps its height and cuts its label off with "…" instead of growing,+ * as FigJam does once the shape's height was set.+ */+ shapeTruncates: booleancomponentId: string | nullinstanceOverrides: InstanceOverrideStatediff --git a/packages/scene-graph/tests/generated/kind.test.ts b/packages/scene-graph/tests/generated/kind.test.tsindex 03ecf67a5..a2baa4074 100644--- a/packages/scene-graph/tests/generated/kind.test.ts+++ b/packages/scene-graph/tests/generated/kind.test.ts@@ -21,18 +21,19 @@ describe('generated frame kinds', () => {expect(generatedFrameKind(sticky)?.complete(graph, sticky)).toBe(true)})- test("a size set outside layout is a shape's given size, which layout's own writes leave", () => {+ test("a height set outside layout is a shape's given height, and it then keeps it", () => {const graph = new SceneGraph()const shape = createShapeWithText(graph, graph.getPages()[0].id, { width: 200, height: 100 })- graph.updateNode(shape.id, { width: 320 })- expect(graph.getNode(shape.id)).toMatchObject({ shapeUserWidth: 320, shapeUserHeight: 100 })+ // A width, or the height it already has, leaves it growing, as in FigJam.+ graph.updateNode(shape.id, { width: 320, height: 100 })+ expect(graph.getNode(shape.id)).toMatchObject({ shapeUserHeight: 100, shapeTruncates: false })graph.updateNodePreview(shape.id, { height: 140 })- expect(graph.getNode(shape.id)?.shapeUserHeight).toBe(140)- // A write that carries the given size itself, as an undo does, keeps it.- graph.updateNode(shape.id, { width: 400, shapeUserWidth: 320 })- expect(graph.getNode(shape.id)?.shapeUserWidth).toBe(320)- graph.withLayoutMutations(() => graph.updateNode(shape.id, { width: 500 }))- expect(graph.getNode(shape.id)?.shapeUserWidth).toBe(320)+ expect(graph.getNode(shape.id)).toMatchObject({ shapeUserHeight: 140, shapeTruncates: true })+ // A write that carries the given height itself, as an undo does, keeps it.+ graph.updateNode(shape.id, { height: 180, shapeUserHeight: 120, shapeTruncates: false })+ expect(graph.getNode(shape.id)).toMatchObject({ shapeUserHeight: 120, shapeTruncates: false })+ graph.withLayoutMutations(() => graph.updateNode(shape.id, { height: 500 }))+ expect(graph.getNode(shape.id)).toMatchObject({ shapeUserHeight: 120, shapeTruncates: false })})test('any other layer has no kind and turns and resizes freely', () => {diff --git a/packages/scene-graph/tests/shape-with-text/fit.test.ts b/packages/scene-graph/tests/shape-with-text/fit.test.tsindex 33a4d0597..0d57b4839 100644--- a/packages/scene-graph/tests/shape-with-text/fit.test.ts+++ b/packages/scene-graph/tests/shape-with-text/fit.test.ts@@ -2,7 +2,8 @@ import { describe, expect, test } from 'bun:test'import {SHAPE_WITH_TEXT_TYPES,- fitShapeWithText,+ fitShapeWithTextHeight,+ shapeWithTextGrows,shapeWithTextLabelBox} from '@open-pencil/scene-graph/shape-with-text'@@ -10,8 +11,9 @@ describe('shape-with-text label boxes and fit', () => {for (const type of SHAPE_WITH_TEXT_TYPES) {test(`${type} keeps its label inside the box`, () => {const box = shapeWithTextLabelBox(type, 200, 100)+ // A file's 64 px folds leave a short one no room, as in FigJam, but never a negative box.expect(box.width).toBeGreaterThan(0)- expect(box.height).toBeGreaterThan(0)+ expect(box.height).toBeGreaterThanOrEqual(0)expect(box.x + box.width).toBeLessThanOrEqual(200)expect(box.y + box.height).toBeLessThanOrEqual(100)})@@ -29,56 +31,57 @@ describe('shape-with-text label boxes and fit', () => {expect(shapeWithTextLabelBox('SQUARE', 0, 0)).toEqual({ x: 0, y: 0, width: 0, height: 0 })})- // A label of 40 characters 8 px wide on 20 px lines, wrapped at `maxWidth`.- const measure = (maxWidth: number) => ({- width: Math.min(320, maxWidth),- height: Math.ceil(320 / Math.max(maxWidth, 1)) * 20+ test('label boxes sit where FigJam lays its labels out', () => {+ // Read from FigJam's saved label layouts: [x, width] across a 176 px wide shape.+ const measured = [+ ['SQUARE', 16, 144],+ ['ELLIPSE', 26, 124],+ ['DIAMOND', 48, 80],+ ['TRIANGLE_UP', 44, 88],+ ['PARALLELOGRAM_RIGHT', 42.9, 90.19],+ ['ENG_QUEUE', 24, 88],+ ['CHEVRON', 43, 90],+ ['STAR', 34.38, 107.25]+ ] as const+ for (const [type, x, width] of measured) {+ const box = shapeWithTextLabelBox(type, 176, 400)+ expect([box.x, box.width]).toEqual([expect.closeTo(x, 1), expect.closeTo(width, 1)])+ }})- test('a shape keeps the size it was given while its label fits', () => {- expect(- fitShapeWithText('SQUARE', { width: 400, height: 100, longestWord: 40, measure })- ).toEqual({ width: 400, height: 100 })+ test('a small shape leaves 8 px around its label', () => {+ expect(shapeWithTextLabelBox('SQUARE', 80, 80)).toEqual({ x: 8, y: 8, width: 64, height: 64 })+ expect(shapeWithTextLabelBox('SQUARE', 100, 100).x).toBe(16)})- test('a box grows taller, not wider, for a label that wraps', () => {- const fitted = fitShapeWithText('SQUARE', { width: 120, height: 40, longestWord: 40, measure })- expect(fitted.width).toBe(120)- expect(fitted.height).toBeGreaterThan(40)- })+ /** A label `height` px tall at any width. */+ const lines = (height: number) => () => ({ width: 40, height })- test('a word wider than the label widens the shape just enough, without splitting it', () => {- const fitted = fitShapeWithText('SQUARE', { width: 60, height: 60, longestWord: 100, measure })- expect(fitted.width).toBeGreaterThan(60)- expect(fitShapeWithText('SQUARE', { ...fitted, longestWord: 100, measure })).toEqual(fitted)+ test('a shape keeps the height it was given while its label fits', () => {+ expect(fitShapeWithTextHeight('SQUARE', 176, 176, lines(24))).toBe(176)})- test('ellipses and diamonds grow in proportion', () => {- for (const type of ['ELLIPSE', 'DIAMOND'] as const) {- const fitted = fitShapeWithText(type, { width: 120, height: 80, longestWord: 40, measure })- expect(fitted.width).toBeGreaterThan(120)- expect(fitted.width / fitted.height).toBeCloseTo(1.5, 1)+ test('a shape grows to the height FigJam grows it to, and never wider', () => {+ // Label heights and the heights FigJam grew a 176 px wide shape to for them.+ const grown = [+ ['SQUARE', 264, 296],+ ['ELLIPSE', 336, 474],+ ['DIAMOND', 504, 1024],+ ['TRIANGLE_UP', 480, 1074],+ ['ENG_DATABASE', 264, 352],+ ['PENTAGON', 288, 449],+ ['STAR', 336, 572],+ ['PLUS', 264, 594]+ ] as const+ for (const [type, label, height] of grown) {+ expect(fitShapeWithTextHeight(type, 176, 176, lines(label))).toBe(height)}})- test('a round kind grows only as much as its label needs', () => {- // Seven 20 px lines: a 208 px diamond's label box is 96 tall, so it needs 228 px.- const sevenLines = () => ({ width: 40, height: 140 })- for (const type of ['DIAMOND', 'ELLIPSE'] as const) {- const fitted = fitShapeWithText(type, {- width: 208,- height: 208,- longestWord: 40,- measure: sevenLines- })- expect(fitted.width).toBe(fitted.height)- expect(- shapeWithTextLabelBox(type, fitted.width, fitted.height).height- ).toBeGreaterThanOrEqual(140)- // Within a pixel of the smallest size that fits.- expect(shapeWithTextLabelBox(type, fitted.width - 2, fitted.height - 2).height).toBeLessThan(- 140- )+ test('summing junctions and ors stay round, their label running past them', () => {+ for (const type of ['SUMMING_JUNCTION', 'OR'] as const) {+ expect(shapeWithTextGrows(type)).toBe(false)+ expect(fitShapeWithTextHeight(type, 176, 176, lines(600))).toBe(176)}})})diff --git a/packages/vue/src/controls/appearance/helpers.ts b/packages/vue/src/controls/appearance/helpers.tsindex 2d9bc037c..f591ca028 100644--- a/packages/vue/src/controls/appearance/helpers.ts+++ b/packages/vue/src/controls/appearance/helpers.ts@@ -15,11 +15,17 @@ const CORNER_RADIUS_TYPES = new Set(['COMPONENT','INSTANCE','POLYGON',- 'STAR'+ 'STAR',+ 'SHAPE_WITH_TEXT'])-/** A polygon's or star's corners share one radius, so Figma offers no per-corner radii for them. */-const SHARED_RADIUS_TYPES = new Set(['POLYGON', 'STAR'])+/**+ * A polygon's, star's or shape with text's corners share one radius, so Figma offers no+ * per-corner radii for them.+ */+const SHARED_RADIUS_TYPES = new Set(['POLYGON', 'STAR', 'SHAPE_WITH_TEXT'])++const POINT_COUNT_TYPES = new Set(['POLYGON', 'STAR'])const CORNER_PATHS: CornerRadiusKey[] = ['topLeftRadius',@@ -139,7 +145,7 @@ export function createAppearanceState({const hasPointCount = computed(() =>selectedNodes.value.length > 0 &&- selectedNodes.value.every((target) => SHARED_RADIUS_TYPES.has(target.type))+ selectedNodes.value.every((target) => POINT_COUNT_TYPES.has(target.type)))const hasStarRatio = computed(() =>diff --git a/packages/vue/src/controls/typography/actions.ts b/packages/vue/src/controls/typography/actions.tsindex 6c95bd122..8e1269b44 100644--- a/packages/vue/src/controls/typography/actions.ts+++ b/packages/vue/src/controls/typography/actions.ts@@ -8,6 +8,7 @@ import {nearestFamilyFace,weightToStyle} from '@open-pencil/core/text'+import { shapeWithTextLabel } from '@open-pencil/scene-graph'import type {SceneNode,TextDecoration,@@ -50,14 +51,21 @@ function sharedFormatting(nodes: readonly SceneNode[]) {return result}+/** The text a selected layer's typography edits: its own, or a shape with text's label. */+function typographyTargets(editor: Editor): SceneNode[] {+ return selectedNodesAsShown(editor).flatMap((n) => {+ if (n.type === 'TEXT') return [n]+ const label = shapeWithTextLabel(editor.graph, n)+ return label ? [label] : []+ })+}+/**- * Typography of the selected text layers. With other layers selected too, Figma shows the text's- * typography and edits only the text, so `nodes` holds just the text layers.+ * Typography of the selected text layers and shapes' labels. With other layers selected too,+ * Figma shows the text's typography and edits only the text, so `nodes` holds just the text.*/export function createTypographyState(editor: Editor) {- const nodes = useSceneComputed<SceneNode[]>(() =>- selectedNodesAsShown(editor).filter((n) => n.type === 'TEXT')- )+ const nodes = useSceneComputed<SceneNode[]>(() => typographyTargets(editor))const node = computed<SceneNode | null>(() => nodes.value.at(0) ?? null)const { missingFonts, hasMissingFonts } = useNodeFontStatus(() => node.value)const fontFamily = computed(() => node.value?.fontFamily ?? '')diff --git a/packages/vue/src/shared/input/draw.ts b/packages/vue/src/shared/input/draw.tsindex 2d9d1560c..ec32c0d5b 100644--- a/packages/vue/src/shared/input/draw.ts+++ b/packages/vue/src/shared/input/draw.ts@@ -107,8 +107,12 @@ function settleDrawnSize(preview: ReturnType<Editor['beginNodePreview']>, node:} else if (node.type === 'LINE' && node.width < 2) {preview.update(node.id, { width: 100, height: 0, rotation: 0 })return true- } else if (clicked && node.type === 'SHAPE_WITH_TEXT') {- preview.update(node.id, { width: SHAPE_WITH_TEXT_SIZE, height: SHAPE_WITH_TEXT_SIZE })+ } else if (node.type === 'SHAPE_WITH_TEXT') {+ // Drawing sizes a new shape rather than resizing it, so it grows to fit its label.+ preview.update(node.id, {+ ...(clicked && { width: SHAPE_WITH_TEXT_SIZE, height: SHAPE_WITH_TEXT_SIZE }),+ shapeTruncates: false+ })} else if (clicked) {preview.update(node.id, { width: 100, height: 100 })}diff --git a/skills/open-pencil/references/design-authoring.md b/skills/open-pencil/references/design-authoring.mdindex 3cd2f50b4..660625276 100644--- a/skills/open-pencil/references/design-authoring.md+++ b/skills/open-pencil/references/design-authoring.md@@ -28,7 +28,7 @@ This reference describes scene creation, not React DOM output. Use the `render`- `Span` styles some characters of a `Text` with `Text`'s own prop names: `size`, `font`, `weight`, `italic`, `color`, `fills`, `lineHeight`, `letterSpacing`, `textDecoration`, the decoration details, and `textCase`. `href` links its characters to a URL without changing how they look. Spans nest; the inner one wins. `Paragraph` writes one paragraph: `list="ordered"` or `list="unordered"` makes it a list item nested at `level` 1–5, and `spacing`, `listSpacing`, and `indent` override the `Text`'s `paragraphSpacing`, `listSpacing`, and `paragraphIndent` for it; `hangingList` on the `Text` hangs list markers outside the text box. A `Text` holds only `Paragraph`s or none; without them, a line break in its text still starts a paragraph.- `Icon` uses an Iconify name, size, and color. Prefer icons to emoji when reliable vector output is needed. Image fills belong on appropriate leaf shapes, not containers whose children must remain visible.- `Sticky` makes a FigJam sticky note whose text is its body: `<Sticky color="yellow" author="Ada">Ship it</Sticky>`. `color` takes a FigJam palette name (`white`, `gray`, `red`, `orange`, `yellow`, `green`, `teal`, `blue`, `violet`, `pink`) or any colour, `author` signs it (`authorVisible={false}` hides the line), `wide` makes it 416 wide instead of 240, `textSize` is `small`, `medium`, `large`, `extraLarge`, or `huge`, `typeface` is `simple`, `bookish`, `technical`, or `scribbled`, and `scale` scales the whole note. A note sizes itself; it takes no `w`, `h`, fills, or layout props.-- `Shape` makes a FigJam shape with text whose text is its label: `<Shape kind="diamond" bg="#FFC943">Valid?</Shape>`. `kind` is `square` (default), `ellipse`, `diamond`, `rounded_rectangle`, `parallelogram_right`, `eng_database`, or another FigJam shape, written in lowercase. `w` and `h` are the size it is given (176 by default); it grows past them to fit its label, and never splits a word. `bg`, `stroke`, `strokeWidth`, `rounded` (6 by default), and `rotate` style it as any layer; the label is centred in the shape and takes the same `textSize` and `typeface` as `Sticky`.+- `Shape` makes a FigJam shape with text whose text is its label: `<Shape kind="diamond" bg="#FFC943">Valid?</Shape>`. `kind` is `square` (default), `ellipse`, `diamond`, `rounded_rectangle`, `parallelogram_right`, `eng_database`, or another FigJam shape, written in lowercase. `w` and `h` are the size it is given (176 by default); it grows taller to fit its label, never wider, so a word too long for it breaks. `truncate` keeps its height and cuts the label off with "…" instead, as FigJam does once a shape's height is set. `bg`, `stroke`, `strokeWidth`, `rounded` (6 by default), and `rotate` style it as any layer; the label is centred in the shape and takes the same `textSize` and `typeface` as `Sticky`.- `Connector` draws a FigJam connector that follows the layers it joins: `<Connector from="Start" to="Done">Next</Connector>`. `from` and `to` name layers of the same JSX, take a `ref()` a layer is marked with (`const card = ref()`, then `<Frame ref={card}>` and `from={card}`), or give `{ x, y }` points in the connector's parent; `fromSide`/`toSide` (`top`, `right`, `bottom`, `left`) fix the side it attaches by, `line` is `elbowed` (default), `straight`, or `curved`, and `startCap`/`endCap` take the same caps as `strokeCap`: `none`, `round`, `square`, `arrow_lines`, `arrow_equilateral`, `triangle_filled`, `diamond_filled`, or `circle_filled` (it starts with none and ends with `arrow_lines`). Its text is the label; `stroke`, `strokeWidth`, and `dashPattern` style the line. When layers share a name, join them by `ref()`; a name more than one layer has joins the first, with a warning.- Design JSX props are the portable authoring interface. Some CSS-style aliases are supported, but this is not a browser CSS engine; do not assume arbitrary HTML, classes, or styles work.diff --git a/src/components/DesignPanel.vue b/src/components/DesignPanel.vueindex 4b258f1be..917438606 100644--- a/src/components/DesignPanel.vue+++ b/src/components/DesignPanel.vue@@ -233,7 +233,8 @@ const { panels } = useI18n()<AppearanceSection /><template v-if="node.type !== 'CONNECTOR'"><MaskSection />- <TypographySection v-if="node.type === 'TEXT'" />+ <!-- A shape with text's typography is its label's, as in Figma. -->+ <TypographySection v-if="node.type === 'TEXT' || node.type === 'SHAPE_WITH_TEXT'" /><FillSection /><template v-if="strokesAndEffects"><StrokeSection />diff --git a/tests/e2e/tools/shape-with-text.spec.ts b/tests/e2e/tools/shape-with-text.spec.tsindex c0d00a6fa..5b5fd8599 100644--- a/tests/e2e/tools/shape-with-text.spec.ts+++ b/tests/e2e/tools/shape-with-text.spec.ts@@ -2,6 +2,7 @@ import type { Vector } from '@open-pencil/scene-graph/primitives'import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'import { shapeWithTextDriver } from '#tests/helpers/canvas/shape-with-text-driver'+import { propertyField, propertySection } from '#tests/helpers/properties'import { toolbarToolTestId } from '#tests/helpers/test-ids'const editor = useEditorSetupWithClear()@@ -142,3 +143,45 @@ test("the properties panel paints a shape with FigJam's palette and sizes its teexpect(huge.label?.fontSize).toBe(96)expect(huge.height).toBeGreaterThan(176)})++test("a shape's panel styles its label and rounds its corners, as Figma's does", async () => {+ await shapes.showTool()+ await shapes.pickKind('Square')+ await clickAt(200, 200)+ await editor.page.keyboard.type('Ship it')+ await editor.page.keyboard.press('Escape')++ await expect(propertySection(editor.page, 'Typography')).toBeVisible()+ await expect(propertyField(editor.page, 'cornerRadius')).toBeVisible()+ const size = propertySection(editor.page, 'Typography').getByRole('spinbutton', {+ name: 'Font size'+ })+ await size.click()+ await editor.page.keyboard.press('ControlOrMeta+a')+ await editor.page.keyboard.type('24')+ await size.press('Enter')+ await editor.canvas.waitForRender()+ expect((await lastShape()).label?.fontSize).toBe(24)+})++test('a shape whose height was set keeps it, and cuts a long label off with "…"', async () => {+ await shapes.showTool()+ await shapes.pickKind('Square')+ await clickAt(200, 200)+ await editor.page.keyboard.press('Escape')++ const heightField = propertyField(editor.page, 'height')+ await heightField.click()+ const height = heightField.getByRole('spinbutton', { name: 'Height' })+ await height.fill('100')+ await height.press('Enter')+ expect(await lastShape()).toMatchObject({ height: 100, truncates: true })++ await editor.page.keyboard.press('Enter')+ await editor.page.keyboard.type('A label far too long for a shape only one hundred pixels tall')+ await editor.page.keyboard.press('Escape')+ await editor.canvas.waitForRender()+ const shape = await lastShape()+ expect(shape).toMatchObject({ width: 176, height: 100 })+ expect(shape.label?.truncation).toBe('ENDING')+})diff --git a/tests/helpers/canvas/shape-with-text-driver.ts b/tests/helpers/canvas/shape-with-text-driver.tsindex 366a1567a..4ced547b9 100644--- a/tests/helpers/canvas/shape-with-text-driver.ts+++ b/tests/helpers/canvas/shape-with-text-driver.ts@@ -36,7 +36,9 @@ export interface ShapeWithTextState {fill: stringstroke: stringstrokeWeight: number- label: { text: string; fontSize: number } | null+ /** Whether it keeps its height and truncates its label, as once its height was set. */+ truncates: boolean+ label: { text: string; fontSize: number; truncation: string } | null}/** Places shapes with text as the editor draws them, each with its label laid out inside. */@@ -130,7 +132,10 @@ export function shapeWithTextDriver(page: () => Page) {fill: hex(node.fills.at(0)),stroke: hex(node.strokes.at(0)),strokeWeight: node.strokes.at(0)?.weight ?? 0,- label: label ? { text: label.text, fontSize: label.fontSize } : null+ truncates: node.shapeTruncates,+ label: label+ ? { text: label.text, fontSize: label.fontSize, truncation: label.textTruncation }+ : null}})})