Skip to content

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

feat: open, draw, style, and save FigJam shapes with text (#1239)

Niraj Sangania4df297120a0
diff --git a/changes/1239/added.md b/changes/1239/added.md
new file mode 100644
index 000000000..e3ce79f04
--- /dev/null
+++ b/changes/1239/added.md
@@ -0,0 +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).
diff --git a/packages/core/AGENTS.md b/packages/core/AGENTS.md
index 36b4aec45..f1cf77958 100644
--- a/packages/core/AGENTS.md
+++ b/packages/core/AGENTS.md
@@ -15,6 +15,7 @@ Renderer, layout, editor, Figma API, tools, clipboard, vector conversion, and do
- `@open-pencil/yoga-layout` supplies both flexbox and CSS Grid.
- Recompute layout after demo creation and for each materialized or imported page; scope computation to the affected page or subtree where possible.
- The first Hug/Fill dimension mutation switches only that axis to Fixed; focus is non-destructive, and mode/value changes share one undo transaction.
+- A shape with text fits itself to its label before its auto layout runs: it grows from its given size only while the label needs room, and layout never changes that given size (`packages/core/tests/layout/generated/shape-with-text.test.ts`).
## Components and instances
diff --git a/packages/core/src/canvas/fills.ts b/packages/core/src/canvas/fills.ts
index a0ddce6f6..d8498ec95 100644
--- a/packages/core/src/canvas/fills.ts
+++ b/packages/core/src/canvas/fills.ts
@@ -108,7 +108,8 @@ export function drawNodeFill(
canvas.drawLine(0, 0, node.width, node.height, r.fillPaint)
break
case 'POLYGON':
- case 'STAR': {
+ case 'STAR':
+ case 'SHAPE_WITH_TEXT': {
const path = r.makePolygonPath(node)
canvas.drawPath(path, r.fillPaint)
path.delete()
diff --git a/packages/core/src/canvas/shapes.ts b/packages/core/src/canvas/shapes.ts
index 975621dff..d85f44e0d 100644
--- a/packages/core/src/canvas/shapes.ts
+++ b/packages/core/src/canvas/shapes.ts
@@ -1,7 +1,8 @@
import type { Canvas, Path, PathBuilder } from 'canvaskit-wasm'
import type { SceneNode } from '@open-pencil/scene-graph'
-import { polygonOutline } from '@open-pencil/scene-graph/polygon'
+import { polygonOutline, type PolygonOutlineCommand } from '@open-pencil/scene-graph/polygon'
+import { shapeWithTextGeometry } from '@open-pencil/scene-graph/shape-with-text'
import { vectorNetworkToPath, geometryBlobToPath } from '#core/vector'
@@ -384,7 +385,8 @@ export function makeNodeShapePath(
break
}
case 'POLYGON':
- case 'STAR': {
+ case 'STAR':
+ case 'SHAPE_WITH_TEXT': {
const polyPath = r.makePolygonPath(node)
path.addPath(polyPath)
polyPath.delete()
@@ -404,10 +406,9 @@ export function makeNodeShapePath(
return path.detachAndDelete()
}
-/** The polygon or star with its corner radius and smoothing, as Figma draws it. */
-export function makePolygonPath(r: SkiaRenderer, node: SceneNode): Path {
+function outlinePath(r: SkiaRenderer, commands: PolygonOutlineCommand[]): Path {
const path = new r.ck.PathBuilder()
- for (const command of polygonOutline(node)) {
+ for (const command of commands) {
if (command.type === 'M') path.moveTo(command.x, command.y)
else if (command.type === 'L') path.lineTo(command.x, command.y)
else if (command.type === 'C')
@@ -417,6 +418,28 @@ export function makePolygonPath(r: SkiaRenderer, node: SceneNode): Path {
return path.detachAndDelete()
}
+/**
+ * The polygon or star with its corner radius and smoothing, as Figma draws it, or the outline of
+ * a shape with text.
+ */
+export function makePolygonPath(r: SkiaRenderer, node: SceneNode): Path {
+ if (node.type === 'SHAPE_WITH_TEXT') {
+ return outlinePath(
+ r,
+ shapeWithTextGeometry(node.shapeWithTextType, node.width, node.height, node.cornerRadius)
+ .outline
+ )
+ }
+ return outlinePath(r, polygonOutline(node))
+}
+
+/** A shape with text's stroke-only inner lines, such as a database's front rim, if it has any. */
+export function makeShapeWithTextDetailsPath(r: SkiaRenderer, node: SceneNode): Path | null {
+ if (node.type !== 'SHAPE_WITH_TEXT') return null
+ const { details } = shapeWithTextGeometry(node.shapeWithTextType, node.width, node.height)
+ return details.length > 0 ? outlinePath(r, details) : null
+}
+
export function makeRRect(r: SkiaRenderer, node: SceneNode): Float32Array {
if (node.independentCorners) {
return new Float32Array([
@@ -507,7 +530,12 @@ export function clipNodeShape(
rect: Float32Array,
hasRadius: boolean
): void {
- if (node.type === 'ELLIPSE') {
+ if (node.type === 'SHAPE_WITH_TEXT') {
+ // Clipped by its kind's outline, so an inside stroke follows it rather than the box.
+ const clipPath = r.makePolygonPath(node)
+ canvas.clipPath(clipPath, r.ck.ClipOp.Intersect, true)
+ clipPath.delete()
+ } else if (node.type === 'ELLIPSE') {
const clipPath = new r.ck.PathBuilder()
clipPath.addOval(rect)
const immutableClipPath = clipPath.detachAndDelete()
diff --git a/packages/core/src/canvas/strokes.ts b/packages/core/src/canvas/strokes.ts
index 3247e5003..f34fd6810 100644
--- a/packages/core/src/canvas/strokes.ts
+++ b/packages/core/src/canvas/strokes.ts
@@ -13,7 +13,7 @@ import type { Color, Vector } from '@open-pencil/scene-graph/primitives'
import { applyGradientFill, applyImageFill } from './fills'
import type { SkiaRenderer } from './renderer'
-import { makeSmoothRRectPath, nodeHasSmoothCorners } from './shapes'
+import { makeShapeWithTextDetailsPath, makeSmoothRRectPath, nodeHasSmoothCorners } from './shapes'
export function getStrokeCapEntity(r: SkiaRenderer, cap: string | undefined): EmbindEnumEntity {
switch (cap) {
@@ -297,6 +297,12 @@ export function drawNodeStroke(
path.delete()
break
}
+ case 'SHAPE_WITH_TEXT': {
+ const path = r.makePolygonPath(node)
+ canvas.drawPath(path, r.strokePaint)
+ path.delete()
+ break
+ }
default:
if (nodeHasSmoothCorners(node)) {
const path = makeSmoothRRectPath(r, node)
@@ -350,6 +356,16 @@ export function drawStrokeWithAlign(
} else {
r.drawNodeStroke(canvas, node, rect, hasRadius)
}
+ // Inner lines, such as a database's front rim, lie inside the outline: they keep the stroke's
+ // own weight whatever its alignment, and end where the outline does.
+ const details = makeShapeWithTextDetailsPath(r, node)
+ if (details) {
+ canvas.save()
+ r.clipNodeShape(canvas, node, rect, hasRadius)
+ canvas.drawPath(details, r.strokePaint)
+ canvas.restore()
+ details.delete()
+ }
}
export function drawRRectStrokeWithAlign(
@@ -431,7 +447,8 @@ export function strokeNodeShape(
canvas.drawLine(0, 0, node.width, node.height, paint)
return
case 'POLYGON':
- case 'STAR': {
+ case 'STAR':
+ case 'SHAPE_WITH_TEXT': {
const path = r.makePolygonPath(node)
canvas.drawPath(path, paint)
path.delete()
diff --git a/packages/core/src/editor/create.ts b/packages/core/src/editor/create.ts
index 68ded0774..d9ece2426 100644
--- a/packages/core/src/editor/create.ts
+++ b/packages/core/src/editor/create.ts
@@ -53,6 +53,7 @@ import { createSelectionActions } from './selection'
import { createShaderActions } from './shaders/actions'
import { createShaderFrames } from './shaders/frames'
import { createShapeActions } from './shapes'
+import { createShapeWithTextActions } from './shapes/with-text'
import { createDefaultEditorState } from './state'
import { createStatusActions } from './statuses'
import { createStickyActions } from './stickies'
@@ -60,6 +61,7 @@ import { createStructureActions } from './structure'
import { createTextActions } from './text'
import { createPendingTextLayout } from './text/pending-layout'
import { createTextSelectionStyle } from './text/selection-style'
+import { createGeneratedTextActions } from './text/typeface'
import type {
EditorContext,
EditorEventName,
@@ -298,6 +300,8 @@ export function createEditor(options?: EditorOptions) {
const vectorize = createVectorizeActions(ctx)
const icons = createIconActions(ctx)
const stickies = createStickyActions(ctx)
+ const shapesWithText = createShapeWithTextActions(ctx)
+ const generatedText = createGeneratedTextActions(ctx)
const statuses = createStatusActions(ctx)
createConnectorRouting(ctx)
const connectorDrawing = createConnectorDrawActions(ctx)
@@ -475,6 +479,8 @@ export function createEditor(options?: EditorOptions) {
...vectorize,
...icons,
...stickies,
+ ...shapesWithText,
+ ...generatedText,
statusWorkflow: statuses.statusWorkflow,
getShownStatus: statuses.getShownStatus,
setStatus: statuses.setStatus,
diff --git a/packages/core/src/editor/shapes.ts b/packages/core/src/editor/shapes.ts
index 145a519ae..98201d773 100644
--- a/packages/core/src/editor/shapes.ts
+++ b/packages/core/src/editor/shapes.ts
@@ -1,6 +1,7 @@
-import type { NodeType, SceneNode } from '@open-pencil/scene-graph'
+import { createShapeWithText, type NodeType, type SceneNode } from '@open-pencil/scene-graph'
import { prepareSlotEdits } from './components/slots'
+import { restoreSubtree, snapshotSubtree } from './history/subtree'
import { adoptCoveredLayers } from './shapes/adopt'
import { newLayerDefaults } from './shapes/defaults'
import { createFramePresetActions } from './shapes/frame-presets'
@@ -49,19 +50,26 @@ export function createShapeActions(ctx: EditorContext, updateNodeWithUndo: Updat
height: h,
name: name ?? drawnLayerName(type, pid)
}
- const node = ctx.graph.createNode(type, pid, overrides)
+ const node =
+ type === 'SHAPE_WITH_TEXT'
+ ? createShapeWithText(ctx.graph, pid, {
+ ...overrides,
+ shapeWithTextType: ctx.state.shapeWithTextKind
+ })
+ : ctx.graph.createNode(type, pid, overrides)
const id = node.id
// Callers finish the layer after this returns (the pen writes its path, fills and strokes),
- // so redo restores the layer as it was when undone, not as first created.
- let snapshot = { ...node }
+ // so redo restores the layer as it was when undone, not as first created. A shape with text
+ // brings its label, so the layer is kept with its sublayers.
+ let snapshots = snapshotSubtree(ctx.graph, id)
ctx.undo.push({
label: `Create ${type.toLowerCase()}`,
forward: () => {
- ctx.graph.createNode(snapshot.type, pid, snapshot)
+ const snapshot = snapshots.get(id)
+ if (snapshot) restoreSubtree(ctx.graph, snapshot, pid, snapshots)
},
inverse: () => {
- const current = ctx.graph.getNode(id)
- if (current) snapshot = { ...current }
+ if (ctx.graph.getNode(id)) snapshots = snapshotSubtree(ctx.graph, id)
ctx.graph.deleteNode(id)
const next = new Set(ctx.state.selectedIds)
next.delete(id)
diff --git a/packages/core/src/editor/shapes/defaults.ts b/packages/core/src/editor/shapes/defaults.ts
index 2c82be652..a7d63b201 100644
--- a/packages/core/src/editor/shapes/defaults.ts
+++ b/packages/core/src/editor/shapes/defaults.ts
@@ -1,5 +1,10 @@
import type { Fill, NodeType, SceneNode, Stroke } from '@open-pencil/scene-graph'
-import { DEFAULT_STROKE_WEIGHT } from '@open-pencil/scene-graph'
+import {
+ DEFAULT_STROKE_WEIGHT,
+ figJamColor,
+ figJamPairedStroke,
+ SHAPE_WITH_TEXT_TOOL_SIZE
+} from '@open-pencil/scene-graph'
import { copyFills, copyStrokes } from '@open-pencil/scene-graph/copy'
import {
@@ -14,11 +19,27 @@ import {
const BLACK_FILL: Fill = { type: 'SOLID', color: BLACK, opacity: 1, visible: true }
const BLACK_STROKE: Stroke = { ...BLACK_FILL, weight: DEFAULT_STROKE_WEIGHT, align: 'CENTER' }
+/** FigJam's shape tool paints a new shape in its palette's white, with white's 4 px outline. */
+const SHAPE_WITH_TEXT_FILL: Fill = {
+ type: 'SOLID',
+ color: figJamColor('white'),
+ opacity: 1,
+ visible: true
+}
+const SHAPE_WITH_TEXT_STROKE: Stroke = {
+ type: 'SOLID',
+ color: figJamPairedStroke('white', 'fill'),
+ opacity: 1,
+ visible: true,
+ weight: 4,
+ align: 'CENTER'
+}
/**
* What a new layer starts with, as Figma gives it from a drawing tool and from the plugin API:
* frames and components white (frames clipping their content), shapes light grey, lines and
- * vectors a black 1 px stroke, text black, and sections filled for the interface `theme`.
+ * vectors a black 1 px stroke, text black, sections filled for the interface `theme`, and shapes
+ * with text as FigJam's shape tool places them.
*/
export function newLayerDefaults(
type: NodeType,
@@ -46,6 +67,14 @@ export function newLayerDefaults(
return { fills: [], strokes: copyStrokes([BLACK_STROKE]) }
case 'TEXT':
return { fills: copyFills([BLACK_FILL]) }
+ case 'SHAPE_WITH_TEXT':
+ return {
+ fills: copyFills([SHAPE_WITH_TEXT_FILL]),
+ strokes: copyStrokes([SHAPE_WITH_TEXT_STROKE]),
+ width: SHAPE_WITH_TEXT_TOOL_SIZE,
+ height: SHAPE_WITH_TEXT_TOOL_SIZE,
+ shapeWithTextType: 'SQUARE'
+ }
default:
return {}
}
diff --git a/packages/core/src/editor/shapes/with-text.ts b/packages/core/src/editor/shapes/with-text.ts
new file mode 100644
index 000000000..5e38b484d
--- /dev/null
+++ b/packages/core/src/editor/shapes/with-text.ts
@@ -0,0 +1,139 @@
+import {
+ figJamColorName,
+ figJamFillMode,
+ figJamLineColorFields,
+ figJamLineStyleFields,
+ figJamShapePaint,
+ figJamTextSizeFields,
+ figJamTypeface,
+ shapeWithTextFrameFields,
+ shapeWithTextLabel,
+ type FigJamColorName,
+ type FigJamFillMode,
+ type FigJamLineStyle,
+ type FigJamTextSize,
+ type SceneNode
+} from '@open-pencil/scene-graph'
+import type { ShapeWithTextType } from '@open-pencil/scene-graph/shape-with-text'
+
+import { recordSubtreeEdit } from '#core/editor/components/slots/history'
+import type { EditorContext } from '#core/editor/types'
+
+const FILL_OPACITY: Record<FigJamFillMode, number> = { fill: 1, transparent: 0.5, none: 0 }
+
+/**
+ * Shape-with-text commands: the kind the tool places, and the kind, colours, outline and text of
+ * shapes already placed, as FigJam's selection toolbar sets them. Each change records the
+ * shapes' whole subtrees as one step, since the label changes with the shape.
+ */
+export function createShapeWithTextActions(ctx: EditorContext) {
+ function shapesAmong(ids: Iterable<string>): SceneNode[] {
+ return [...ids].flatMap((id) => {
+ const node = ctx.graph.getNode(id)
+ return node?.type === 'SHAPE_WITH_TEXT' ? [node] : []
+ })
+ }
+
+ function editShapes(label: string, ids: Iterable<string>, change: (shape: SceneNode) => void) {
+ const shapes = shapesAmong(ids)
+ if (shapes.length === 0) return
+ recordSubtreeEdit(
+ ctx,
+ label,
+ shapes.map((shape) => shape.id),
+ () => shapes.forEach(change)
+ )
+ }
+
+ /** Makes `kind` the one the shape tool places, as picking it in FigJam's Shapes panel does. */
+ function setShapeWithTextKind(kind: ShapeWithTextType) {
+ ctx.state.shapeWithTextKind = kind
+ }
+
+ /**
+ * Turns the shapes with text among `ids` into `kind`, keeping their size, as FigJam's shape
+ * switcher does; each lays its label out in the new kind's label area.
+ */
+ function changeShapesWithTextKind(ids: Iterable<string>, kind: ShapeWithTextType) {
+ const changing = shapesAmong(ids).filter((shape) => shape.shapeWithTextType !== kind)
+ editShapes(
+ 'Change shape',
+ changing.map((shape) => shape.id),
+ (shape) => {
+ ctx.graph.updateNode(shape.id, {
+ shapeWithTextType: kind,
+ ...shapeWithTextFrameFields(kind, shape.width, shape.height)
+ })
+ }
+ )
+ }
+
+ function paint(shape: SceneNode, name: FigJamColorName, mode: FigJamFillMode) {
+ const label = shapeWithTextLabel(ctx.graph, shape)
+ const painted = figJamShapePaint(shape, label, name, mode)
+ ctx.graph.updateNode(shape.id, painted.shape)
+ if (label) ctx.graph.updateNode(label.id, painted.label)
+ }
+
+ /**
+ * Paints the shapes in palette colour `name`. A see-through fill stays see-through, and a shape
+ * without fill is filled again.
+ */
+ function setShapesWithTextColor(ids: Iterable<string>, name: FigJamColorName) {
+ editShapes('Change shape color', ids, (shape) => {
+ const mode = figJamFillMode(shape.fills.at(0))
+ paint(shape, name, mode === 'none' ? 'fill' : mode)
+ })
+ }
+
+ /** Fills the shapes solid, see-through, or not at all, keeping their colour. */
+ function setShapesWithTextFillMode(ids: Iterable<string>, mode: FigJamFillMode) {
+ editShapes('Change shape fill', ids, (shape) => {
+ const fill = shape.fills.at(0)
+ const name = figJamColorName(fill?.color)
+ if (name) paint(shape, name, mode)
+ else if (fill) {
+ ctx.graph.updateNode(shape.id, {
+ fills: [{ ...fill, opacity: FILL_OPACITY[mode] }, ...shape.fills.slice(1)]
+ })
+ }
+ })
+ }
+
+ /** Draws the shapes' outlines solid, dashed, or not at all. */
+ function setShapesWithTextLineStyle(ids: Iterable<string>, style: FigJamLineStyle) {
+ editShapes('Change shape line', ids, (shape) =>
+ ctx.graph.updateNode(shape.id, figJamLineStyleFields(shape, style))
+ )
+ }
+
+ /** Colours the shapes' outlines in palette colour `name`, which later fills leave alone. */
+ function setShapesWithTextLineColor(ids: Iterable<string>, name: FigJamColorName) {
+ editShapes('Change shape line color', ids, (shape) =>
+ ctx.graph.updateNode(shape.id, figJamLineColorFields(shape, name))
+ )
+ }
+
+ /** Sets the shapes' label text to one of FigJam's sizes; each grows or shrinks to fit it. */
+ function setShapesWithTextTextSize(ids: Iterable<string>, size: FigJamTextSize) {
+ editShapes('Change shape text size', ids, (shape) => {
+ const label = shapeWithTextLabel(ctx.graph, shape)
+ if (label) {
+ ctx.graph.updateNode(
+ label.id,
+ figJamTextSizeFields(size, figJamTypeface(label) ?? 'simple')
+ )
+ }
+ })
+ }
+
+ return {
+ setShapeWithTextKind,
+ changeShapesWithTextKind,
+ setShapesWithTextColor,
+ setShapesWithTextFillMode,
+ setShapesWithTextLineStyle,
+ setShapesWithTextLineColor,
+ setShapesWithTextTextSize
+ }
+}
diff --git a/packages/core/src/editor/state/shared.ts b/packages/core/src/editor/state/shared.ts
index 5bb6335ee..fdcf93f4f 100644
--- a/packages/core/src/editor/state/shared.ts
+++ b/packages/core/src/editor/state/shared.ts
@@ -4,6 +4,7 @@ import type { EditorSharedState } from '#core/editor/types'
export function createDefaultEditorSharedState(): EditorSharedState {
return {
activeTool: 'SELECT',
+ shapeWithTextKind: 'SQUARE',
readOnly: false,
snappingPreferences: { ...DEFAULT_SNAPPING_PREFERENCES },
showPixelGrid: true,
diff --git a/packages/core/src/editor/stickies.ts b/packages/core/src/editor/stickies.ts
index a90810cb0..421fe02d9 100644
--- a/packages/core/src/editor/stickies.ts
+++ b/packages/core/src/editor/stickies.ts
@@ -1,47 +1,21 @@
import {
createSticky,
DEFAULT_STICKY_COLOR,
- generatedFrameOwner,
rescaleNodeTree,
stickyScale,
stickyWidth,
STICKY_SIZE,
- stickyBodySizeFields,
+ figJamTextSizeFields,
+ figJamTypeface,
stickySublayers
} from '@open-pencil/scene-graph'
-import type { SceneNode, StickyTextSize } from '@open-pencil/scene-graph'
+import type { SceneNode, FigJamTextSize } from '@open-pencil/scene-graph'
import type { Color, Vector } from '@open-pencil/scene-graph/primitives'
import { recordSubtreeEdit } from '#core/editor/components/slots/history'
import type { EditorContext } from '#core/editor/types'
import { pushCreatedSubtreesUndo } from '#core/editor/undo'
-/** The name a note takes from its body while it was never renamed, as FigJam names it. */
-function stickyNameFor(text: string): string {
- return text.trim() === '' ? 'Sticky' : text
-}
-
-/**
- * Typing in a note's body renames a note that was never renamed, as FigJam does. The caller
- * records the text edit; this records the rename beside it.
- */
-export function applyStickyNameEdit(
- ctx: Pick<EditorContext, 'graph' | 'undo'>,
- nodeId: string,
- text: string
-): void {
- const node = ctx.graph.getNode(nodeId)
- const sticky = node && generatedFrameOwner(ctx.graph, node)
- if (sticky?.type !== 'STICKY' || !sticky.autoRename) return
- if (stickySublayers(ctx.graph, sticky)?.body.id !== nodeId) return
- const before = sticky.name
- const after = stickyNameFor(text)
- if (before === after) return
- const rename = (name: string) => () => ctx.graph.updateNode(sticky.id, { name })
- rename(after)()
- ctx.undo.push({ label: 'Rename sticky', forward: rename(after), inverse: rename(before) })
-}
-
/**
* Sticky note commands. A note's colour sits on the note and its text on its sublayers, so each
* change records the notes' whole subtrees as one step.
@@ -102,11 +76,13 @@ export function createStickyActions(ctx: EditorContext) {
})
}
- /** Sets the size of the notes' body text to one of FigJam's presets. */
- function setStickyTextSize(ids: Iterable<string>, size: StickyTextSize) {
+ /** Sets the size of the notes' body text to one of FigJam's presets, in the body's typeface. */
+ function setStickyTextSize(ids: Iterable<string>, size: FigJamTextSize) {
editStickies('Change sticky text size', ids, (sticky) => {
const body = stickySublayers(ctx.graph, sticky)?.body
- if (body) ctx.graph.updateNode(body.id, stickyBodySizeFields(size))
+ if (body) {
+ ctx.graph.updateNode(body.id, figJamTextSizeFields(size, figJamTypeface(body) ?? 'simple'))
+ }
})
}
diff --git a/packages/core/src/editor/text.ts b/packages/core/src/editor/text.ts
index 601c2d337..2cfe89c50 100644
--- a/packages/core/src/editor/text.ts
+++ b/packages/core/src/editor/text.ts
@@ -12,7 +12,7 @@ import { weightToStyle } from '#core/text/fonts'
import { hasGlyphOutlines } from '#core/text/opentype'
import { applyBoundTextEdit } from './components/authoring/text-edit'
-import { applyStickyNameEdit } from './stickies'
+import { applyGeneratedTextNameEdit } from './text/name'
import { pathTextEditChanges } from './text/path-edit'
import {
createTextEditSession,
@@ -207,7 +207,7 @@ export function createTextActions(ctx: EditorContext) {
})
if (before.text !== after.text) {
applyBoundTextEdit(ctx, result.nodeId, after.text)
- applyStickyNameEdit(ctx, result.nodeId, after.text)
+ applyGeneratedTextNameEdit(ctx, result.nodeId, after.text)
}
})
}
diff --git a/packages/core/src/editor/text/name.ts b/packages/core/src/editor/text/name.ts
new file mode 100644
index 000000000..1c2d160ef
--- /dev/null
+++ b/packages/core/src/editor/text/name.ts
@@ -0,0 +1,30 @@
+import {
+ generatedFrameKind,
+ generatedFrameOwner,
+ generatedFrameText
+} from '@open-pencil/scene-graph'
+
+import { defaultNodeName } from '#core/editor/structure/rename'
+import type { EditorContext } from '#core/editor/types'
+
+/**
+ * Typing in the text a generated frame is named by, such as a sticky note's body or a shape's
+ * label, renames a frame that was never renamed, as FigJam does; emptied, it takes its type's
+ * name back. The caller records the text edit; this records the rename beside it.
+ */
+export function applyGeneratedTextNameEdit(
+ ctx: Pick<EditorContext, 'graph' | 'undo'>,
+ nodeId: string,
+ text: string
+): void {
+ const node = ctx.graph.getNode(nodeId)
+ const frame = node && generatedFrameOwner(ctx.graph, node)
+ if (!frame?.autoRename || !generatedFrameKind(frame)?.namedByText) return
+ if (generatedFrameText(ctx.graph, frame)?.id !== nodeId) return
+ const before = frame.name
+ const after = text.trim() === '' ? defaultNodeName(frame.type) : text
+ if (before === after) return
+ const rename = (name: string) => () => ctx.graph.updateNode(frame.id, { name })
+ rename(after)()
+ ctx.undo.push({ label: 'Rename', forward: rename(after), inverse: rename(before) })
+}
diff --git a/packages/core/src/editor/text/typeface.ts b/packages/core/src/editor/text/typeface.ts
new file mode 100644
index 000000000..35c3defcd
--- /dev/null
+++ b/packages/core/src/editor/text/typeface.ts
@@ -0,0 +1,40 @@
+import {
+ FIGJAM_TYPEFACES,
+ figJamTypefaceFields,
+ generatedFrameText,
+ type FigJamTypeface
+} from '@open-pencil/scene-graph'
+
+import { recordSubtreeEdit } from '#core/editor/components/slots/history'
+import type { EditorContext } from '#core/editor/types'
+import { weightToStyle } from '#core/text/fonts'
+
+/** Typefaces for the text generated frames are named by, such as a sticky note's body or a shape's label. */
+export function createGeneratedTextActions(ctx: EditorContext) {
+ /**
+ * Sets the text that sticky notes and shapes among `ids` are named by in one of FigJam's
+ * typefaces, once its face is loaded.
+ */
+ async function setGeneratedTextTypeface(ids: Iterable<string>, typeface: FigJamTypeface) {
+ const { fontFamily, fontWeight } = FIGJAM_TYPEFACES[typeface]
+ await ctx.loadFont(fontFamily, weightToStyle(fontWeight, false))
+ const frames = [...ids].flatMap((id) => {
+ const node = ctx.graph.getNode(id)
+ return node && generatedFrameText(ctx.graph, node) ? [node] : []
+ })
+ if (frames.length === 0) return
+ recordSubtreeEdit(
+ ctx,
+ 'Change typeface',
+ frames.map((frame) => frame.id),
+ () => {
+ for (const frame of frames) {
+ const text = generatedFrameText(ctx.graph, frame)
+ if (text) ctx.graph.updateNode(text.id, figJamTypefaceFields(typeface, text))
+ }
+ }
+ )
+ }
+
+ return { setGeneratedTextTypeface }
+}
diff --git a/packages/core/src/editor/tool-registry.ts b/packages/core/src/editor/tool-registry.ts
index 80f819b11..c9aa9a8fa 100644
--- a/packages/core/src/editor/tool-registry.ts
+++ b/packages/core/src/editor/tool-registry.ts
@@ -20,6 +20,8 @@ export const EDITOR_TOOLS: EditorToolDef[] = [
{ key: 'TEXT', label: 'Text', shortcut: 'T' },
// Figma's S is Slice, and FigJam's sticky tool has no key in Figma Design.
{ key: 'STICKY', label: 'Sticky note', shortcut: '' },
+ // FigJam's R; here R is the rectangle, as in Figma Design.
+ { key: 'SHAPE_WITH_TEXT', label: 'Shape', shortcut: '' },
// FigJam's X; Figma Design has no connector tool to take a key from.
{ key: 'CONNECTOR', label: 'Connector', shortcut: '' },
{ key: 'HAND', label: 'Hand', shortcut: 'H' },
diff --git a/packages/core/src/editor/types.ts b/packages/core/src/editor/types.ts
index f1a221362..bf73999d8 100644
--- a/packages/core/src/editor/types.ts
+++ b/packages/core/src/editor/types.ts
@@ -11,6 +11,7 @@ import type {
} from '@open-pencil/scene-graph'
import type { CanvasGuide } from '@open-pencil/scene-graph/guides'
import type { Color, Rect, Vector } from '@open-pencil/scene-graph/primitives'
+import type { ShapeWithTextType } from '@open-pencil/scene-graph/shape-with-text'
import type { SnapGuide } from '@open-pencil/scene-graph/snap'
import type { UndoManager } from '@open-pencil/scene-graph/undo'
@@ -44,6 +45,7 @@ export type Tool =
| 'STAR'
| 'TEXT'
| 'STICKY'
+ | 'SHAPE_WITH_TEXT'
| 'CONNECTOR'
| 'PEN'
| 'PENCIL'
@@ -74,6 +76,8 @@ export interface ShapeHandleHover {
export interface EditorSharedState {
activeTool: Tool
+ /** The kind the shape-with-text tool places: the one picked last, as in FigJam. */
+ shapeWithTextKind: ShapeWithTextType
/**
* The document can be looked at, selected in, and copied from but not changed, as for a viewer
* or an earlier version; set with `setReadOnly`.
diff --git a/packages/core/src/io/formats/svg/paths.ts b/packages/core/src/io/formats/svg/paths.ts
index 78c69e774..a38f15b28 100644
--- a/packages/core/src/io/formats/svg/paths.ts
+++ b/packages/core/src/io/formats/svg/paths.ts
@@ -7,7 +7,7 @@ import type {
VectorVertex
} from '@open-pencil/scene-graph'
import { polygonVertices } from '@open-pencil/scene-graph/geometry'
-import { polygonOutline } from '@open-pencil/scene-graph/polygon'
+import { outlineSVGPath, polygonOutline } from '@open-pencil/scene-graph/polygon'
import { nodeHasRadius } from '#core/canvas/shapes'
@@ -236,14 +236,7 @@ export function vectorNetworkToSVGPaths(
/** The outline of a polygon or star whose corners are rounded, as path data. */
export function roundedPolygonPath(node: SceneNode): string {
- return polygonOutline(node)
- .map((command) => {
- if (command.type === 'Z') return 'Z'
- if (command.type === 'C')
- return `C${[command.x1, command.y1, command.x2, command.y2, command.x, command.y].map(round).join(' ')}`
- return `${command.type}${round(command.x)} ${round(command.y)}`
- })
- .join('')
+ return outlineSVGPath(polygonOutline(node), (value) => round(value))
}
export function makePolygonPoints(node: SceneNode): string {
diff --git a/packages/core/src/layout.ts b/packages/core/src/layout.ts
index fe63e5b6b..c1167df55 100644
--- a/packages/core/src/layout.ts
+++ b/packages/core/src/layout.ts
@@ -44,6 +44,7 @@ import {
type SceneNode
} from '@open-pencil/scene-graph'
+import { fitShapeWithTextFrame } from './layout/shape-with-text'
import { estimateTextSize, getTextMeasurer, measureTextForLayout } from './layout/text-measurement'
import {
applyMinMaxConstraints,
@@ -66,6 +67,8 @@ export function computeLayout(graph: SceneGraph, frameId: string): void {
function computeLayoutInternal(graph: SceneGraph, frameId: string): void {
const frame = graph.getNode(frameId)
if (!frame || frame.layoutMode === 'NONE') return
+ // A shape with text takes its size from its label before laying the label out in it.
+ fitShapeWithTextFrame(graph, frame)
const rootDirection = resolveComputedLayoutDirection(graph, frame)
const yogaDirection = rootDirection === 'RTL' ? Direction.RTL : Direction.LTR
diff --git a/packages/core/src/layout/shape-with-text.ts b/packages/core/src/layout/shape-with-text.ts
new file mode 100644
index 000000000..3ee26fd15
--- /dev/null
+++ b/packages/core/src/layout/shape-with-text.ts
@@ -0,0 +1,61 @@
+import { compact } from 'es-toolkit'
+
+import { 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 { 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 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.
+ */
+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
+ )
+ )
+ size = fitShapeWithText(shape.shapeWithTextType, {
+ ...given,
+ longestWord,
+ measure: (maxWidth) => measureTextForLayout({ ...wrapping, width: maxWidth }, maxWidth)
+ })
+ }
+ return {
+ ...size,
+ ...shapeWithTextFrameFields(shape.shapeWithTextType, size.width, size.height)
+ }
+}
+
+/** Fits a shape with text to 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)
+ const changes = Object.fromEntries(
+ Object.entries(fit).filter(([key, value]) => Reflect.get(shape, key) !== value)
+ )
+ if (Object.keys(changes).length > 0) graph.updateNode(shape.id, changes)
+}
diff --git a/packages/core/tests/clipboard/figma/connectors.test.ts b/packages/core/tests/clipboard/figma/connectors.test.ts
index 5a46ffba4..f5b6dc74e 100644
--- a/packages/core/tests/clipboard/figma/connectors.test.ts
+++ b/packages/core/tests/clipboard/figma/connectors.test.ts
@@ -53,9 +53,10 @@ describe('FigJam connectors', () => {
expect(label).toMatchObject({ text: 'label', visible: true })
expect(labelBackground.visible).toBe(true)
- // Its end on a FigJam shape, which does not paste, stays where Figma drew it.
+ // Its end on a FigJam shape with text binds to the shape it pasted as.
const straight = byName('c-straight-magnets')
- expect(straight.connectorEnd).toMatchObject({ nodeId: null, magnet: 'NONE' })
+ expect(straight.connectorEnd).toMatchObject({ magnet: 'CENTER' })
+ expect(endName(graph, straight, 'connectorEnd')).toBe('c-shape')
const free = byName('c-curved-free')
expect(free.connectorEnd).toEqual({
nodeId: null,
@@ -103,13 +104,18 @@ describe('FigJam connectors', () => {
if (node.type === 'CONNECTOR') delete node.derivedImmutableFrameData
}
const graph = new SceneGraph()
- const ids = importClipboardNodes(parsed.nodes, graph, graph.getPages()[0].id, 0, 0, parsed.blobs)
+ const ids = importClipboardNodes(
+ parsed.nodes,
+ graph,
+ graph.getPages()[0].id,
+ 0,
+ 0,
+ parsed.blobs
+ )
// The fixture's other two connectors keep a cut from a label since cleared, and one ends on
// a layer left out of the copy, so Figma's saved routes for them are not what it would route.
const routed = ['c-elbow-auto', 'c-curved-free'].map((name) =>
- expectDefined(
- ids.map((id) => graph.getNode(id)).find((node) => node?.name === name)
- )
+ expectDefined(ids.map((id) => graph.getNode(id)).find((node) => node?.name === name))
)
for (const connector of routed) {
const figma = drawn.byName(connector.name)
diff --git a/packages/core/tests/design-jsx/shapes-with-text.test.ts b/packages/core/tests/design-jsx/shapes-with-text.test.ts
new file mode 100644
index 000000000..6a6e6e371
--- /dev/null
+++ b/packages/core/tests/design-jsx/shapes-with-text.test.ts
@@ -0,0 +1,89 @@
+import { describe, expect, test } from 'bun:test'
+
+import { getNodeOrThrow } from '#core-tests/helpers/assert'
+
+import { renderJSX } from '@open-pencil/core/design-jsx'
+import { sceneNodeToJSX } from '@open-pencil/design-jsx'
+import { SceneGraph, shapeWithTextLabel } from '@open-pencil/scene-graph'
+
+const BOARD = `
+ <Frame name="Board" w={900} h={400}>
+ <Shape x={0} y={0} bg="#FFC943" stroke="#000000">Start</Shape>
+ <Shape name="Check" x={300} y={0} kind="diamond" w={240} h={160} rounded={0}>Valid?</Shape>
+ </Frame>`
+
+describe('shapes with text in design JSX', () => {
+ test('are made as the shape tool makes them, named by their label', async () => {
+ const graph = new SceneGraph()
+ const [result] = await renderJSX(graph, BOARD)
+ const [square, diamond] = graph.getChildren(getNodeOrThrow(graph, result.id).id)
+ expect(square).toMatchObject({
+ type: 'SHAPE_WITH_TEXT',
+ shapeWithTextType: 'SQUARE',
+ name: 'Start',
+ autoRename: true,
+ width: 208,
+ height: 208,
+ cornerRadius: 6
+ })
+ expect(shapeWithTextLabel(graph, square)?.text).toBe('Start')
+ expect(diamond).toMatchObject({
+ shapeWithTextType: 'DIAMOND',
+ name: 'Check',
+ autoRename: false,
+ width: 240,
+ height: 160,
+ shapeUserWidth: 240,
+ shapeUserHeight: 160,
+ cornerRadius: 0
+ })
+ })
+
+ test('write back as Shape elements', async () => {
+ const graph = new SceneGraph()
+ const [result] = await renderJSX(graph, BOARD)
+ const jsx = sceneNodeToJSX(result.id, graph)
+ expect(jsx).toContain('<Shape bg="#FFC943" stroke="#000000">Start</Shape>')
+ expect(jsx).toContain(
+ '<Shape name="Check" x={300} kind="diamond" w={240} h={160} rounded={0}>Valid?</Shape>'
+ )
+ const again = new SceneGraph()
+ const [reread] = await renderJSX(again, jsx)
+ expect(sceneNodeToJSX(reread.id, again)).toBe(jsx)
+ })
+
+ test('write the size they were given, not the size their label grew them to', 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}>${label}</Shape>`)
+ const shape = getNodeOrThrow(graph, result.id)
+ expect(shape.height).toBeGreaterThan(120)
+ expect(sceneNodeToJSX(result.id, graph)).toContain('w={120} h={120}')
+ })
+
+ 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>')
+ expect(result.warnings).toEqual([
+ expect.stringContaining(
+ 'Unknown kind "blob" on <shape> is ignored; expected square, ellipse'
+ ),
+ 'Invalid w 0 on <shape> is ignored; expected >0.'
+ ])
+ expect(getNodeOrThrow(graph, result.id)).toMatchObject({
+ shapeWithTextType: 'SQUARE',
+ width: 208
+ })
+ })
+
+ test('take FigJam text sizes and typefaces for their label, and write them back', async () => {
+ const graph = new SceneGraph()
+ const [result] = await renderJSX(
+ graph,
+ '<Shape textSize="large" typeface="technical">Deploy</Shape>'
+ )
+ const label = shapeWithTextLabel(graph, getNodeOrThrow(graph, result.id))
+ expect(label).toMatchObject({ fontSize: 40, fontFamily: 'Roboto Mono' })
+ expect(sceneNodeToJSX(result.id, graph)).toContain('textSize="large" typeface="technical"')
+ })
+})
diff --git a/packages/core/tests/design-jsx/stickies.test.ts b/packages/core/tests/design-jsx/stickies.test.ts
index e9869d023..7a250a4d3 100644
--- a/packages/core/tests/design-jsx/stickies.test.ts
+++ b/packages/core/tests/design-jsx/stickies.test.ts
@@ -130,4 +130,12 @@ describe('sticky notes in design JSX', () => {
expect(connector.connectorStart?.nodeId).toBe(sticky.id)
expect(connector.connectorEnd?.nodeId).toBe(text.id)
})
+
+ test('take a FigJam typeface for their body, and write it back', async () => {
+ const graph = new SceneGraph()
+ const [result] = await renderJSX(graph, '<Sticky typeface="bookish">Notes</Sticky>')
+ const body = stickySublayers(graph, getNodeOrThrow(graph, result.id))?.body
+ expect(body?.fontFamily).toBe('Merriweather')
+ expect(sceneNodeToJSX(result.id, graph)).toContain('typeface="bookish"')
+ })
})
diff --git a/packages/core/tests/editor/clipboard/import-nodes/filtering.test.ts b/packages/core/tests/editor/clipboard/import-nodes/filtering.test.ts
index 0587118ea..b57d88df6 100644
--- a/packages/core/tests/editor/clipboard/import-nodes/filtering.test.ts
+++ b/packages/core/tests/editor/clipboard/import-nodes/filtering.test.ts
@@ -90,7 +90,6 @@ describe('importClipboardNodes: filtering', () => {
'WIDGET',
'STAMP',
'CODE_BLOCK',
- 'SHAPE_WITH_TEXT',
'TABLE_NODE',
'TABLE_CELL'
]
diff --git a/packages/core/tests/editor/shapes/with-text.test.ts b/packages/core/tests/editor/shapes/with-text.test.ts
new file mode 100644
index 000000000..93fa610a2
--- /dev/null
+++ b/packages/core/tests/editor/shapes/with-text.test.ts
@@ -0,0 +1,100 @@
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+
+import { setTextMeasurer } from '@open-pencil/core'
+import { createEditor } from '@open-pencil/core/editor'
+import { shapeWithTextLabel } from '@open-pencil/scene-graph'
+import { colorToHex } from '@open-pencil/scene-graph/color'
+
+import { applyGeneratedTextNameEdit } from '#core/editor/text/name'
+
+function setup() {
+ const editor = createEditor({ loadFont: () => Promise.resolve(null) })
+ return { editor, pageId: editor.state.currentPageId }
+}
+
+beforeEach(() => {
+ setTextMeasurer((node, maxWidth) => ({
+ width: maxWidth ?? node.width,
+ height: node.text.split('\n').length * (node.lineHeight ?? node.fontSize)
+ }))
+})
+afterEach(() => setTextMeasurer(null))
+
+describe('shapes with text in the editor', () => {
+ test('the tool places the kind picked last, painted as FigJam paints a new shape', () => {
+ const { editor, pageId } = setup()
+ editor.setShapeWithTextKind('DIAMOND')
+ const id = editor.createShape('SHAPE_WITH_TEXT', 0, 0, 176, 176, pageId)
+ const shape = expectDefined(editor.graph.getNode(id))
+ expect(shape.shapeWithTextType).toBe('DIAMOND')
+ expect(shape.fills[0]?.color).toEqual({ r: 1, g: 1, b: 1, a: 1 })
+ expect(shape.strokes[0]).toMatchObject({ weight: 4, align: 'CENTER' })
+ expect(expectDefined(shapeWithTextLabel(editor.graph, shape)).fontSize).toBe(16)
+ })
+
+ test('switching the kind keeps the size, and is one undo step', () => {
+ const { editor, pageId } = setup()
+ const id = editor.createShape('SHAPE_WITH_TEXT', 0, 0, 240, 120, pageId)
+ editor.changeShapesWithTextKind([id], 'HEXAGON')
+ expect(editor.graph.getNode(id)).toMatchObject({
+ shapeWithTextType: 'HEXAGON',
+ width: 240,
+ height: 120
+ })
+ editor.undo.undo()
+ expect(editor.graph.getNode(id)?.shapeWithTextType).toBe('SQUARE')
+ })
+
+ test("typing in a shape's label renames a shape that was never renamed", () => {
+ const { editor, pageId } = setup()
+ const id = editor.createShape('SHAPE_WITH_TEXT', 0, 0, 176, 176, pageId)
+ const shape = expectDefined(editor.graph.getNode(id))
+ const label = expectDefined(shapeWithTextLabel(editor.graph, shape))
+ applyGeneratedTextNameEdit(editor, label.id, 'Valid?')
+ expect(editor.graph.getNode(id)?.name).toBe('Valid?')
+ applyGeneratedTextNameEdit(editor, label.id, '')
+ expect(editor.graph.getNode(id)?.name).toBe('Shape with text')
+ })
+
+ test("FigJam's colour menu paints the shape, its outline and its label, in one step", () => {
+ const { editor, pageId } = setup()
+ const id = editor.createShape('SHAPE_WITH_TEXT', 0, 0, 176, 176, pageId)
+ editor.setShapesWithTextColor([id], 'violet')
+ const shape = expectDefined(editor.graph.getNode(id))
+ const hex = (color = shape.fills[0]?.color) => color && colorToHex(color).toLowerCase()
+ expect([hex(), hex(shape.strokes[0]?.color)]).toEqual(['#874fff', '#5427b4'])
+ expect(expectDefined(shapeWithTextLabel(editor.graph, shape)).fills[0]?.color).toMatchObject({
+ r: 1,
+ g: 1,
+ b: 1
+ })
+ editor.setShapesWithTextFillMode([id], 'transparent')
+ expect(editor.graph.getNode(id)?.fills[0]?.opacity).toBe(0.5)
+ editor.setShapesWithTextFillMode([id], 'none')
+ editor.setShapesWithTextColor([id], 'violet')
+ // A colour picked for a shape without fill fills it again.
+ expect(editor.graph.getNode(id)?.fills[0]?.opacity).toBe(1)
+ editor.undo.undo()
+ editor.undo.undo()
+ editor.undo.undo()
+ editor.undo.undo()
+ expect(hex(editor.graph.getNode(id)?.fills[0]?.color)).toBe('#ffffff')
+ })
+
+ test('the line menu dashes the outline, and a larger text size grows the shape', () => {
+ const { editor, pageId } = setup()
+ const id = editor.createShape('SHAPE_WITH_TEXT', 0, 0, 176, 176, pageId)
+ editor.setShapesWithTextLineStyle([id], 'dashed')
+ expect(editor.graph.getNode(id)?.dashPattern).toEqual([16, 10])
+ const shape = expectDefined(editor.graph.getNode(id))
+ const label = expectDefined(shapeWithTextLabel(editor.graph, shape))
+ editor.graph.updateNode(label.id, { text: 'one\ntwo\nthree' })
+ editor.setShapesWithTextTextSize([id], 'huge')
+ expect(editor.graph.getNode(label.id)?.fontSize).toBe(96)
+ expect(editor.graph.getNode(id)?.height).toBeGreaterThan(176)
+ editor.setShapesWithTextTextSize([id], 'small')
+ expect(editor.graph.getNode(id)?.height).toBe(176)
+ })
+})
diff --git a/packages/core/tests/editor/stickies.test.ts b/packages/core/tests/editor/stickies.test.ts
index 585a9d6ed..f0cee9d3b 100644
--- a/packages/core/tests/editor/stickies.test.ts
+++ b/packages/core/tests/editor/stickies.test.ts
@@ -5,7 +5,7 @@ import { createEditor } from '@open-pencil/core/editor'
import { STICKY_COLORS, stickySublayers } from '@open-pencil/scene-graph'
import type { SceneNode } from '@open-pencil/scene-graph'
-import { applyStickyNameEdit } from '#core/editor/stickies'
+import { applyGeneratedTextNameEdit } from '#core/editor/text/name'
import { expectDefined } from '../helpers/assert'
@@ -89,16 +89,24 @@ describe('sticky notes', () => {
expect(editor.graph.getNode(sticky.id)).toMatchObject({ x: 0, width: 416 })
})
+ test('a new text size keeps the body in its typeface, as Scribbled sets no tracking', () => {
+ const { editor, pageId } = setup()
+ const sticky = editor.createStickyNote(pageId, { x: 0, y: 0 })
+ editor.graph.updateNode(sublayers(editor, sticky).body.id, { fontFamily: 'Figma Hand' })
+ editor.setStickyTextSize([sticky.id], 'large')
+ expect(sublayers(editor, sticky).body).toMatchObject({ fontSize: 40, letterSpacing: 0 })
+ })
+
test("typing in a note's body renames a note that was never renamed", () => {
const { editor, pageId } = setup()
const sticky = editor.createStickyNote(pageId, { x: 0, y: 0 })
const { body, author } = sublayers(editor, sticky)
- applyStickyNameEdit(editor, body.id, 'Hello')
+ applyGeneratedTextNameEdit(editor, body.id, 'Hello')
expect(editor.graph.getNode(sticky.id)?.name).toBe('Hello')
- applyStickyNameEdit(editor, author.id, 'Someone')
+ applyGeneratedTextNameEdit(editor, author.id, 'Someone')
expect(editor.graph.getNode(sticky.id)?.name).toBe('Hello')
editor.renameNode(sticky.id, 'Kept')
- applyStickyNameEdit(editor, body.id, 'Changed')
+ applyGeneratedTextNameEdit(editor, body.id, 'Changed')
expect(editor.graph.getNode(sticky.id)?.name).toBe('Kept')
editor.undo.undo()
expect(editor.graph.getNode(sticky.id)?.autoRename).toBe(true)
diff --git a/packages/core/tests/editor/text/typeface.test.ts b/packages/core/tests/editor/text/typeface.test.ts
new file mode 100644
index 000000000..2a0c5136f
--- /dev/null
+++ b/packages/core/tests/editor/text/typeface.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, test } from 'bun:test'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+
+import { createEditor } from '@open-pencil/core/editor'
+import { createSticky, shapeWithTextLabel, stickySublayers } from '@open-pencil/scene-graph'
+
+function setup() {
+ const editor = createEditor({ loadFont: () => Promise.resolve(null) })
+ return { editor, pageId: editor.state.currentPageId }
+}
+
+describe('typefaces of generated text', () => {
+ test('a typeface sets the text that a shape or a sticky note is named by', async () => {
+ const { editor, pageId } = setup()
+ const id = editor.createShape('SHAPE_WITH_TEXT', 0, 0, 176, 176, pageId)
+ const sticky = createSticky(editor.graph, pageId, {})
+ await editor.setGeneratedTextTypeface([id, sticky.id], 'technical')
+ const shape = expectDefined(editor.graph.getNode(id))
+ expect(shapeWithTextLabel(editor.graph, shape)?.fontFamily).toBe('Roboto Mono')
+ expect(stickySublayers(editor.graph, sticky)?.body.fontFamily).toBe('Roboto Mono')
+ })
+})
diff --git a/packages/core/tests/layout/generated/shape-with-text.test.ts b/packages/core/tests/layout/generated/shape-with-text.test.ts
new file mode 100644
index 000000000..d7e36a1ae
--- /dev/null
+++ b/packages/core/tests/layout/generated/shape-with-text.test.ts
@@ -0,0 +1,57 @@
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test'
+
+import { getNodeOrThrow } from '#core-tests/helpers/assert'
+
+import { computeAllLayouts, SceneGraph, setTextMeasurer } from '@open-pencil/core'
+import { createShapeWithText, shapeWithTextLabel } from '@open-pencil/scene-graph'
+
+/** One 36 px line per line break, 12 px a character, never wrapping. */
+beforeEach(() =>
+ setTextMeasurer((node, maxWidth) => {
+ const lines = node.text.split('\n')
+ const widest = Math.max(...lines.map((line) => line.length * 12))
+ return { width: Math.min(maxWidth ?? widest, widest), height: lines.length * 36 }
+ })
+)
+afterEach(() => setTextMeasurer(null))
+
+function drawnShape(graph: SceneGraph, text = 'Hi') {
+ const shape = createShapeWithText(graph, graph.getPages()[0].id, {}, { text })
+ computeAllLayouts(graph, shape.id)
+ return shape.id
+}
+
+describe('shape with text size', () => {
+ test('a resize previewed during a drag is the size layout keeps', () => {
+ const graph = new SceneGraph()
+ const id = drawnShape(graph)
+ graph.updateNodePreview(id, { width: 400, height: 300 })
+ graph.runPreviewUpdates(() => computeAllLayouts(graph, id))
+ expect(getNodeOrThrow(graph, id)).toMatchObject({ width: 400, height: 300 })
+ })
+
+ test('putting the size back, as an undo or a cancelled drag does, shrinks it again', () => {
+ const graph = new SceneGraph()
+ const id = drawnShape(graph)
+ graph.updateNode(id, { width: 400, height: 300 })
+ computeAllLayouts(graph, id)
+ graph.updateNode(id, { width: 208, height: 208 })
+ computeAllLayouts(graph, id)
+ expect(getNodeOrThrow(graph, id)).toMatchObject({ width: 208, height: 208 })
+ })
+
+ test('growing for its label leaves the given size, so a shorter label shrinks it back', () => {
+ const graph = new SceneGraph()
+ const id = drawnShape(graph)
+ 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)
+ const grown = getNodeOrThrow(graph, id)
+ expect(grown.height).toBeGreaterThan(208)
+ expect(grown.shapeUserHeight).toBe(208)
+ graph.updateNode(label.id, { text: 'Hi' })
+ computeAllLayouts(graph, id)
+ expect(getNodeOrThrow(graph, id).height).toBe(208)
+ })
+})
diff --git a/packages/design-jsx/src/connectors.ts b/packages/design-jsx/src/connectors.ts
index 9e7a26a95..99756f237 100644
--- a/packages/design-jsx/src/connectors.ts
+++ b/packages/design-jsx/src/connectors.ts
@@ -17,15 +17,14 @@ import {
type SceneGraph,
type SceneNode
} from '@open-pencil/scene-graph'
-import { colorToHex, tryParseColor } from '@open-pencil/scene-graph/color'
-import type { Color, Vector } from '@open-pencil/scene-graph/primitives'
+import { colorToHex } from '@open-pencil/scene-graph/color'
+import type { Vector } from '@open-pencil/scene-graph/primitives'
import { CONNECTOR_LINE, CONNECTOR_SIDE, enumProp, STROKE_CAP } from './enums'
import { Reference } from './export/value'
-import { isColor } from './overrides/fills'
import { isLayerRef, type LayerRef, type LayerRefs } from './refs'
import { plainTextOf, type TreeNode } from './tree'
-import { OwnLayerProps, readElementProps } from './validation'
+import { ColorProp, OwnLayerProps, readElementProps } from './validation'
/**
* `<Connector from="A" to="B">`: a FigJam connector whose ends name other layers of the same
@@ -40,23 +39,6 @@ const ConnectorEnd = v.union(
'expected a layer name, a ref(), or { x, y }'
)
-/** A colour as a string, or as the colour a `designVar()` resolves to. */
-const LineColor = v.union(
- [
- v.pipe(
- v.string(),
- v.rawTransform(({ dataset, addIssue, NEVER }): Color => {
- const color = tryParseColor(dataset.value)
- if (color) return color
- addIssue({ message: 'expected a colour' })
- return NEVER
- })
- ),
- v.custom<Color>(isColor)
- ],
- 'expected a colour'
-)
-
/** The props `<Connector>` takes: its own, and the layer props that style its line. */
export const ConnectorProps = v.object({
from: v.optional(ConnectorEnd),
@@ -67,7 +49,7 @@ export const ConnectorProps = v.object({
startCap: v.optional(enumProp(STROKE_CAP)),
endCap: v.optional(enumProp(STROKE_CAP)),
...OwnLayerProps.entries,
- stroke: v.optional(LineColor),
+ stroke: v.optional(ColorProp),
strokeWidth: v.optional(v.pipe(v.number(), v.gtValue(0))),
dashPattern: v.optional(v.array(v.number()))
})
diff --git a/packages/design-jsx/src/elements.ts b/packages/design-jsx/src/elements.ts
index c0566af49..e98647cdd 100644
--- a/packages/design-jsx/src/elements.ts
+++ b/packages/design-jsx/src/elements.ts
@@ -15,6 +15,7 @@ import {
DESIGN_JSX_SUPPORTED_PROPERTY_NAMES,
DESIGN_JSX_TEXT_PARAGRAPH_PROPERTY_NAMES
} from './schema'
+import { renderShapeNode, ShapeLayerProps, ShapeProps } from './shapes-with-text'
import { renderStickyNode, StickyLayerProps, StickyProps } from './stickies'
import type { TreeNode } from './tree'
import type { ElementPropsSchema } from './validation'
@@ -182,6 +183,14 @@ export const DESIGN_JSX_ELEMENTS: DesignJSXElementDefinition[] = [
ownLayer: { layer: StickyLayerProps, render: renderStickyNode },
writes: ['STICKY']
},
+ {
+ name: 'Shape',
+ runtimeType: 'shape',
+ description: 'A FigJam shape with text; its text is the label.',
+ schema: ShapeProps,
+ ownLayer: { layer: ShapeLayerProps, render: renderShapeNode },
+ writes: ['SHAPE_WITH_TEXT']
+ },
{
name: 'Connector',
runtimeType: 'connector',
diff --git a/packages/design-jsx/src/enums.ts b/packages/design-jsx/src/enums.ts
index 9aa1ee567..f74b9b900 100644
--- a/packages/design-jsx/src/enums.ts
+++ b/packages/design-jsx/src/enums.ts
@@ -8,7 +8,8 @@ import type {
MaskType,
SceneNode,
Stroke,
- StickyTextSize,
+ FigJamTextSize,
+ FigJamTypeface,
StrokeCap,
StrokeJoin,
TextAutoResize,
@@ -17,6 +18,10 @@ import type {
TextDecorationStyle,
TextDirection
} from '@open-pencil/scene-graph'
+import {
+ SHAPE_WITH_TEXT_TYPES,
+ type ShapeWithTextType
+} from '@open-pencil/scene-graph/shape-with-text'
/**
* A Figma enum as design JSX spells it. Reading and writing come from one table, so whatever the
@@ -134,13 +139,22 @@ export const TEXT_DECORATION = lowercaseEnum<TextDecoration>(['NONE', 'UNDERLINE
export const TEXT_DECORATION_STYLE = lowercaseEnum<TextDecorationStyle>(['SOLID', 'DOTTED', 'WAVY'])
export const TEXT_CASE = lowercaseEnum<TextCase>(['ORIGINAL', 'UPPER', 'LOWER', 'TITLE'])
-export const STICKY_TEXT_SIZE = jsxEnum<StickyTextSize>({
+export const FIGJAM_TEXT_SIZE = jsxEnum<FigJamTextSize>({
small: 'small',
medium: 'medium',
large: 'large',
extraLarge: 'extraLarge',
huge: 'huge'
})
+/** FigJam's typefaces, as its text menus name them. */
+export const FIGJAM_TYPEFACE = jsxEnum<FigJamTypeface>({
+ simple: 'simple',
+ bookish: 'bookish',
+ technical: 'technical',
+ scribbled: 'scribbled'
+})
+/** The kinds a `<Shape>` draws, as FigJam names them: `rounded_rectangle`, `eng_database`. */
+export const SHAPE_KIND = lowercaseEnum<ShapeWithTextType>(SHAPE_WITH_TEXT_TYPES)
export const CONNECTOR_LINE = lowercaseEnum<ConnectorLineType>(['ELBOWED', 'STRAIGHT', 'CURVED'])
/** The sides a `<Connector>` end attaches by; the other magnets come only from files. */
export const CONNECTOR_SIDE = lowercaseEnum<
diff --git a/packages/design-jsx/src/export/index.ts b/packages/design-jsx/src/export/index.ts
index ee1a3cbb5..c1961ace4 100644
--- a/packages/design-jsx/src/export/index.ts
+++ b/packages/design-jsx/src/export/index.ts
@@ -16,10 +16,11 @@ import {
type ConnectorExportScope
} from '../connectors'
import { elementTag } from '../elements'
-import { stickyBody, stickyName, stickyProps } from '../stickies'
+import { shapeWithTextLabelText, shapeWithTextProps } from '../shapes-with-text'
+import { stickyBody, stickyProps } from '../stickies'
import { rekaExport, type RekaExport } from './behaviours'
import { iconProps } from './icons'
-import { collectProps, positionProps } from './props'
+import { collectProps, positionProps, presenceProps } from './props'
import { textChildren } from './text'
import { plainValue, propAttribute, Reference, type JSXProp } from './value'
@@ -65,6 +66,14 @@ interface OwnElement {
text: string
}
+/**
+ * The name an element named by its text writes: none while the layer still follows its text, and
+ * its name once renamed, even to its text, so reading it back keeps the name from following it.
+ */
+function textNamedName(node: SceneNode): JSXProp[] {
+ return node.autoRename ? [] : [['name', node.name]]
+}
+
/**
* The layers whose elements take props of their own rather than the layer props: every generated
* frame, whose sublayers its element writes as props and text.
@@ -73,17 +82,24 @@ const OWN_ELEMENTS: Record<
GeneratedFrameType,
(graph: SceneGraph, node: SceneNode, scope?: ConnectorExportScope) => OwnElement
> = {
- STICKY: (graph, node) => {
- const name = stickyName(node)
- return {
- props: [
- ...(name ? [['name', name] satisfies JSXProp] : []),
- ...positionProps(node, graph),
- ...stickyProps(graph, node).map(([key, value]): JSXProp => [key, plainValue(value)])
- ],
- text: stickyBody(graph, node)
- }
- },
+ STICKY: (graph, node) => ({
+ props: [
+ ...textNamedName(node),
+ ...positionProps(node, graph),
+ ...stickyProps(graph, node).map(([key, value]): JSXProp => [key, plainValue(value)]),
+ ...presenceProps(node)
+ ],
+ text: stickyBody(graph, node)
+ }),
+ SHAPE_WITH_TEXT: (graph, node) => ({
+ props: [
+ ...textNamedName(node),
+ ...positionProps(node, graph),
+ ...shapeWithTextProps(graph, node),
+ ...presenceProps(node)
+ ],
+ text: shapeWithTextLabelText(graph, node)
+ }),
CONNECTOR: (graph, node, scope) => ({
props: connectorProps(graph, node, scope).map(([key, value]): JSXProp => [
key,
diff --git a/packages/design-jsx/src/export/props.ts b/packages/design-jsx/src/export/props.ts
index 5c9876e78..d63a5ec1a 100644
--- a/packages/design-jsx/src/export/props.ts
+++ b/packages/design-jsx/src/export/props.ts
@@ -146,6 +146,14 @@ function collectPositionProps(
if (node.y !== 0) props.push(['y', node.y])
}
+/** A layer's opacity and whether it is hidden, for an element that writes its own props. */
+export function presenceProps(node: SceneNode): JSXProp[] {
+ const props: JSXProp[] = []
+ if (node.opacity < 1) props.push(['opacity', Math.round(node.opacity * 100) / 100])
+ if (!node.visible) props.push(['visible', false])
+ return props
+}
+
/** Where a layer sits in its parent, as the export writes any layer's position. */
export function positionProps(node: SceneNode, graph: SceneGraph): JSXProp[] {
const props: JSXProp[] = []
diff --git a/packages/design-jsx/src/figjam-text.ts b/packages/design-jsx/src/figjam-text.ts
new file mode 100644
index 000000000..ff337d0ae
--- /dev/null
+++ b/packages/design-jsx/src/figjam-text.ts
@@ -0,0 +1,37 @@
+import {
+ figJamTextSize,
+ figJamTextSizeFields,
+ figJamTypeface,
+ figJamTypefaceFields,
+ type FigJamTextSize,
+ type FigJamTypeface,
+ type SceneNode
+} from '@open-pencil/scene-graph'
+
+import { FIGJAM_TEXT_SIZE, FIGJAM_TYPEFACE } from './enums'
+
+/**
+ * The fields a sticky note's body or a shape's label takes from `textSize` and `typeface`, as
+ * FigJam's text menus set them; the typeface keeps the size the text ends up at.
+ */
+export function figJamTextFields(
+ text: Pick<SceneNode, 'fontSize'>,
+ textSize: FigJamTextSize | undefined,
+ typeface: FigJamTypeface | undefined
+): Partial<SceneNode> {
+ const sized = textSize ? figJamTextSizeFields(textSize, typeface) : {}
+ if (!typeface) return sized
+ return figJamTypefaceFields(typeface, { fontSize: sized.fontSize ?? text.fontSize })
+}
+
+/** `textSize` and `typeface` as an element writes them, each left out at FigJam's default. */
+export function figJamTextProps(
+ text: Pick<SceneNode, 'fontSize' | 'fontFamily'>
+): Array<[string, string]> {
+ const props: Array<[string, string]> = []
+ const size = figJamTextSize(text)
+ if (size !== 'small') props.push(['textSize', FIGJAM_TEXT_SIZE.print(size)])
+ const typeface = figJamTypeface(text)
+ if (typeface && typeface !== 'simple') props.push(['typeface', FIGJAM_TYPEFACE.print(typeface)])
+ return props
+}
diff --git a/packages/design-jsx/src/overrides/strokes.ts b/packages/design-jsx/src/overrides/strokes.ts
index bff0085c0..27a4fdabb 100644
--- a/packages/design-jsx/src/overrides/strokes.ts
+++ b/packages/design-jsx/src/overrides/strokes.ts
@@ -22,7 +22,7 @@ function isColor(value: unknown): value is Color {
return value !== null && typeof value === 'object' && 'r' in value && 'a' in value
}
-function isStrokeValue(value: unknown): value is StrokeValue {
+export function isStrokeValue(value: unknown): value is StrokeValue {
if (value === null || typeof value !== 'object' || !('color' in value)) return false
return typeof value.color === 'string' || isColor(value.color)
}
diff --git a/packages/design-jsx/src/reference/authoring.md b/packages/design-jsx/src/reference/authoring.md
index 84ffe1463..6328d0664 100644
--- a/packages/design-jsx/src/reference/authoring.md
+++ b/packages/design-jsx/src/reference/authoring.md
@@ -25,7 +25,8 @@ This reference describes scene creation, not React DOM output. Use the `render`
- Text content belongs inside `Text`. Use `size`, `font`, `weight`, `italic`, `lineHeight`, `letterSpacing`, `textAlign`, `textAlignVertical`, `textDecoration`, and `textCase`. Decorations take CSS's names and values: `textDecorationStyle` (`solid`, `dotted`, `wavy`), `textDecorationColor` (`currentColor` follows the text), `textDecorationThickness` and `textUnderlineOffset` (pixels or `auto`), and `textDecorationSkipInk`. `lineHeight="auto"` follows the font, and `fills={[]}` paints no text. Verify fonts actually load before judging dimensions; do not assume every font is available.
- `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`, and `scale` scales the whole note. A note sizes itself; it takes no `w`, `h`, fills, or layout props.
+- `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 (208 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`.
- `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.ts
new file mode 100644
index 000000000..f74f2fe5d
--- /dev/null
+++ b/packages/design-jsx/src/shapes-with-text.ts
@@ -0,0 +1,122 @@
+import * as v from 'valibot'
+
+import {
+ createShapeWithText,
+ SHAPE_WITH_TEXT_CORNER_RADIUS,
+ SHAPE_WITH_TEXT_SIZE,
+ shapeWithTextLabel,
+ type SceneGraph,
+ type SceneNode
+} from '@open-pencil/scene-graph'
+
+import {
+ enumProp,
+ FIGJAM_TEXT_SIZE,
+ FIGJAM_TYPEFACE,
+ SHAPE_KIND,
+ STROKE_ALIGN,
+ STROKE_CAP,
+ STROKE_JOIN
+} from './enums'
+import { collectFillProps, collectStrokeProps } from './export/paint'
+import type { JSXProp } from './export/value'
+import { figJamTextFields, figJamTextProps } from './figjam-text'
+import { isFillValue } from './overrides/fills'
+import { isStrokeValue } from './overrides/strokes'
+import { plainTextOf, type TreeNode } from './tree'
+import { ColorProp, PlacedOwnLayerProps, readElementProps } from './validation'
+
+/**
+ * `<Shape kind="diamond" bg="#FFC943">Decide</Shape>`: a FigJam shape with text, made from the
+ * same template as the shape tool's. Its text is the label.
+ */
+export const SHAPE_ELEMENT = 'shape'
+
+const Size = v.pipe(v.number(), v.gtValue(0))
+const Dash = v.array(v.number())
+
+/**
+ * The layer props a shape has: its place, the size it is given, which it grows past to fit its
+ * label, and its paint. The label is styled as FigJam styles it, and the shape lays it out.
+ */
+export const ShapeLayerProps = v.object({
+ ...PlacedOwnLayerProps.entries,
+ w: v.optional(Size),
+ h: v.optional(Size),
+ rotate: v.optional(v.number()),
+ rounded: v.optional(v.pipe(v.number(), v.minValue(0))),
+ bg: v.optional(v.custom(isFillValue, 'expected a colour or a paint')),
+ fills: v.optional(v.array(v.custom(isFillValue, 'expected a colour or a paint'))),
+ stroke: v.optional(ColorProp),
+ strokeWidth: v.optional(Size),
+ strokeAlign: v.optional(enumProp(STROKE_ALIGN)),
+ strokeDash: v.optional(Dash),
+ strokes: v.optional(v.array(v.custom(isStrokeValue, 'expected a stroke'))),
+ strokeCap: v.optional(enumProp(STROKE_CAP)),
+ strokeJoin: v.optional(enumProp(STROKE_JOIN)),
+ dashPattern: v.optional(Dash)
+})
+
+/** The props `<Shape>` takes: its kind, and the layer props a shape has. */
+export const ShapeProps = v.object({
+ kind: v.optional(enumProp(SHAPE_KIND)),
+ textSize: v.optional(enumProp(FIGJAM_TEXT_SIZE)),
+ typeface: v.optional(enumProp(FIGJAM_TYPEFACE)),
+ ...ShapeLayerProps.entries
+})
+
+/**
+ * The shape an element describes, with `layer`'s fields; it is named by its label, as FigJam
+ * names a shape, until given a name.
+ */
+export function renderShapeNode(
+ graph: SceneGraph,
+ tree: TreeNode,
+ parentId: string,
+ layer: Partial<SceneNode>
+) {
+ const props = readElementProps(ShapeProps, tree.props)
+ const text = plainTextOf(tree)
+ const shape = createShapeWithText(
+ graph,
+ parentId,
+ {
+ ...layer,
+ name: layer.name ?? (text.trim() || 'Shape with text'),
+ autoRename: !layer.name,
+ shapeWithTextType: props.kind ?? 'SQUARE'
+ },
+ { text }
+ )
+ const label = shapeWithTextLabel(graph, shape)
+ if (label) graph.updateNode(label.id, figJamTextFields(label, props.textSize, props.typeface))
+ return shape
+}
+
+/**
+ * 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.
+ */
+export function shapeWithTextProps(graph: SceneGraph, node: SceneNode): JSXProp[] {
+ const props: JSXProp[] = []
+ if (node.shapeWithTextType !== 'SQUARE') {
+ props.push(['kind', SHAPE_KIND.print(node.shapeWithTextType)])
+ }
+ 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])
+ if (height !== SHAPE_WITH_TEXT_SIZE) props.push(['h', height])
+ if (node.rotation !== 0) props.push(['rotate', Math.round(node.rotation * 100) / 100])
+ collectFillProps(node, props)
+ collectStrokeProps(node, props)
+ if (node.cornerRadius !== SHAPE_WITH_TEXT_CORNER_RADIUS)
+ props.push(['rounded', node.cornerRadius])
+ return props
+}
+
+/** The label a shape writes as its children. */
+export function shapeWithTextLabelText(graph: SceneGraph, node: SceneNode): string {
+ return shapeWithTextLabel(graph, node)?.text ?? ''
+}
diff --git a/packages/design-jsx/src/stickies.ts b/packages/design-jsx/src/stickies.ts
index d459942e2..bc26905be 100644
--- a/packages/design-jsx/src/stickies.ts
+++ b/packages/design-jsx/src/stickies.ts
@@ -4,17 +4,16 @@ import {
createSticky,
isWideSticky,
STICKY_COLORS,
- stickyBodySizeFields,
stickyScale,
stickySublayers,
- stickyTextSize,
type SceneGraph,
type SceneNode
} from '@open-pencil/scene-graph'
import { colorToHex, tryParseColor } from '@open-pencil/scene-graph/color'
import type { Color } from '@open-pencil/scene-graph/primitives'
-import { enumProp, STICKY_TEXT_SIZE } from './enums'
+import { enumProp, FIGJAM_TEXT_SIZE, FIGJAM_TYPEFACE } from './enums'
+import { figJamTextFields, figJamTextProps } from './figjam-text'
import { plainTextOf, type TreeNode } from './tree'
import { PlacedOwnLayerProps, readElementProps } from './validation'
@@ -52,7 +51,8 @@ export const StickyProps = v.object({
author: v.optional(v.string()),
authorVisible: v.optional(v.boolean()),
wide: v.optional(v.boolean()),
- textSize: v.optional(enumProp(STICKY_TEXT_SIZE)),
+ textSize: v.optional(enumProp(FIGJAM_TEXT_SIZE)),
+ typeface: v.optional(enumProp(FIGJAM_TYPEFACE)),
scale: v.optional(v.pipe(v.number(), v.gtValue(0))),
...StickyLayerProps.entries
})
@@ -84,7 +84,7 @@ export function renderStickyNode(
{ ...layer, name: layer.name ?? (text.trim() || 'Sticky'), autoRename: !layer.name }
)
const body = stickySublayers(graph, sticky)?.body
- if (body && props.textSize) graph.updateNode(body.id, stickyBodySizeFields(props.textSize))
+ if (body) graph.updateNode(body.id, figJamTextFields(body, props.textSize, props.typeface))
return sticky
}
@@ -95,14 +95,6 @@ function colorName(color: Color): string {
return named ? named[0] : hex
}
-/**
- * The name `<Sticky>` writes: none while the note is still named by its body, and its name once
- * renamed, even to its body, so reading it back keeps the name from following the body.
- */
-export function stickyName(node: SceneNode): string | null {
- return node.autoRename ? null : node.name
-}
-
/** A note's own props as `<Sticky>` writes them, after its name and position. */
export function stickyProps(graph: SceneGraph, node: SceneNode): Array<[string, unknown]> {
const layers = stickySublayers(graph, node)
@@ -112,13 +104,9 @@ export function stickyProps(graph: SceneGraph, node: SceneNode): Array<[string,
if (layers?.author.text) props.push(['author', layers.author.text])
if (layers?.author.text && !layers.author.visible) props.push(['authorVisible', false])
if (isWideSticky(graph, node)) props.push(['wide', true])
- if (layers && stickyTextSize(layers.body) !== 'small') {
- props.push(['textSize', stickyTextSize(layers.body)])
- }
+ if (layers) props.push(...figJamTextProps(layers.body))
const scale = layers ? stickyScale(layers.author) : 1
if (scale !== 1) props.push(['scale', scale])
- if (node.opacity < 1) props.push(['opacity', Math.round(node.opacity * 100) / 100])
- if (!node.visible) props.push(['visible', false])
return props
}
diff --git a/packages/design-jsx/src/validation.ts b/packages/design-jsx/src/validation.ts
index 56a7feccf..dbec84e99 100644
--- a/packages/design-jsx/src/validation.ts
+++ b/packages/design-jsx/src/validation.ts
@@ -1,6 +1,10 @@
import { mapValues } from 'es-toolkit/object'
import * as v from 'valibot'
+import { tryParseColor } from '@open-pencil/scene-graph/color'
+import type { Color } from '@open-pencil/scene-graph/primitives'
+
+import { isColor } from './overrides/fills'
import { isVariable } from './vars'
/**
@@ -36,6 +40,23 @@ export const PlacedOwnLayerProps = v.object({
position: v.optional(v.picklist(['absolute']))
})
+/** A colour as a string, or as the colour a `designVar()` resolves to. */
+export const ColorProp = v.union(
+ [
+ v.pipe(
+ v.string(),
+ v.rawTransform(({ dataset, addIssue, NEVER }): Color => {
+ const color = tryParseColor(dataset.value)
+ if (color) return color
+ addIssue({ message: 'expected a colour' })
+ return NEVER
+ })
+ ),
+ v.custom<Color>(isColor)
+ ],
+ 'expected a colour'
+)
+
/** The props of an element read one at a time, each of them optional. */
export type ElementPropsSchema = v.ObjectSchema<v.ObjectEntries, undefined>
diff --git a/packages/design-jsx/tests/enums.test.ts b/packages/design-jsx/tests/enums.test.ts
index 89d12805a..5d7737c25 100644
--- a/packages/design-jsx/tests/enums.test.ts
+++ b/packages/design-jsx/tests/enums.test.ts
@@ -4,7 +4,7 @@ import {
BLEND_MODE,
CONSTRAINT,
MASK_TYPE,
- STICKY_TEXT_SIZE,
+ FIGJAM_TEXT_SIZE,
STROKE_ALIGN,
STROKE_CAP,
STROKE_JOIN,
@@ -114,8 +114,8 @@ describe('design JSX enums', () => {
})
test('a sticky text size reads as its camelCase name in any case, and an unknown one warns', async () => {
- expect(STICKY_TEXT_SIZE.parse('extralarge')).toBe('extraLarge')
- expect(STICKY_TEXT_SIZE.print('extraLarge')).toBe('extraLarge')
+ expect(FIGJAM_TEXT_SIZE.parse('extralarge')).toBe('extraLarge')
+ expect(FIGJAM_TEXT_SIZE.print('extraLarge')).toBe('extraLarge')
const { warnings } = await render('<Sticky textSize="giant">Hi</Sticky>')
expect(warnings[0]).toStartWith('Unknown textSize "giant" on <sticky> is ignored')
})
diff --git a/packages/docs/reference/design-authoring.md b/packages/docs/reference/design-authoring.md
index 610a3b4b0..5d64ae9a1 100644
--- a/packages/docs/reference/design-authoring.md
+++ b/packages/docs/reference/design-authoring.md
@@ -27,7 +27,8 @@ This reference describes scene creation, not React DOM output. Use the `render`
- Text content belongs inside `Text`. Use `size`, `font`, `weight`, `italic`, `lineHeight`, `letterSpacing`, `textAlign`, `textAlignVertical`, `textDecoration`, and `textCase`. Decorations take CSS's names and values: `textDecorationStyle` (`solid`, `dotted`, `wavy`), `textDecorationColor` (`currentColor` follows the text), `textDecorationThickness` and `textUnderlineOffset` (pixels or `auto`), and `textDecorationSkipInk`. `lineHeight="auto"` follows the font, and `fills={[]}` paints no text. Verify fonts actually load before judging dimensions; do not assume every font is available.
- `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`, and `scale` scales the whole note. A note sizes itself; it takes no `w`, `h`, fills, or layout props.
+- `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 (208 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`.
- `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.
@@ -104,7 +105,7 @@ The examples below are executed by the authoring-reference tests. Create the nam
Generated from the renderer metadata. This inventory lists accepted names, not arbitrary browser CSS support.
-**Elements:** `Frame`, `Text`, `Span`, `Paragraph`, `Rectangle`, `Ellipse`, `Line`, `Star`, `Polygon`, `Vector`, `Group`, `Section`, `Component`, `ComponentSet`, `Instance`, `View`, `Rect`, `Icon`, `Sticky`, `Connector`, `Button.Root`, `Toggle.Root`, `Switch.Root`, `Switch.Thumb`, `Checkbox.Root`, `Checkbox.Indicator`, `RadioGroup.Root`, `RadioGroup.Item`, `RadioGroup.Indicator`, `ToggleGroup.Root`, `ToggleGroup.Item`, `Slider.Root`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Progress.Root`, `Progress.Track`, `Progress.Indicator`, `Tabs.Root`, `Tabs.List`, `Tabs.Trigger`, `Tabs.Content`, `Collapsible.Root`, `Collapsible.Trigger`, `Collapsible.Content`, `Accordion.Root`, `Accordion.Item`, `Accordion.Header`, `Accordion.Trigger`, `Accordion.Content`, `NumberField.Root`, `NumberField.Input`, `NumberField.Increment`, `NumberField.Decrement`, `TextField.Root`, `TextField.Input`, `Textarea.Root`, `Textarea.Input`.
+**Elements:** `Frame`, `Text`, `Span`, `Paragraph`, `Rectangle`, `Ellipse`, `Line`, `Star`, `Polygon`, `Vector`, `Group`, `Section`, `Component`, `ComponentSet`, `Instance`, `View`, `Rect`, `Icon`, `Sticky`, `Shape`, `Connector`, `Button.Root`, `Toggle.Root`, `Switch.Root`, `Switch.Thumb`, `Checkbox.Root`, `Checkbox.Indicator`, `RadioGroup.Root`, `RadioGroup.Item`, `RadioGroup.Indicator`, `ToggleGroup.Root`, `ToggleGroup.Item`, `Slider.Root`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Progress.Root`, `Progress.Track`, `Progress.Indicator`, `Tabs.Root`, `Tabs.List`, `Tabs.Trigger`, `Tabs.Content`, `Collapsible.Root`, `Collapsible.Trigger`, `Collapsible.Content`, `Accordion.Root`, `Accordion.Item`, `Accordion.Header`, `Accordion.Trigger`, `Accordion.Content`, `NumberField.Root`, `NumberField.Input`, `NumberField.Increment`, `NumberField.Decrement`, `TextField.Root`, `TextField.Input`, `Textarea.Root`, `Textarea.Input`.
**Helpers:** `solid`, `gradient`, `linearGradient`, `radialGradient`, `angularGradient`, `diamondGradient`, `shader`, `dropShadow`, `innerShadow`, `layerBlur`, `backgroundBlur`, `foregroundBlur`, `designVar`, `defineVars`, `ref`.
diff --git a/packages/fig/src/node-change/convert.ts b/packages/fig/src/node-change/convert.ts
index ec5f19548..e0f5cf347 100644
--- a/packages/fig/src/node-change/convert.ts
+++ b/packages/fig/src/node-change/convert.ts
@@ -11,6 +11,7 @@ import {
} from '@open-pencil/scene-graph'
import { createDefaultSourceMetadata } from '@open-pencil/scene-graph/node-defaults'
import { POINT_COUNT_RANGE } from '@open-pencil/scene-graph/polygon'
+import { isShapeWithTextType } from '@open-pencil/scene-graph/shape-with-text'
import { parseVariantName } from '@open-pencil/scene-graph/variant-name'
/* eslint-disable max-lines -- kiwi↔scene conversion helpers are tightly coupled */
@@ -409,6 +410,27 @@ function convertParagraphProps(
}
}
+/** A size a record gives, or 0 (unset) when it is missing, negative or not a finite number. */
+function givenSize(value: unknown): number {
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0
+}
+
+/**
+ * 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.
+ */
+function convertShapeWithTextProps(
+ nc: NodeChange
+): Partial<Pick<SceneNode, 'shapeWithTextType' | 'shapeUserHeight' | 'shapeUserWidth'>> {
+ 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))
+ }
+}
+
function convertTextProps(nc: NodeChange, blobs: Uint8Array[]): TextProps {
return {
text: nc.textData?.characters ?? '',
@@ -708,6 +730,7 @@ export function nodeChangeToProps(
...convertCornerProps(nc),
...convertPolygonProps(nc),
...convertTextProps(nc, blobs),
+ ...convertShapeWithTextProps(nc),
horizontalConstraint: mapConstraint(nc.horizontalConstraint as string),
verticalConstraint: mapConstraint(nc.verticalConstraint as string),
...convertLayoutProps(nc),
diff --git a/packages/fig/src/node-change/export/node.ts b/packages/fig/src/node-change/export/node.ts
index dff619a5c..b1d1d9c90 100644
--- a/packages/fig/src/node-change/export/node.ts
+++ b/packages/fig/src/node-change/export/node.ts
@@ -908,6 +908,13 @@ 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
@@ -1052,6 +1059,7 @@ 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 = pluginData
diff --git a/packages/fig/src/node-change/generated/codecs.ts b/packages/fig/src/node-change/generated/codecs.ts
index 7acc77e1f..e103fe15e 100644
--- a/packages/fig/src/node-change/generated/codecs.ts
+++ b/packages/fig/src/node-change/generated/codecs.ts
@@ -2,10 +2,12 @@ import type { NodeType } from '@open-pencil/scene-graph'
import type { GeneratedFrameCodec } from './codec'
import { CONNECTOR_CODEC } from './connector'
+import { SHAPE_WITH_TEXT_CODEC } from './shape-with-text'
import { STICKY_CODEC } from './sticky'
/** Each generated frame type's codec; a type without one is written as a plain frame. */
const GENERATED_FRAME_CODECS: Partial<Record<NodeType, GeneratedFrameCodec>> = {
+ SHAPE_WITH_TEXT: SHAPE_WITH_TEXT_CODEC,
STICKY: STICKY_CODEC,
CONNECTOR: CONNECTOR_CODEC
}
diff --git a/packages/fig/src/node-change/generated/shape-with-text.ts b/packages/fig/src/node-change/generated/shape-with-text.ts
new file mode 100644
index 000000000..01dcc8f17
--- /dev/null
+++ b/packages/fig/src/node-change/generated/shape-with-text.ts
@@ -0,0 +1,167 @@
+import { pick } from 'es-toolkit'
+
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import {
+ buildShapeWithTextLabel,
+ SHAPE_WITH_TEXT_LABEL_LAYOUT,
+ shapeWithTextFrameFields,
+ shapeWithTextLabel
+} from '@open-pencil/scene-graph'
+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+
+import { cloneRecord } from '../clone'
+import { nodeChangeToProps } from '../convert'
+import type { KiwiNodeChange, SceneNodeToKiwiContext } from '../export/context'
+import type { GeneratedFrameCodec } from './codec'
+import { placement, shaped, sublayerRecord, textSublayer } from './entries'
+import {
+ derivedFrameEntriesOf,
+ generatedSlotPath,
+ generationOverridesOf,
+ type GeneratedEntry
+} from './records'
+
+/** Where FigJam keeps a shape with text's parts: its paint on the background, its text on the label. */
+export const SHAPE_WITH_TEXT_SLOTS = { background: 0, label: 1 } as const
+
+/**
+ * The fields a SHAPE_WITH_TEXT's own record keeps, as FigJam writes it. Its paint, corners and
+ * effects live on its background and its text on its label, and the auto layout that only places
+ * the label stays out.
+ */
+const SHAPE_WITH_TEXT_RECORD_FIELDS = [
+ 'guid',
+ 'parentIndex',
+ 'phase',
+ 'type',
+ 'name',
+ 'visible',
+ 'opacity',
+ 'blendMode',
+ 'locked',
+ 'size',
+ 'transform',
+ 'autoRename',
+ 'frameMaskDisabled',
+ 'exportSettings',
+ 'pluginData',
+ 'pluginRelaunchData'
+] 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',
+ 'strokePaints',
+ 'strokeWeight',
+ 'strokeAlign',
+ 'strokeCap',
+ 'strokeJoin',
+ 'dashPattern',
+ 'effects',
+ 'styleIdForFill',
+ 'styleIdForStrokeFill',
+ 'styleIdForEffect'
+] as const
+
+/** A shape with text's paint, corners and effects, as its background holds them. */
+function backgroundProps(
+ entry: GeneratedEntry | undefined,
+ blobs: Uint8Array[]
+): Partial<SceneNode> {
+ if (!entry) return {}
+ const { guidPath: _slot, ...fields } = cloneRecord(entry)
+ const props = nodeChangeToProps({ ...fields, type: 'RECTANGLE' }, blobs, 'occurrence')
+ return pick(props, [
+ 'fills',
+ 'strokes',
+ 'strokeCap',
+ 'strokeJoin',
+ 'dashPattern',
+ 'cornerRadius',
+ 'effects',
+ 'fillStyleId',
+ 'strokeStyleId',
+ 'effectStyleId'
+ ])
+}
+
+function labelProps(
+ entry: GeneratedEntry | undefined,
+ derived: GeneratedEntry | undefined,
+ blobs: Uint8Array[]
+): Partial<SceneNode> {
+ if (!entry) return {}
+ const {
+ nodeType: _type,
+ name: _name,
+ ...props
+ } = nodeChangeToProps(sublayerRecord('TEXT', entry, derived), blobs, 'occurrence')
+ return { ...props, ...SHAPE_WITH_TEXT_LABEL_LAYOUT }
+}
+
+/**
+ * Gives an imported SHAPE_WITH_TEXT its paint from its background and its label, centred in the
+ * label area of its kind. A shape without a generated label gets an empty one, which typing fills.
+ */
+function readShapeWithText(
+ graph: SceneGraph,
+ shape: SceneNode,
+ record: NodeChange,
+ blobs: Uint8Array[]
+): void {
+ const { background, label } = SHAPE_WITH_TEXT_SLOTS
+ 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)
+ })
+ const derived = derivedFrameEntriesOf(record).get(label)
+ buildShapeWithTextLabel(graph, shape, labelProps(overrides.get(label), derived, blobs))
+}
+
+/**
+ * A shape with text's record as FigJam writes it: its kind on it, its paint on its generated
+ * background and its text on its generated label, with the derived layout when the label is shaped.
+ */
+function writeShapeWithText(
+ context: SceneNodeToKiwiContext,
+ node: SceneNode,
+ nc: KiwiNodeChange
+): KiwiNodeChange {
+ const label = shapeWithTextLabel(context.graph, node)
+ if (!label) return nc
+ const record: KiwiNodeChange = pick(nc, SHAPE_WITH_TEXT_RECORD_FIELDS)
+ record.shapeWithTextType = node.shapeWithTextType
+ if (node.shapeUserHeight > 0) record.shapeUserHeight = node.shapeUserHeight
+ const slots = SHAPE_WITH_TEXT_SLOTS
+ const background: GeneratedEntry = {
+ guidPath: generatedSlotPath(slots.background),
+ ...pick(nc, SHAPE_WITH_TEXT_BACKGROUND_FIELDS),
+ cornerRadius: node.cornerRadius
+ }
+ const text = textSublayer(context, slots.label, label)
+ record.nodeGenerationData = {
+ overrides: [background, text.entry],
+ useFineGrainedSyncing: false,
+ diffOnlyRemovals: []
+ }
+ if (shaped(label, text.derived)) {
+ const backgroundPlacement: GeneratedEntry = {
+ guidPath: generatedSlotPath(slots.background),
+ ...placement({ ...node, x: 0, y: 0 })
+ }
+ record.derivedImmutableFrameData = {
+ overrides: [backgroundPlacement, text.derived],
+ version: 1
+ }
+ }
+ return record
+}
+
+/** A FigJam shape with text: its paint on a background slot, and its label as a text slot. */
+export const SHAPE_WITH_TEXT_CODEC: GeneratedFrameCodec = {
+ read: readShapeWithText,
+ write: writeShapeWithText
+}
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.ts
new file mode 100644
index 000000000..1f0fea178
--- /dev/null
+++ b/packages/fig/tests/node-change/generated/shape-with-text.test.ts
@@ -0,0 +1,177 @@
+import { describe, expect, test } from 'bun:test'
+
+import { expectDefined } from '#fig-tests/helpers/assert'
+import { normalizeFigFragment } from '#fig/document/fragment'
+import { generationOverridesOf } from '#fig/node-change/generated/records'
+import { nodeChangeToProps, sceneNodeToKiwi } from '#fig/node-change/index'
+
+import { materializeDocument } from '@open-pencil/fig'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { createShapeWithText, shapeWithTextLabel } from '@open-pencil/scene-graph'
+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import type { Color } from '@open-pencil/scene-graph/primitives'
+import { shapeWithTextLabelBox } from '@open-pencil/scene-graph/shape-with-text'
+
+const guid = (localID: number) => ({ sessionID: 0, localID })
+const slot = (localID: number) => ({ guids: [{ sessionID: 40_000_000, localID }] })
+const at = (x: number, y: number) => ({ m00: 1, m01: 0, m02: x, m10: 0, m11: 1, m12: y })
+const solid = (color: Color, opacity = 1) => ({
+ type: 'SOLID' as const,
+ color,
+ opacity,
+ visible: true
+})
+const green = { r: 0.804, g: 0.957, b: 0.827, a: 1 }
+const darkGreen = { r: 0.4, g: 0.835, b: 0.459, a: 1 }
+const black = { r: 0, g: 0, b: 0, a: 1 }
+
+/**
+ * A diamond from a FigJam board, trimmed to the fields read here: the shape's paint and corners
+ * sit on its generated background (slot 0), its text on its generated label (slot 1), and its
+ * own record carries neither.
+ */
+const decision: NodeChange = {
+ guid: guid(2),
+ type: 'SHAPE_WITH_TEXT',
+ name: 'Decision',
+ size: { x: 232.111, y: 152.572 },
+ transform: at(286.11, 177.54),
+ shapeWithTextType: 'DIAMOND',
+ shapeUserHeight: 152.572,
+ nodeGenerationData: {
+ overrides: [
+ {
+ guidPath: slot(0),
+ fillPaints: [solid(green)],
+ strokePaints: [solid(darkGreen)],
+ strokeWeight: 4,
+ strokeAlign: 'CENTER',
+ strokeCap: 'ROUND',
+ strokeJoin: 'MITER',
+ cornerRadius: 6
+ },
+ {
+ guidPath: slot(1),
+ fontSize: 24,
+ fontName: { family: 'Inter', style: 'Medium', postscript: 'Inter-Medium' },
+ lineHeight: { value: 1.5, units: 'RAW' },
+ textAlignHorizontal: 'CENTER',
+ textAlignVertical: 'TOP',
+ textData: { characters: 'Decision' },
+ fillPaints: [solid(black, 0.8)]
+ }
+ ]
+ },
+ derivedImmutableFrameData: {
+ overrides: [{ guidPath: slot(1), size: { x: 108.056, y: 36 }, transform: at(62.03, 58) }],
+ version: 1
+ }
+} as NodeChange
+
+function importShape(record: NodeChange): { graph: SceneGraph; shape: SceneNode } {
+ const graph = materializeDocument(normalizeFigFragment([record])).graph
+ const shape = graph.getChildren(graph.getPages()[0].id)[0]
+ return { graph, shape }
+}
+
+describe('shapes with text', () => {
+ test('import paints the shape from its background and builds its label', () => {
+ const { graph, shape } = importShape(decision)
+ expect(shape).toMatchObject({
+ type: 'SHAPE_WITH_TEXT',
+ shapeWithTextType: 'DIAMOND',
+ cornerRadius: 6,
+ layoutMode: 'VERTICAL',
+ primaryAxisAlign: 'CENTER'
+ })
+ expect(shape.fills[0]?.color).toEqual(green)
+ expect(shape.strokes[0]).toMatchObject({ color: darkGreen, weight: 4 })
+ const label = expectDefined(shapeWithTextLabel(graph, shape))
+ expect(label).toMatchObject({
+ text: 'Decision',
+ fontFamily: 'Inter',
+ fontWeight: 500,
+ fontSize: 24,
+ lineHeight: 36,
+ textAutoResize: 'HEIGHT'
+ })
+ expect(label.fills[0]).toMatchObject({ color: black })
+ expect(label.fills[0]?.opacity).toBeCloseTo(0.8)
+ })
+
+ test("the label box matches where FigJam laid this diamond's label out", () => {
+ const box = shapeWithTextLabelBox('DIAMOND', 232.111, 152.572)
+ expect(box.x).toBeCloseTo(62.03, 1)
+ expect(box.width).toBeCloseTo(108.06, 1)
+ })
+
+ test('export writes the paint on the background and the text on the label', () => {
+ const { graph, shape } = importShape(decision)
+ const [record] = sceneNodeToKiwi(shape, guid(1), 0, { value: 10 }, graph, [])
+ expect(record).toMatchObject({
+ type: 'SHAPE_WITH_TEXT',
+ shapeWithTextType: 'DIAMOND',
+ shapeUserHeight: 152.572
+ })
+ expect(record.fillPaints).toBeUndefined()
+ expect(record.strokePaints).toBeUndefined()
+ expect(record.stackMode).toBeUndefined()
+ expect(record.textData).toBeUndefined()
+ const overrides = generationOverridesOf(record)
+ const background = expectDefined(overrides.get(0))
+ expect(background.fillPaints?.[0]?.color).toEqual(green)
+ expect(background.strokePaints?.[0]?.color).toEqual(darkGreen)
+ expect(background).toMatchObject({ strokeWeight: 4, cornerRadius: 6 })
+ expect(overrides.get(1)?.textData?.characters).toBe('Decision')
+ })
+
+ test('a new shape round-trips through its record', () => {
+ const { graph } = importShape(decision)
+ const page = graph.getPages()[0]
+ const shape = createShapeWithText(
+ graph,
+ page.id,
+ { shapeWithTextType: 'ENG_DATABASE', width: 160, height: 120, fills: [solid(green)] },
+ { text: 'Orders' }
+ )
+ const [record] = sceneNodeToKiwi(shape, guid(1), 0, { value: 10 }, graph, [])
+ const { graph: reread, shape: copy } = importShape({ ...record, guid: guid(5) })
+ expect(copy).toMatchObject({ shapeWithTextType: 'ENG_DATABASE', cornerRadius: 6 })
+ expect(copy.fills[0]?.color).toEqual(green)
+ expect(shapeWithTextLabel(reread, copy)?.text).toBe('Orders')
+ })
+
+ test('a shape widened for a long word reopens with the width it was given', () => {
+ 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' }
+ )
+ const [record] = sceneNodeToKiwi(shape, guid(1), 0, { value: 10 }, graph, [])
+ const { shape: copy } = importShape({ ...record, guid: guid(6) })
+ expect([copy.width, copy.shapeUserWidth, copy.shapeUserHeight]).toEqual([180, 120, 100])
+ })
+
+ test('a given height that is not a finite positive number is unset', () => {
+ for (const shapeUserHeight of [Number.POSITIVE_INFINITY, Number.NaN, -4]) {
+ const props = nodeChangeToProps({ ...decision, shapeUserHeight }, [])
+ expect(props.shapeUserHeight).toBe(0)
+ }
+ })
+
+ test('a shape with no generated layers gets an empty label to type into', () => {
+ const { graph, shape } = importShape({ ...decision, nodeGenerationData: undefined })
+ expect(shapeWithTextLabel(graph, shape)?.text).toBe('')
+ })
+
+ test('fall back to a square for a kind FigJam does not have', () => {
+ const props = nodeChangeToProps(
+ { type: 'SHAPE_WITH_TEXT', size: { x: 10, y: 10 }, shapeWithTextType: 'CLOUD' } as NodeChange,
+ []
+ )
+ expect(props).toMatchObject({ shapeWithTextType: 'SQUARE' })
+ })
+})
diff --git a/packages/scene-graph/AGENTS.md b/packages/scene-graph/AGENTS.md
index fbbb1420f..1892e09b6 100644
--- a/packages/scene-graph/AGENTS.md
+++ b/packages/scene-graph/AGENTS.md
@@ -9,7 +9,7 @@ Framework-neutral document model. Owns node types, primitives, geometry, matrice
- Bounds accumulation goes through the helpers in `packages/scene-graph/src/geometry.ts` (`computeBounds`, `computeAbsoluteBounds`, `computeVisualBounds`); do not add another min/max loop.
- Reparenting preserves child world positions; groups preserve them too. Sort children geometrically before creating auto-layout. Consumers such as layer trees must react to reparenting rather than retaining stale child references.
- Use the copy helpers in `packages/scene-graph/src/copy.ts` for nested values (fills, strokes, effects); never hand-copy node properties.
-- A generated frame (Figma's immutable frames such as `STICKY` and `CONNECTOR`) owns real child layers built from its template in `packages/scene-graph/src/generated/` (a connector's in `packages/scene-graph/src/connectors/`); nothing adds, moves, or removes them (`slotScope` reports `locked`), and the layers panel lists the frame alone. Each type registers a `GeneratedFrameKind` in `GENERATED_FRAME_KINDS`, and the editor asks it (`layerRotates`, `layerResizes`, `generatedFrameText`) instead of testing node types (`packages/scene-graph/tests/generated/kind.test.ts`). A connector's ends name the layers they follow by ID; a transfer that leaves those layers behind keeps the IDs, and a reader that cannot find one leaves that end free where it was drawn (`packages/scene-graph/tests/connectors/endpoints.test.ts`).
+- A generated frame (Figma's immutable frames such as `STICKY`, `SHAPE_WITH_TEXT` and `CONNECTOR`) owns real child layers built from its template in `packages/scene-graph/src/generated/` (a connector's in `packages/scene-graph/src/connectors/`); nothing adds, moves, or removes them (`slotScope` reports `locked`), and the layers panel lists the frame alone. Each type registers a `GeneratedFrameKind` in `GENERATED_FRAME_KINDS`, and the editor asks it (`layerRotates`, `layerResizes`, `generatedFrameText`) instead of testing node types. A kind's `sized` hook says what a width or height set outside layout also sets, such as a shape's given size, and `updateNode` and `updateNodePreview` apply it to every such write (`packages/scene-graph/tests/generated/kind.test.ts`). A connector's ends name the layers they follow by ID; a transfer that leaves those layers behind keeps the IDs, and a reader that cannot find one leaves that end free where it was drawn (`packages/scene-graph/tests/connectors/endpoints.test.ts`).
- A connector's route derives from the layers its ends follow: `routeConnector` routes as FigJam does and `layoutConnector` lays the line, label plate, and label out to match. Core's editor routes again when those layers change, during previews too, and deletes connectors with the layers they attach to; loading a document keeps the routes it saved, and one saved without a route is routed by layout or when its page is shown, once its label is measured (`packages/scene-graph/tests/connectors/route.test.ts` against recorded Figma routes, `packages/core/tests/editor/connectors/routing.test.ts`).
- Instance children map to component children through `componentId`; runtime overrides use the structured `InstanceOverrideState` (`self` and `descendants` maps) in `packages/scene-graph/src/instance-overrides.ts`.
- A bound numeric field records its unit conversion in `variableBindingScales`; preserve it through clone, copy, and transfer so a binding keeps meaning in its new scope. Core reconciles bindings and layout together in `packages/core/src/layout/variables.ts`, which the editor and the Figma API both call rather than reimplementing.
diff --git a/packages/scene-graph/package.json b/packages/scene-graph/package.json
index b5098df23..1c721e3dc 100644
--- a/packages/scene-graph/package.json
+++ b/packages/scene-graph/package.json
@@ -173,6 +173,12 @@
"import": "./dist/polygon.js",
"default": "./dist/polygon.js"
},
+ "./shape-with-text": {
+ "types": "./dist/shape-with-text.d.ts",
+ "bun": "./src/shape-with-text/index.ts",
+ "import": "./dist/shape-with-text.js",
+ "default": "./dist/shape-with-text.js"
+ },
"./resize": {
"types": "./dist/resize.d.ts",
"bun": "./src/resize.ts",
diff --git a/packages/scene-graph/src/figjam/index.ts b/packages/scene-graph/src/figjam/index.ts
new file mode 100644
index 000000000..64b5009fd
--- /dev/null
+++ b/packages/scene-graph/src/figjam/index.ts
@@ -0,0 +1,2 @@
+export * from './palette'
+export * from './text'
diff --git a/packages/scene-graph/src/figjam/palette.ts b/packages/scene-graph/src/figjam/palette.ts
new file mode 100644
index 000000000..308b69c0e
--- /dev/null
+++ b/packages/scene-graph/src/figjam/palette.ts
@@ -0,0 +1,308 @@
+import { parseColor } from '../color'
+import { BLACK, WHITE } from '../constants'
+import type { Color } from '../primitives'
+import type { Fill, SceneNode, Stroke } from '../types'
+
+/**
+ * FigJam's board palette, in its menus' order, as its colour menu paints a shape with text: each
+ * fill pairs with a darker stroke, a light label on the darkest fills, and, made transparent, a
+ * lighter fill and its own stroke. Its line menu and connectors take the fills as line colours.
+ */
+const PALETTE = {
+ black: {
+ fill: '#1e1e1e',
+ stroke: '#242424',
+ lightLabel: true,
+ transparent: 0.5,
+ transparentStroke: '#929292'
+ },
+ darkGray: {
+ fill: '#757575',
+ stroke: '#424242',
+ lightLabel: true,
+ transparent: 0.5,
+ transparentStroke: '#a1a1a1'
+ },
+ red: {
+ fill: '#f24822',
+ stroke: '#bd2915',
+ lightLabel: true,
+ transparent: 0.5,
+ transparentStroke: '#c7968f'
+ },
+ orange: {
+ fill: '#ff9e42',
+ stroke: '#eb7500',
+ lightLabel: false,
+ transparent: 0.5,
+ transparentStroke: '#e9b780'
+ },
+ yellow: {
+ fill: '#ffc943',
+ stroke: '#e8a302',
+ lightLabel: false,
+ transparent: 0.5,
+ transparentStroke: '#f5d280'
+ },
+ green: {
+ fill: '#66d575',
+ stroke: '#3e9b4b',
+ lightLabel: false,
+ transparent: 0.5,
+ transparentStroke: '#80c79e'
+ },
+ teal: {
+ fill: '#5ad8cc',
+ stroke: '#369e94',
+ lightLabel: false,
+ transparent: 0.5,
+ transparentStroke: '#80c9c6'
+ },
+ blue: {
+ fill: '#3dadff',
+ stroke: '#007ad2',
+ lightLabel: true,
+ transparent: 0.7,
+ transparentStroke: '#4d99d3'
+ },
+ violet: {
+ fill: '#874fff',
+ stroke: '#5427b4',
+ lightLabel: true,
+ transparent: 0.5,
+ transparentStroke: '#a792d0'
+ },
+ pink: {
+ fill: '#f849c1',
+ stroke: '#b42487',
+ lightLabel: true,
+ transparent: 0.5,
+ transparentStroke: '#ce92bb'
+ },
+ white: {
+ fill: '#ffffff',
+ stroke: '#757575',
+ lightLabel: false,
+ transparent: 0.5,
+ transparentStroke: '#f1f1f1'
+ },
+ gray: {
+ fill: '#b3b3b3',
+ stroke: '#797979',
+ lightLabel: false,
+ transparent: 0.5,
+ transparentStroke: '#bcbcbc'
+ },
+ lightGray: {
+ fill: '#d9d9d9',
+ stroke: '#a5a5a5',
+ lightLabel: false,
+ transparent: 0.7,
+ transparentStroke: '#c0c0c0'
+ },
+ lightRed: {
+ fill: '#ffc7c2',
+ stroke: '#f24822',
+ lightLabel: false,
+ transparent: 0.7,
+ transparentStroke: '#ff9d8f'
+ },
+ lightOrange: {
+ fill: '#ffe0c2',
+ stroke: '#ff9e42',
+ lightLabel: false,
+ transparent: 0.7,
+ transparentStroke: '#f6c34d'
+ },
+ lightYellow: {
+ fill: '#ffecbd',
+ stroke: '#ffc943',
+ lightLabel: false,
+ transparent: 0.7,
+ transparentStroke: '#efd54d'
+ },
+ lightGreen: {
+ fill: '#cdf4d3',
+ stroke: '#66d575',
+ lightLabel: false,
+ transparent: 0.7,
+ transparentStroke: '#a8d7b4'
+ },
+ lightTeal: {
+ fill: '#c6faf6',
+ stroke: '#5ad8cc',
+ lightLabel: false,
+ transparent: 0.5,
+ transparentStroke: '#bcebeb'
+ },
+ lightBlue: {
+ fill: '#c2e5ff',
+ stroke: '#3dadff',
+ lightLabel: false,
+ transparent: 0.7,
+ transparentStroke: '#76ccff'
+ },
+ lightViolet: {
+ fill: '#dcccff',
+ stroke: '#874fff',
+ lightLabel: false,
+ transparent: 0.7,
+ transparentStroke: '#d5a3ff'
+ },
+ lightPink: {
+ fill: '#ffc2ec',
+ stroke: '#f849c1',
+ lightLabel: false,
+ transparent: 0.5,
+ transparentStroke: '#ffaaeb'
+ }
+} as const
+
+export type FigJamColorName = keyof typeof PALETTE
+
+export const FIGJAM_COLOR_NAMES = Object.keys(PALETTE) as FigJamColorName[]
+
+/** How a shape's colour fills it: solid, see-through, or not at all, as FigJam's menu sets it. */
+export type FigJamFillMode = 'fill' | 'transparent' | 'none'
+
+/** How a shape's outline is drawn, as FigJam's line menu sets it. */
+export type FigJamLineStyle = 'solid' | 'dashed' | 'none'
+
+/** The dash FigJam's line menu draws a shape's outline with. */
+export const FIGJAM_SHAPE_DASH = [16, 10] as const
+
+/** A palette colour as a colour. */
+export function figJamColor(name: FigJamColorName): Color {
+ return parseColor(PALETTE[name].fill)
+}
+
+function sameColor(a: Color | undefined, b: Color): boolean {
+ if (!a) return false
+ const close = (x: number, y: number) => Math.abs(x - y) < 1 / 512
+ return close(a.r, b.r) && close(a.g, b.g) && close(a.b, b.b)
+}
+
+/** The palette colour a paint is, if any. */
+export function figJamColorName(color: Color | undefined): FigJamColorName | null {
+ return FIGJAM_COLOR_NAMES.find((name) => sameColor(color, figJamColor(name))) ?? null
+}
+
+/** The fill mode a shape's first fill shows. */
+export function figJamFillMode(fill: Fill | undefined): FigJamFillMode {
+ if (!fill || !fill.visible || fill.opacity === 0) return 'none'
+ return fill.opacity < 1 ? 'transparent' : 'fill'
+}
+
+/** The outline FigJam pairs with a colour in a fill mode. */
+export function figJamPairedStroke(name: FigJamColorName, mode: FigJamFillMode): Color {
+ const entry = PALETTE[name]
+ return parseColor(mode === 'fill' ? entry.stroke : entry.transparentStroke)
+}
+
+/** The label paint FigJam pairs with a colour in a fill mode. */
+function pairedLabel(name: FigJamColorName, mode: FigJamFillMode): Fill {
+ const light = PALETTE[name].lightLabel && (mode === 'fill' || name === 'black') && mode !== 'none'
+ return light
+ ? { type: 'SOLID', color: { ...WHITE }, opacity: 1, visible: true }
+ : { type: 'SOLID', color: { ...BLACK }, opacity: 0.8, visible: true }
+}
+
+/** How opaque FigJam fills a colour in a fill mode. */
+function fillOpacity(name: FigJamColorName, mode: FigJamFillMode): number {
+ if (mode === 'transparent') return PALETTE[name].transparent
+ return mode === 'fill' ? 1 : 0
+}
+
+/** What a shape with text and its label become when painted `name` in `mode`. */
+export interface FigJamShapePaint {
+ shape: Partial<SceneNode>
+ label: Partial<SceneNode>
+}
+
+/**
+ * A shape painted `name` in `mode`, as FigJam's colour menu paints it. The stroke and label follow
+ * the colour only while they are still the ones FigJam paired with the current paint: a line or
+ * text colour set by hand stays.
+ */
+export function figJamShapePaint(
+ shape: Pick<SceneNode, 'fills' | 'strokes'>,
+ label: Pick<SceneNode, 'fills'> | null,
+ name: FigJamColorName,
+ mode: FigJamFillMode
+): FigJamShapePaint {
+ const fill = shape.fills.at(0)
+ const current = figJamColorName(fill?.color)
+ const currentMode = figJamFillMode(fill)
+ const opacity = fillOpacity(name, mode)
+ const result: FigJamShapePaint = {
+ shape: { fills: [{ type: 'SOLID', color: figJamColor(name), opacity, visible: true }] },
+ label: {}
+ }
+ const stroke = shape.strokes.at(0)
+ const strokeFollows =
+ !stroke || !current || sameColor(stroke.color, figJamPairedStroke(current, currentMode))
+ if (stroke && strokeFollows) {
+ result.shape.strokes = [
+ { ...stroke, color: figJamPairedStroke(name, mode) },
+ ...shape.strokes.slice(1)
+ ]
+ }
+ const labelFill = label?.fills.at(0)
+ const paired = current ? pairedLabel(current, currentMode) : null
+ const labelFollows =
+ !labelFill ||
+ !paired ||
+ (sameColor(labelFill.color, paired.color) &&
+ Math.abs(labelFill.opacity - paired.opacity) < 0.01)
+ if (label && labelFollows) result.label = { fills: [pairedLabel(name, mode)] }
+ return result
+}
+
+/**
+ * A shape's outline drawn `style`, as FigJam's line menu draws it; the weight stays. The dash is
+ * the layer's, as files keep it, and each stroke's, as it is drawn.
+ */
+export function figJamLineStyleFields(
+ shape: Pick<SceneNode, 'strokes'>,
+ style: FigJamLineStyle
+): Partial<SceneNode> {
+ const dashPattern = style === 'dashed' ? [...FIGJAM_SHAPE_DASH] : []
+ const strokes = shape.strokes.map((stroke): Stroke => ({
+ ...stroke,
+ opacity: style === 'none' ? 0 : 1,
+ dashPattern: [...dashPattern]
+ }))
+ return { strokes, dashPattern }
+}
+
+/** The line style a shape's outline shows. */
+export function figJamLineStyle(shape: Pick<SceneNode, 'strokes'>): FigJamLineStyle {
+ const stroke = shape.strokes.at(0)
+ if (!stroke || !stroke.visible || stroke.opacity === 0) return 'none'
+ return (stroke.dashPattern?.length ?? 0) > 0 ? 'dashed' : 'solid'
+}
+
+/**
+ * A shape's outline in palette colour `name`, as FigJam's line menu colours it; a hidden outline
+ * shows again, keeping its dash.
+ */
+export function figJamLineColorFields(
+ shape: Pick<SceneNode, 'strokes'>,
+ name: FigJamColorName
+): Partial<SceneNode> {
+ const color = figJamColor(name)
+ const strokes =
+ shape.strokes.length > 0
+ ? shape.strokes.map((stroke): Stroke => ({ ...stroke, color, opacity: 1 }))
+ : [
+ {
+ type: 'SOLID',
+ color,
+ opacity: 1,
+ visible: true,
+ weight: 4,
+ align: 'CENTER'
+ } satisfies Stroke
+ ]
+ return { strokes }
+}
diff --git a/packages/scene-graph/src/figjam/text.ts b/packages/scene-graph/src/figjam/text.ts
new file mode 100644
index 000000000..b3bbdf10e
--- /dev/null
+++ b/packages/scene-graph/src/figjam/text.ts
@@ -0,0 +1,72 @@
+import type { SceneNode } from '../types'
+
+/**
+ * FigJam's text sizes for sticky notes and shapes, each with the tracking it sets, as a fraction
+ * of the size; the line stays one and a half times the size.
+ */
+export const FIGJAM_TEXT_SIZES = {
+ small: { fontSize: 16, tracking: -0.011 },
+ medium: { fontSize: 24, tracking: -0.019 },
+ large: { fontSize: 40, tracking: -0.022 },
+ extraLarge: { fontSize: 64, tracking: -0.022 },
+ huge: { fontSize: 96, tracking: -0.023 }
+} as const
+
+export type FigJamTextSize = keyof typeof FIGJAM_TEXT_SIZES
+
+/**
+ * FigJam's typefaces, as its text menus name them, and the face each sets. Scribbled is Figma's
+ * own hand font, which FigJam sets without tracking.
+ */
+export const FIGJAM_TYPEFACES = {
+ simple: { fontFamily: 'Inter', fontWeight: 500, tracked: true },
+ bookish: { fontFamily: 'Merriweather', fontWeight: 400, tracked: true },
+ technical: { fontFamily: 'Roboto Mono', fontWeight: 500, tracked: true },
+ scribbled: { fontFamily: 'Figma Hand', fontWeight: 400, tracked: false }
+} as const
+
+export type FigJamTypeface = keyof typeof FIGJAM_TYPEFACES
+
+export function isFigJamTypeface(value: unknown): value is FigJamTypeface {
+ return typeof value === 'string' && Object.hasOwn(FIGJAM_TYPEFACES, value)
+}
+
+/** Text at a size preset in `typeface`. */
+export function figJamTextSizeFields(
+ size: FigJamTextSize,
+ typeface: FigJamTypeface = 'simple'
+): Partial<SceneNode> {
+ const { fontSize, tracking } = FIGJAM_TEXT_SIZES[size]
+ const tracked = FIGJAM_TYPEFACES[typeface].tracked
+ return { fontSize, lineHeight: fontSize * 1.5, letterSpacing: tracked ? fontSize * tracking : 0 }
+}
+
+/** The preset a text is closest to, as FigJam's size menu shows a rescaled one. */
+export function figJamTextSize(text: Pick<SceneNode, 'fontSize'>): FigJamTextSize {
+ const sizes = Object.entries(FIGJAM_TEXT_SIZES) as [FigJamTextSize, { fontSize: number }][]
+ return sizes.reduce((best, entry) =>
+ Math.abs(entry[1].fontSize - text.fontSize) < Math.abs(best[1].fontSize - text.fontSize)
+ ? entry
+ : best
+ )[0]
+}
+
+/** The typeface a text is set in, or null for a face FigJam's menu does not offer. */
+export function figJamTypeface(text: Pick<SceneNode, 'fontFamily'>): FigJamTypeface | null {
+ const entries = Object.entries(FIGJAM_TYPEFACES) as [FigJamTypeface, { fontFamily: string }][]
+ return entries.find(([, face]) => face.fontFamily === text.fontFamily)?.[0] ?? null
+}
+
+/** Text set in `typeface` at its current size, as FigJam's typeface menu sets it. */
+export function figJamTypefaceFields(
+ typeface: FigJamTypeface,
+ text: Pick<SceneNode, 'fontSize'>
+): Partial<SceneNode> {
+ const { fontFamily, fontWeight } = FIGJAM_TYPEFACES[typeface]
+ return {
+ fontFamily,
+ fontWeight,
+ italic: false,
+ ...figJamTextSizeFields(figJamTextSize(text), typeface)
+ }
+}
diff --git a/packages/scene-graph/src/generated/index.ts b/packages/scene-graph/src/generated/index.ts
index d0d9c732f..33c49026c 100644
--- a/packages/scene-graph/src/generated/index.ts
+++ b/packages/scene-graph/src/generated/index.ts
@@ -2,6 +2,7 @@ import { CONNECTOR_KIND } from '../connectors/sublayers'
import type { SceneGraph } from '../index'
import type { NodeType, SceneNode } from '../types'
import type { GeneratedFrameKind } from './kind'
+import { SHAPE_WITH_TEXT_KIND } from './shape-with-text'
import { STICKY_KIND } from './sticky'
/**
@@ -14,6 +15,7 @@ import { STICKY_KIND } from './sticky'
* the type.
*/
const GENERATED_FRAME_KINDS = {
+ SHAPE_WITH_TEXT: SHAPE_WITH_TEXT_KIND,
STICKY: STICKY_KIND,
CONNECTOR: CONNECTOR_KIND
} satisfies Partial<Record<NodeType, GeneratedFrameKind>>
@@ -46,6 +48,19 @@ export function generatedFrameText(graph: SceneGraph, node: SceneNode): SceneNod
return generatedFrameKind(node)?.text(graph, node)
}
+/**
+ * `changes` with what a width or height in them also sets on a generated frame
+ * (`GeneratedFrameKind.sized`); fields `changes` sets itself, such as an undo restoring them, win.
+ */
+export function withGeneratedFrameSize(
+ node: Pick<SceneNode, 'type'>,
+ 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 }
+}
+
/** Whether a layer turns: any layer but a generated frame that stays upright. */
export function layerRotates(node: Pick<SceneNode, 'type'>): boolean {
return generatedFrameKind(node)?.rotates ?? true
@@ -57,4 +72,5 @@ export function layerResizes(node: Pick<SceneNode, 'type'>): boolean {
}
export type { GeneratedFrameKind } from './kind'
+export * from './shape-with-text'
export * from './sticky'
diff --git a/packages/scene-graph/src/generated/kind.ts b/packages/scene-graph/src/generated/kind.ts
index a10a1c95e..a955632d0 100644
--- a/packages/scene-graph/src/generated/kind.ts
+++ b/packages/scene-graph/src/generated/kind.ts
@@ -16,4 +16,9 @@ export interface GeneratedFrameKind {
resizes: boolean
/** 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.
+ */
+ sized?(changes: Partial<SceneNode>): Partial<SceneNode>
}
diff --git a/packages/scene-graph/src/generated/shape-with-text.ts b/packages/scene-graph/src/generated/shape-with-text.ts
new file mode 100644
index 000000000..a75d2144f
--- /dev/null
+++ b/packages/scene-graph/src/generated/shape-with-text.ts
@@ -0,0 +1,132 @@
+import { BLACK } from '../constants'
+import { FIGJAM_TYPEFACES, figJamTextSizeFields } from '../figjam/text'
+import type { SceneGraph } from '../index'
+import { shapeWithTextLabelBox } from '../shape-with-text/fit'
+import type { ShapeWithTextType } from '../shape-with-text/kinds'
+import type { Fill, SceneNode } from '../types'
+import type { GeneratedFrameKind } from './kind'
+
+/** FigJam's plugin API makes a shape with text 208 px square. */
+export const SHAPE_WITH_TEXT_SIZE = 208
+/** FigJam's shape tool places a shape 176 px square where it is clicked. */
+export const SHAPE_WITH_TEXT_TOOL_SIZE = 176
+/** FigJam rounds every corner of a shape by 6 px. */
+export const SHAPE_WITH_TEXT_CORNER_RADIUS = 6
+
+const LABEL_FILL: Fill = { type: 'SOLID', color: { ...BLACK }, opacity: 0.8, visible: true }
+
+/** How the label sits in its shape: as wide as the label box, as tall as its text. */
+export const SHAPE_WITH_TEXT_LABEL_LAYOUT = {
+ textAutoResize: 'HEIGHT',
+ layoutAlignSelf: 'STRETCH'
+} as const satisfies Partial<SceneNode>
+
+/**
+ * The shape's own layout: a vertical auto layout that centres the label in the label box of its
+ * kind, which the padding leaves free. The padding follows the kind and size, so it is set again
+ * whenever either changes.
+ */
+export function shapeWithTextFrameFields(
+ kind: ShapeWithTextType,
+ width: number,
+ height: number
+): Partial<SceneNode> {
+ const box = shapeWithTextLabelBox(kind, width, height)
+ return {
+ layoutMode: 'VERTICAL',
+ primaryAxisAlign: 'CENTER',
+ counterAxisAlign: 'CENTER',
+ primaryAxisSizing: 'FIXED',
+ counterAxisSizing: 'FIXED',
+ itemSpacing: 0,
+ paddingTop: box.y,
+ paddingRight: Math.max(0, width - box.x - box.width),
+ paddingBottom: Math.max(0, height - box.y - box.height),
+ paddingLeft: box.x,
+ clipsContent: false
+ }
+}
+
+/** The label's text style as FigJam starts it: Inter Medium at its Small size, black at 80%. */
+export function shapeWithTextLabelFields(): Partial<SceneNode> {
+ return {
+ name: 'Text',
+ fontFamily: FIGJAM_TYPEFACES.simple.fontFamily,
+ fontWeight: FIGJAM_TYPEFACES.simple.fontWeight,
+ ...figJamTextSizeFields('small'),
+ textAlignHorizontal: 'CENTER',
+ textAlignVertical: 'TOP',
+ fills: [{ ...LABEL_FILL, color: { ...LABEL_FILL.color } }],
+ ...SHAPE_WITH_TEXT_LABEL_LAYOUT
+ }
+}
+
+/** A shape's label: its one text sublayer. */
+export function shapeWithTextLabel(graph: SceneGraph, shape: SceneNode): SceneNode | null {
+ if (shape.type !== 'SHAPE_WITH_TEXT') return null
+ const children = graph.getChildren(shape.id)
+ if (children.length !== 1) return null
+ const [label] = children
+ return label.type === 'TEXT' ? label : null
+}
+
+/**
+ * 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.
+ */
+export const SHAPE_WITH_TEXT_KIND: GeneratedFrameKind = {
+ complete: (graph, frame) => shapeWithTextLabel(graph, frame) !== null,
+ text: (graph, frame) => shapeWithTextLabel(graph, frame) ?? undefined,
+ rotates: true,
+ resizes: true,
+ namedByText: true,
+ sized: ({ width, height }) => ({
+ ...(width !== undefined && { shapeUserWidth: width }),
+ ...(height !== undefined && { shapeUserHeight: height })
+ })
+}
+
+/** Adds the label to a SHAPE_WITH_TEXT the caller created, styled as FigJam generates it. */
+export function buildShapeWithTextLabel(
+ graph: SceneGraph,
+ shape: SceneNode,
+ props: Partial<SceneNode> = {}
+): SceneNode {
+ const box = shapeWithTextLabelBox(shape.shapeWithTextType, shape.width, shape.height)
+ const fields = shapeWithTextLabelFields()
+ return graph.createNode('TEXT', shape.id, {
+ ...fields,
+ x: box.x,
+ y: box.y,
+ width: box.width,
+ height: fields.lineHeight ?? undefined,
+ text: '',
+ ...props
+ })
+}
+
+/** A new shape with text and its label; the caller lays it out to grow it to its text. */
+export function createShapeWithText(
+ graph: SceneGraph,
+ parentId: string,
+ props: Partial<SceneNode> = {},
+ label: Partial<SceneNode> = {}
+): SceneNode {
+ const kind = props.shapeWithTextType ?? 'SQUARE'
+ const width = props.width ?? SHAPE_WITH_TEXT_SIZE
+ const height = props.height ?? SHAPE_WITH_TEXT_SIZE
+ const shape = graph.createNode('SHAPE_WITH_TEXT', parentId, {
+ name: 'Shape with text',
+ cornerRadius: SHAPE_WITH_TEXT_CORNER_RADIUS,
+ ...props,
+ shapeWithTextType: kind,
+ width,
+ height,
+ shapeUserWidth: props.shapeUserWidth ?? width,
+ shapeUserHeight: props.shapeUserHeight ?? height,
+ ...shapeWithTextFrameFields(kind, width, height)
+ })
+ buildShapeWithTextLabel(graph, shape, label)
+ return shape
+}
diff --git a/packages/scene-graph/src/generated/sticky.ts b/packages/scene-graph/src/generated/sticky.ts
index 3227b6aee..ff6f1d8be 100644
--- a/packages/scene-graph/src/generated/sticky.ts
+++ b/packages/scene-graph/src/generated/sticky.ts
@@ -35,33 +35,6 @@ export const STICKY_COLORS = {
export const DEFAULT_STICKY_COLOR: Color = STICKY_COLORS.blue
-/** FigJam's body text sizes, each with the tracking it sets, as a fraction of the size. */
-export const STICKY_TEXT_SIZES = {
- small: { fontSize: 16, tracking: -0.011 },
- medium: { fontSize: 24, tracking: -0.019 },
- large: { fontSize: 40, tracking: -0.022 },
- extraLarge: { fontSize: 64, tracking: -0.022 },
- huge: { fontSize: 96, tracking: -0.023 }
-} as const
-
-export type StickyTextSize = keyof typeof STICKY_TEXT_SIZES
-
-/** A body's text at a size preset: its line stays one and a half times the size. */
-export function stickyBodySizeFields(size: StickyTextSize): Partial<SceneNode> {
- const { fontSize, tracking } = STICKY_TEXT_SIZES[size]
- return { fontSize, lineHeight: fontSize * 1.5, letterSpacing: fontSize * tracking }
-}
-
-/** The preset a body's text is closest to, as FigJam's size menu shows a rescaled note's. */
-export function stickyTextSize(body: Pick<SceneNode, 'fontSize'>): StickyTextSize {
- const sizes = Object.entries(STICKY_TEXT_SIZES) as [StickyTextSize, { fontSize: number }][]
- return sizes.reduce((best, entry) =>
- Math.abs(entry[1].fontSize - body.fontSize) < Math.abs(best[1].fontSize - body.fontSize)
- ? entry
- : best
- )[0]
-}
-
function solid(color: Color, opacity = 1): Fill {
return { type: 'SOLID', color: { ...color }, opacity, visible: true }
}
diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.ts
index d980b2749..eae57ca96 100644
--- a/packages/scene-graph/src/index.ts
+++ b/packages/scene-graph/src/index.ts
@@ -42,6 +42,7 @@ export * from './slots/content'
export * from './slots/authoring'
export * from './slots/limits'
export * from './connectors'
+export * from './figjam'
export * from './generated'
export * from './behaviours/kinds'
export * from './icons/schema'
@@ -108,6 +109,7 @@ export { CommittedGraphEventError } from './buffered-events'
import { BufferedSceneEmitter } from './buffered-events'
import { cloneNodeProps } from './copy'
import { bindNodeEvents } from './events'
+import { withGeneratedFrameSize } from './generated'
import * as HitTest from './hit-test'
export type { DropTargetOptions } from './hit-test'
import * as Instances from './instances'
@@ -680,6 +682,8 @@ export class SceneGraph {
this.updateNodePreview(id, { x, y })
}
updateNodePreview(id: string, changes: Partial<SceneNode>): void {
+ const node = this.nodes.get(id)
+ if (node) changes = this.sizedChanges(node, changes)
const appliedChanges = updateNodePreview(this, id, changes, (node, applied) => {
for (const observe of this.previewObservers) observe(node, applied)
})
@@ -695,7 +699,12 @@ export class SceneGraph {
const node = this.nodes.get(id)
if (!node) return
changes = stripUndefinedProps(styleDetachmentChanges(node, stripUndefinedProps(changes)))
- this.applyNodeChanges(node, changes)
+ this.applyNodeChanges(node, this.sizedChanges(node, changes))
+ }
+
+ /** A size set from outside layout, with what it also sets on a generated frame. */
+ private sizedChanges(node: SceneNode, changes: Partial<SceneNode>): Partial<SceneNode> {
+ return this.isApplyingLayout ? changes : withGeneratedFrameSize(node, changes)
}
/** Replay captured properties without dropping explicit undefined values or absent keys. */
diff --git a/packages/scene-graph/src/instances/fields.ts b/packages/scene-graph/src/instances/fields.ts
index 733c897c6..984c211aa 100644
--- a/packages/scene-graph/src/instances/fields.ts
+++ b/packages/scene-graph/src/instances/fields.ts
@@ -45,7 +45,10 @@ export const INSTANCE_FOLLOWED_FIELDS = [
'maskType',
'arcData',
'pointCount',
- 'starInnerRadius'
+ 'starInnerRadius',
+ 'shapeWithTextType',
+ 'shapeUserHeight',
+ 'shapeUserWidth'
] 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.ts
index b0ebc0dc9..00c9ff31d 100644
--- a/packages/scene-graph/src/node-defaults.ts
+++ b/packages/scene-graph/src/node-defaults.ts
@@ -182,6 +182,9 @@ export function createDefaultNode(
autoRename: true,
pointCount: 5,
starInnerRadius: 0.38,
+ shapeWithTextType: 'SQUARE',
+ shapeUserHeight: 0,
+ shapeUserWidth: 0,
componentId: null,
instanceOverrides: createInstanceOverrideState(),
componentPropertyDefinitions: [],
diff --git a/packages/scene-graph/src/plugin-data/fields.ts b/packages/scene-graph/src/plugin-data/fields.ts
index 8f9b6312b..f32801f56 100644
--- a/packages/scene-graph/src/plugin-data/fields.ts
+++ b/packages/scene-graph/src/plugin-data/fields.ts
@@ -230,6 +230,15 @@ 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/polygon.ts b/packages/scene-graph/src/polygon.ts
index 6a148b258..c4eabe979 100644
--- a/packages/scene-graph/src/polygon.ts
+++ b/packages/scene-graph/src/polygon.ts
@@ -16,6 +16,23 @@ export type PolygonOutlineCommand =
| { type: 'C'; x1: number; y1: number; x2: number; y2: number; x: number; y: number }
| { type: 'Z' }
+/** Outline commands as SVG path data, with each coordinate passed through `round`. */
+export function outlineSVGPath(
+ commands: readonly PolygonOutlineCommand[],
+ round: (value: number) => number = (value) => Math.round(value * 100) / 100
+): string {
+ return commands
+ .map((command) => {
+ if (command.type === 'Z') return 'Z'
+ if (command.type === 'C') {
+ const points = [command.x1, command.y1, command.x2, command.y2, command.x, command.y]
+ return `C${points.map(round).join(' ')}`
+ }
+ return `${command.type}${round(command.x)} ${round(command.y)}`
+ })
+ .join('')
+}
+
type PolygonNode = Pick<
SceneNode,
| 'type'
diff --git a/packages/scene-graph/src/shape-with-text/fit.ts b/packages/scene-graph/src/shape-with-text/fit.ts
new file mode 100644
index 000000000..5250d2950
--- /dev/null
+++ b/packages/scene-graph/src/shape-with-text/fit.ts
@@ -0,0 +1,175 @@
+import type { ShapeWithTextType } from './kinds'
+
+/** The height of a database's elliptical cap: FigJam keeps it 24 px tall at any size. */
+export function databaseCap(w: number, h: number): number {
+ return Math.min(24, h * 0.25, w * 0.25)
+}
+
+export interface LabelBox {
+ x: number
+ y: number
+ width: number
+ 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]
+}
+
+/** Padding FigJam leaves around a label, 16 px, less on small shapes. */
+function labelPadding(size: number): number {
+ return Math.min(16, size * 0.1)
+}
+
+/** 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
+ }
+}
+
+/** Where a shape's label sits inside its `width` × `height` box. */
+export function shapeWithTextLabelBox(
+ type: ShapeWithTextType,
+ 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)
+ return {
+ x,
+ y,
+ width: Math.max(0, width - x - right),
+ height: Math.max(0, height - y - bottom)
+ }
+}
+
+/** 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'
+])
+
+/** 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)
+ while (!fits(high)) {
+ low = high
+ high *= 2
+ if (high > LARGEST) return LARGEST
+ }
+ while (high - low > 0.5) {
+ const middle = (low + high) / 2
+ if (fits(middle)) high = middle
+ else 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/geometry.ts b/packages/scene-graph/src/shape-with-text/geometry.ts
new file mode 100644
index 000000000..6255301c0
--- /dev/null
+++ b/packages/scene-graph/src/shape-with-text/geometry.ts
@@ -0,0 +1,496 @@
+import type { PolygonOutlineCommand } from '../polygon'
+import { databaseCap } from './fit'
+import type { ShapeWithTextType } from './kinds'
+
+export interface ShapeWithTextGeometry {
+ /** The closed outline that is filled and stroked, and that connectors attach to. */
+ outline: PolygonOutlineCommand[]
+ /** Inner lines that are stroked only, such as a database's front rim. */
+ details: PolygonOutlineCommand[]
+}
+
+/** Bezier handle length for a quarter ellipse. */
+const KAPPA = 0.5522847498
+
+type Point = readonly [number, number]
+
+function polygon(points: Point[]): PolygonOutlineCommand[] {
+ const commands: PolygonOutlineCommand[] = points.map(([x, y], index) => ({
+ type: index === 0 ? 'M' : 'L',
+ x,
+ y
+ }))
+ commands.push({ type: 'Z' })
+ return commands
+}
+
+function line(from: Point, to: Point): PolygonOutlineCommand[] {
+ return [
+ { type: 'M', x: from[0], y: from[1] },
+ { type: 'L', x: to[0], y: to[1] }
+ ]
+}
+
+function curve(x1: number, y1: number, x2: number, y2: number, x: number, y: number) {
+ return { type: 'C', x1, y1, x2, y2, x, y } as const
+}
+
+function ellipse(x: number, y: number, w: number, h: number): PolygonOutlineCommand[] {
+ const rx = w / 2
+ const ry = h / 2
+ const cx = x + rx
+ const cy = y + ry
+ const kx = rx * KAPPA
+ const ky = ry * KAPPA
+ return [
+ { type: 'M', x: cx, y },
+ curve(cx + kx, y, x + w, cy - ky, x + w, cy),
+ curve(x + w, cy + ky, cx + kx, y + h, cx, y + h),
+ curve(cx - kx, y + h, x, cy + ky, x, cy),
+ curve(x, cy - ky, cx - kx, y, cx, y),
+ { type: 'Z' }
+ ]
+}
+
+function roundedRect(w: number, h: number, radius: number): PolygonOutlineCommand[] {
+ const r = Math.max(0, Math.min(radius, w / 2, h / 2))
+ const k = r * (1 - KAPPA)
+ return [
+ { type: 'M', x: r, y: 0 },
+ { type: 'L', x: w - r, y: 0 },
+ curve(w - k, 0, w, k, w, r),
+ { type: 'L', x: w, y: h - r },
+ curve(w, h - k, w - k, h, w - r, h),
+ { type: 'L', x: r, y: h },
+ curve(k, h, 0, h - k, 0, h - r),
+ { type: 'L', x: 0, y: r },
+ curve(0, k, k, 0, r, 0),
+ { type: 'Z' }
+ ]
+}
+
+/** A page with a wavy bottom edge, the flowchart "document" symbol. */
+function documentPage(x: number, y: number, w: number, h: number): PolygonOutlineCommand[] {
+ const wave = h * 0.1
+ const base = y + h - wave
+ return [
+ { type: 'M', x, y },
+ { type: 'L', x: x + w, y },
+ { type: 'L', x: x + w, y: base },
+ curve(x + w * 0.8, base - wave * 1.2, x + w * 0.7, base - wave * 1.2, x + w * 0.5, base),
+ curve(x + w * 0.3, base + wave, x + w * 0.2, base + wave, x, base),
+ { type: 'Z' }
+ ]
+}
+
+function star(w: number, h: number): Point[] {
+ const points: Point[] = []
+ for (let i = 0; i < 10; i++) {
+ const angle = -Math.PI / 2 + (i * Math.PI) / 5
+ const radius = i % 2 === 0 ? 1 : 0.382
+ points.push([
+ w / 2 + (Math.cos(angle) * radius * w) / 2,
+ h / 2 + (Math.sin(angle) * radius * h) / 2 + h * 0.05
+ ])
+ }
+ return points
+}
+
+/** A point on the ellipse filling the box, at `angle` radians clockwise from the right. */
+function onEllipse(w: number, h: number, angle: number): Point {
+ return [w / 2 + (Math.cos(angle) * w) / 2, h / 2 + (Math.sin(angle) * h) / 2]
+}
+
+/** A plain box with stroke-only inner lines. */
+function boxWithLines(
+ w: number,
+ h: number,
+ details: PolygonOutlineCommand[]
+): ShapeWithTextGeometry {
+ return {
+ outline: polygon([
+ [0, 0],
+ [w, 0],
+ [w, h],
+ [0, h]
+ ]),
+ details
+ }
+}
+
+/** A rounded box with a tail below its left side; the tail joins the bottom edge. */
+function speechBubble(w: number, h: number): PolygonOutlineCommand[] {
+ const body = h * 0.8
+ const box = roundedRect(w, body, Math.min(w, body) * 0.2)
+ // The fifth command draws the bottom edge leftwards; the tail goes just before it.
+ const tail: PolygonOutlineCommand[] = [
+ { type: 'L', x: w * 0.38, y: body },
+ { type: 'L', x: w * 0.18, y: h },
+ { type: 'L', x: w * 0.22, y: body }
+ ]
+ return [...box.slice(0, 5), ...tail, ...box.slice(5)]
+}
+
+const plain = (outline: PolygonOutlineCommand[]): ShapeWithTextGeometry => ({
+ outline,
+ details: []
+})
+
+type Builder = (w: number, h: number, min: number) => ShapeWithTextGeometry
+
+/** How far a parallelogram's sides lean: FigJam leans them with the height, not the width. */
+export function parallelogramSlant(w: number, h: number): number {
+ return Math.min(h * 0.43, w * 0.45)
+}
+
+/** Each kind's outline and inner lines for a `w` × `h` box, `min` being its shorter side. */
+const BUILDERS: Record<ShapeWithTextType, Builder> = {
+ SQUARE: (w, h) =>
+ plain(
+ polygon([
+ [0, 0],
+ [w, 0],
+ [w, h],
+ [0, h]
+ ])
+ ),
+ ELLIPSE: (w, h) => plain(ellipse(0, 0, w, h)),
+ DIAMOND: (w, h) =>
+ plain(
+ polygon([
+ [w / 2, 0],
+ [w, h / 2],
+ [w / 2, h],
+ [0, h / 2]
+ ])
+ ),
+ TRIANGLE_UP: (w, h) =>
+ plain(
+ polygon([
+ [w / 2, 0],
+ [w, h],
+ [0, h]
+ ])
+ ),
+ TRIANGLE_DOWN: (w, h) =>
+ plain(
+ polygon([
+ [0, 0],
+ [w, 0],
+ [w / 2, h]
+ ])
+ ),
+ // FigJam rounds the ends to 0.4 of the shorter side, as its saved outlines show.
+ ROUNDED_RECTANGLE: (w, h, min) => plain(roundedRect(w, h, min * 0.4)),
+ PARALLELOGRAM_RIGHT: (w, h) => {
+ const s = parallelogramSlant(w, h)
+ return plain(
+ polygon([
+ [s, 0],
+ [w, 0],
+ [w - s, h],
+ [0, h]
+ ])
+ )
+ },
+ PARALLELOGRAM_LEFT: (w, h) => {
+ const s = parallelogramSlant(w, h)
+ return plain(
+ polygon([
+ [0, 0],
+ [w - s, 0],
+ [w, h],
+ [s, h]
+ ])
+ )
+ },
+ ENG_DATABASE: (w, h) => {
+ const ry = databaseCap(w, h)
+ const kx = (w / 2) * KAPPA
+ const ky = ry * KAPPA
+ return {
+ outline: [
+ { type: 'M', x: 0, y: ry },
+ curve(0, ry - ky, w / 2 - kx, 0, w / 2, 0),
+ curve(w / 2 + kx, 0, w, ry - ky, w, ry),
+ { type: 'L', x: w, y: h - ry },
+ curve(w, h - ry + ky, w / 2 + kx, h, w / 2, h),
+ curve(w / 2 - kx, h, 0, h - ry + ky, 0, h - ry),
+ { type: 'Z' }
+ ],
+ details: [
+ { type: 'M', x: 0, y: ry },
+ curve(0, ry + ky, w / 2 - kx, ry * 2, w / 2, ry * 2),
+ curve(w / 2 + kx, ry * 2, w, ry + ky, w, ry)
+ ]
+ }
+ },
+ ENG_QUEUE: (w, h) => {
+ const rx = Math.min(w * 0.15, h * 0.25)
+ const kx = rx * KAPPA
+ const ky = (h / 2) * KAPPA
+ return {
+ outline: [
+ { type: 'M', x: rx, y: 0 },
+ { type: 'L', x: w - rx, y: 0 },
+ curve(w - rx + kx, 0, w, h / 2 - ky, w, h / 2),
+ curve(w, h / 2 + ky, w - rx + kx, h, w - rx, h),
+ { type: 'L', x: rx, y: h },
+ curve(rx - kx, h, 0, h / 2 + ky, 0, h / 2),
+ curve(0, h / 2 - ky, rx - kx, 0, rx, 0),
+ { type: 'Z' }
+ ],
+ details: [
+ { type: 'M', x: w - rx, y: 0 },
+ curve(w - rx - kx, 0, w - rx * 2, h / 2 - ky, w - rx * 2, h / 2),
+ curve(w - rx * 2, h / 2 + ky, w - rx - kx, h, w - rx, h)
+ ]
+ }
+ },
+ ENG_FILE: (w, h, min) => {
+ const f = min * 0.25
+ return {
+ outline: polygon([
+ [0, 0],
+ [w - f, 0],
+ [w, f],
+ [w, h],
+ [0, h]
+ ]),
+ details: [...line([w - f, 0], [w - f, f]), { type: 'L', x: w, y: f }]
+ }
+ },
+ ENG_FOLDER: (w, h) => {
+ const tab = Math.min(h * 0.18, w * 0.2)
+ return plain(
+ polygon([
+ [0, 0],
+ [w * 0.4, 0],
+ [w * 0.4 + tab, tab],
+ [w, tab],
+ [w, h],
+ [0, h]
+ ])
+ )
+ },
+ TRAPEZOID: (w, h) => {
+ const s = Math.min(w * 0.2, h)
+ return plain(
+ polygon([
+ [s, 0],
+ [w - s, 0],
+ [w, h],
+ [0, h]
+ ])
+ )
+ },
+ PREDEFINED_PROCESS: (w, h) => {
+ const e = Math.min(w * 0.1, h * 0.5)
+ return boxWithLines(w, h, [...line([e, 0], [e, h]), ...line([w - e, 0], [w - e, h])])
+ },
+ SHIELD: (w, h) =>
+ plain([
+ { type: 'M', x: 0, y: 0 },
+ { type: 'L', x: w, y: 0 },
+ { type: 'L', x: w, y: h * 0.45 },
+ curve(w, h * 0.75, w * 0.75, h * 0.9, w / 2, h),
+ curve(w * 0.25, h * 0.9, 0, h * 0.75, 0, h * 0.45),
+ { type: 'Z' }
+ ]),
+ DOCUMENT_SINGLE: (w, h) => plain(documentPage(0, 0, w, h)),
+ DOCUMENT_MULTIPLE: (w, h, min) => {
+ const o = min * 0.06
+ return {
+ outline: documentPage(0, o * 2, w - o * 2, h - o * 2),
+ details: [
+ ...line([o, o * 2], [o, o]),
+ { type: 'L', x: w - o, y: o },
+ { type: 'L', x: w - o, y: h - o * 2 },
+ ...line([o * 2, o], [o * 2, 0]),
+ { type: 'L', x: w, y: 0 },
+ { type: 'L', x: w, y: h - o * 3 }
+ ]
+ }
+ },
+ MANUAL_INPUT: (w, h) =>
+ plain(
+ polygon([
+ [0, h * 0.25],
+ [w, 0],
+ [w, h],
+ [0, h]
+ ])
+ ),
+ HEXAGON: (w, h) => {
+ const s = Math.min(w * 0.25, h * 0.5)
+ return plain(
+ polygon([
+ [s, 0],
+ [w - s, 0],
+ [w, h / 2],
+ [w - s, h],
+ [s, h],
+ [0, h / 2]
+ ])
+ )
+ },
+ CHEVRON: (w, h) => {
+ const p = Math.min(w * 0.25, h * 0.5)
+ return plain(
+ polygon([
+ [0, 0],
+ [w - p, 0],
+ [w, h / 2],
+ [w - p, h],
+ [0, h],
+ [p, h / 2]
+ ])
+ )
+ },
+ PENTAGON: (w, h) =>
+ plain(
+ polygon([
+ [w / 2, 0],
+ [w, h * 0.38],
+ [w * 0.81, h],
+ [w * 0.19, h],
+ [0, h * 0.38]
+ ])
+ ),
+ OCTAGON: (w, h, min) => {
+ const c = min * 0.29
+ return plain(
+ polygon([
+ [c, 0],
+ [w - c, 0],
+ [w, c],
+ [w, h - c],
+ [w - c, h],
+ [c, h],
+ [0, h - c],
+ [0, c]
+ ])
+ )
+ },
+ STAR: (w, h) => plain(polygon(star(w, h))),
+ PLUS: (w, h) => {
+ const a = w / 3
+ const b = h / 3
+ return plain(
+ polygon([
+ [a, 0],
+ [a * 2, 0],
+ [a * 2, b],
+ [w, b],
+ [w, b * 2],
+ [a * 2, b * 2],
+ [a * 2, h],
+ [a, h],
+ [a, b * 2],
+ [0, b * 2],
+ [0, b],
+ [a, b]
+ ])
+ )
+ },
+ ARROW_RIGHT: (w, h) => {
+ const head = Math.min(w * 0.4, h * 0.5)
+ return plain(
+ polygon([
+ [0, h * 0.25],
+ [w - head, h * 0.25],
+ [w - head, 0],
+ [w, h / 2],
+ [w - head, h],
+ [w - head, h * 0.75],
+ [0, h * 0.75]
+ ])
+ )
+ },
+ ARROW_LEFT: (w, h) => {
+ const head = Math.min(w * 0.4, h * 0.5)
+ return plain(
+ polygon([
+ [w, h * 0.25],
+ [head, h * 0.25],
+ [head, 0],
+ [0, h / 2],
+ [head, h],
+ [head, h * 0.75],
+ [w, h * 0.75]
+ ])
+ )
+ },
+ SUMMING_JUNCTION: (w, h) => {
+ const q = Math.PI / 4
+ return {
+ outline: ellipse(0, 0, w, h),
+ details: [
+ ...line(onEllipse(w, h, -q), onEllipse(w, h, Math.PI - q)),
+ ...line(onEllipse(w, h, q), onEllipse(w, h, Math.PI + q))
+ ]
+ }
+ },
+ OR: (w, h) => ({
+ outline: ellipse(0, 0, w, h),
+ details: [...line([w / 2, 0], [w / 2, h]), ...line([0, h / 2], [w, h / 2])]
+ }),
+ SPEECH_BUBBLE: (w, h) => plain(speechBubble(w, h)),
+ INTERNAL_STORAGE: (w, h, min) => {
+ const e = min * 0.15
+ return boxWithLines(w, h, [...line([e, 0], [e, h]), ...line([0, e], [w, e])])
+ }
+}
+
+/**
+ * The outline with each straight corner rounded to `radius` (FigJam rounds them all to its corner
+ * radius), shortened where an edge is too short for it. Outlines with curves keep their shape.
+ */
+function roundCorners(commands: PolygonOutlineCommand[], radius: number): PolygonOutlineCommand[] {
+ if (radius <= 0 || commands.some((command) => command.type === 'C')) return commands
+ const points: Point[] = []
+ for (const command of commands) if (command.type !== 'Z') points.push([command.x, command.y])
+ if (points.length < 3) return commands
+ const rounded: PolygonOutlineCommand[] = []
+ points.forEach((vertex, index) => {
+ const before = points[(index + points.length - 1) % points.length]
+ const after = points[(index + 1) % points.length]
+ const toward = (to: Point): Point => {
+ const length = Math.hypot(to[0] - vertex[0], to[1] - vertex[1])
+ const t = length > 0 ? Math.min(radius, length / 2) / length : 0
+ return [vertex[0] + (to[0] - vertex[0]) * t, vertex[1] + (to[1] - vertex[1]) * t]
+ }
+ const [inX, inY] = toward(before)
+ const [outX, outY] = toward(after)
+ rounded.push({ type: index === 0 ? 'M' : 'L', x: inX, y: inY })
+ rounded.push(
+ curve(
+ inX + (vertex[0] - inX) * KAPPA,
+ inY + (vertex[1] - inY) * KAPPA,
+ outX + (vertex[0] - outX) * KAPPA,
+ outY + (vertex[1] - outY) * KAPPA,
+ outX,
+ outY
+ )
+ )
+ })
+ rounded.push({ type: 'Z' })
+ return rounded
+}
+
+/**
+ * The outline and inner lines of a shape of `type` filling a `width` × `height` box. Outlines
+ * made only of straight segments have their corners rounded to `cornerRadius`; outlines with
+ * curves, such as a rounded rectangle, keep their own shape.
+ */
+export function shapeWithTextGeometry(
+ type: ShapeWithTextType,
+ width: number,
+ height: number,
+ cornerRadius = 0
+): ShapeWithTextGeometry {
+ const w = Math.max(0, width)
+ const h = Math.max(0, height)
+ const geometry = BUILDERS[type](w, h, Math.min(w, h))
+ return { ...geometry, outline: roundCorners(geometry.outline, cornerRadius) }
+}
diff --git a/packages/scene-graph/src/shape-with-text/index.ts b/packages/scene-graph/src/shape-with-text/index.ts
new file mode 100644
index 000000000..b3761c332
--- /dev/null
+++ b/packages/scene-graph/src/shape-with-text/index.ts
@@ -0,0 +1,10 @@
+export * from './kinds'
+export * from './geometry'
+export {
+ databaseCap,
+ fitShapeWithText,
+ shapeWithTextLabelBox,
+ type LabelBox,
+ type LabelMeasure,
+ type ShapeWithTextFit
+} from './fit'
diff --git a/packages/scene-graph/src/shape-with-text/kinds.ts b/packages/scene-graph/src/shape-with-text/kinds.ts
new file mode 100644
index 000000000..303546039
--- /dev/null
+++ b/packages/scene-graph/src/shape-with-text/kinds.ts
@@ -0,0 +1,86 @@
+/**
+ * FigJam's shape-with-text kinds, as Figma names them in `.fig` files and in its plugin API
+ * (`ShapeWithTextNode.shapeType`). Each kind is drawn from its size here, so rendering, hit
+ * testing, export and connectors share one outline.
+ */
+export const SHAPE_WITH_TEXT_TYPES = [
+ 'SQUARE',
+ 'ELLIPSE',
+ 'DIAMOND',
+ 'TRIANGLE_UP',
+ 'TRIANGLE_DOWN',
+ 'ROUNDED_RECTANGLE',
+ 'PARALLELOGRAM_RIGHT',
+ 'PARALLELOGRAM_LEFT',
+ 'ENG_DATABASE',
+ 'ENG_QUEUE',
+ 'ENG_FILE',
+ 'ENG_FOLDER',
+ 'TRAPEZOID',
+ 'PREDEFINED_PROCESS',
+ 'SHIELD',
+ 'DOCUMENT_SINGLE',
+ 'DOCUMENT_MULTIPLE',
+ 'MANUAL_INPUT',
+ 'HEXAGON',
+ 'CHEVRON',
+ 'PENTAGON',
+ 'OCTAGON',
+ 'STAR',
+ 'PLUS',
+ 'ARROW_LEFT',
+ 'ARROW_RIGHT',
+ 'SUMMING_JUNCTION',
+ 'OR',
+ 'SPEECH_BUBBLE',
+ 'INTERNAL_STORAGE'
+] as const
+
+export type ShapeWithTextType = (typeof SHAPE_WITH_TEXT_TYPES)[number]
+
+const KNOWN = new Set<string>(SHAPE_WITH_TEXT_TYPES)
+
+export function isShapeWithTextType(value: unknown): value is ShapeWithTextType {
+ return typeof value === 'string' && KNOWN.has(value)
+}
+
+/**
+ * The kinds as FigJam's Shapes panel offers them, in its order: Basic, then Flowchart. Together
+ * they are every kind.
+ */
+export const SHAPE_WITH_TEXT_GROUPS = {
+ basic: [
+ 'SQUARE',
+ 'ELLIPSE',
+ 'DIAMOND',
+ 'TRIANGLE_UP',
+ 'TRIANGLE_DOWN',
+ 'ROUNDED_RECTANGLE',
+ 'PENTAGON',
+ 'OCTAGON',
+ 'PLUS',
+ 'ARROW_LEFT',
+ 'ARROW_RIGHT',
+ 'CHEVRON',
+ 'STAR',
+ 'SPEECH_BUBBLE'
+ ],
+ flowchart: [
+ 'PARALLELOGRAM_RIGHT',
+ 'PARALLELOGRAM_LEFT',
+ 'ENG_DATABASE',
+ 'ENG_QUEUE',
+ 'ENG_FILE',
+ 'ENG_FOLDER',
+ 'DOCUMENT_SINGLE',
+ 'DOCUMENT_MULTIPLE',
+ 'PREDEFINED_PROCESS',
+ 'SHIELD',
+ 'TRAPEZOID',
+ 'MANUAL_INPUT',
+ 'HEXAGON',
+ 'INTERNAL_STORAGE',
+ 'OR',
+ 'SUMMING_JUNCTION'
+ ]
+} as const satisfies Record<string, readonly ShapeWithTextType[]>
diff --git a/packages/scene-graph/src/types.ts b/packages/scene-graph/src/types.ts
index 6b8952642..4bdc1328e 100644
--- a/packages/scene-graph/src/types.ts
+++ b/packages/scene-graph/src/types.ts
@@ -4,6 +4,7 @@ import type { ExportFormatId } from './export-format'
import type { CanvasGuide } from './guides'
import type { InstanceOverrideState } from './instance-overrides'
import type { Color, Matrix, Rect, Vector } from './primitives'
+import type { ShapeWithTextType } from './shape-with-text/kinds'
export interface SceneGraphEvents {
'node:created': (node: SceneNode) => void
@@ -736,6 +737,12 @@ export interface SceneNode {
pointCount: number
starInnerRadius: number
+ /** The FigJam kind a SHAPE_WITH_TEXT draws; its label is the node's own text. */
+ 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
componentId: string | null
instanceOverrides: InstanceOverrideState
diff --git a/packages/scene-graph/tests/figjam/palette.test.ts b/packages/scene-graph/tests/figjam/palette.test.ts
new file mode 100644
index 000000000..999f22328
--- /dev/null
+++ b/packages/scene-graph/tests/figjam/palette.test.ts
@@ -0,0 +1,91 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ createShapeWithText,
+ figJamColor,
+ figJamColorName,
+ figJamLineColorFields,
+ figJamLineStyle,
+ figJamLineStyleFields,
+ figJamShapePaint,
+ SceneGraph,
+ shapeWithTextLabel
+} from '@open-pencil/scene-graph'
+import { colorToHex } from '@open-pencil/scene-graph/color'
+
+/** A shape as FigJam's tool places it: white, with its #757575 outline and a dark label. */
+function placedShape() {
+ const graph = new SceneGraph()
+ const shape = createShapeWithText(graph, graph.getPages()[0].id, {
+ fills: [{ type: 'SOLID', color: figJamColor('white'), opacity: 1, visible: true }],
+ strokes: [
+ {
+ type: 'SOLID',
+ color: { r: 0x75 / 255, g: 0x75 / 255, b: 0x75 / 255, a: 1 },
+ opacity: 1,
+ visible: true,
+ weight: 4,
+ align: 'CENTER'
+ }
+ ]
+ })
+ const label = shapeWithTextLabel(graph, shape)
+ if (!label) throw new Error('shape has no label')
+ return { graph, shape, label }
+}
+
+function hexes(paints: { color: { r: number; g: number; b: number } }[] | undefined) {
+ return paints?.map((paint) => colorToHex({ ...paint.color, a: 1 }).toLowerCase())
+}
+
+// Values measured in FigJam's colour and line menus.
+describe("FigJam's shape colours", () => {
+ test('a fill brings its paired outline and, on the darkest colours, a light label', () => {
+ const { shape, label } = placedShape()
+ const red = figJamShapePaint(shape, label, 'red', 'fill')
+ expect(hexes(red.shape.fills)).toEqual(['#f24822'])
+ expect(hexes(red.shape.strokes)).toEqual(['#bd2915'])
+ expect(red.label.fills?.[0]).toMatchObject({ color: { r: 1, g: 1, b: 1 }, opacity: 1 })
+
+ const yellow = figJamShapePaint(shape, label, 'lightYellow', 'fill')
+ expect(hexes(yellow.shape.strokes)).toEqual(['#ffc943'])
+ expect(yellow.label.fills?.[0]).toMatchObject({ color: { r: 0, g: 0, b: 0 }, opacity: 0.8 })
+ })
+
+ test('transparent and no fill keep the colour at their opacity, with their own outline', () => {
+ const { shape, label } = placedShape()
+ const blue = figJamShapePaint(shape, label, 'blue', 'transparent')
+ expect(blue.shape.fills?.[0]?.opacity).toBe(0.7)
+ expect(hexes(blue.shape.strokes)).toEqual(['#4d99d3'])
+ const none = figJamShapePaint(shape, label, 'yellow', 'none')
+ expect(none.shape.fills?.[0]).toMatchObject({ opacity: 0 })
+ expect(hexes(none.shape.strokes)).toEqual(['#f5d280'])
+ })
+
+ test('an outline coloured by hand stays when the fill changes', () => {
+ const { shape, label } = placedShape()
+ const blueLine = { ...shape, ...figJamLineColorFields(shape, 'blue') }
+ const repainted = figJamShapePaint(blueLine, label, 'red', 'fill')
+ expect(repainted.shape.strokes).toBeUndefined()
+ })
+
+ test('a palette colour is found back from a paint', () => {
+ expect(figJamColorName(figJamColor('lightViolet'))).toBe('lightViolet')
+ expect(figJamColorName({ r: 0.1, g: 0.2, b: 0.3, a: 1 })).toBeNull()
+ })
+
+ test('the line menu dashes or hides the outline, keeping its weight', () => {
+ const { shape } = placedShape()
+ const dashed = figJamLineStyleFields(shape, 'dashed')
+ expect(dashed.dashPattern).toEqual([16, 10])
+ // Strokes are drawn with their own dash, and files keep the layer's.
+ expect(dashed.strokes?.[0]?.dashPattern).toEqual([16, 10])
+ expect(figJamLineStyle({ ...shape, ...dashed })).toBe('dashed')
+ const hidden = figJamLineStyleFields(shape, 'none')
+ expect(hidden.strokes?.[0]).toMatchObject({ opacity: 0, weight: 4 })
+ expect(figJamLineStyle({ ...shape, ...hidden })).toBe('none')
+ // Colouring a hidden outline shows it again.
+ const shown = figJamLineColorFields({ ...shape, ...hidden }, 'red')
+ expect(shown.strokes?.[0]?.opacity).toBe(1)
+ })
+})
diff --git a/packages/scene-graph/tests/figjam/text.test.ts b/packages/scene-graph/tests/figjam/text.test.ts
new file mode 100644
index 000000000..7536a1392
--- /dev/null
+++ b/packages/scene-graph/tests/figjam/text.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ figJamTextSizeFields,
+ figJamTypeface,
+ figJamTypefaceFields
+} from '@open-pencil/scene-graph'
+
+// Values measured in FigJam's text menus.
+describe("FigJam's text", () => {
+ test('each size sets its tracking, and the line stays one and a half times the size', () => {
+ expect(figJamTextSizeFields('huge')).toEqual({
+ fontSize: 96,
+ lineHeight: 144,
+ letterSpacing: 96 * -0.023
+ })
+ })
+
+ test('typefaces set their face, and Scribbled sets no tracking', () => {
+ expect(figJamTypefaceFields('bookish', { fontSize: 24 })).toMatchObject({
+ fontFamily: 'Merriweather',
+ fontWeight: 400,
+ fontSize: 24,
+ letterSpacing: 24 * -0.019
+ })
+ expect(figJamTypefaceFields('scribbled', { fontSize: 16 })).toMatchObject({
+ fontFamily: 'Figma Hand',
+ letterSpacing: 0
+ })
+ expect(figJamTypeface({ fontFamily: 'Roboto Mono' })).toBe('technical')
+ expect(figJamTypeface({ fontFamily: 'Comic Sans' })).toBeNull()
+ })
+})
diff --git a/packages/scene-graph/tests/generated/kind.test.ts b/packages/scene-graph/tests/generated/kind.test.ts
index c414d1bfb..03ecf67a5 100644
--- a/packages/scene-graph/tests/generated/kind.test.ts
+++ b/packages/scene-graph/tests/generated/kind.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, test } from 'bun:test'
import {
+ createShapeWithText,
createSticky,
generatedFrameKind,
generatedFrameText,
@@ -20,6 +21,20 @@ 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", () => {
+ 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 })
+ 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)
+ })
+
test('any other layer has no kind and turns and resizes freely', () => {
const rectangle = { type: 'RECTANGLE' as const }
expect(generatedFrameKind(rectangle)).toBeUndefined()
diff --git a/packages/scene-graph/tests/shape-with-text/fit.test.ts b/packages/scene-graph/tests/shape-with-text/fit.test.ts
new file mode 100644
index 000000000..33a4d0597
--- /dev/null
+++ b/packages/scene-graph/tests/shape-with-text/fit.test.ts
@@ -0,0 +1,84 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ SHAPE_WITH_TEXT_TYPES,
+ fitShapeWithText,
+ shapeWithTextLabelBox
+} from '@open-pencil/scene-graph/shape-with-text'
+
+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)
+ expect(box.width).toBeGreaterThan(0)
+ expect(box.height).toBeGreaterThan(0)
+ expect(box.x + box.width).toBeLessThanOrEqual(200)
+ expect(box.y + box.height).toBeLessThanOrEqual(100)
+ })
+ }
+
+ test('a small shape keeps every label box inside it', () => {
+ for (const type of SHAPE_WITH_TEXT_TYPES) {
+ const box = shapeWithTextLabelBox(type, 20, 20)
+ expect(box.x + box.width).toBeLessThanOrEqual(20)
+ expect(box.y + box.height).toBeLessThanOrEqual(20)
+ }
+ })
+
+ test('a zero-sized shape gives an empty label box instead of a negative one', () => {
+ 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('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 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)
+ })
+
+ 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('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 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
+ )
+ }
+ })
+})
diff --git a/packages/scene-graph/tests/shape-with-text/geometry.test.ts b/packages/scene-graph/tests/shape-with-text/geometry.test.ts
new file mode 100644
index 000000000..342700218
--- /dev/null
+++ b/packages/scene-graph/tests/shape-with-text/geometry.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, test } from 'bun:test'
+
+import type { Vector } from '@open-pencil/scene-graph'
+import type { PolygonOutlineCommand } from '@open-pencil/scene-graph/polygon'
+import {
+ SHAPE_WITH_TEXT_TYPES,
+ shapeWithTextGeometry
+} from '@open-pencil/scene-graph/shape-with-text'
+
+function points(commands: PolygonOutlineCommand[]): Vector[] {
+ return commands.flatMap((command) => {
+ if (command.type === 'Z') return []
+ if (command.type === 'C') {
+ return [
+ { x: command.x1, y: command.y1 },
+ { x: command.x2, y: command.y2 },
+ { x: command.x, y: command.y }
+ ]
+ }
+ return [{ x: command.x, y: command.y }]
+ })
+}
+
+describe('shape-with-text geometry', () => {
+ for (const type of SHAPE_WITH_TEXT_TYPES) {
+ test(`${type} is one closed outline inside its box`, () => {
+ const { outline, details } = shapeWithTextGeometry(type, 200, 100)
+ expect(outline[0]?.type).toBe('M')
+ expect(outline.at(-1)?.type).toBe('Z')
+ expect(outline.filter((command) => command.type === 'M')).toHaveLength(1)
+ for (const point of [...points(outline), ...points(details)]) {
+ expect(point.x).toBeGreaterThanOrEqual(-1e-9)
+ expect(point.x).toBeLessThanOrEqual(200 + 1e-9)
+ expect(point.y).toBeGreaterThanOrEqual(-1e-9)
+ expect(point.y).toBeLessThanOrEqual(100 + 1e-9)
+ }
+ })
+ }
+
+ test('a diamond reaches the middle of each side and nothing else', () => {
+ const { outline } = shapeWithTextGeometry('DIAMOND', 200, 100)
+ expect(points(outline)).toEqual([
+ { x: 100, y: 0 },
+ { x: 200, y: 50 },
+ { x: 100, y: 100 },
+ { x: 0, y: 50 }
+ ])
+ })
+
+ test('a database draws its front rim as a stroke-only detail', () => {
+ const { details } = shapeWithTextGeometry('ENG_DATABASE', 120, 160)
+ expect(details[0]).toEqual({ type: 'M', x: 0, y: 24 })
+ expect(details.at(-1)).toMatchObject({ type: 'C', x: 120, y: 24 })
+ })
+})
diff --git a/packages/scene-graph/tests/shape-with-text/kinds.test.ts b/packages/scene-graph/tests/shape-with-text/kinds.test.ts
new file mode 100644
index 000000000..126272169
--- /dev/null
+++ b/packages/scene-graph/tests/shape-with-text/kinds.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ SHAPE_WITH_TEXT_GROUPS,
+ SHAPE_WITH_TEXT_TYPES,
+ isShapeWithTextType
+} from '@open-pencil/scene-graph/shape-with-text'
+
+describe('shape-with-text kinds', () => {
+ test('FigJam has 30 kinds, named as in .fig files and the plugin API', () => {
+ expect(SHAPE_WITH_TEXT_TYPES).toHaveLength(30)
+ expect(isShapeWithTextType('ENG_DATABASE')).toBe(true)
+ expect(isShapeWithTextType('CLOUD')).toBe(false)
+ expect(isShapeWithTextType(undefined)).toBe(false)
+ })
+
+ test("FigJam's Basic and Flowchart groups offer every kind once", () => {
+ const grouped = [...SHAPE_WITH_TEXT_GROUPS.basic, ...SHAPE_WITH_TEXT_GROUPS.flowchart]
+ expect(grouped.toSorted()).toEqual([...SHAPE_WITH_TEXT_TYPES].toSorted())
+ })
+})
diff --git a/packages/scene-graph/tsdown.config.ts b/packages/scene-graph/tsdown.config.ts
index 7cc150073..271b05f89 100644
--- a/packages/scene-graph/tsdown.config.ts
+++ b/packages/scene-graph/tsdown.config.ts
@@ -26,6 +26,7 @@ export default defineConfig({
geometry: './src/geometry.ts',
gradient: './src/gradient.ts',
polygon: './src/polygon.ts',
+ 'shape-with-text': './src/shape-with-text/index.ts',
guides: './src/guides.ts',
layout: './src/layout/index.ts',
text: './src/text/index.ts',
diff --git a/packages/vue/src/controls/shape-with-text/use.ts b/packages/vue/src/controls/shape-with-text/use.ts
new file mode 100644
index 000000000..99b2f4899
--- /dev/null
+++ b/packages/vue/src/controls/shape-with-text/use.ts
@@ -0,0 +1,128 @@
+import { computed } from 'vue'
+
+import {
+ figJamColorName,
+ figJamFillMode,
+ figJamLineStyle,
+ figJamTextSize,
+ figJamTypeface,
+ shapeWithTextLabel
+} from '@open-pencil/scene-graph'
+import type {
+ FigJamColorName,
+ FigJamFillMode,
+ FigJamLineStyle,
+ FigJamTextSize,
+ FigJamTypeface,
+ SceneNode
+} from '@open-pencil/scene-graph'
+import type { ShapeWithTextType } from '@open-pencil/scene-graph/shape-with-text'
+
+import { useEditor } from '#vue/editor/context'
+import { useSelectionState } from '#vue/editor/selection-state/use'
+import { useSceneComputed } from '#vue/internal/scene-computed/use'
+
+/**
+ * Headless state and actions for shapes with text: the kind the shape tool places, and the kind,
+ * colours, outline and text of the selected shapes, as FigJam's selection toolbar sets them. A
+ * selection of several shapes reads its first shape and changes them all.
+ */
+export function useShapeWithText() {
+ const editor = useEditor()
+ const { selectedIds } = useSelectionState()
+
+ const shapes = useSceneComputed(() => {
+ const nodes = [...selectedIds.value].map((id) => editor.graph.getNode(id))
+ return nodes.length > 0 && nodes.every((node) => node?.type === 'SHAPE_WITH_TEXT')
+ ? nodes.filter((node): node is SceneNode => node !== undefined)
+ : []
+ })
+ const ids = computed(() => shapes.value.map((shape) => shape.id))
+ // Read from the scene each time it changes: a shape is edited in place, so a computed holding
+ // the node itself would never see its colour or text change.
+ const style = useSceneComputed(() => {
+ const first = shapes.value.at(0)
+ if (!first) return null
+ const label = shapeWithTextLabel(editor.graph, first)
+ return {
+ kind: first.shapeWithTextType,
+ color: figJamColorName(first.fills.at(0)?.color),
+ fillMode: figJamFillMode(first.fills.at(0)),
+ lineStyle: figJamLineStyle(first),
+ lineColor: figJamColorName(first.strokes.at(0)?.color),
+ textSize: label ? figJamTextSize(label) : null,
+ typeface: label ? figJamTypeface(label) : null,
+ labelFont: label?.fontFamily ?? null
+ }
+ })
+
+ const active = computed(() => shapes.value.length > 0)
+ const kind = computed<ShapeWithTextType | null>(() => style.value?.kind ?? null)
+ const color = computed<FigJamColorName | null>(() => style.value?.color ?? null)
+ const fillMode = computed<FigJamFillMode | null>(() => style.value?.fillMode ?? null)
+ const lineStyle = computed<FigJamLineStyle | null>(() => style.value?.lineStyle ?? null)
+ const lineColor = computed<FigJamColorName | null>(() => style.value?.lineColor ?? null)
+ const textSize = computed<FigJamTextSize | null>(() => style.value?.textSize ?? null)
+ const typeface = computed<FigJamTypeface | null>(() => style.value?.typeface ?? null)
+ /** The label's font family, which names a face FigJam's typeface menu does not offer. */
+ const labelFont = computed(() => style.value?.labelFont ?? null)
+ const toolKind = computed(() => editor.state.shapeWithTextKind)
+ const toolActive = computed(() => editor.state.activeTool === 'SHAPE_WITH_TEXT')
+
+ /** Turns the selected shapes into `value`, keeping their size. */
+ function setKind(value: ShapeWithTextType) {
+ editor.changeShapesWithTextKind(ids.value, value)
+ }
+
+ function setColor(value: FigJamColorName) {
+ editor.setShapesWithTextColor(ids.value, value)
+ }
+
+ function setFillMode(value: FigJamFillMode) {
+ editor.setShapesWithTextFillMode(ids.value, value)
+ }
+
+ function setLineStyle(value: FigJamLineStyle) {
+ editor.setShapesWithTextLineStyle(ids.value, value)
+ }
+
+ function setLineColor(value: FigJamColorName) {
+ editor.setShapesWithTextLineColor(ids.value, value)
+ }
+
+ function setTextSize(value: FigJamTextSize) {
+ editor.setShapesWithTextTextSize(ids.value, value)
+ }
+
+ function setTypeface(value: FigJamTypeface) {
+ return editor.setGeneratedTextTypeface(ids.value, value)
+ }
+
+ /** Picks `value` for the shape tool and arms it, as FigJam's Shapes panel does. */
+ function drawKind(value: ShapeWithTextType) {
+ editor.setShapeWithTextKind(value)
+ editor.setTool('SHAPE_WITH_TEXT')
+ }
+
+ return {
+ active,
+ kind,
+ color,
+ fillMode,
+ lineStyle,
+ lineColor,
+ textSize,
+ typeface,
+ labelFont,
+ toolKind,
+ toolActive,
+ setKind,
+ setColor,
+ setFillMode,
+ setLineStyle,
+ setLineColor,
+ setTextSize,
+ setTypeface,
+ drawKind
+ }
+}
diff --git a/packages/vue/src/controls/sticky/use.ts b/packages/vue/src/controls/sticky/use.ts
index efa82c7c8..e1382b039 100644
--- a/packages/vue/src/controls/sticky/use.ts
+++ b/packages/vue/src/controls/sticky/use.ts
@@ -1,7 +1,7 @@
import { computed } from 'vue'
-import { stickySublayers, stickyTextSize } from '@open-pencil/scene-graph'
-import type { SceneNode, StickyTextSize } from '@open-pencil/scene-graph'
+import { figJamTextSize, figJamTypeface, stickySublayers } from '@open-pencil/scene-graph'
+import type { FigJamTextSize, FigJamTypeface, SceneNode } from '@open-pencil/scene-graph'
import type { Color } from '@open-pencil/scene-graph/primitives'
import { useEditor } from '#vue/editor/context'
@@ -30,16 +30,21 @@ export function useStickyNote() {
})
const color = computed<Color | null>(() => stickies.value.at(0)?.fills.at(0)?.color ?? null)
- const textSize = computed<StickyTextSize | null>(() =>
- sublayers.value ? stickyTextSize(sublayers.value.body) : null
+ const textSize = computed<FigJamTextSize | null>(() =>
+ sublayers.value ? figJamTextSize(sublayers.value.body) : null
)
const authorVisible = computed(() => sublayers.value?.author.visible ?? false)
+ /** The body's font family, which names a face FigJam's typeface menu does not offer. */
+ const bodyFont = computed(() => sublayers.value?.body.fontFamily ?? null)
+ const typeface = computed<FigJamTypeface | null>(() =>
+ sublayers.value ? figJamTypeface(sublayers.value.body) : null
+ )
function setColor(value: Color) {
editor.setStickyColor(ids.value, value)
}
- function setTextSize(value: StickyTextSize) {
+ function setTextSize(value: FigJamTextSize) {
editor.setStickyTextSize(ids.value, value)
}
@@ -47,5 +52,20 @@ export function useStickyNote() {
editor.setStickyAuthorVisible(ids.value, value)
}
- return { active, color, textSize, authorVisible, setColor, setTextSize, setAuthorVisible }
+ function setTypeface(value: FigJamTypeface) {
+ return editor.setGeneratedTextTypeface(ids.value, value)
+ }
+
+ return {
+ active,
+ color,
+ textSize,
+ authorVisible,
+ typeface,
+ bodyFont,
+ setColor,
+ setTextSize,
+ setAuthorVisible,
+ setTypeface
+ }
}
diff --git a/packages/vue/src/editor/tool-cursor/index.ts b/packages/vue/src/editor/tool-cursor/index.ts
index 40cf874bd..f6d086637 100644
--- a/packages/vue/src/editor/tool-cursor/index.ts
+++ b/packages/vue/src/editor/tool-cursor/index.ts
@@ -32,6 +32,7 @@ const TOOL_CURSORS: Record<Tool, string> = {
STAR: 'crosshair',
TEXT: 'text',
STICKY: 'crosshair',
+ SHAPE_WITH_TEXT: 'crosshair',
CONNECTOR: 'crosshair',
PEN: PEN_CURSOR,
PENCIL: PENCIL_CURSOR,
diff --git a/packages/vue/src/i18n/index.ts b/packages/vue/src/i18n/index.ts
index afafb1bfd..65edd88dd 100644
--- a/packages/vue/src/i18n/index.ts
+++ b/packages/vue/src/i18n/index.ts
@@ -24,6 +24,8 @@ export {
useSettingsMessages,
useStatusMessages,
useStorageMessages,
+ useFigJamMessages,
+ useShapeMessages,
useToolMessages,
useUpdateMessages,
useCloudMessages,
diff --git a/packages/vue/src/i18n/locales/de/figjam.json b/packages/vue/src/i18n/locales/de/figjam.json
new file mode 100644
index 000000000..acdef87d2
--- /dev/null
+++ b/packages/vue/src/i18n/locales/de/figjam.json
@@ -0,0 +1,34 @@
+{
+ "textSize": "Textgröße",
+ "textSmall": "Klein",
+ "textMedium": "Mittel",
+ "textLarge": "Groß",
+ "textExtraLarge": "Sehr groß",
+ "textHuge": "Riesig",
+ "typeface": "Schriftart",
+ "typefaceSimple": "Schlicht",
+ "typefaceBookish": "Buchartig",
+ "typefaceTechnical": "Technisch",
+ "typefaceScribbled": "Gekritzelt",
+ "colorBlack": "Schwarz",
+ "colorDarkGray": "Dunkelgrau",
+ "colorRed": "Rot",
+ "colorOrange": "Orange",
+ "colorYellow": "Gelb",
+ "colorGreen": "Grün",
+ "colorTeal": "Türkis",
+ "colorBlue": "Blau",
+ "colorViolet": "Violett",
+ "colorPink": "Rosa",
+ "colorWhite": "Weiß",
+ "colorGray": "Grau",
+ "colorLightGray": "Hellgrau",
+ "colorLightRed": "Hellrot",
+ "colorLightOrange": "Hellorange",
+ "colorLightYellow": "Hellgelb",
+ "colorLightGreen": "Hellgrün",
+ "colorLightTeal": "Helltürkis",
+ "colorLightBlue": "Hellblau",
+ "colorLightViolet": "Hellviolett",
+ "colorLightPink": "Hellrosa"
+}
diff --git a/packages/vue/src/i18n/locales/de/index.ts b/packages/vue/src/i18n/locales/de/index.ts
index dbb09c01a..bc7336c30 100644
--- a/packages/vue/src/i18n/locales/de/index.ts
+++ b/packages/vue/src/i18n/locales/de/index.ts
@@ -13,6 +13,7 @@ import credentials from './credentials.json'
import designCheck from './design-check.json'
import diagnostics from './diagnostics.json'
import editor from './editor.json'
+import figjam from './figjam.json'
import files from './files.json'
import fonts from './fonts.json'
import media from './media.json'
@@ -23,6 +24,7 @@ import recovery from './recovery.json'
import rename from './rename.json'
import rendering from './rendering.json'
import settings from './settings.json'
+import shapes from './shapes.json'
import statuses from './statuses.json'
import storage from './storage.json'
import tools from './tools.json'
@@ -44,6 +46,7 @@ export default {
designCheck,
diagnostics,
editor,
+ figjam,
files,
fonts,
media,
@@ -54,6 +57,7 @@ export default {
rendering,
rename,
settings,
+ shapes,
statuses,
storage,
tools,
diff --git a/packages/vue/src/i18n/locales/de/panels.json b/packages/vue/src/i18n/locales/de/panels.json
index 2127d19e1..248589cbc 100644
--- a/packages/vue/src/i18n/locales/de/panels.json
+++ b/packages/vue/src/i18n/locales/de/panels.json
@@ -469,12 +469,6 @@
"stickyColorBlue": "Blau",
"stickyColorViolet": "Violett",
"stickyColorPink": "Rosa",
- "stickyTextSize": "Textgröße",
- "stickyTextSmall": "Klein",
- "stickyTextMedium": "Mittel",
- "stickyTextLarge": "Groß",
- "stickyTextExtraLarge": "Sehr groß",
- "stickyTextHuge": "Riesig",
"stickyShowAuthor": "Autor anzeigen",
"blendModePassThrough": "Durchreichen",
"blendModeNormal": "Normal",
diff --git a/packages/vue/src/i18n/locales/de/shapes.json b/packages/vue/src/i18n/locales/de/shapes.json
new file mode 100644
index 000000000..ce0bada2b
--- /dev/null
+++ b/packages/vue/src/i18n/locales/de/shapes.json
@@ -0,0 +1,43 @@
+{
+ "search": "Formen suchen",
+ "noResults": "Keine Formen gefunden",
+ "basic": "Grundformen",
+ "flowchart": "Flussdiagramm",
+ "kind": "Form",
+ "fill": "Füllung",
+ "fillTransparent": "Transparent",
+ "fillNone": "Keine",
+ "line": "Linie",
+ "lineDashed": "Gestrichelt",
+ "lineNone": "Keine",
+ "square": "Quadrat",
+ "ellipse": "Ellipse",
+ "diamond": "Raute",
+ "triangleUp": "Dreieck",
+ "triangleDown": "Nach unten zeigendes Dreieck",
+ "roundedRectangle": "Abgerundetes Rechteck",
+ "pentagon": "Fünfeck",
+ "octagon": "Achteck",
+ "plus": "Plus",
+ "arrowLeft": "Pfeil nach links",
+ "arrowRight": "Pfeil nach rechts",
+ "chevron": "Chevron",
+ "star": "Stern",
+ "speechBubble": "Sprechblase",
+ "parallelogramRight": "Nach rechts geneigtes Parallelogramm",
+ "parallelogramLeft": "Nach links geneigtes Parallelogramm",
+ "engDatabase": "Zylinder",
+ "engQueue": "Liegender Zylinder",
+ "engFile": "Datei",
+ "engFolder": "Ordner",
+ "documentSingle": "Dokument",
+ "documentMultiple": "Mehrere Dokumente",
+ "predefinedProcess": "Vordefinierter Prozess",
+ "shield": "Schild",
+ "trapezoid": "Trapez",
+ "manualInput": "Manuelle Eingabe",
+ "hexagon": "Sechseck",
+ "internalStorage": "Interner Speicher",
+ "or": "Oder",
+ "summingJunction": "Summierungspunkt"
+}
diff --git a/packages/vue/src/i18n/locales/de/tools.json b/packages/vue/src/i18n/locales/de/tools.json
index a53b520c3..e6c358915 100644
--- a/packages/vue/src/i18n/locales/de/tools.json
+++ b/packages/vue/src/i18n/locales/de/tools.json
@@ -11,6 +11,7 @@
"pencil": "Bleistift",
"text": "Text",
"sticky": "Haftnotiz",
+ "shape": "Form",
"connector": "Verbinder",
"hand": "Hand",
"comment": "Kommentar"
diff --git a/packages/vue/src/i18n/locales/es/figjam.json b/packages/vue/src/i18n/locales/es/figjam.json
new file mode 100644
index 000000000..4d9f91ae2
--- /dev/null
+++ b/packages/vue/src/i18n/locales/es/figjam.json
@@ -0,0 +1,34 @@
+{
+ "textSize": "Tamaño del texto",
+ "textSmall": "Pequeño",
+ "textMedium": "Mediano",
+ "textLarge": "Grande",
+ "textExtraLarge": "Muy grande",
+ "textHuge": "Enorme",
+ "typeface": "Tipo de letra",
+ "typefaceSimple": "Sencilla",
+ "typefaceBookish": "Libresca",
+ "typefaceTechnical": "Técnica",
+ "typefaceScribbled": "Garabateada",
+ "colorBlack": "Negro",
+ "colorDarkGray": "Gris oscuro",
+ "colorRed": "Rojo",
+ "colorOrange": "Naranja",
+ "colorYellow": "Amarillo",
+ "colorGreen": "Verde",
+ "colorTeal": "Verde azulado",
+ "colorBlue": "Azul",
+ "colorViolet": "Violeta",
+ "colorPink": "Rosa",
+ "colorWhite": "Blanco",
+ "colorGray": "Gris",
+ "colorLightGray": "Gris claro",
+ "colorLightRed": "Rojo claro",
+ "colorLightOrange": "Naranja claro",
+ "colorLightYellow": "Amarillo claro",
+ "colorLightGreen": "Verde claro",
+ "colorLightTeal": "Verde azulado claro",
+ "colorLightBlue": "Azul claro",
+ "colorLightViolet": "Violeta claro",
+ "colorLightPink": "Rosa claro"
+}
diff --git a/packages/vue/src/i18n/locales/es/index.ts b/packages/vue/src/i18n/locales/es/index.ts
index dbb09c01a..bc7336c30 100644
--- a/packages/vue/src/i18n/locales/es/index.ts
+++ b/packages/vue/src/i18n/locales/es/index.ts
@@ -13,6 +13,7 @@ import credentials from './credentials.json'
import designCheck from './design-check.json'
import diagnostics from './diagnostics.json'
import editor from './editor.json'
+import figjam from './figjam.json'
import files from './files.json'
import fonts from './fonts.json'
import media from './media.json'
@@ -23,6 +24,7 @@ import recovery from './recovery.json'
import rename from './rename.json'
import rendering from './rendering.json'
import settings from './settings.json'
+import shapes from './shapes.json'
import statuses from './statuses.json'
import storage from './storage.json'
import tools from './tools.json'
@@ -44,6 +46,7 @@ export default {
designCheck,
diagnostics,
editor,
+ figjam,
files,
fonts,
media,
@@ -54,6 +57,7 @@ export default {
rendering,
rename,
settings,
+ shapes,
statuses,
storage,
tools,
diff --git a/packages/vue/src/i18n/locales/es/panels.json b/packages/vue/src/i18n/locales/es/panels.json
index d6bb3a9f9..c3c1dc0bb 100644
--- a/packages/vue/src/i18n/locales/es/panels.json
+++ b/packages/vue/src/i18n/locales/es/panels.json
@@ -469,12 +469,6 @@
"stickyColorBlue": "Azul",
"stickyColorViolet": "Violeta",
"stickyColorPink": "Rosa",
- "stickyTextSize": "Tamaño del texto",
- "stickyTextSmall": "Pequeño",
- "stickyTextMedium": "Mediano",
- "stickyTextLarge": "Grande",
- "stickyTextExtraLarge": "Muy grande",
- "stickyTextHuge": "Enorme",
"stickyShowAuthor": "Mostrar autor",
"blendModePassThrough": "Pasar a través",
"blendModeNormal": "Normal",
diff --git a/packages/vue/src/i18n/locales/es/shapes.json b/packages/vue/src/i18n/locales/es/shapes.json
new file mode 100644
index 000000000..8ad409c59
--- /dev/null
+++ b/packages/vue/src/i18n/locales/es/shapes.json
@@ -0,0 +1,43 @@
+{
+ "search": "Buscar formas",
+ "noResults": "No se encontraron formas",
+ "basic": "Básicas",
+ "flowchart": "Diagrama de flujo",
+ "kind": "Forma",
+ "fill": "Relleno",
+ "fillTransparent": "Transparente",
+ "fillNone": "Ninguno",
+ "line": "Línea",
+ "lineDashed": "Discontinua",
+ "lineNone": "Ninguna",
+ "square": "Cuadrado",
+ "ellipse": "Elipse",
+ "diamond": "Rombo",
+ "triangleUp": "Triángulo",
+ "triangleDown": "Triángulo hacia abajo",
+ "roundedRectangle": "Rectángulo redondeado",
+ "pentagon": "Pentágono",
+ "octagon": "Octágono",
+ "plus": "Más",
+ "arrowLeft": "Flecha izquierda",
+ "arrowRight": "Flecha derecha",
+ "chevron": "Cheurón",
+ "star": "Estrella",
+ "speechBubble": "Bocadillo",
+ "parallelogramRight": "Paralelogramo inclinado a la derecha",
+ "parallelogramLeft": "Paralelogramo inclinado a la izquierda",
+ "engDatabase": "Cilindro",
+ "engQueue": "Cilindro horizontal",
+ "engFile": "Archivo",
+ "engFolder": "Carpeta",
+ "documentSingle": "Documento",
+ "documentMultiple": "Varios documentos",
+ "predefinedProcess": "Proceso predefinido",
+ "shield": "Escudo",
+ "trapezoid": "Trapecio",
+ "manualInput": "Entrada manual",
+ "hexagon": "Hexágono",
+ "internalStorage": "Almacenamiento interno",
+ "or": "O",
+ "summingJunction": "Unión de suma"
+}
diff --git a/packages/vue/src/i18n/locales/es/tools.json b/packages/vue/src/i18n/locales/es/tools.json
index ee78bafdd..1e938a304 100644
--- a/packages/vue/src/i18n/locales/es/tools.json
+++ b/packages/vue/src/i18n/locales/es/tools.json
@@ -11,6 +11,7 @@
"pencil": "Lápiz",
"text": "Texto",
"sticky": "Nota adhesiva",
+ "shape": "Forma",
"connector": "Conector",
"hand": "Mano",
"comment": "Comentario"
diff --git a/packages/vue/src/i18n/locales/fr/figjam.json b/packages/vue/src/i18n/locales/fr/figjam.json
new file mode 100644
index 000000000..83c18c00c
--- /dev/null
+++ b/packages/vue/src/i18n/locales/fr/figjam.json
@@ -0,0 +1,34 @@
+{
+ "textSize": "Taille du texte",
+ "textSmall": "Petite",
+ "textMedium": "Moyenne",
+ "textLarge": "Grande",
+ "textExtraLarge": "Très grande",
+ "textHuge": "Énorme",
+ "typeface": "Police",
+ "typefaceSimple": "Simple",
+ "typefaceBookish": "Livresque",
+ "typefaceTechnical": "Technique",
+ "typefaceScribbled": "Griffonnée",
+ "colorBlack": "Noir",
+ "colorDarkGray": "Gris foncé",
+ "colorRed": "Rouge",
+ "colorOrange": "Orange",
+ "colorYellow": "Jaune",
+ "colorGreen": "Vert",
+ "colorTeal": "Sarcelle",
+ "colorBlue": "Bleu",
+ "colorViolet": "Violet",
+ "colorPink": "Rose",
+ "colorWhite": "Blanc",
+ "colorGray": "Gris",
+ "colorLightGray": "Gris clair",
+ "colorLightRed": "Rouge clair",
+ "colorLightOrange": "Orange clair",
+ "colorLightYellow": "Jaune clair",
+ "colorLightGreen": "Vert clair",
+ "colorLightTeal": "Sarcelle clair",
+ "colorLightBlue": "Bleu clair",
+ "colorLightViolet": "Violet clair",
+ "colorLightPink": "Rose clair"
+}
diff --git a/packages/vue/src/i18n/locales/fr/index.ts b/packages/vue/src/i18n/locales/fr/index.ts
index dbb09c01a..bc7336c30 100644
--- a/packages/vue/src/i18n/locales/fr/index.ts
+++ b/packages/vue/src/i18n/locales/fr/index.ts
@@ -13,6 +13,7 @@ import credentials from './credentials.json'
import designCheck from './design-check.json'
import diagnostics from './diagnostics.json'
import editor from './editor.json'
+import figjam from './figjam.json'
import files from './files.json'
import fonts from './fonts.json'
import media from './media.json'
@@ -23,6 +24,7 @@ import recovery from './recovery.json'
import rename from './rename.json'
import rendering from './rendering.json'
import settings from './settings.json'
+import shapes from './shapes.json'
import statuses from './statuses.json'
import storage from './storage.json'
import tools from './tools.json'
@@ -44,6 +46,7 @@ export default {
designCheck,
diagnostics,
editor,
+ figjam,
files,
fonts,
media,
@@ -54,6 +57,7 @@ export default {
rendering,
rename,
settings,
+ shapes,
statuses,
storage,
tools,
diff --git a/packages/vue/src/i18n/locales/fr/panels.json b/packages/vue/src/i18n/locales/fr/panels.json
index 17857675a..66d42d623 100644
--- a/packages/vue/src/i18n/locales/fr/panels.json
+++ b/packages/vue/src/i18n/locales/fr/panels.json
@@ -469,12 +469,6 @@
"stickyColorBlue": "Bleu",
"stickyColorViolet": "Violet",
"stickyColorPink": "Rose",
- "stickyTextSize": "Taille du texte",
- "stickyTextSmall": "Petite",
- "stickyTextMedium": "Moyenne",
- "stickyTextLarge": "Grande",
- "stickyTextExtraLarge": "Très grande",
- "stickyTextHuge": "Énorme",
"stickyShowAuthor": "Afficher l’auteur",
"blendModePassThrough": "Traverser",
"blendModeNormal": "Normal",
diff --git a/packages/vue/src/i18n/locales/fr/shapes.json b/packages/vue/src/i18n/locales/fr/shapes.json
new file mode 100644
index 000000000..15ce7ff7d
--- /dev/null
+++ b/packages/vue/src/i18n/locales/fr/shapes.json
@@ -0,0 +1,43 @@
+{
+ "search": "Rechercher des formes",
+ "noResults": "Aucune forme trouvée",
+ "basic": "Formes de base",
+ "flowchart": "Organigramme",
+ "kind": "Forme",
+ "fill": "Remplissage",
+ "fillTransparent": "Transparent",
+ "fillNone": "Aucun",
+ "line": "Trait",
+ "lineDashed": "Tirets",
+ "lineNone": "Aucun",
+ "square": "Carré",
+ "ellipse": "Ellipse",
+ "diamond": "Losange",
+ "triangleUp": "Triangle",
+ "triangleDown": "Triangle pointant vers le bas",
+ "roundedRectangle": "Rectangle arrondi",
+ "pentagon": "Pentagone",
+ "octagon": "Octogone",
+ "plus": "Plus",
+ "arrowLeft": "Flèche gauche",
+ "arrowRight": "Flèche droite",
+ "chevron": "Chevron",
+ "star": "Étoile",
+ "speechBubble": "Bulle",
+ "parallelogramRight": "Parallélogramme incliné à droite",
+ "parallelogramLeft": "Parallélogramme incliné à gauche",
+ "engDatabase": "Cylindre",
+ "engQueue": "Cylindre horizontal",
+ "engFile": "Fichier",
+ "engFolder": "Dossier",
+ "documentSingle": "Document",
+ "documentMultiple": "Documents multiples",
+ "predefinedProcess": "Processus prédéfini",
+ "shield": "Bouclier",
+ "trapezoid": "Trapèze",
+ "manualInput": "Saisie manuelle",
+ "hexagon": "Hexagone",
+ "internalStorage": "Stockage interne",
+ "or": "Ou",
+ "summingJunction": "Jonction de sommation"
+}
diff --git a/packages/vue/src/i18n/locales/fr/tools.json b/packages/vue/src/i18n/locales/fr/tools.json
index 5b60ea5cf..5c07dad4e 100644
--- a/packages/vue/src/i18n/locales/fr/tools.json
+++ b/packages/vue/src/i18n/locales/fr/tools.json
@@ -11,6 +11,7 @@
"pencil": "Crayon",
"text": "Texte",
"sticky": "Note autocollante",
+ "shape": "Forme",
"connector": "Connecteur",
"hand": "Main",
"comment": "Commentaire"
diff --git a/packages/vue/src/i18n/locales/it/figjam.json b/packages/vue/src/i18n/locales/it/figjam.json
new file mode 100644
index 000000000..2fa9ac0d4
--- /dev/null
+++ b/packages/vue/src/i18n/locales/it/figjam.json
@@ -0,0 +1,34 @@
+{
+ "textSize": "Dimensione del testo",
+ "textSmall": "Piccolo",
+ "textMedium": "Medio",
+ "textLarge": "Grande",
+ "textExtraLarge": "Molto grande",
+ "textHuge": "Enorme",
+ "typeface": "Carattere",
+ "typefaceSimple": "Semplice",
+ "typefaceBookish": "Libresco",
+ "typefaceTechnical": "Tecnico",
+ "typefaceScribbled": "Scarabocchiato",
+ "colorBlack": "Nero",
+ "colorDarkGray": "Grigio scuro",
+ "colorRed": "Rosso",
+ "colorOrange": "Arancione",
+ "colorYellow": "Giallo",
+ "colorGreen": "Verde",
+ "colorTeal": "Verde acqua",
+ "colorBlue": "Blu",
+ "colorViolet": "Viola",
+ "colorPink": "Rosa",
+ "colorWhite": "Bianco",
+ "colorGray": "Grigio",
+ "colorLightGray": "Grigio chiaro",
+ "colorLightRed": "Rosso chiaro",
+ "colorLightOrange": "Arancione chiaro",
+ "colorLightYellow": "Giallo chiaro",
+ "colorLightGreen": "Verde chiaro",
+ "colorLightTeal": "Verde acqua chiaro",
+ "colorLightBlue": "Blu chiaro",
+ "colorLightViolet": "Viola chiaro",
+ "colorLightPink": "Rosa chiaro"
+}
diff --git a/packages/vue/src/i18n/locales/it/index.ts b/packages/vue/src/i18n/locales/it/index.ts
index dbb09c01a..bc7336c30 100644
--- a/packages/vue/src/i18n/locales/it/index.ts
+++ b/packages/vue/src/i18n/locales/it/index.ts
@@ -13,6 +13,7 @@ import credentials from './credentials.json'
import designCheck from './design-check.json'
import diagnostics from './diagnostics.json'
import editor from './editor.json'
+import figjam from './figjam.json'
import files from './files.json'
import fonts from './fonts.json'
import media from './media.json'
@@ -23,6 +24,7 @@ import recovery from './recovery.json'
import rename from './rename.json'
import rendering from './rendering.json'
import settings from './settings.json'
+import shapes from './shapes.json'
import statuses from './statuses.json'
import storage from './storage.json'
import tools from './tools.json'
@@ -44,6 +46,7 @@ export default {
designCheck,
diagnostics,
editor,
+ figjam,
files,
fonts,
media,
@@ -54,6 +57,7 @@ export default {
rendering,
rename,
settings,
+ shapes,
statuses,
storage,
tools,
diff --git a/packages/vue/src/i18n/locales/it/panels.json b/packages/vue/src/i18n/locales/it/panels.json
index e2fdd882b..bf03af46d 100644
--- a/packages/vue/src/i18n/locales/it/panels.json
+++ b/packages/vue/src/i18n/locales/it/panels.json
@@ -469,12 +469,6 @@
"stickyColorBlue": "Blu",
"stickyColorViolet": "Viola",
"stickyColorPink": "Rosa",
- "stickyTextSize": "Dimensione del testo",
- "stickyTextSmall": "Piccolo",
- "stickyTextMedium": "Medio",
- "stickyTextLarge": "Grande",
- "stickyTextExtraLarge": "Molto grande",
- "stickyTextHuge": "Enorme",
"stickyShowAuthor": "Mostra autore",
"blendModePassThrough": "Attraversa",
"blendModeNormal": "Normale",
diff --git a/packages/vue/src/i18n/locales/it/shapes.json b/packages/vue/src/i18n/locales/it/shapes.json
new file mode 100644
index 000000000..69201ac18
--- /dev/null
+++ b/packages/vue/src/i18n/locales/it/shapes.json
@@ -0,0 +1,43 @@
+{
+ "search": "Cerca forme",
+ "noResults": "Nessuna forma trovata",
+ "basic": "Di base",
+ "flowchart": "Diagramma di flusso",
+ "kind": "Forma",
+ "fill": "Riempimento",
+ "fillTransparent": "Trasparente",
+ "fillNone": "Nessuno",
+ "line": "Linea",
+ "lineDashed": "Tratteggiata",
+ "lineNone": "Nessuna",
+ "square": "Quadrato",
+ "ellipse": "Ellisse",
+ "diamond": "Rombo",
+ "triangleUp": "Triangolo",
+ "triangleDown": "Triangolo rivolto verso il basso",
+ "roundedRectangle": "Rettangolo arrotondato",
+ "pentagon": "Pentagono",
+ "octagon": "Ottagono",
+ "plus": "Più",
+ "arrowLeft": "Freccia sinistra",
+ "arrowRight": "Freccia destra",
+ "chevron": "Gallone",
+ "star": "Stella",
+ "speechBubble": "Fumetto",
+ "parallelogramRight": "Parallelogramma inclinato a destra",
+ "parallelogramLeft": "Parallelogramma inclinato a sinistra",
+ "engDatabase": "Cilindro",
+ "engQueue": "Cilindro orizzontale",
+ "engFile": "File",
+ "engFolder": "Cartella",
+ "documentSingle": "Documento",
+ "documentMultiple": "Documenti multipli",
+ "predefinedProcess": "Processo predefinito",
+ "shield": "Scudo",
+ "trapezoid": "Trapezio",
+ "manualInput": "Input manuale",
+ "hexagon": "Esagono",
+ "internalStorage": "Memoria interna",
+ "or": "Oppure",
+ "summingJunction": "Giunzione di somma"
+}
diff --git a/packages/vue/src/i18n/locales/it/tools.json b/packages/vue/src/i18n/locales/it/tools.json
index 4efb89869..421aba957 100644
--- a/packages/vue/src/i18n/locales/it/tools.json
+++ b/packages/vue/src/i18n/locales/it/tools.json
@@ -11,6 +11,7 @@
"pencil": "Matita",
"text": "Testo",
"sticky": "Nota adesiva",
+ "shape": "Forma",
"connector": "Connettore",
"hand": "Mano",
"comment": "Commento"
diff --git a/packages/vue/src/i18n/locales/ja/figjam.json b/packages/vue/src/i18n/locales/ja/figjam.json
new file mode 100644
index 000000000..43e1c1eb5
--- /dev/null
+++ b/packages/vue/src/i18n/locales/ja/figjam.json
@@ -0,0 +1,34 @@
+{
+ "textSize": "テキストサイズ",
+ "textSmall": "小",
+ "textMedium": "中",
+ "textLarge": "大",
+ "textExtraLarge": "特大",
+ "textHuge": "最大",
+ "typeface": "書体",
+ "typefaceSimple": "シンプル",
+ "typefaceBookish": "ブック",
+ "typefaceTechnical": "テクニカル",
+ "typefaceScribbled": "手書き",
+ "colorBlack": "黒",
+ "colorDarkGray": "ダークグレー",
+ "colorRed": "赤",
+ "colorOrange": "オレンジ",
+ "colorYellow": "黄",
+ "colorGreen": "緑",
+ "colorTeal": "ティール",
+ "colorBlue": "青",
+ "colorViolet": "紫",
+ "colorPink": "ピンク",
+ "colorWhite": "白",
+ "colorGray": "グレー",
+ "colorLightGray": "ライトグレー",
+ "colorLightRed": "ライトレッド",
+ "colorLightOrange": "ライトオレンジ",
+ "colorLightYellow": "ライトイエロー",
+ "colorLightGreen": "ライトグリーン",
+ "colorLightTeal": "ライトティール",
+ "colorLightBlue": "ライトブルー",
+ "colorLightViolet": "ライトバイオレット",
+ "colorLightPink": "ライトピンク"
+}
diff --git a/packages/vue/src/i18n/locales/ja/index.ts b/packages/vue/src/i18n/locales/ja/index.ts
index dbb09c01a..bc7336c30 100644
--- a/packages/vue/src/i18n/locales/ja/index.ts
+++ b/packages/vue/src/i18n/locales/ja/index.ts
@@ -13,6 +13,7 @@ import credentials from './credentials.json'
import designCheck from './design-check.json'
import diagnostics from './diagnostics.json'
import editor from './editor.json'
+import figjam from './figjam.json'
import files from './files.json'
import fonts from './fonts.json'
import media from './media.json'
@@ -23,6 +24,7 @@ import recovery from './recovery.json'
import rename from './rename.json'
import rendering from './rendering.json'
import settings from './settings.json'
+import shapes from './shapes.json'
import statuses from './statuses.json'
import storage from './storage.json'
import tools from './tools.json'
@@ -44,6 +46,7 @@ export default {
designCheck,
diagnostics,
editor,
+ figjam,
files,
fonts,
media,
@@ -54,6 +57,7 @@ export default {
rendering,
rename,
settings,
+ shapes,
statuses,
storage,
tools,
diff --git a/packages/vue/src/i18n/locales/ja/panels.json b/packages/vue/src/i18n/locales/ja/panels.json
index 64cf89b20..beac08144 100644
--- a/packages/vue/src/i18n/locales/ja/panels.json
+++ b/packages/vue/src/i18n/locales/ja/panels.json
@@ -463,12 +463,6 @@
"stickyColorBlue": "青",
"stickyColorViolet": "紫",
"stickyColorPink": "ピンク",
- "stickyTextSize": "テキストサイズ",
- "stickyTextSmall": "小",
- "stickyTextMedium": "中",
- "stickyTextLarge": "大",
- "stickyTextExtraLarge": "特大",
- "stickyTextHuge": "最大",
"stickyShowAuthor": "作成者を表示",
"blendModePassThrough": "通過",
"blendModeNormal": "通常",
diff --git a/packages/vue/src/i18n/locales/ja/shapes.json b/packages/vue/src/i18n/locales/ja/shapes.json
new file mode 100644
index 000000000..1c068a821
--- /dev/null
+++ b/packages/vue/src/i18n/locales/ja/shapes.json
@@ -0,0 +1,43 @@
+{
+ "search": "シェイプを検索",
+ "noResults": "シェイプが見つかりません",
+ "basic": "基本",
+ "flowchart": "フローチャート",
+ "kind": "シェイプ",
+ "fill": "塗り",
+ "fillTransparent": "半透明",
+ "fillNone": "なし",
+ "line": "線",
+ "lineDashed": "破線",
+ "lineNone": "なし",
+ "square": "正方形",
+ "ellipse": "楕円",
+ "diamond": "ひし形",
+ "triangleUp": "三角形",
+ "triangleDown": "下向き三角形",
+ "roundedRectangle": "角丸長方形",
+ "pentagon": "五角形",
+ "octagon": "八角形",
+ "plus": "プラス",
+ "arrowLeft": "左矢印",
+ "arrowRight": "右矢印",
+ "chevron": "シェブロン",
+ "star": "星",
+ "speechBubble": "吹き出し",
+ "parallelogramRight": "右に傾いた平行四辺形",
+ "parallelogramLeft": "左に傾いた平行四辺形",
+ "engDatabase": "円柱",
+ "engQueue": "横向きの円柱",
+ "engFile": "ファイル",
+ "engFolder": "フォルダー",
+ "documentSingle": "ドキュメント",
+ "documentMultiple": "複数のドキュメント",
+ "predefinedProcess": "定義済み処理",
+ "shield": "盾",
+ "trapezoid": "台形",
+ "manualInput": "手操作入力",
+ "hexagon": "六角形",
+ "internalStorage": "内部記憶",
+ "or": "論理和",
+ "summingJunction": "加算結合"
+}
diff --git a/packages/vue/src/i18n/locales/ja/tools.json b/packages/vue/src/i18n/locales/ja/tools.json
index b06b54df3..289e657d1 100644
--- a/packages/vue/src/i18n/locales/ja/tools.json
+++ b/packages/vue/src/i18n/locales/ja/tools.json
@@ -11,6 +11,7 @@
"pencil": "鉛筆",
"text": "テキスト",
"sticky": "付箋",
+ "shape": "シェイプ",
"connector": "コネクタ",
"hand": "手のひらツール",
"comment": "コメント"
diff --git a/packages/vue/src/i18n/locales/pl/figjam.json b/packages/vue/src/i18n/locales/pl/figjam.json
new file mode 100644
index 000000000..35ff32236
--- /dev/null
+++ b/packages/vue/src/i18n/locales/pl/figjam.json
@@ -0,0 +1,34 @@
+{
+ "textSize": "Rozmiar tekstu",
+ "textSmall": "Mały",
+ "textMedium": "Średni",
+ "textLarge": "Duży",
+ "textExtraLarge": "Bardzo duży",
+ "textHuge": "Ogromny",
+ "typeface": "Krój pisma",
+ "typefaceSimple": "Prosty",
+ "typefaceBookish": "Książkowy",
+ "typefaceTechnical": "Techniczny",
+ "typefaceScribbled": "Odręczny",
+ "colorBlack": "Czarny",
+ "colorDarkGray": "Ciemnoszary",
+ "colorRed": "Czerwony",
+ "colorOrange": "Pomarańczowy",
+ "colorYellow": "Żółty",
+ "colorGreen": "Zielony",
+ "colorTeal": "Morski",
+ "colorBlue": "Niebieski",
+ "colorViolet": "Fioletowy",
+ "colorPink": "Różowy",
+ "colorWhite": "Biały",
+ "colorGray": "Szary",
+ "colorLightGray": "Jasnoszary",
+ "colorLightRed": "Jasnoczerwony",
+ "colorLightOrange": "Jasnopomarańczowy",
+ "colorLightYellow": "Jasnożółty",
+ "colorLightGreen": "Jasnozielony",
+ "colorLightTeal": "Jasnomorski",
+ "colorLightBlue": "Jasnoniebieski",
+ "colorLightViolet": "Jasnofioletowy",
+ "colorLightPink": "Jasnoróżowy"
+}
diff --git a/packages/vue/src/i18n/locales/pl/index.ts b/packages/vue/src/i18n/locales/pl/index.ts
index dbb09c01a..bc7336c30 100644
--- a/packages/vue/src/i18n/locales/pl/index.ts
+++ b/packages/vue/src/i18n/locales/pl/index.ts
@@ -13,6 +13,7 @@ import credentials from './credentials.json'
import designCheck from './design-check.json'
import diagnostics from './diagnostics.json'
import editor from './editor.json'
+import figjam from './figjam.json'
import files from './files.json'
import fonts from './fonts.json'
import media from './media.json'
@@ -23,6 +24,7 @@ import recovery from './recovery.json'
import rename from './rename.json'
import rendering from './rendering.json'
import settings from './settings.json'
+import shapes from './shapes.json'
import statuses from './statuses.json'
import storage from './storage.json'
import tools from './tools.json'
@@ -44,6 +46,7 @@ export default {
designCheck,
diagnostics,
editor,
+ figjam,
files,
fonts,
media,
@@ -54,6 +57,7 @@ export default {
rendering,
rename,
settings,
+ shapes,
statuses,
storage,
tools,
diff --git a/packages/vue/src/i18n/locales/pl/panels.json b/packages/vue/src/i18n/locales/pl/panels.json
index 0bc5dcbb2..1cdb4597a 100644
--- a/packages/vue/src/i18n/locales/pl/panels.json
+++ b/packages/vue/src/i18n/locales/pl/panels.json
@@ -475,12 +475,6 @@
"stickyColorBlue": "Niebieski",
"stickyColorViolet": "Fioletowy",
"stickyColorPink": "Różowy",
- "stickyTextSize": "Rozmiar tekstu",
- "stickyTextSmall": "Mały",
- "stickyTextMedium": "Średni",
- "stickyTextLarge": "Duży",
- "stickyTextExtraLarge": "Bardzo duży",
- "stickyTextHuge": "Ogromny",
"stickyShowAuthor": "Pokaż autora",
"blendModePassThrough": "Przepuszczanie",
"blendModeNormal": "Normalny",
diff --git a/packages/vue/src/i18n/locales/pl/shapes.json b/packages/vue/src/i18n/locales/pl/shapes.json
new file mode 100644
index 000000000..34a8417ed
--- /dev/null
+++ b/packages/vue/src/i18n/locales/pl/shapes.json
@@ -0,0 +1,43 @@
+{
+ "search": "Szukaj kształtów",
+ "noResults": "Nie znaleziono kształtów",
+ "basic": "Podstawowe",
+ "flowchart": "Schemat blokowy",
+ "kind": "Kształt",
+ "fill": "Wypełnienie",
+ "fillTransparent": "Przezroczyste",
+ "fillNone": "Brak",
+ "line": "Linia",
+ "lineDashed": "Przerywana",
+ "lineNone": "Brak",
+ "square": "Kwadrat",
+ "ellipse": "Elipsa",
+ "diamond": "Romb",
+ "triangleUp": "Trójkąt",
+ "triangleDown": "Trójkąt skierowany w dół",
+ "roundedRectangle": "Zaokrąglony prostokąt",
+ "pentagon": "Pięciokąt",
+ "octagon": "Ośmiokąt",
+ "plus": "Plus",
+ "arrowLeft": "Strzałka w lewo",
+ "arrowRight": "Strzałka w prawo",
+ "chevron": "Szewron",
+ "star": "Gwiazda",
+ "speechBubble": "Dymek",
+ "parallelogramRight": "Równoległobok pochylony w prawo",
+ "parallelogramLeft": "Równoległobok pochylony w lewo",
+ "engDatabase": "Walec",
+ "engQueue": "Walec poziomy",
+ "engFile": "Plik",
+ "engFolder": "Folder",
+ "documentSingle": "Dokument",
+ "documentMultiple": "Wiele dokumentów",
+ "predefinedProcess": "Proces zdefiniowany",
+ "shield": "Tarcza",
+ "trapezoid": "Trapez",
+ "manualInput": "Wprowadzanie ręczne",
+ "hexagon": "Sześciokąt",
+ "internalStorage": "Pamięć wewnętrzna",
+ "or": "Lub",
+ "summingJunction": "Węzeł sumujący"
+}
diff --git a/packages/vue/src/i18n/locales/pl/tools.json b/packages/vue/src/i18n/locales/pl/tools.json
index cdb776fae..56bc842b0 100644
--- a/packages/vue/src/i18n/locales/pl/tools.json
+++ b/packages/vue/src/i18n/locales/pl/tools.json
@@ -11,6 +11,7 @@
"pencil": "Ołówek",
"text": "Tekst",
"sticky": "Karteczka",
+ "shape": "Kształt",
"connector": "Łącznik",
"hand": "Dłoń",
"comment": "Komentarz"
diff --git a/packages/vue/src/i18n/locales/ru/figjam.json b/packages/vue/src/i18n/locales/ru/figjam.json
new file mode 100644
index 000000000..16004e34f
--- /dev/null
+++ b/packages/vue/src/i18n/locales/ru/figjam.json
@@ -0,0 +1,34 @@
+{
+ "textSize": "Размер текста",
+ "textSmall": "Маленький",
+ "textMedium": "Средний",
+ "textLarge": "Крупный",
+ "textExtraLarge": "Очень крупный",
+ "textHuge": "Огромный",
+ "typeface": "Шрифт",
+ "typefaceSimple": "Простой",
+ "typefaceBookish": "Книжный",
+ "typefaceTechnical": "Технический",
+ "typefaceScribbled": "Рукописный",
+ "colorBlack": "Чёрный",
+ "colorDarkGray": "Тёмно-серый",
+ "colorRed": "Красный",
+ "colorOrange": "Оранжевый",
+ "colorYellow": "Жёлтый",
+ "colorGreen": "Зелёный",
+ "colorTeal": "Бирюзовый",
+ "colorBlue": "Синий",
+ "colorViolet": "Фиолетовый",
+ "colorPink": "Розовый",
+ "colorWhite": "Белый",
+ "colorGray": "Серый",
+ "colorLightGray": "Светло-серый",
+ "colorLightRed": "Светло-красный",
+ "colorLightOrange": "Светло-оранжевый",
+ "colorLightYellow": "Светло-жёлтый",
+ "colorLightGreen": "Светло-зелёный",
+ "colorLightTeal": "Светло-бирюзовый",
+ "colorLightBlue": "Светло-синий",
+ "colorLightViolet": "Светло-фиолетовый",
+ "colorLightPink": "Светло-розовый"
+}
diff --git a/packages/vue/src/i18n/locales/ru/index.ts b/packages/vue/src/i18n/locales/ru/index.ts
index dbb09c01a..bc7336c30 100644
--- a/packages/vue/src/i18n/locales/ru/index.ts
+++ b/packages/vue/src/i18n/locales/ru/index.ts
@@ -13,6 +13,7 @@ import credentials from './credentials.json'
import designCheck from './design-check.json'
import diagnostics from './diagnostics.json'
import editor from './editor.json'
+import figjam from './figjam.json'
import files from './files.json'
import fonts from './fonts.json'
import media from './media.json'
@@ -23,6 +24,7 @@ import recovery from './recovery.json'
import rename from './rename.json'
import rendering from './rendering.json'
import settings from './settings.json'
+import shapes from './shapes.json'
import statuses from './statuses.json'
import storage from './storage.json'
import tools from './tools.json'
@@ -44,6 +46,7 @@ export default {
designCheck,
diagnostics,
editor,
+ figjam,
files,
fonts,
media,
@@ -54,6 +57,7 @@ export default {
rendering,
rename,
settings,
+ shapes,
statuses,
storage,
tools,
diff --git a/packages/vue/src/i18n/locales/ru/panels.json b/packages/vue/src/i18n/locales/ru/panels.json
index 7ba640856..6b2904f8a 100644
--- a/packages/vue/src/i18n/locales/ru/panels.json
+++ b/packages/vue/src/i18n/locales/ru/panels.json
@@ -475,12 +475,6 @@
"stickyColorBlue": "Синий",
"stickyColorViolet": "Фиолетовый",
"stickyColorPink": "Розовый",
- "stickyTextSize": "Размер текста",
- "stickyTextSmall": "Маленький",
- "stickyTextMedium": "Средний",
- "stickyTextLarge": "Крупный",
- "stickyTextExtraLarge": "Очень крупный",
- "stickyTextHuge": "Огромный",
"stickyShowAuthor": "Показывать автора",
"blendModePassThrough": "Сквозной",
"blendModeNormal": "Обычный",
diff --git a/packages/vue/src/i18n/locales/ru/shapes.json b/packages/vue/src/i18n/locales/ru/shapes.json
new file mode 100644
index 000000000..f152994cc
--- /dev/null
+++ b/packages/vue/src/i18n/locales/ru/shapes.json
@@ -0,0 +1,43 @@
+{
+ "search": "Поиск фигур",
+ "noResults": "Фигуры не найдены",
+ "basic": "Основные",
+ "flowchart": "Блок-схема",
+ "kind": "Фигура",
+ "fill": "Заливка",
+ "fillTransparent": "Прозрачная",
+ "fillNone": "Нет",
+ "line": "Линия",
+ "lineDashed": "Пунктирная",
+ "lineNone": "Нет",
+ "square": "Квадрат",
+ "ellipse": "Эллипс",
+ "diamond": "Ромб",
+ "triangleUp": "Треугольник",
+ "triangleDown": "Треугольник вершиной вниз",
+ "roundedRectangle": "Скруглённый прямоугольник",
+ "pentagon": "Пятиугольник",
+ "octagon": "Восьмиугольник",
+ "plus": "Плюс",
+ "arrowLeft": "Стрелка влево",
+ "arrowRight": "Стрелка вправо",
+ "chevron": "Шеврон",
+ "star": "Звезда",
+ "speechBubble": "Выноска",
+ "parallelogramRight": "Параллелограмм с наклоном вправо",
+ "parallelogramLeft": "Параллелограмм с наклоном влево",
+ "engDatabase": "Цилиндр",
+ "engQueue": "Горизонтальный цилиндр",
+ "engFile": "Файл",
+ "engFolder": "Папка",
+ "documentSingle": "Документ",
+ "documentMultiple": "Несколько документов",
+ "predefinedProcess": "Предопределённый процесс",
+ "shield": "Щит",
+ "trapezoid": "Трапеция",
+ "manualInput": "Ручной ввод",
+ "hexagon": "Шестиугольник",
+ "internalStorage": "Внутренняя память",
+ "or": "Или",
+ "summingJunction": "Суммирующий узел"
+}
diff --git a/packages/vue/src/i18n/locales/ru/tools.json b/packages/vue/src/i18n/locales/ru/tools.json
index 9ccdbb2e1..86114e3b3 100644
--- a/packages/vue/src/i18n/locales/ru/tools.json
+++ b/packages/vue/src/i18n/locales/ru/tools.json
@@ -11,6 +11,7 @@
"pencil": "Карандаш",
"text": "Текст",
"sticky": "Стикер",
+ "shape": "Фигура",
"connector": "Соединитель",
"hand": "Рука",
"comment": "Комментарий"
diff --git a/packages/vue/src/i18n/locales/zh-cn/figjam.json b/packages/vue/src/i18n/locales/zh-cn/figjam.json
new file mode 100644
index 000000000..1c85ab684
--- /dev/null
+++ b/packages/vue/src/i18n/locales/zh-cn/figjam.json
@@ -0,0 +1,34 @@
+{
+ "textSize": "文字大小",
+ "textSmall": "小",
+ "textMedium": "中",
+ "textLarge": "大",
+ "textExtraLarge": "特大",
+ "textHuge": "超大",
+ "typeface": "字体",
+ "typefaceSimple": "简洁",
+ "typefaceBookish": "书卷",
+ "typefaceTechnical": "技术",
+ "typefaceScribbled": "手写",
+ "colorBlack": "黑色",
+ "colorDarkGray": "深灰色",
+ "colorRed": "红色",
+ "colorOrange": "橙色",
+ "colorYellow": "黄色",
+ "colorGreen": "绿色",
+ "colorTeal": "青色",
+ "colorBlue": "蓝色",
+ "colorViolet": "紫色",
+ "colorPink": "粉色",
+ "colorWhite": "白色",
+ "colorGray": "灰色",
+ "colorLightGray": "浅灰色",
+ "colorLightRed": "浅红色",
+ "colorLightOrange": "浅橙色",
+ "colorLightYellow": "浅黄色",
+ "colorLightGreen": "浅绿色",
+ "colorLightTeal": "浅青色",
+ "colorLightBlue": "浅蓝色",
+ "colorLightViolet": "浅紫色",
+ "colorLightPink": "浅粉色"
+}
diff --git a/packages/vue/src/i18n/locales/zh-cn/index.ts b/packages/vue/src/i18n/locales/zh-cn/index.ts
index dbb09c01a..bc7336c30 100644
--- a/packages/vue/src/i18n/locales/zh-cn/index.ts
+++ b/packages/vue/src/i18n/locales/zh-cn/index.ts
@@ -13,6 +13,7 @@ import credentials from './credentials.json'
import designCheck from './design-check.json'
import diagnostics from './diagnostics.json'
import editor from './editor.json'
+import figjam from './figjam.json'
import files from './files.json'
import fonts from './fonts.json'
import media from './media.json'
@@ -23,6 +24,7 @@ import recovery from './recovery.json'
import rename from './rename.json'
import rendering from './rendering.json'
import settings from './settings.json'
+import shapes from './shapes.json'
import statuses from './statuses.json'
import storage from './storage.json'
import tools from './tools.json'
@@ -44,6 +46,7 @@ export default {
designCheck,
diagnostics,
editor,
+ figjam,
files,
fonts,
media,
@@ -54,6 +57,7 @@ export default {
rendering,
rename,
settings,
+ shapes,
statuses,
storage,
tools,
diff --git a/packages/vue/src/i18n/locales/zh-cn/panels.json b/packages/vue/src/i18n/locales/zh-cn/panels.json
index 4becb5111..6e2eb0978 100644
--- a/packages/vue/src/i18n/locales/zh-cn/panels.json
+++ b/packages/vue/src/i18n/locales/zh-cn/panels.json
@@ -463,12 +463,6 @@
"stickyColorBlue": "蓝色",
"stickyColorViolet": "紫色",
"stickyColorPink": "粉色",
- "stickyTextSize": "文字大小",
- "stickyTextSmall": "小",
- "stickyTextMedium": "中",
- "stickyTextLarge": "大",
- "stickyTextExtraLarge": "特大",
- "stickyTextHuge": "超大",
"stickyShowAuthor": "显示作者",
"blendModePassThrough": "穿透",
"blendModeNormal": "正常",
diff --git a/packages/vue/src/i18n/locales/zh-cn/shapes.json b/packages/vue/src/i18n/locales/zh-cn/shapes.json
new file mode 100644
index 000000000..e8bc30e2a
--- /dev/null
+++ b/packages/vue/src/i18n/locales/zh-cn/shapes.json
@@ -0,0 +1,43 @@
+{
+ "search": "搜索形状",
+ "noResults": "未找到形状",
+ "basic": "基本",
+ "flowchart": "流程图",
+ "kind": "形状",
+ "fill": "填充",
+ "fillTransparent": "半透明",
+ "fillNone": "无",
+ "line": "线条",
+ "lineDashed": "虚线",
+ "lineNone": "无",
+ "square": "正方形",
+ "ellipse": "椭圆",
+ "diamond": "菱形",
+ "triangleUp": "三角形",
+ "triangleDown": "倒三角形",
+ "roundedRectangle": "圆角矩形",
+ "pentagon": "五边形",
+ "octagon": "八边形",
+ "plus": "加号",
+ "arrowLeft": "左箭头",
+ "arrowRight": "右箭头",
+ "chevron": "人字形",
+ "star": "星形",
+ "speechBubble": "对话气泡",
+ "parallelogramRight": "右倾平行四边形",
+ "parallelogramLeft": "左倾平行四边形",
+ "engDatabase": "圆柱",
+ "engQueue": "横向圆柱",
+ "engFile": "文件",
+ "engFolder": "文件夹",
+ "documentSingle": "文档",
+ "documentMultiple": "多个文档",
+ "predefinedProcess": "预定义流程",
+ "shield": "盾形",
+ "trapezoid": "梯形",
+ "manualInput": "手动输入",
+ "hexagon": "六边形",
+ "internalStorage": "内部存储",
+ "or": "或",
+ "summingJunction": "求和连接"
+}
diff --git a/packages/vue/src/i18n/locales/zh-cn/tools.json b/packages/vue/src/i18n/locales/zh-cn/tools.json
index 0c0ea18e3..cf4b87360 100644
--- a/packages/vue/src/i18n/locales/zh-cn/tools.json
+++ b/packages/vue/src/i18n/locales/zh-cn/tools.json
@@ -11,6 +11,7 @@
"pencil": "铅笔",
"text": "文本",
"sticky": "便利贴",
+ "shape": "形状",
"connector": "连接线",
"hand": "抓手",
"comment": "评论"
diff --git a/packages/vue/src/i18n/messages.ts b/packages/vue/src/i18n/messages.ts
index 932594d11..e762df1ad 100644
--- a/packages/vue/src/i18n/messages.ts
+++ b/packages/vue/src/i18n/messages.ts
@@ -14,6 +14,7 @@ import { credentialsMessageDefaults, credentialsMessages } from '#vue/i18n/messa
import { designCheckMessageDefaults, designCheckMessages } from '#vue/i18n/messages/design-check'
import { diagnosticsMessageDefaults, diagnosticsMessages } from '#vue/i18n/messages/diagnostics'
import { editorMessageDefaults, editorMessages } from '#vue/i18n/messages/editor'
+import { figJamMessageDefaults, figJamMessages } from '#vue/i18n/messages/figjam'
import { filesMessageDefaults, filesMessages } from '#vue/i18n/messages/files'
import { fontsMessageDefaults, fontsMessages } from '#vue/i18n/messages/fonts'
import { mediaMessageDefaults, mediaMessages } from '#vue/i18n/messages/media'
@@ -24,6 +25,7 @@ import { recoveryMessageDefaults, recoveryMessages } from '#vue/i18n/messages/re
import { renameMessageDefaults, renameMessages } from '#vue/i18n/messages/rename'
import { renderingMessageDefaults, renderingMessages } from '#vue/i18n/messages/rendering'
import { settingsMessageDefaults, settingsMessages } from '#vue/i18n/messages/settings'
+import { shapeMessageDefaults, shapeMessages } from '#vue/i18n/messages/shapes'
import { statusMessageDefaults, statusMessages } from '#vue/i18n/messages/statuses'
import { storageMessageDefaults, storageMessages } from '#vue/i18n/messages/storage'
import { toolMessageDefaults, toolMessages } from '#vue/i18n/messages/tools'
@@ -46,6 +48,7 @@ export {
designCheckMessages,
diagnosticsMessages,
editorMessages,
+ figJamMessages,
filesMessages,
fontsMessages,
mediaMessages,
@@ -56,6 +59,7 @@ export {
renderingMessages,
renameMessages,
settingsMessages,
+ shapeMessages,
statusMessages,
storageMessages,
toolMessages,
@@ -78,6 +82,7 @@ export const messageDefaults = {
designCheck: designCheckMessageDefaults,
diagnostics: diagnosticsMessageDefaults,
editor: editorMessageDefaults,
+ figjam: figJamMessageDefaults,
files: filesMessageDefaults,
fonts: fontsMessageDefaults,
media: mediaMessageDefaults,
@@ -88,6 +93,7 @@ export const messageDefaults = {
rendering: renderingMessageDefaults,
rename: renameMessageDefaults,
settings: settingsMessageDefaults,
+ shapes: shapeMessageDefaults,
statuses: statusMessageDefaults,
storage: storageMessageDefaults,
tools: toolMessageDefaults,
diff --git a/packages/vue/src/i18n/messages/figjam.ts b/packages/vue/src/i18n/messages/figjam.ts
new file mode 100644
index 000000000..682cd79b2
--- /dev/null
+++ b/packages/vue/src/i18n/messages/figjam.ts
@@ -0,0 +1,39 @@
+import { i18n } from '#vue/i18n/create'
+
+/** FigJam's text sizes, typefaces and board palette, shared by sticky notes and shapes. */
+export const figJamMessageDefaults = {
+ textSize: 'Text size',
+ textSmall: 'Small',
+ textMedium: 'Medium',
+ textLarge: 'Large',
+ textExtraLarge: 'Extra large',
+ textHuge: 'Huge',
+ typeface: 'Typeface',
+ typefaceSimple: 'Simple',
+ typefaceBookish: 'Bookish',
+ typefaceTechnical: 'Technical',
+ typefaceScribbled: 'Scribbled',
+ colorBlack: 'Black',
+ colorDarkGray: 'Dark gray',
+ colorRed: 'Red',
+ colorOrange: 'Orange',
+ colorYellow: 'Yellow',
+ colorGreen: 'Green',
+ colorTeal: 'Teal',
+ colorBlue: 'Blue',
+ colorViolet: 'Violet',
+ colorPink: 'Pink',
+ colorWhite: 'White',
+ colorGray: 'Gray',
+ colorLightGray: 'Light gray',
+ colorLightRed: 'Light red',
+ colorLightOrange: 'Light orange',
+ colorLightYellow: 'Light yellow',
+ colorLightGreen: 'Light green',
+ colorLightTeal: 'Light teal',
+ colorLightBlue: 'Light blue',
+ colorLightViolet: 'Light violet',
+ colorLightPink: 'Light pink'
+} as const
+
+export const figJamMessages = i18n('figjam', figJamMessageDefaults)
diff --git a/packages/vue/src/i18n/messages/panels.ts b/packages/vue/src/i18n/messages/panels.ts
index dbbfb23b3..bbf4333ab 100644
--- a/packages/vue/src/i18n/messages/panels.ts
+++ b/packages/vue/src/i18n/messages/panels.ts
@@ -382,12 +382,6 @@ export const panelMessageDefaults = {
stickyColorBlue: 'Blue',
stickyColorViolet: 'Violet',
stickyColorPink: 'Pink',
- stickyTextSize: 'Text size',
- stickyTextSmall: 'Small',
- stickyTextMedium: 'Medium',
- stickyTextLarge: 'Large',
- stickyTextExtraLarge: 'Extra large',
- stickyTextHuge: 'Huge',
stickyShowAuthor: 'Show author',
blendModePassThrough: 'Pass through',
diff --git a/packages/vue/src/i18n/messages/shapes.ts b/packages/vue/src/i18n/messages/shapes.ts
new file mode 100644
index 000000000..0b65b0d43
--- /dev/null
+++ b/packages/vue/src/i18n/messages/shapes.ts
@@ -0,0 +1,48 @@
+import { i18n } from '#vue/i18n/create'
+
+/** The shape-with-text picker: its search, FigJam's groups, and each kind as FigJam names it. */
+export const shapeMessageDefaults = {
+ search: 'Search shapes',
+ noResults: 'No shapes found',
+ basic: 'Basic',
+ flowchart: 'Flowchart',
+ kind: 'Shape',
+ fill: 'Fill',
+ fillTransparent: 'Transparent',
+ fillNone: 'None',
+ line: 'Line',
+ lineDashed: 'Dashed',
+ lineNone: 'None',
+ square: 'Square',
+ ellipse: 'Ellipse',
+ diamond: 'Diamond',
+ triangleUp: 'Triangle',
+ triangleDown: 'Downward-pointing triangle',
+ roundedRectangle: 'Rounded rectangle',
+ pentagon: 'Pentagon',
+ octagon: 'Octagon',
+ plus: 'Plus',
+ arrowLeft: 'Left arrow',
+ arrowRight: 'Right arrow',
+ chevron: 'Chevron',
+ star: 'Star',
+ speechBubble: 'Speech bubble',
+ parallelogramRight: 'Right-leaning parallelogram',
+ parallelogramLeft: 'Left-leaning parallelogram',
+ engDatabase: 'Cylinder',
+ engQueue: 'Horizontal cylinder',
+ engFile: 'File',
+ engFolder: 'Folder',
+ documentSingle: 'Document',
+ documentMultiple: 'Multiple documents',
+ predefinedProcess: 'Predefined process',
+ shield: 'Shield',
+ trapezoid: 'Trapezoid',
+ manualInput: 'Manual input',
+ hexagon: 'Hexagon',
+ internalStorage: 'Internal storage',
+ or: 'Or',
+ summingJunction: 'Summing junction'
+} as const
+
+export const shapeMessages = i18n('shapes', shapeMessageDefaults)
diff --git a/packages/vue/src/i18n/messages/tools.ts b/packages/vue/src/i18n/messages/tools.ts
index 396ad6c46..1988bf763 100644
--- a/packages/vue/src/i18n/messages/tools.ts
+++ b/packages/vue/src/i18n/messages/tools.ts
@@ -13,6 +13,7 @@ export const toolMessageDefaults = {
pencil: 'Pencil',
text: 'Text',
sticky: 'Sticky note',
+ shape: 'Shape',
connector: 'Connector',
hand: 'Hand',
comment: 'Comment'
diff --git a/packages/vue/src/i18n/useI18n.ts b/packages/vue/src/i18n/useI18n.ts
index 8cacfd239..1c7752a54 100644
--- a/packages/vue/src/i18n/useI18n.ts
+++ b/packages/vue/src/i18n/useI18n.ts
@@ -16,6 +16,7 @@ import {
designCheckMessages,
diagnosticsMessages,
editorMessages,
+ figJamMessages,
filesMessages,
fontsMessages,
mediaMessages,
@@ -26,6 +27,7 @@ import {
renderingMessages,
renameMessages,
settingsMessages,
+ shapeMessages,
statusMessages,
storageMessages,
toolMessages,
@@ -51,6 +53,7 @@ export const useCredentialMessages = () => useI18nNamespace(credentialsMessages)
export const useDesignCheckMessages = () => useI18nNamespace(designCheckMessages)
export const useDiagnosticsMessages = () => useI18nNamespace(diagnosticsMessages)
export const useEditorMessages = () => useI18nNamespace(editorMessages)
+export const useFigJamMessages = () => useI18nNamespace(figJamMessages)
export const useFileMessages = () => useI18nNamespace(filesMessages)
export const useFontMessages = () => useI18nNamespace(fontsMessages)
export const useMediaMessages = () => useI18nNamespace(mediaMessages)
@@ -61,6 +64,7 @@ export const useRecoveryMessages = () => useI18nNamespace(recoveryMessages)
export const useRenderingMessages = () => useI18nNamespace(renderingMessages)
export const useRenameMessages = () => useI18nNamespace(renameMessages)
export const useSettingsMessages = () => useI18nNamespace(settingsMessages)
+export const useShapeMessages = () => useI18nNamespace(shapeMessages)
export const useStatusMessages = () => useI18nNamespace(statusMessages)
export const useStorageMessages = () => useI18nNamespace(storageMessages)
export const useToolMessages = () => useI18nNamespace(toolMessages)
diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.ts
index fb01c1fae..1dbe5bcfd 100644
--- a/packages/vue/src/index.ts
+++ b/packages/vue/src/index.ts
@@ -127,6 +127,7 @@ export {
} from '#vue/controls/variable-modes/helpers'
export { useMask } from '#vue/controls/mask/use'
export { useConnector } from '#vue/controls/connector/use'
+export { useShapeWithText } from '#vue/controls/shape-with-text/use'
export { useStickyNote } from '#vue/controls/sticky/use'
export { useIcon } from '#vue/controls/icon/use'
export { useIconSearch } from '#vue/controls/icon/search'
diff --git a/packages/vue/src/primitives/LayerTree/context.ts b/packages/vue/src/primitives/LayerTree/context.ts
index 43fe17b37..a5c8fb512 100644
--- a/packages/vue/src/primitives/LayerTree/context.ts
+++ b/packages/vue/src/primitives/LayerTree/context.ts
@@ -1,6 +1,7 @@
import { type ComputedRef, type InjectionKey, type Ref, inject, provide } from 'vue'
import type { Editor } from '@open-pencil/core/editor'
+import type { ShapeWithTextType } from '@open-pencil/scene-graph/shape-with-text'
export interface LayerNode {
id: string
@@ -11,6 +12,8 @@ export interface LayerNode {
slot?: boolean
/** Whether the layer is an icon from a set, which keeps its name to be swapped or exported. */
icon?: boolean
+ /** A shape with text's kind, which its row draws. */
+ shapeWithTextType?: ShapeWithTextType
visible: boolean
locked: boolean
/** The variable modes set on the layer itself, which Figma tags its row with. */
diff --git a/packages/vue/src/primitives/LayerTree/model.ts b/packages/vue/src/primitives/LayerTree/model.ts
index 190a338ca..bad2f0d5f 100644
--- a/packages/vue/src/primitives/LayerTree/model.ts
+++ b/packages/vue/src/primitives/LayerTree/model.ts
@@ -2,6 +2,7 @@ import { isEqual } from 'es-toolkit'
import { isGeneratedFrame, readIcon, slotPropertyId } from '@open-pencil/scene-graph'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import type { ShapeWithTextType } from '@open-pencil/scene-graph/shape-with-text'
import type { LayerNode, LayerRow, LayerSelectionMode } from '#vue/primitives/LayerTree/context'
@@ -10,6 +11,10 @@ function explicitModeIds(node: SceneNode): string[] | undefined {
return ids.length > 0 ? ids : undefined
}
+function shapeWithTextTypeOf(node: SceneNode): ShapeWithTextType | undefined {
+ return node.type === 'SHAPE_WITH_TEXT' ? node.shapeWithTextType : undefined
+}
+
function nodeToLayerNode(node: SceneNode): LayerNode {
return {
id: node.id,
@@ -18,6 +23,7 @@ function nodeToLayerNode(node: SceneNode): LayerNode {
layoutMode: node.layoutMode,
slot: !!slotPropertyId(node),
icon: !!readIcon(node),
+ shapeWithTextType: shapeWithTextTypeOf(node),
visible: node.visible,
locked: node.locked,
modeIds: explicitModeIds(node)
@@ -72,6 +78,7 @@ export function patchLayerNode(target: LayerNode, source: SceneNode): boolean {
target.layoutMode !== source.layoutMode ||
target.slot !== !!slotPropertyId(source) ||
target.icon !== !!readIcon(source) ||
+ target.shapeWithTextType !== shapeWithTextTypeOf(source) ||
target.visible !== source.visible ||
target.locked !== source.locked ||
!isEqual(target.modeIds, explicitModeIds(source))
@@ -81,6 +88,7 @@ export function patchLayerNode(target: LayerNode, source: SceneNode): boolean {
target.layoutMode = source.layoutMode
target.slot = !!slotPropertyId(source)
target.icon = !!readIcon(source)
+ target.shapeWithTextType = shapeWithTextTypeOf(source)
target.visible = source.visible
target.locked = source.locked
target.modeIds = explicitModeIds(source)
diff --git a/packages/vue/src/shared/input/draw.ts b/packages/vue/src/shared/input/draw.ts
index 13361b386..25914a8e2 100644
--- a/packages/vue/src/shared/input/draw.ts
+++ b/packages/vue/src/shared/input/draw.ts
@@ -1,5 +1,6 @@
import { DEFAULT_TEXT_HEIGHT, DEFAULT_TEXT_WIDTH } from '@open-pencil/core/constants'
import type { Editor } from '@open-pencil/core/editor'
+import { generatedFrameText, SHAPE_WITH_TEXT_TOOL_SIZE } from '@open-pencil/scene-graph'
import type { NodeType, SceneNode } from '@open-pencil/scene-graph'
import { getWorldMatrix } from '@open-pencil/scene-graph/coordinate'
import Matrix from '@open-pencil/scene-graph/matrix'
@@ -106,12 +107,20 @@ 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_TOOL_SIZE, height: SHAPE_WITH_TEXT_TOOL_SIZE })
} else if (clicked) {
preview.update(node.id, { width: 100, height: 100 })
}
return clicked
}
+/** A new text, or a new shape's label, takes typing at once, as in FigJam. */
+function startTyping(editor: Editor, node: SceneNode) {
+ const typed = node.type === 'TEXT' ? node : generatedFrameText(editor.graph, node)
+ if (typed) editor.startTextEditing(typed.id)
+}
+
function createDraw(
editor: Editor,
nodeId: string,
@@ -147,6 +156,8 @@ function createDraw(
// Drawn into auto layout, the layer joins the flow at the end.
const parent = graph.getNode(node?.parentId ?? '')
if (parent && parent.layoutMode !== 'NONE') editor.runLayoutForNode(parent.id)
+ // A shape with text lays its label out in the size it was drawn at.
+ if (node?.type === 'SHAPE_WITH_TEXT') editor.runLayoutForNode(node.id)
// A frame made by a click, not drawn over anything, takes nothing in.
if (node?.type === 'SECTION' || (node?.type === 'FRAME' && !clicked)) {
editor.adoptCoveredLayers(node.id)
@@ -158,7 +169,7 @@ function createDraw(
throw error
}
editor.setTool('SELECT')
- if (node?.type === 'TEXT') editor.startTextEditing(node.id)
+ if (node) startTyping(editor, node)
}
// Creation itself is already an edit: avoid rebuilding the backing on the first held frame.
diff --git a/packages/vue/src/shared/input/types.ts b/packages/vue/src/shared/input/types.ts
index e2133947d..490a463e6 100644
--- a/packages/vue/src/shared/input/types.ts
+++ b/packages/vue/src/shared/input/types.ts
@@ -311,5 +311,6 @@ export const TOOL_TO_NODE: Partial<Record<Tool, NodeType>> = {
LINE: 'LINE',
POLYGON: 'POLYGON',
STAR: 'STAR',
- TEXT: 'TEXT'
+ TEXT: 'TEXT',
+ SHAPE_WITH_TEXT: 'SHAPE_WITH_TEXT'
}
diff --git a/packages/vue/tests/primitives/LayerTree/model.test.ts b/packages/vue/tests/primitives/LayerTree/model.test.ts
index 8375307b7..cf5d9a552 100644
--- a/packages/vue/tests/primitives/LayerTree/model.test.ts
+++ b/packages/vue/tests/primitives/LayerTree/model.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test'
-import { SceneGraph, withIcon } from '@open-pencil/scene-graph'
+import { createShapeWithText, SceneGraph, withIcon } from '@open-pencil/scene-graph'
import { buildLayerTreeModel, patchLayerNode } from '@open-pencil/vue'
import { dropIndex } from '#vue/primitives/LayerTree/model'
@@ -40,6 +40,20 @@ describe('layer tree model', () => {
expect(patchLayerNode(row, frame)).toBe(true)
expect(row.modeIds).toEqual([dark])
})
+
+ test("carries a shape with text's kind, so its row draws the outline", () => {
+ const graph = new SceneGraph()
+ const pageId = graph.getPages()[0].id
+ const shape = createShapeWithText(graph, pageId, { shapeWithTextType: 'DIAMOND' })
+
+ const row = buildLayerTreeModel(graph, pageId).byId.get(shape.id)
+ if (!row) throw new Error('Expected the shape in the model')
+ expect(row.shapeWithTextType).toBe('DIAMOND')
+
+ graph.updateNode(shape.id, { shapeWithTextType: 'ELLIPSE' })
+ expect(patchLayerNode(row, shape)).toBe(true)
+ expect(row.shapeWithTextType).toBe('ELLIPSE')
+ })
})
describe('drop index', () => {
diff --git a/skills/open-pencil/references/design-authoring.md b/skills/open-pencil/references/design-authoring.md
index 610a3b4b0..5d64ae9a1 100644
--- a/skills/open-pencil/references/design-authoring.md
+++ b/skills/open-pencil/references/design-authoring.md
@@ -27,7 +27,8 @@ This reference describes scene creation, not React DOM output. Use the `render`
- Text content belongs inside `Text`. Use `size`, `font`, `weight`, `italic`, `lineHeight`, `letterSpacing`, `textAlign`, `textAlignVertical`, `textDecoration`, and `textCase`. Decorations take CSS's names and values: `textDecorationStyle` (`solid`, `dotted`, `wavy`), `textDecorationColor` (`currentColor` follows the text), `textDecorationThickness` and `textUnderlineOffset` (pixels or `auto`), and `textDecorationSkipInk`. `lineHeight="auto"` follows the font, and `fills={[]}` paints no text. Verify fonts actually load before judging dimensions; do not assume every font is available.
- `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`, and `scale` scales the whole note. A note sizes itself; it takes no `w`, `h`, fills, or layout props.
+- `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 (208 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`.
- `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.
@@ -104,7 +105,7 @@ The examples below are executed by the authoring-reference tests. Create the nam
Generated from the renderer metadata. This inventory lists accepted names, not arbitrary browser CSS support.
-**Elements:** `Frame`, `Text`, `Span`, `Paragraph`, `Rectangle`, `Ellipse`, `Line`, `Star`, `Polygon`, `Vector`, `Group`, `Section`, `Component`, `ComponentSet`, `Instance`, `View`, `Rect`, `Icon`, `Sticky`, `Connector`, `Button.Root`, `Toggle.Root`, `Switch.Root`, `Switch.Thumb`, `Checkbox.Root`, `Checkbox.Indicator`, `RadioGroup.Root`, `RadioGroup.Item`, `RadioGroup.Indicator`, `ToggleGroup.Root`, `ToggleGroup.Item`, `Slider.Root`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Progress.Root`, `Progress.Track`, `Progress.Indicator`, `Tabs.Root`, `Tabs.List`, `Tabs.Trigger`, `Tabs.Content`, `Collapsible.Root`, `Collapsible.Trigger`, `Collapsible.Content`, `Accordion.Root`, `Accordion.Item`, `Accordion.Header`, `Accordion.Trigger`, `Accordion.Content`, `NumberField.Root`, `NumberField.Input`, `NumberField.Increment`, `NumberField.Decrement`, `TextField.Root`, `TextField.Input`, `Textarea.Root`, `Textarea.Input`.
+**Elements:** `Frame`, `Text`, `Span`, `Paragraph`, `Rectangle`, `Ellipse`, `Line`, `Star`, `Polygon`, `Vector`, `Group`, `Section`, `Component`, `ComponentSet`, `Instance`, `View`, `Rect`, `Icon`, `Sticky`, `Shape`, `Connector`, `Button.Root`, `Toggle.Root`, `Switch.Root`, `Switch.Thumb`, `Checkbox.Root`, `Checkbox.Indicator`, `RadioGroup.Root`, `RadioGroup.Item`, `RadioGroup.Indicator`, `ToggleGroup.Root`, `ToggleGroup.Item`, `Slider.Root`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Progress.Root`, `Progress.Track`, `Progress.Indicator`, `Tabs.Root`, `Tabs.List`, `Tabs.Trigger`, `Tabs.Content`, `Collapsible.Root`, `Collapsible.Trigger`, `Collapsible.Content`, `Accordion.Root`, `Accordion.Item`, `Accordion.Header`, `Accordion.Trigger`, `Accordion.Content`, `NumberField.Root`, `NumberField.Input`, `NumberField.Increment`, `NumberField.Decrement`, `TextField.Root`, `TextField.Input`, `Textarea.Root`, `Textarea.Input`.
**Helpers:** `solid`, `gradient`, `linearGradient`, `radialGradient`, `angularGradient`, `diamondGradient`, `shader`, `dropShadow`, `innerShadow`, `layerBlur`, `backgroundBlur`, `foregroundBlur`, `designVar`, `defineVars`, `ref`.
diff --git a/src/app/editor/icons.ts b/src/app/editor/icons.ts
index 7471ef13a..2673e356e 100644
--- a/src/app/editor/icons.ts
+++ b/src/app/editor/icons.ts
@@ -14,6 +14,7 @@ import IconMousePointer from '~icons/lucide/mouse-pointer'
import IconPenTool from '~icons/lucide/pen-tool'
import IconPencil from '~icons/lucide/pencil'
import IconRows from '~icons/lucide/rows-3'
+import IconShapes from '~icons/lucide/shapes'
import IconSmile from '~icons/lucide/smile'
import IconSpline from '~icons/lucide/spline'
import IconSquare from '~icons/lucide/square'
@@ -24,8 +25,10 @@ import IconTriangle from '~icons/lucide/triangle'
import IconType from '~icons/lucide/type'
import { readIcon, slotPropertyId, type SceneNode } from '@open-pencil/scene-graph'
+import type { ShapeWithTextType } from '@open-pencil/scene-graph/shape-with-text'
import type { Tool } from '@/app/editor/session'
+import { SHAPE_KIND_ICONS } from '@/app/editor/shape-icons'
export const toolIcons: Record<Tool, Component> = {
SELECT: IconMousePointer,
@@ -40,6 +43,7 @@ export const toolIcons: Record<Tool, Component> = {
PENCIL: IconPencil,
TEXT: IconType,
STICKY: IconStickyNote,
+ SHAPE_WITH_TEXT: IconShapes,
CONNECTOR: IconSpline,
HAND: IconHand,
COMMENT: IconMessageCircle
@@ -71,14 +75,21 @@ export const COMPONENT_TYPES = new Set(['COMPONENT', 'COMPONENT_SET', 'INSTANCE'
export { IconFrame, IconSquare }
-/** The glyph for a layer: its kind, or a slot or icon frame. A component keeps its own glyph. */
+/**
+ * The glyph for a layer: its kind, or a slot or icon frame. A component keeps its own glyph, and
+ * a shape with text shows its outline.
+ */
export function nodeIcon(node: {
type: string
layoutMode: string
slot?: boolean
icon?: boolean
+ shapeWithTextType?: ShapeWithTextType
}) {
if (node.slot) return IconSlot
+ if (node.type === 'SHAPE_WITH_TEXT' && node.shapeWithTextType) {
+ return SHAPE_KIND_ICONS[node.shapeWithTextType]
+ }
if (node.icon && node.type === 'FRAME') return IconSmile
if (node.type === 'FRAME' && node.layoutMode !== 'NONE')
return AUTO_LAYOUT_ICONS[node.layoutMode] ?? IconFrame
diff --git a/src/app/editor/shape-icons.ts b/src/app/editor/shape-icons.ts
new file mode 100644
index 000000000..04473668c
--- /dev/null
+++ b/src/app/editor/shape-icons.ts
@@ -0,0 +1,63 @@
+import { h, type FunctionalComponent } from 'vue'
+
+import { outlineSVGPath, type PolygonOutlineCommand } from '@open-pencil/scene-graph/polygon'
+import {
+ SHAPE_WITH_TEXT_TYPES,
+ shapeWithTextGeometry,
+ type ShapeWithTextType
+} from '@open-pencil/scene-graph/shape-with-text'
+
+/** The icon box, and the outline inside it, as lucide draws its icons. */
+const BOX = 24
+const INSET = 3
+const STROKE = 1.5
+
+function inset(commands: PolygonOutlineCommand[]): PolygonOutlineCommand[] {
+ return commands.map((command) => {
+ if (command.type === 'Z') return command
+ if (command.type === 'C') {
+ return {
+ ...command,
+ x1: command.x1 + INSET,
+ y1: command.y1 + INSET,
+ x2: command.x2 + INSET,
+ y2: command.y2 + INSET,
+ x: command.x + INSET,
+ y: command.y + INSET
+ }
+ }
+ return { ...command, x: command.x + INSET, y: command.y + INSET }
+ })
+}
+
+/** A kind's outline as icon markup, drawn from the same geometry the canvas draws it from. */
+export function shapeKindIconSVG(kind: ShapeWithTextType): string {
+ const size = BOX - INSET * 2
+ const { outline, details } = shapeWithTextGeometry(kind, size, size, 1)
+ const paths = [outline, details]
+ .filter((commands) => commands.length > 0)
+ .map((commands) => `<path d="${outlineSVGPath(inset(commands))}"/>`)
+ .join('')
+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${BOX} ${BOX}" fill="none" stroke="black" stroke-width="${STROKE}" stroke-linejoin="round">${paths}</svg>`
+}
+
+/**
+ * Each kind's outline as an icon component, drawn in the text color through a mask so the
+ * markup never runs in the page; the caller's class sizes it.
+ */
+export const SHAPE_KIND_ICONS = Object.fromEntries(
+ SHAPE_WITH_TEXT_TYPES.map((kind): [ShapeWithTextType, FunctionalComponent] => {
+ const mask = `url("data:image/svg+xml,${encodeURIComponent(shapeKindIconSVG(kind))}")`
+ const icon: FunctionalComponent = (_props, { attrs }) =>
+ h('span', {
+ ...attrs,
+ 'aria-hidden': 'true',
+ class: [
+ 'inline-block shrink-0 bg-current mask-(--shape-kind) mask-contain mask-center mask-no-repeat',
+ attrs.class
+ ],
+ style: { '--shape-kind': mask }
+ })
+ return [kind, icon]
+ })
+) as Record<ShapeWithTextType, FunctionalComponent>
diff --git a/src/app/editor/toolbar/layout.ts b/src/app/editor/toolbar/layout.ts
index 679ca5f52..763a7b6e0 100644
--- a/src/app/editor/toolbar/layout.ts
+++ b/src/app/editor/toolbar/layout.ts
@@ -26,9 +26,9 @@ export const PINNED_TOOLBAR_ENTRY: ToolbarEntry = 'SELECT'
/**
* Tools the toolbar keeps hidden until shown from Customize toolbar, such as FigJam's sticky
- * note and connector, which Figma's own toolbar does not offer.
+ * note, shape and connector, which Figma's own toolbar does not offer.
*/
-const HIDDEN_BY_DEFAULT: readonly ToolbarEntry[] = ['STICKY', 'CONNECTOR']
+const HIDDEN_BY_DEFAULT: readonly ToolbarEntry[] = ['STICKY', 'SHAPE_WITH_TEXT', 'CONNECTOR']
export const DEFAULT_TOOLBAR_LAYOUT: Readonly<ToolbarLayout> = {
groups: [
diff --git a/src/app/editor/toolbar/shortcuts.ts b/src/app/editor/toolbar/shortcuts.ts
index 68a6ef61d..fb55fa3d3 100644
--- a/src/app/editor/toolbar/shortcuts.ts
+++ b/src/app/editor/toolbar/shortcuts.ts
@@ -17,6 +17,7 @@ const TOOL_SHORTCUT_KEYS: Readonly<Record<Tool, string>> = {
PENCIL: 'SHIFT+P',
TEXT: 'T',
STICKY: '',
+ SHAPE_WITH_TEXT: '',
CONNECTOR: '',
HAND: 'H',
COMMENT: 'C'
diff --git a/src/components/DesignPanel.vue b/src/components/DesignPanel.vue
index a5ac9300e..ae27093f9 100644
--- a/src/components/DesignPanel.vue
+++ b/src/components/DesignPanel.vue
@@ -41,6 +41,7 @@ import PositionSection from './properties/PositionSection.vue'
import SelectionColorsSection from './properties/selection/SelectionColorsSection.vue'
import SelectionLayoutSection from './properties/selection/SelectionLayoutSection.vue'
import SelectionActionsControl from './properties/SelectionActionsControl.vue'
+import ShapeWithTextSection from './properties/shape-with-text/ShapeWithTextSection.vue'
import StatusesSection from './properties/status/StatusesSection.vue'
import StatusSection from './properties/status/StatusSection.vue'
import StickySection from './properties/sticky/StickySection.vue'
@@ -213,6 +214,7 @@ const { panels } = useI18n()
<IconSection />
<StickySection />
+ <ShapeWithTextSection />
<ConnectorSection />
<!-- A connector is placed and shaped by its ends, and styled by its line. -->
<template v-if="node.type !== 'CONNECTOR'">
diff --git a/src/components/figjam/FigJamPalette.vue b/src/components/figjam/FigJamPalette.vue
new file mode 100644
index 000000000..10e8cbb53
--- /dev/null
+++ b/src/components/figjam/FigJamPalette.vue
@@ -0,0 +1,65 @@
+<script setup lang="ts">
+import { computed } from 'vue'
+
+import { FIGJAM_COLOR_NAMES, figJamColor, type FigJamColorName } from '@open-pencil/scene-graph'
+import { colorToHex } from '@open-pencil/scene-graph/color'
+import { useFigJamMessages } from '@open-pencil/vue'
+
+import Swatches from './Swatches.vue'
+
+/** FigJam's board palette in its menus' order, closed by a swatch for no colour at all. */
+const { label, selected, noneLabel, none } = defineProps<{
+ label: string
+ selected: FigJamColorName | null
+ noneLabel: string
+ /** Whether no colour is shown, which the none swatch marks. */
+ none: boolean
+}>()
+const emit = defineEmits<{ select: [name: FigJamColorName]; none: [] }>()
+const figjam = useFigJamMessages()
+
+type FigJamMessages = (typeof figjam)['value']
+
+const COLOR_LABEL_KEYS = {
+ black: 'colorBlack',
+ darkGray: 'colorDarkGray',
+ red: 'colorRed',
+ orange: 'colorOrange',
+ yellow: 'colorYellow',
+ green: 'colorGreen',
+ teal: 'colorTeal',
+ blue: 'colorBlue',
+ violet: 'colorViolet',
+ pink: 'colorPink',
+ white: 'colorWhite',
+ gray: 'colorGray',
+ lightGray: 'colorLightGray',
+ lightRed: 'colorLightRed',
+ lightOrange: 'colorLightOrange',
+ lightYellow: 'colorLightYellow',
+ lightGreen: 'colorLightGreen',
+ lightTeal: 'colorLightTeal',
+ lightBlue: 'colorLightBlue',
+ lightViolet: 'colorLightViolet',
+ lightPink: 'colorLightPink'
+} as const satisfies Record<FigJamColorName, keyof FigJamMessages>
+
+const swatches = computed(() =>
+ FIGJAM_COLOR_NAMES.map((name) => ({
+ value: name,
+ hex: colorToHex(figJamColor(name)),
+ label: figjam.value[COLOR_LABEL_KEYS[name]]
+ }))
+)
+</script>
+
+<template>
+ <Swatches
+ :label="label"
+ :swatches="swatches"
+ :selected="selected"
+ :none="{ label: noneLabel, active: none }"
+ @select="emit('select', $event)"
+ @none="emit('none')"
+ />
+</template>
diff --git a/src/components/figjam/Swatches.vue b/src/components/figjam/Swatches.vue
new file mode 100644
index 000000000..5eac005a0
--- /dev/null
+++ b/src/components/figjam/Swatches.vue
@@ -0,0 +1,54 @@
+<script setup lang="ts" generic="T extends string">
+import { tv } from 'tailwind-variants'
+
+import theme from '@/theme/figjam/swatches'
+
+/** A swatch for one colour of a palette, as sticky notes and shapes pick theirs. */
+export interface Swatch<T extends string> {
+ value: T
+ hex: string
+ label: string
+}
+
+/**
+ * A palette as a row of round swatches, eleven to a line as in FigJam's colour menus, and,
+ * when `none` is given, a last swatch for no colour at all.
+ */
+const { label, swatches, selected, none } = defineProps<{
+ label: string
+ swatches: Swatch<T>[]
+ selected: T | null
+ none?: { label: string; active: boolean }
+}>()
+const emit = defineEmits<{ select: [value: T]; none: [] }>()
+const styles = tv(theme)
+</script>
+
+<template>
+ <div :class="styles().root()" role="radiogroup" :aria-label="label">
+ <button
+ v-for="swatch in swatches"
+ :key="swatch.value"
+ type="button"
+ role="radio"
+ :aria-checked="!none?.active && swatch.value === selected"
+ :aria-label="swatch.label"
+ :data-swatch="swatch.value"
+ :class="styles({ active: !none?.active && swatch.value === selected }).swatch()"
+ :style="{ backgroundColor: swatch.hex }"
+ @click="emit('select', swatch.value)"
+ />
+ <button
+ v-if="none"
+ type="button"
+ role="radio"
+ :aria-checked="none.active"
+ :aria-label="none.label"
+ data-swatch="none"
+ :class="styles({ active: none.active }).swatch({ class: styles().none() })"
+ @click="emit('none')"
+ >
+ <icon-lucide-ban class="size-3.5" />
+ </button>
+ </div>
+</template>
diff --git a/src/components/figjam/text-options.ts b/src/components/figjam/text-options.ts
new file mode 100644
index 000000000..86b9407a2
--- /dev/null
+++ b/src/components/figjam/text-options.ts
@@ -0,0 +1,43 @@
+import { computed } from 'vue'
+
+import {
+ isFigJamTypeface,
+ type FigJamTextSize,
+ type FigJamTypeface
+} from '@open-pencil/scene-graph'
+import { useFigJamMessages } from '@open-pencil/vue'
+
+/** FigJam's text sizes and typefaces as select options, shared by sticky notes and shapes. */
+export function useFigJamTextOptions() {
+ const figjam = useFigJamMessages()
+ const sizeOptions = computed<Array<{ value: FigJamTextSize; label: string }>>(() => [
+ { value: 'small', label: figjam.value.textSmall },
+ { value: 'medium', label: figjam.value.textMedium },
+ { value: 'large', label: figjam.value.textLarge },
+ { value: 'extraLarge', label: figjam.value.textExtraLarge },
+ { value: 'huge', label: figjam.value.textHuge }
+ ])
+ const typefaceOptions = computed<Array<{ value: FigJamTypeface; label: string }>>(() => [
+ { value: 'simple', label: figjam.value.typefaceSimple },
+ { value: 'bookish', label: figjam.value.typefaceBookish },
+ { value: 'technical', label: figjam.value.typefaceTechnical },
+ { value: 'scribbled', label: figjam.value.typefaceScribbled }
+ ])
+ return { sizeOptions, typefaceOptions }
+}
+
+/**
+ * A typeface select's model: the text's typeface, or none for a face FigJam's menu does not
+ * offer, which the select then shows by name.
+ */
+export function typefaceModel(
+ typeface: () => FigJamTypeface | null,
+ set: (value: FigJamTypeface) => void
+) {
+ return computed<string>({
+ get: () => typeface() ?? '',
+ set: (value) => {
+ if (isFigJamTypeface(value)) set(value)
+ }
+ })
+}
diff --git a/src/components/properties/layout/LayoutSection.vue b/src/components/properties/layout/LayoutSection.vue
index 9587a2c43..abe1c9f58 100644
--- a/src/components/properties/layout/LayoutSection.vue
+++ b/src/components/properties/layout/LayoutSection.vue
@@ -1,4 +1,5 @@
<script setup lang="ts">
+import { isGeneratedFrame } from '@open-pencil/scene-graph'
import { LAYOUT_CONTAINER_TYPES, LayoutControlsRoot, useI18n } from '@open-pencil/vue'
import ClipContentControl from '@/components/properties/layout/ClipContentControl.vue'
@@ -18,7 +19,14 @@ const { panels } = useI18n()
<template>
<LayoutControlsRoot v-slot="ctx">
<template v-if="ctx.node">
- <PanelSection :label="ctx.node.layoutMode === 'NONE' ? panels.layout : panels.autoLayout">
+ <!-- A generated frame, such as a shape with text, lays out its own sublayers; its auto layout is not offered. -->
+ <PanelSection
+ :label="
+ ctx.node.layoutMode === 'NONE' || isGeneratedFrame(ctx.node)
+ ? panels.layout
+ : panels.autoLayout
+ "
+ >
<template v-if="LAYOUT_CONTAINER_TYPES.has(ctx.node.type)" #actions>
<IconButton
:label="ctx.node.layoutMode === 'NONE' ? panels.addAutoLayout : panels.removeAutoLayout"
diff --git a/src/components/properties/shape-with-text/ShapeWithTextControls.stories.ts b/src/components/properties/shape-with-text/ShapeWithTextControls.stories.ts
new file mode 100644
index 000000000..086d65495
--- /dev/null
+++ b/src/components/properties/shape-with-text/ShapeWithTextControls.stories.ts
@@ -0,0 +1,80 @@
+import type { Meta, StoryObj } from '@storybook/vue3-vite'
+import { expect, userEvent, within } from 'storybook/test'
+import { ref } from 'vue'
+
+import type {
+ FigJamColorName,
+ FigJamFillMode,
+ FigJamLineStyle,
+ FigJamTextSize,
+ FigJamTypeface
+} from '@open-pencil/scene-graph'
+import type { ShapeWithTextType } from '@open-pencil/scene-graph/shape-with-text'
+
+import ShapeWithTextControls from './ShapeWithTextControls.vue'
+
+const meta = {
+ title: 'App/Editor/Properties/Shape With Text',
+ tags: ['autodocs'],
+ parameters: {
+ docs: {
+ description: {
+ component:
+ "A selected shape with text's kind, FigJam palette fill and outline, see-through and dashed toggles, text size, and typeface, as the Design panel shows them."
+ }
+ }
+ },
+ render: () => ({
+ components: { ShapeWithTextControls },
+ setup() {
+ const kind = ref<ShapeWithTextType>('DIAMOND')
+ const color = ref<FigJamColorName | null>('yellow')
+ const fillMode = ref<FigJamFillMode>('fill')
+ const lineStyle = ref<FigJamLineStyle>('solid')
+ const lineColor = ref<FigJamColorName | null>(null)
+ const textSize = ref<FigJamTextSize>('small')
+ const typeface = ref<FigJamTypeface>('simple')
+ return { kind, color, fillMode, lineStyle, lineColor, textSize, typeface }
+ },
+ template: `
+ <div class="w-[240px] bg-panel p-4">
+ <ShapeWithTextControls
+ :kind="kind"
+ :color="color"
+ :fill-mode="fillMode"
+ :line-style="lineStyle"
+ :line-color="lineColor"
+ :text-size="textSize"
+ :typeface="typeface"
+ @update:kind="kind = $event"
+ @update:color="color = $event; if (fillMode === 'none') fillMode = 'fill'"
+ @update:fill-mode="fillMode = $event"
+ @update:line-style="lineStyle = $event"
+ @update:line-color="lineColor = $event"
+ @update:text-size="textSize = $event"
+ @update:typeface="typeface = $event"
+ />
+ </div>`
+ })
+} satisfies Meta
+export default meta
+type Story = StoryObj<typeof meta>
+
+export const Default: Story = {}
+
+export const PickColorsAndToggles: Story = {
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement)
+ const fill = within(canvas.getByRole('radiogroup', { name: 'Fill' }))
+ await userEvent.click(fill.getByRole('radio', { name: 'Violet' }))
+ await expect(fill.getByRole('radio', { name: 'Violet' })).toHaveAttribute(
+ 'aria-checked',
+ 'true'
+ )
+ await userEvent.click(fill.getByRole('radio', { name: 'None' }))
+ await expect(fill.getByRole('radio', { name: 'None' })).toHaveAttribute('aria-checked', 'true')
+ const dashed = canvas.getByRole('button', { name: 'Dashed' })
+ await userEvent.click(dashed)
+ await expect(dashed).toHaveAttribute('aria-pressed', 'true')
+ }
+}
diff --git a/src/components/properties/shape-with-text/ShapeWithTextControls.vue b/src/components/properties/shape-with-text/ShapeWithTextControls.vue
new file mode 100644
index 000000000..4e554b46c
--- /dev/null
+++ b/src/components/properties/shape-with-text/ShapeWithTextControls.vue
@@ -0,0 +1,154 @@
+<script setup lang="ts">
+import { tv } from 'tailwind-variants'
+import { computed } from 'vue'
+
+import type {
+ FigJamColorName,
+ FigJamFillMode,
+ FigJamLineStyle,
+ FigJamTextSize,
+ FigJamTypeface
+} from '@open-pencil/scene-graph'
+import type { ShapeWithTextType } from '@open-pencil/scene-graph/shape-with-text'
+import { useFigJamMessages, useShapeMessages } from '@open-pencil/vue'
+
+import { SHAPE_KIND_ICONS } from '@/app/editor/shape-icons'
+import FigJamPalette from '@/components/figjam/FigJamPalette.vue'
+import { typefaceModel, useFigJamTextOptions } from '@/components/figjam/text-options'
+import { useShapeKindLabels } from '@/components/shapes/labels'
+import ShapeKindPicker from '@/components/shapes/ShapeKindPicker.vue'
+import IconButton from '@/components/ui/button/IconButton.vue'
+import PanelFieldGroup from '@/components/ui/panel/PanelFieldGroup.vue'
+import AppSelect from '@/components/ui/select/AppSelect.vue'
+import selectTheme from '@/theme/select/app'
+import theme from '@/theme/shape-with-text-controls'
+
+/**
+ * A shape with text's kind, colour, outline and text, as FigJam's selection toolbar sets them:
+ * its palette, closed by no colour, with a see-through fill and a dashed outline as toggles,
+ * and its text sizes and typefaces.
+ */
+const { kind, color, fillMode, lineStyle, lineColor, textSize, typeface, labelFont } = defineProps<{
+ kind: ShapeWithTextType
+ color: FigJamColorName | null
+ fillMode: FigJamFillMode
+ lineStyle: FigJamLineStyle
+ lineColor: FigJamColorName | null
+ textSize: FigJamTextSize | null
+ typeface: FigJamTypeface | null
+ /** The label's font family, which names a face FigJam's typeface menu does not offer. */
+ labelFont?: string
+}>()
+const emit = defineEmits<{
+ 'update:kind': [value: ShapeWithTextType]
+ 'update:color': [value: FigJamColorName]
+ 'update:fillMode': [value: FigJamFillMode]
+ 'update:lineStyle': [value: FigJamLineStyle]
+ 'update:lineColor': [value: FigJamColorName]
+ 'update:textSize': [value: FigJamTextSize]
+ 'update:typeface': [value: FigJamTypeface]
+}>()
+
+const shapes = useShapeMessages()
+const figjam = useFigJamMessages()
+const label = useShapeKindLabels()
+const { sizeOptions, typefaceOptions } = useFigJamTextOptions()
+const styles = tv(theme)()
+const select = tv(selectTheme)()
+
+const selectedSize = computed<FigJamTextSize>({
+ get: () => textSize ?? 'small',
+ set: (value) => emit('update:textSize', value)
+})
+const selectedTypeface = typefaceModel(
+ () => typeface,
+ (value) => emit('update:typeface', value)
+)
+</script>
+
+<template>
+ <div :class="styles.root()">
+ <ShapeKindPicker
+ :heading="shapes.kind"
+ :selected="kind"
+ side="left"
+ align="start"
+ @select="emit('update:kind', $event)"
+ >
+ <template #trigger>
+ <button
+ type="button"
+ aria-haspopup="listbox"
+ data-property="shape-kind"
+ :aria-label="shapes.kind"
+ :class="select.trigger()"
+ >
+ <component :is="SHAPE_KIND_ICONS[kind]" class="mr-1.5 size-4 text-muted" />
+ <span :class="select.value()">{{ label(kind) }}</span>
+ <icon-lucide-chevron-down class="ml-1 size-3 shrink-0 text-muted" />
+ </button>
+ </template>
+ </ShapeKindPicker>
+ <div>
+ <div :class="styles.header()">
+ <span :class="styles.label()">{{ shapes.fill }}</span>
+ <IconButton
+ toggle
+ :label="shapes.fillTransparent"
+ :active="fillMode === 'transparent'"
+ data-property="shape-fill-transparent"
+ @click="emit('update:fillMode', fillMode === 'transparent' ? 'fill' : 'transparent')"
+ >
+ <icon-lucide-contrast class="size-3.5" />
+ </IconButton>
+ </div>
+ <FigJamPalette
+ :label="shapes.fill"
+ :selected="color"
+ :none-label="shapes.fillNone"
+ :none="fillMode === 'none'"
+ @select="emit('update:color', $event)"
+ @none="emit('update:fillMode', 'none')"
+ />
+ </div>
+ <div>
+ <div :class="styles.header()">
+ <span :class="styles.label()">{{ shapes.line }}</span>
+ <IconButton
+ toggle
+ :label="shapes.lineDashed"
+ :active="lineStyle === 'dashed'"
+ data-property="shape-line-dashed"
+ @click="emit('update:lineStyle', lineStyle === 'dashed' ? 'solid' : 'dashed')"
+ >
+ <icon-lucide-circle-dashed class="size-3.5" />
+ </IconButton>
+ </div>
+ <FigJamPalette
+ :label="shapes.line"
+ :selected="lineColor"
+ :none-label="shapes.lineNone"
+ :none="lineStyle === 'none'"
+ @select="emit('update:lineColor', $event)"
+ @none="emit('update:lineStyle', 'none')"
+ />
+ </div>
+ <PanelFieldGroup :label="figjam.textSize">
+ <AppSelect
+ v-model="selectedSize"
+ :label="figjam.textSize"
+ :options="sizeOptions"
+ data-property="shape-text-size"
+ />
+ </PanelFieldGroup>
+ <PanelFieldGroup :label="figjam.typeface">
+ <AppSelect
+ v-model="selectedTypeface"
+ :label="figjam.typeface"
+ :placeholder="labelFont ?? figjam.typeface"
+ :options="typefaceOptions"
+ data-property="shape-typeface"
+ />
+ </PanelFieldGroup>
+ </div>
+</template>
diff --git a/src/components/properties/shape-with-text/ShapeWithTextSection.vue b/src/components/properties/shape-with-text/ShapeWithTextSection.vue
new file mode 100644
index 000000000..46f1e791b
--- /dev/null
+++ b/src/components/properties/shape-with-text/ShapeWithTextSection.vue
@@ -0,0 +1,49 @@
+<script setup lang="ts">
+import { useShapeMessages, useShapeWithText } from '@open-pencil/vue'
+
+import PanelSection from '@/components/ui/panel/PanelSection.vue'
+
+import ShapeWithTextControls from './ShapeWithTextControls.vue'
+
+const shapes = useShapeMessages()
+const {
+ active,
+ kind,
+ color,
+ fillMode,
+ lineStyle,
+ lineColor,
+ textSize,
+ typeface,
+ labelFont,
+ setKind,
+ setColor,
+ setFillMode,
+ setLineStyle,
+ setLineColor,
+ setTextSize,
+ setTypeface
+} = useShapeWithText()
+</script>
+
+<template>
+ <PanelSection v-if="active && kind && fillMode && lineStyle" :label="shapes.kind">
+ <ShapeWithTextControls
+ :kind="kind"
+ :color="color"
+ :fill-mode="fillMode"
+ :line-style="lineStyle"
+ :line-color="lineColor"
+ :text-size="textSize"
+ :typeface="typeface"
+ :label-font="labelFont ?? undefined"
+ @update:kind="setKind"
+ @update:color="setColor"
+ @update:fill-mode="setFillMode"
+ @update:line-style="setLineStyle"
+ @update:line-color="setLineColor"
+ @update:text-size="setTextSize"
+ @update:typeface="setTypeface"
+ />
+ </PanelSection>
+</template>
diff --git a/src/components/properties/sticky/StickyControls.stories.ts b/src/components/properties/sticky/StickyControls.stories.ts
index 0e6371a4f..e4580ccff 100644
--- a/src/components/properties/sticky/StickyControls.stories.ts
+++ b/src/components/properties/sticky/StickyControls.stories.ts
@@ -2,7 +2,7 @@ import type { Meta, StoryObj } from '@storybook/vue3-vite'
import { expect, userEvent, within } from 'storybook/test'
import { ref } from 'vue'
-import { DEFAULT_STICKY_COLOR, type StickyTextSize } from '@open-pencil/scene-graph'
+import { DEFAULT_STICKY_COLOR, type FigJamTextSize } from '@open-pencil/scene-graph'
import type { Color } from '@open-pencil/scene-graph/primitives'
import StickyControls from './StickyControls.vue'
@@ -22,7 +22,7 @@ const meta = {
components: { StickyControls },
setup() {
const color = ref<Color>({ ...DEFAULT_STICKY_COLOR })
- const textSize = ref<StickyTextSize>('small')
+ const textSize = ref<FigJamTextSize>('small')
const authorVisible = ref(true)
return { color, textSize, authorVisible }
},
@@ -32,6 +32,7 @@ const meta = {
:color="color"
:text-size="textSize"
:author-visible="authorVisible"
+ :typeface="null"
@update:color="color = $event"
@update:text-size="textSize = $event"
@update:author-visible="authorVisible = $event"
diff --git a/src/components/properties/sticky/StickyControls.vue b/src/components/properties/sticky/StickyControls.vue
index 4e276efe2..0555f1275 100644
--- a/src/components/properties/sticky/StickyControls.vue
+++ b/src/components/properties/sticky/StickyControls.vue
@@ -2,11 +2,13 @@
import { tv } from 'tailwind-variants'
import { computed } from 'vue'
-import { STICKY_COLORS, type StickyTextSize } from '@open-pencil/scene-graph'
+import { STICKY_COLORS, type FigJamTextSize, type FigJamTypeface } from '@open-pencil/scene-graph'
import { colorToHex } from '@open-pencil/scene-graph/color'
import type { Color } from '@open-pencil/scene-graph/primitives'
-import { useI18n } from '@open-pencil/vue'
+import { useFigJamMessages, useI18n } from '@open-pencil/vue'
+import Swatches from '@/components/figjam/Swatches.vue'
+import { typefaceModel, useFigJamTextOptions } from '@/components/figjam/text-options'
import PanelFieldGroup from '@/components/ui/panel/PanelFieldGroup.vue'
import AppSelect from '@/components/ui/select/AppSelect.vue'
import AppSwitch from '@/components/ui/toggle/AppSwitch.vue'
@@ -14,19 +16,24 @@ import stickyControlsTheme from '@/theme/sticky-controls'
type StickyColorName = keyof typeof STICKY_COLORS
-const { color, textSize, authorVisible } = defineProps<{
+const { color, textSize, authorVisible, typeface, bodyFont } = defineProps<{
color: Color | null
- textSize: StickyTextSize | null
+ textSize: FigJamTextSize | null
authorVisible: boolean
+ typeface: FigJamTypeface | null
+ /** The body's font family, which names a face FigJam's typeface menu does not offer. */
+ bodyFont?: string
}>()
const emit = defineEmits<{
'update:color': [value: Color]
- 'update:textSize': [value: StickyTextSize]
+ 'update:textSize': [value: FigJamTextSize]
'update:authorVisible': [value: boolean]
+ 'update:typeface': [value: FigJamTypeface]
}>()
const { panels } = useI18n()
+const figjam = useFigJamMessages()
const styles = tv(stickyControlsTheme)
const COLOR_LABEL_KEYS = {
@@ -44,54 +51,57 @@ const COLOR_LABEL_KEYS = {
const swatches = computed(() =>
(Object.entries(STICKY_COLORS) as [StickyColorName, Color][]).map(([name, value]) => ({
- name,
- value,
+ value: name,
hex: colorToHex(value),
- label: panels.value[COLOR_LABEL_KEYS[name]],
- active: color !== null && colorToHex(color) === colorToHex(value)
+ label: panels.value[COLOR_LABEL_KEYS[name]]
}))
)
+const selectedColor = computed(
+ () =>
+ swatches.value.find((swatch) => color !== null && swatch.hex === colorToHex(color))?.value ??
+ null
+)
-const sizeOptions = computed<Array<{ value: StickyTextSize; label: string }>>(() => [
- { value: 'small', label: panels.value.stickyTextSmall },
- { value: 'medium', label: panels.value.stickyTextMedium },
- { value: 'large', label: panels.value.stickyTextLarge },
- { value: 'extraLarge', label: panels.value.stickyTextExtraLarge },
- { value: 'huge', label: panels.value.stickyTextHuge }
-])
+const { sizeOptions, typefaceOptions } = useFigJamTextOptions()
-const selectedSize = computed<StickyTextSize>({
+const selectedSize = computed<FigJamTextSize>({
get: () => textSize ?? 'small',
set: (value) => emit('update:textSize', value)
})
+
+const selectedTypeface = typefaceModel(
+ () => typeface,
+ (value) => emit('update:typeface', value)
+)
</script>
<template>
<div :class="styles().root()">
<PanelFieldGroup :label="panels.stickyColor">
- <div :class="styles().swatches()" role="radiogroup" :aria-label="panels.stickyColor">
- <button
- v-for="swatch in swatches"
- :key="swatch.name"
- type="button"
- role="radio"
- :aria-checked="swatch.active"
- :aria-label="swatch.label"
- :data-sticky-color="swatch.name"
- :class="styles({ active: swatch.active }).swatch()"
- :style="{ backgroundColor: swatch.hex }"
- @click="emit('update:color', swatch.value)"
- />
- </div>
+ <Swatches
+ :label="panels.stickyColor"
+ :swatches="swatches"
+ :selected="selectedColor"
+ @select="emit('update:color', STICKY_COLORS[$event])"
+ />
</PanelFieldGroup>
- <PanelFieldGroup :label="panels.stickyTextSize">
+ <PanelFieldGroup :label="figjam.textSize">
<AppSelect
v-model="selectedSize"
- :label="panels.stickyTextSize"
+ :label="figjam.textSize"
:options="sizeOptions"
data-property="sticky-text-size"
/>
</PanelFieldGroup>
+ <PanelFieldGroup :label="figjam.typeface">
+ <AppSelect
+ v-model="selectedTypeface"
+ :label="figjam.typeface"
+ :placeholder="bodyFont ?? figjam.typeface"
+ :options="typefaceOptions"
+ data-property="sticky-typeface"
+ />
+ </PanelFieldGroup>
<label :class="styles().option()">
<span>{{ panels.stickyShowAuthor }}</span>
<AppSwitch
diff --git a/src/components/properties/sticky/StickySection.vue b/src/components/properties/sticky/StickySection.vue
index 386a027a3..3aa8f6152 100644
--- a/src/components/properties/sticky/StickySection.vue
+++ b/src/components/properties/sticky/StickySection.vue
@@ -6,8 +6,18 @@ import PanelSection from '@/components/ui/panel/PanelSection.vue'
import StickyControls from './StickyControls.vue'
const { panels } = useI18n()
-const { active, color, textSize, authorVisible, setColor, setTextSize, setAuthorVisible } =
- useStickyNote()
+const {
+ active,
+ color,
+ textSize,
+ authorVisible,
+ typeface,
+ bodyFont,
+ setColor,
+ setTextSize,
+ setAuthorVisible,
+ setTypeface
+} = useStickyNote()
</script>
<template>
@@ -16,9 +26,12 @@ const { active, color, textSize, authorVisible, setColor, setTextSize, setAuthor
:color="color"
:text-size="textSize"
:author-visible="authorVisible"
+ :typeface="typeface"
+ :body-font="bodyFont ?? undefined"
@update:color="setColor"
@update:text-size="setTextSize"
@update:author-visible="setAuthorVisible"
+ @update:typeface="setTypeface"
/>
</PanelSection>
</template>
diff --git a/src/components/shapes/ShapeKindPicker.stories.ts b/src/components/shapes/ShapeKindPicker.stories.ts
new file mode 100644
index 000000000..ee94d0f28
--- /dev/null
+++ b/src/components/shapes/ShapeKindPicker.stories.ts
@@ -0,0 +1,70 @@
+import type { Meta, StoryObj } from '@storybook/vue3-vite'
+import { expect, userEvent, waitFor, within } from 'storybook/test'
+import { ref } from 'vue'
+
+import type { ShapeWithTextType } from '@open-pencil/scene-graph/shape-with-text'
+
+import { SHAPE_KIND_ICONS } from '@/app/editor/shape-icons'
+
+import ShapeKindPicker from './ShapeKindPicker.vue'
+
+const meta = {
+ title: 'App/Editor/Shapes/Shape Kind Picker',
+ tags: ['autodocs'],
+ parameters: {
+ docs: {
+ description: {
+ component:
+ "FigJam's shape-with-text kinds as a searchable grid of their outlines, Basic then Flowchart, as the Shape tool and the Design panel offer them."
+ }
+ }
+ },
+ render: () => ({
+ components: { ShapeKindPicker },
+ setup() {
+ const kind = ref<ShapeWithTextType>('DIAMOND')
+ return { kind, icons: SHAPE_KIND_ICONS }
+ },
+ template: `
+ <div class="flex h-[520px] items-end justify-center bg-canvas p-4">
+ <ShapeKindPicker heading="Shape" tooltip="Shape" :selected="kind" @select="kind = $event">
+ <template #trigger>
+ <button type="button" aria-label="Shape" class="flex items-center gap-2 rounded-md bg-panel px-2 py-1 text-surface">
+ <component :is="icons[kind]" class="size-5" />
+ <span>{{ kind }}</span>
+ </button>
+ </template>
+ </ShapeKindPicker>
+ </div>`
+ })
+} satisfies Meta
+export default meta
+type Story = StoryObj<typeof meta>
+
+export const Default: Story = {}
+
+async function openPicker(canvasElement: HTMLElement) {
+ const canvas = within(canvasElement)
+ const page = within(canvasElement.ownerDocument.body)
+ await userEvent.click(canvas.getByRole('button', { name: 'Shape' }))
+ return { canvas, page }
+}
+
+export const PickKind: Story = {
+ play: async ({ canvasElement }) => {
+ const { canvas, page } = await openPicker(canvasElement)
+ await expect(await page.findByText('Basic')).toBeVisible()
+ await expect(page.getByText('Flowchart')).toBeVisible()
+ await userEvent.click(page.getByRole('option', { name: 'Cylinder' }))
+ await waitFor(() => expect(canvas.getByText('ENG_DATABASE')).toBeVisible())
+ }
+}
+
+export const Search: Story = {
+ play: async ({ canvasElement }) => {
+ const { page } = await openPicker(canvasElement)
+ await userEvent.keyboard('hexa')
+ await waitFor(() => expect(page.queryByRole('option', { name: 'Square' })).toBeNull())
+ await expect(page.getByRole('option', { name: 'Hexagon' })).toBeVisible()
+ }
+}
diff --git a/src/components/shapes/ShapeKindPicker.vue b/src/components/shapes/ShapeKindPicker.vue
new file mode 100644
index 000000000..e36c3c55c
--- /dev/null
+++ b/src/components/shapes/ShapeKindPicker.vue
@@ -0,0 +1,90 @@
+<script setup lang="ts">
+import { computed } from 'vue'
+
+import {
+ SHAPE_WITH_TEXT_GROUPS,
+ isShapeWithTextType,
+ type ShapeWithTextType
+} from '@open-pencil/scene-graph/shape-with-text'
+import { useCommonMessages, useShapeMessages } from '@open-pencil/vue'
+
+import { SHAPE_KIND_ICONS } from '@/app/editor/shape-icons'
+import AppPicker from '@/components/ui/select/AppPicker.vue'
+import type { AppPickerItem } from '@/components/ui/select/AppPicker.vue'
+
+import { useShapeKindLabels } from './labels'
+
+/**
+ * FigJam's shape kinds as a searchable grid of their outlines, Basic then Flowchart, as its
+ * Shapes panel offers them.
+ */
+const {
+ heading,
+ selected,
+ tooltip,
+ side = 'top',
+ align = 'center'
+} = defineProps<{
+ heading: string
+ selected?: ShapeWithTextType
+ tooltip?: string
+ side?: 'left' | 'right' | 'top' | 'bottom'
+ align?: 'start' | 'center' | 'end'
+}>()
+const emit = defineEmits<{ select: [kind: ShapeWithTextType] }>()
+const open = defineModel<boolean>('open', { default: false })
+defineSlots<{ trigger(): unknown }>()
+
+const shapes = useShapeMessages()
+const common = useCommonMessages()
+const label = useShapeKindLabels()
+
+const items = computed<AppPickerItem[]>(() =>
+ (['basic', 'flowchart'] as const).flatMap((group) =>
+ SHAPE_WITH_TEXT_GROUPS[group].map((kind) => ({
+ value: kind,
+ label: label.value(kind),
+ group: shapes.value[group]
+ }))
+ )
+)
+
+function pick(value: string) {
+ if (isShapeWithTextType(value)) emit('select', value)
+}
+</script>
+
+<template>
+ <AppPicker
+ v-model:open="open"
+ layout="grid"
+ :heading="heading"
+ :items="items"
+ :selected="selected"
+ :tooltip="tooltip"
+ :side="side"
+ :align="align"
+ :search-placeholder="shapes.search"
+ :empty-label="shapes.noResults"
+ :close-label="common.close"
+ @select="pick"
+ >
+ <template #trigger>
+ <slot name="trigger" />
+ </template>
+ <template #leading="{ item }">
+ <component
+ :is="SHAPE_KIND_ICONS[item.value]"
+ v-if="isShapeWithTextType(item.value)"
+ class="size-5"
+ />
+ </template>
+ <template #footer="{ highlighted }">
+ <p class="flex h-5 items-center truncate px-1 text-[11px] text-muted">
+ <span class="truncate" :class="highlighted && 'text-surface'">
+ {{ highlighted?.label ?? label(selected ?? 'SQUARE') }}
+ </span>
+ </p>
+ </template>
+ </AppPicker>
+</template>
diff --git a/src/components/shapes/labels.ts b/src/components/shapes/labels.ts
new file mode 100644
index 000000000..a26e13e3d
--- /dev/null
+++ b/src/components/shapes/labels.ts
@@ -0,0 +1,46 @@
+import { computed } from 'vue'
+
+import type { ShapeWithTextType } from '@open-pencil/scene-graph/shape-with-text'
+import { useShapeMessages } from '@open-pencil/vue'
+
+type ShapeMessages = ReturnType<typeof useShapeMessages>['value']
+
+/** Each kind's name as FigJam's Shapes panel gives it. */
+const KIND_LABEL_KEYS = {
+ SQUARE: 'square',
+ ELLIPSE: 'ellipse',
+ DIAMOND: 'diamond',
+ TRIANGLE_UP: 'triangleUp',
+ TRIANGLE_DOWN: 'triangleDown',
+ ROUNDED_RECTANGLE: 'roundedRectangle',
+ PARALLELOGRAM_RIGHT: 'parallelogramRight',
+ PARALLELOGRAM_LEFT: 'parallelogramLeft',
+ ENG_DATABASE: 'engDatabase',
+ ENG_QUEUE: 'engQueue',
+ ENG_FILE: 'engFile',
+ ENG_FOLDER: 'engFolder',
+ TRAPEZOID: 'trapezoid',
+ PREDEFINED_PROCESS: 'predefinedProcess',
+ SHIELD: 'shield',
+ DOCUMENT_SINGLE: 'documentSingle',
+ DOCUMENT_MULTIPLE: 'documentMultiple',
+ MANUAL_INPUT: 'manualInput',
+ HEXAGON: 'hexagon',
+ CHEVRON: 'chevron',
+ PENTAGON: 'pentagon',
+ OCTAGON: 'octagon',
+ STAR: 'star',
+ PLUS: 'plus',
+ ARROW_LEFT: 'arrowLeft',
+ ARROW_RIGHT: 'arrowRight',
+ SUMMING_JUNCTION: 'summingJunction',
+ OR: 'or',
+ SPEECH_BUBBLE: 'speechBubble',
+ INTERNAL_STORAGE: 'internalStorage'
+} as const satisfies Record<ShapeWithTextType, keyof ShapeMessages>
+
+/** Each kind's name in the interface language. */
+export function useShapeKindLabels() {
+ const shapes = useShapeMessages()
+ return computed(() => (kind: ShapeWithTextType) => shapes.value[KIND_LABEL_KEYS[kind]])
+}
diff --git a/src/components/toolbar/DesktopToolbar.vue b/src/components/toolbar/DesktopToolbar.vue
index 6b861937b..ffd08007e 100644
--- a/src/components/toolbar/DesktopToolbar.vue
+++ b/src/components/toolbar/DesktopToolbar.vue
@@ -12,6 +12,7 @@ import type { Tool } from '@open-pencil/vue'
import type { ToolbarAction, ToolbarItem as ToolbarLayoutItem } from '@/app/editor/toolbar/layout'
import { toolTip } from '@/app/editor/toolbar/shortcuts'
+import ShapeToolButton from '@/components/toolbar/ShapeToolButton.vue'
import ToolButton from '@/components/toolbar/ToolButton.vue'
import ToolFlyout from '@/components/toolbar/ToolFlyout.vue'
import type { ToolbarUI, ToolIconMap, ToolLabels } from '@/components/toolbar/types'
@@ -55,6 +56,8 @@ defineSlots<{
<template v-for="item in items" :key="item.kind === 'tool' ? item.tool.key : item.action">
<slot v-if="item.kind === 'action'" name="action" :action="item.action" />
+ <ShapeToolButton v-else-if="item.tool.key === 'SHAPE_WITH_TEXT'" :ui="ui" />
+
<Tip
v-else-if="item.tool.flyout"
:label="
diff --git a/src/components/toolbar/MobileToolbar.vue b/src/components/toolbar/MobileToolbar.vue
index a32086ee5..3d5e2b4f5 100644
--- a/src/components/toolbar/MobileToolbar.vue
+++ b/src/components/toolbar/MobileToolbar.vue
@@ -11,6 +11,7 @@ import type { Tool } from '@open-pencil/vue'
import { animationsEnabled } from '@/app/shell/motion'
import { useMotionTransitions } from '@/app/shell/motion/transitions'
+import ShapeToolButton from '@/components/toolbar/ShapeToolButton.vue'
import ToolbarActionGroup from '@/components/toolbar/ToolbarActionGroup.vue'
import ToolButton from '@/components/toolbar/ToolButton.vue'
import ToolFlyout from '@/components/toolbar/ToolFlyout.vue'
@@ -117,8 +118,10 @@ function navigationClass(disabled: boolean) {
:transition="itemTransition"
>
<template v-for="tool in tools" :key="tool.key">
+ <ShapeToolButton v-if="tool.key === 'SHAPE_WITH_TEXT'" mobile :ui="ui" />
+
<ToolFlyout
- v-if="tool.flyout"
+ v-else-if="tool.flyout"
mobile
:tool="tool"
:active-tool="activeTool"
diff --git a/src/components/toolbar/ShapeToolButton.vue b/src/components/toolbar/ShapeToolButton.vue
new file mode 100644
index 000000000..02c29aac6
--- /dev/null
+++ b/src/components/toolbar/ShapeToolButton.vue
@@ -0,0 +1,46 @@
+<script setup lang="ts">
+import { ref } from 'vue'
+
+import type { ShapeWithTextType } from '@open-pencil/scene-graph/shape-with-text'
+import { toolbarToolTestId, useShapeWithText, useToolMessages } from '@open-pencil/vue'
+
+import { SHAPE_KIND_ICONS } from '@/app/editor/shape-icons'
+import ShapeKindPicker from '@/components/shapes/ShapeKindPicker.vue'
+import ToolButton from '@/components/toolbar/ToolButton.vue'
+import type { ToolbarUI } from '@/components/toolbar/types'
+
+/**
+ * The shape-with-text tool: its button draws the kind picked last and opens the kinds to pick
+ * from, and picking one arms the tool, as FigJam's Shapes panel does.
+ */
+const { ui, mobile = false } = defineProps<{ ui?: ToolbarUI; mobile?: boolean }>()
+const tools = useToolMessages()
+const { toolKind, toolActive, drawKind } = useShapeWithText()
+const open = ref(false)
+
+function pick(kind: ShapeWithTextType) {
+ drawKind(kind)
+ open.value = false
+}
+</script>
+
+<template>
+ <ShapeKindPicker
+ v-model:open="open"
+ :heading="tools.shape"
+ :tooltip="tools.shape"
+ :selected="toolKind"
+ @select="pick"
+ >
+ <template #trigger>
+ <ToolButton
+ :data-test-id="toolbarToolTestId('SHAPE_WITH_TEXT', mobile)"
+ :icon="SHAPE_KIND_ICONS[toolKind]"
+ :label="tools.shape"
+ :active="toolActive || open"
+ :mobile="mobile"
+ :ui="ui"
+ />
+ </template>
+ </ShapeKindPicker>
+</template>
diff --git a/src/components/toolbar/labels.ts b/src/components/toolbar/labels.ts
index da7d946a9..86ba042d9 100644
--- a/src/components/toolbar/labels.ts
+++ b/src/components/toolbar/labels.ts
@@ -22,6 +22,7 @@ export function useToolLabels() {
PENCIL: tools.value.pencil,
TEXT: tools.value.text,
STICKY: tools.value.sticky,
+ SHAPE_WITH_TEXT: tools.value.shape,
CONNECTOR: tools.value.connector,
HAND: tools.value.hand,
COMMENT: tools.value.comment
diff --git a/src/theme/figjam/swatches.ts b/src/theme/figjam/swatches.ts
new file mode 100644
index 000000000..87e60e1ca
--- /dev/null
+++ b/src/theme/figjam/swatches.ts
@@ -0,0 +1,20 @@
+const swatchesTheme = {
+ slots: {
+ root: 'grid grid-cols-11 justify-items-center gap-[3px]',
+ swatch:
+ 'size-4 cursor-pointer rounded-full border border-border focus-visible:ring-2 focus-visible:ring-accent/50 focus-visible:outline-none',
+ none: 'flex items-center justify-center bg-transparent text-muted'
+ },
+ variants: {
+ active: {
+ true: { swatch: 'ring-2 ring-accent ring-offset-1 ring-offset-panel' },
+ false: { swatch: 'hover:border-muted' }
+ }
+ },
+ defaultVariants: {
+ active: false
+ }
+}
+
+export type SwatchesTheme = typeof swatchesTheme
+export default swatchesTheme
diff --git a/src/theme/shape-with-text-controls.ts b/src/theme/shape-with-text-controls.ts
new file mode 100644
index 000000000..76a1d88f6
--- /dev/null
+++ b/src/theme/shape-with-text-controls.ts
@@ -0,0 +1,10 @@
+const shapeWithTextControlsTheme = {
+ slots: {
+ root: 'grid gap-3',
+ header: 'mb-1 flex items-center justify-between',
+ label: 'text-[11px] text-muted'
+ }
+}
+
+export type ShapeWithTextControlsTheme = typeof shapeWithTextControlsTheme
+export default shapeWithTextControlsTheme
diff --git a/src/theme/sticky-controls.ts b/src/theme/sticky-controls.ts
index 5cff26292..d19c5c43a 100644
--- a/src/theme/sticky-controls.ts
+++ b/src/theme/sticky-controls.ts
@@ -1,19 +1,7 @@
const stickyControlsTheme = {
slots: {
root: 'grid gap-2.5',
- swatches: 'flex flex-wrap gap-1',
- swatch:
- 'size-[18px] cursor-pointer rounded-full border border-border focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/50',
option: 'flex items-center justify-between gap-1.5 text-[11px] text-muted'
- },
- variants: {
- active: {
- true: { swatch: 'ring-2 ring-accent ring-offset-1 ring-offset-panel' },
- false: { swatch: 'hover:border-muted' }
- }
- },
- defaultVariants: {
- active: false
}
}
diff --git a/tests/app/editor/toolbar/layout.test.ts b/tests/app/editor/toolbar/layout.test.ts
index 09dcc6f5e..188fc84b1 100644
--- a/tests/app/editor/toolbar/layout.test.ts
+++ b/tests/app/editor/toolbar/layout.test.ts
@@ -37,8 +37,8 @@ describe('normalizeToolbarLayout', () => {
const groups = [['SELECT', 'LASSO', 'SELECT'], [], ['FRAME', 'SECTION', 'FRAME']]
const result = normalizeToolbarLayout(groups, ['HAND', 'HAND', 'GHOST'])
expect(result.groups.slice(0, 2)).toEqual([['SELECT'], ['FRAME', 'SECTION']])
- // The sticky and connector tools are placed hidden, as the default layout keeps them.
- expect(result.hidden).toEqual(['HAND', 'STICKY', 'CONNECTOR'])
+ // The sticky, shape and connector tools are placed hidden, as the default layout keeps them.
+ expect(result.hidden).toEqual(['HAND', 'STICKY', 'SHAPE_WITH_TEXT', 'CONNECTOR'])
})
test('never hides Move', () => {
@@ -47,8 +47,9 @@ describe('normalizeToolbarLayout', () => {
test('keeps commands out of flyouts', () => {
const result = layout([['SELECT', 'insert-icon', 'HAND'], ['COMMENT']])
- expect(result.groups.slice(-5)).toEqual([
+ expect(result.groups.slice(-6)).toEqual([
['STICKY'],
+ ['SHAPE_WITH_TEXT'],
['CONNECTOR'],
['insert-icon'],
['HAND'],
@@ -67,6 +68,7 @@ describe('normalizeToolbarLayout', () => {
expect(layout(stored).groups).toEqual([
['TEXT'],
['STICKY'],
+ ['SHAPE_WITH_TEXT'],
['CONNECTOR'],
['SELECT'],
['FRAME', 'SECTION'],
diff --git a/tests/e2e/canvas/shape-with-text-visual.spec.ts b/tests/e2e/canvas/shape-with-text-visual.spec.ts
new file mode 100644
index 000000000..ec4170f25
--- /dev/null
+++ b/tests/e2e/canvas/shape-with-text-visual.spec.ts
@@ -0,0 +1,65 @@
+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'
+import {
+ shapeWithTextDriver,
+ type ShapeWithTextSetup
+} from '#tests/helpers/canvas/shape-with-text-driver'
+
+const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')
+const shapes = shapeWithTextDriver(() => editor.page)
+
+const KINDS = [
+ ['SQUARE', 'Process'],
+ ['DIAMOND', 'Paid?'],
+ ['ENG_DATABASE', 'Orders'],
+ ['DOCUMENT_MULTIPLE', 'Invoices'],
+ ['ELLIPSE', 'Start'],
+ ['PARALLELOGRAM_RIGHT', 'Read input'],
+ ['ARROW_RIGHT', 'Next'],
+ ['SPEECH_BUBBLE', 'Hello']
+] as const
+
+test('shapes with text draw their kind with the label inside', async () => {
+ await shapes.place(
+ KINDS.map(([kind, label], index): ShapeWithTextSetup => ({
+ kind,
+ label,
+ x: 40 + (index % 4) * 170,
+ y: 40 + Math.floor(index / 4) * 140,
+ width: 150,
+ height: 110,
+ fill: [0.86, 0.92, 1],
+ stroke: [0.1, 0.12, 0.2],
+ labelColor: [0.75, 0.1, 0.1]
+ }))
+ )
+ await editor.canvas.waitForRender()
+ editor.canvas.assertNoErrors()
+ expect(await editor.canvas.screenshotCanvasRegion()).toMatchSnapshot('shapes-with-text.png')
+})
+
+const STROKED = ['ELLIPSE', 'ROUNDED_RECTANGLE', 'SHIELD', 'ENG_DATABASE'] as const
+
+test('inside and outside strokes follow the outline, and inner lines keep their weight', async () => {
+ await shapes.place(
+ (['INSIDE', 'OUTSIDE'] as const).flatMap((strokeAlign, row) =>
+ STROKED.map((kind, index): ShapeWithTextSetup => ({
+ kind,
+ label: '',
+ x: 40 + index * 170,
+ y: 40 + row * 170,
+ width: 130,
+ height: 130,
+ fill: [0.86, 0.92, 1],
+ stroke: [0.1, 0.12, 0.2],
+ labelColor: [0.1, 0.12, 0.2],
+ strokeAlign,
+ strokeWeight: 6
+ }))
+ )
+ )
+ await editor.canvas.waitForRender()
+ editor.canvas.assertNoErrors()
+ expect(await editor.canvas.screenshotCanvasRegion()).toMatchSnapshot(
+ 'shapes-with-text-aligned-strokes.png'
+ )
+})
diff --git a/tests/e2e/canvas/shape-with-text-visual.spec.ts-snapshots/shapes-with-text-aligned-strokes-openpencil-darwin.png b/tests/e2e/canvas/shape-with-text-visual.spec.ts-snapshots/shapes-with-text-aligned-strokes-openpencil-darwin.png
new file mode 100644
index 000000000..17fee42cf
Binary files /dev/null and b/tests/e2e/canvas/shape-with-text-visual.spec.ts-snapshots/shapes-with-text-aligned-strokes-openpencil-darwin.png differ
diff --git a/tests/e2e/canvas/shape-with-text-visual.spec.ts-snapshots/shapes-with-text-openpencil-darwin.png b/tests/e2e/canvas/shape-with-text-visual.spec.ts-snapshots/shapes-with-text-openpencil-darwin.png
new file mode 100644
index 000000000..1463e98d4
Binary files /dev/null and b/tests/e2e/canvas/shape-with-text-visual.spec.ts-snapshots/shapes-with-text-openpencil-darwin.png differ
diff --git a/tests/e2e/tools/shape-with-text.spec.ts b/tests/e2e/tools/shape-with-text.spec.ts
new file mode 100644
index 000000000..c0d00a6fa
--- /dev/null
+++ b/tests/e2e/tools/shape-with-text.spec.ts
@@ -0,0 +1,144 @@
+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 { toolbarToolTestId } from '#tests/helpers/test-ids'
+
+const editor = useEditorSetupWithClear()
+const shapes = shapeWithTextDriver(() => editor.page)
+
+test.beforeEach(async () => {
+ await editor.page.keyboard.press('Escape')
+ await shapes.showOrigin()
+})
+
+async function lastShape() {
+ const shape = (await shapes.shapes()).at(-1)
+ if (!shape) throw new Error('Missing shape with text')
+ return shape
+}
+
+async function clickAt(x: number, y: number) {
+ const point = shapes.point(x, y)
+ await editor.canvas.click(point.x, point.y)
+ await editor.canvas.waitForRender()
+}
+
+async function dragFrom(from: Vector, to: Vector) {
+ const box = await editor.canvas.canvas.boundingBox()
+ if (!box) throw new Error('Missing canvas')
+ const start = shapes.point(from.x, from.y)
+ const end = shapes.point(to.x, to.y)
+ await editor.page.mouse.move(box.x + start.x, box.y + start.y)
+ await editor.page.mouse.down()
+ await editor.page.mouse.move(box.x + end.x, box.y + end.y, { steps: 6 })
+ await editor.page.mouse.up()
+ await editor.canvas.waitForRender()
+}
+
+test('the toolbar keeps the shape tool hidden', async () => {
+ await expect(editor.page.getByTestId(toolbarToolTestId('SHAPE_WITH_TEXT'))).toHaveCount(0)
+})
+
+test('a picked kind is placed by a click, as FigJam places it, with its label to type into', async () => {
+ await shapes.showTool()
+ await shapes.pickKind('Diamond')
+ expect((await shapes.focus()).tool).toBe('SHAPE_WITH_TEXT')
+ await clickAt(300, 200)
+ const placed = await lastShape()
+ expect(placed).toMatchObject({
+ kind: 'DIAMOND',
+ x: 300,
+ y: 200,
+ width: 176,
+ height: 176,
+ fill: '#ffffff',
+ stroke: '#757575',
+ strokeWeight: 4,
+ label: { text: '', fontSize: 16 }
+ })
+ expect(await shapes.focus()).toMatchObject({ tool: 'SELECT', selected: [placed.id] })
+ expect((await shapes.focus()).editing).not.toBeNull()
+
+ await editor.page.keyboard.type('Valid?')
+ await editor.page.keyboard.press('Escape')
+ await editor.canvas.waitForRender()
+ expect(await lastShape()).toMatchObject({ name: 'Valid?', label: { text: 'Valid?' } })
+})
+
+test('the tool keeps the kind picked last, and a drag draws the shape as large as the drag', async () => {
+ await shapes.showTool()
+ await shapes.pickKind('Cylinder')
+ await clickAt(100, 100)
+ await editor.page.keyboard.press('Escape')
+ await editor.page.keyboard.press('Escape')
+ const before = (await shapes.shapes()).length
+
+ await editor.page.getByTestId(toolbarToolTestId('SHAPE_WITH_TEXT')).click()
+ const cylinder = editor.page.getByRole('option', { name: 'Cylinder', exact: true })
+ await expect(cylinder).toHaveAttribute('data-selected', 'true')
+ await cylinder.click()
+ await dragFrom({ x: 400, y: 100 }, { x: 640, y: 260 })
+ expect(await lastShape()).toMatchObject({
+ kind: 'ENG_DATABASE',
+ x: 400,
+ y: 100,
+ width: 240,
+ height: 160
+ })
+ await editor.page.keyboard.press('Escape')
+ // Drawing it was one step.
+ await editor.page.keyboard.press('ControlOrMeta+z')
+ await editor.canvas.waitForRender()
+ expect(await shapes.shapes()).toHaveLength(before)
+})
+
+test('the properties panel switches a shape to another kind, keeping its size', async () => {
+ await shapes.showTool()
+ await shapes.pickKind('Square')
+ await clickAt(200, 200)
+ await editor.page.keyboard.press('Escape')
+ await editor.page.locator('[data-property="shape-kind"]').click()
+ await editor.page.getByRole('option', { name: 'Hexagon', exact: true }).click()
+ await editor.canvas.waitForRender()
+ expect(await lastShape()).toMatchObject({ kind: 'HEXAGON', width: 176, height: 176 })
+
+ await editor.page.keyboard.press('ControlOrMeta+z')
+ await editor.canvas.waitForRender()
+ expect((await lastShape()).kind).toBe('SQUARE')
+})
+
+test("the properties panel paints a shape with FigJam's palette and sizes its text", 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')
+
+ const fill = editor.page.getByRole('radiogroup', { name: 'Fill' })
+ await fill.getByRole('radio', { name: 'Violet', exact: true }).click()
+ await expect(fill.getByRole('radio', { name: 'Violet', exact: true })).toHaveAttribute(
+ 'aria-checked',
+ 'true'
+ )
+ expect(await lastShape()).toMatchObject({ fill: '#874fff', stroke: '#5427b4' })
+
+ const dashed = editor.page.locator('[data-property="shape-line-dashed"]')
+ await dashed.click()
+ await expect(dashed).toHaveAttribute('aria-pressed', 'true')
+ const noFill = editor.page
+ .getByRole('radiogroup', { name: 'Fill' })
+ .getByRole('radio', { name: 'None', exact: true })
+ await noFill.click()
+ await expect(noFill).toHaveAttribute('aria-checked', 'true')
+ await fill.getByRole('radio', { name: 'Violet', exact: true }).click()
+ expect(await lastShape()).toMatchObject({ fill: '#874fff' })
+
+ await editor.page.locator('[data-property="shape-text-size"]').click()
+ await editor.page.getByRole('option', { name: 'Huge', exact: true }).click()
+ await editor.canvas.waitForRender()
+ await expect(editor.page.locator('[data-property="shape-text-size"]')).toContainText('Huge')
+ const huge = await lastShape()
+ expect(huge.label?.fontSize).toBe(96)
+ expect(huge.height).toBeGreaterThan(176)
+})
diff --git a/tests/helpers/canvas/shape-with-text-driver.ts b/tests/helpers/canvas/shape-with-text-driver.ts
new file mode 100644
index 000000000..366a1567a
--- /dev/null
+++ b/tests/helpers/canvas/shape-with-text-driver.ts
@@ -0,0 +1,172 @@
+import { expect, type Page } from '@playwright/test'
+
+import type { ShapeWithTextType } from '@open-pencil/scene-graph/shape-with-text'
+
+import { toolbarToolTestId } from '#tests/helpers/test-ids'
+
+/** The canvas point the page's origin is shown at, at 100%. */
+const ORIGIN = 100
+
+type RGB = readonly [number, number, number]
+
+export interface ShapeWithTextSetup {
+ kind: ShapeWithTextType
+ label: string
+ x: number
+ y: number
+ width: number
+ height: number
+ fill: RGB
+ stroke: RGB
+ /** The label's own colour, kept on the label layer as FigJam keeps it. */
+ labelColor: RGB
+ /** Where the stroke sits on the outline; centred unless set. */
+ strokeAlign?: 'INSIDE' | 'CENTER' | 'OUTSIDE'
+ strokeWeight?: number
+}
+
+export interface ShapeWithTextState {
+ id: string
+ name: string
+ kind: ShapeWithTextType
+ x: number
+ y: number
+ width: number
+ height: number
+ fill: string
+ stroke: string
+ strokeWeight: number
+ label: { text: string; fontSize: number } | null
+}
+
+/** Places shapes with text as the editor draws them, each with its label laid out inside. */
+export function shapeWithTextDriver(page: () => Page) {
+ return {
+ place(shapes: readonly ShapeWithTextSetup[]) {
+ return page().evaluate((setups) => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ const solid = ([r, g, b]: readonly [number, number, number]) => ({
+ type: 'SOLID' as const,
+ color: { r, g, b, a: 1 },
+ visible: true,
+ opacity: 1
+ })
+ for (const shape of setups) {
+ const id = store.createShape(
+ 'SHAPE_WITH_TEXT',
+ shape.x,
+ shape.y,
+ shape.width,
+ shape.height
+ )
+ store.graph.updateNode(id, {
+ name: shape.label,
+ shapeWithTextType: shape.kind,
+ fills: [solid(shape.fill)],
+ strokes: [
+ {
+ ...solid(shape.stroke),
+ weight: shape.strokeWeight ?? 2,
+ align: shape.strokeAlign ?? 'CENTER'
+ }
+ ]
+ })
+ const [label] = store.graph.getChildren(id)
+ store.graph.updateNode(label.id, { text: shape.label, fills: [solid(shape.labelColor)] })
+ store.runLayoutForNode(id)
+ }
+ store.clearSelection()
+ store.requestRender()
+ }, shapes)
+ },
+
+ /** Setup: shows the page's origin at a known canvas point. */
+ showOrigin() {
+ return page().evaluate((origin) => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ store.state.zoom = 1
+ store.state.panX = origin
+ store.state.panY = origin
+ store.requestRender()
+ }, ORIGIN)
+ },
+
+ /** Canvas coordinates of a page point, under `showOrigin`. */
+ point(x: number, y: number) {
+ return { x: ORIGIN + x, y: ORIGIN + y }
+ },
+
+ /** Probe: the page's shapes with text, the last placed last. */
+ shapes(): Promise<ShapeWithTextState[]> {
+ return page().evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ const hex = (paint?: { color: { r: number; g: number; b: number } }) =>
+ paint
+ ? '#' +
+ [paint.color.r, paint.color.g, paint.color.b]
+ .map((value) =>
+ Math.round(value * 255)
+ .toString(16)
+ .padStart(2, '0')
+ )
+ .join('')
+ : ''
+ return store.graph
+ .getChildren(store.state.currentPageId)
+ .filter((node) => node.type === 'SHAPE_WITH_TEXT')
+ .map((node) => {
+ const [label] = store.graph.getChildren(node.id)
+ return {
+ id: node.id,
+ name: node.name,
+ kind: node.shapeWithTextType,
+ x: node.x,
+ y: node.y,
+ width: node.width,
+ height: node.height,
+ 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
+ }
+ })
+ })
+ },
+
+ /** Probe: the active tool, the selection, and the text being typed into. */
+ focus() {
+ return page().evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ return {
+ tool: store.state.activeTool,
+ selected: [...store.state.selectedIds],
+ editing: store.state.editingTextId
+ }
+ })
+ },
+
+ /** Setup: shows the shape tool, which the toolbar keeps hidden, from Customize toolbar. */
+ async showTool() {
+ const button = page().getByTestId(toolbarToolTestId('SHAPE_WITH_TEXT'))
+ if ((await button.count()) > 0) return
+ await page().getByTestId('toolbar').click({ button: 'right' })
+ await page().getByRole('menuitem', { name: 'Customize toolbar…' }).click()
+ await page()
+ .getByTestId('settings-toolbar-panel')
+ .getByRole('switch', { name: 'Show Shape', exact: true })
+ .click()
+ await page().getByTestId('app-settings-done').click()
+ await expect(button).toBeVisible()
+ },
+
+ /** Driver: opens the shape tool's kinds and picks one by its name. */
+ async pickKind(name: string) {
+ await page().getByTestId(toolbarToolTestId('SHAPE_WITH_TEXT')).click()
+ await page().getByRole('option', { name, exact: true }).click()
+ }
+ }
+}
diff --git a/tools/checks/i18n/translation-baseline.txt b/tools/checks/i18n/translation-baseline.txt
index 6965359dd..3484b232c 100644
--- a/tools/checks/i18n/translation-baseline.txt
+++ b/tools/checks/i18n/translation-baseline.txt
@@ -453,6 +453,7 @@ it:cloud.roleEditor
it:cloud.homeAccount
it:cloud.homeCloudOnHost
it:cloud.settingsTitle
+it:shapes.engFile
ja:cloud.productName
ja:cloud.homeCloudOnHost
ja:cloud.inviteEmailPlaceholder
@@ -465,11 +466,27 @@ de:cloud.saveName
de:cloud.homeCloudOnHost
de:cloud.inviteEmailPlaceholder
de:cloud.settingsTitle
+de:shapes.ellipse
+de:shapes.plus
+de:shapes.chevron
+de:shapes.fillTransparent
+de:figjam.colorOrange
fr:cloud.productName
fr:cloud.homeCloudOnHost
fr:cloud.settingsTitle
+fr:shapes.ellipse
+fr:shapes.triangleUp
+fr:shapes.plus
+fr:shapes.chevron
+fr:shapes.documentSingle
+fr:shapes.fillTransparent
+fr:figjam.typefaceSimple
+fr:figjam.colorOrange
+fr:figjam.colorViolet
pl:cloud.productName
pl:cloud.homeCloudOnHost
+pl:shapes.plus
+pl:shapes.engFolder
ru:cloud.productName
ru:cloud.homeCloudOnHost
ru:cloud.inviteEmailPlaceholder