Skip to content

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

feat!: match Outline stroke to Figma and exported SVG strokes and text to the canvas (#1527)

Danila Poyarkov509b893be962
diff --git a/changes/1527/breaking.md b/changes/1527/breaking.md
new file mode 100644
index 000000000..b73b717ae
--- /dev/null
+++ b/changes/1527/breaking.md
@@ -0,0 +1 @@
+- `@open-pencil/core/canvas` replaces `outlineStrokeNodesToVectorProps` and `hasVisibleStrokeSourceNode` with `outlineStrokeLayer` and `layersToOutline`, and the editor's `copySelectionAsSVG` returns a promise.
diff --git a/changes/1527/changed.md b/changes/1527/changed.md
new file mode 100644
index 000000000..86d8eeff2
--- /dev/null
+++ b/changes/1527/changed.md
@@ -0,0 +1 @@
+- Outline stroke works as in Figma: each stroked layer is replaced by its fill and, above it, its stroke filled with the stroke's paints where the stroke is drawn, both keeping the layer's rotation, opacity, and effects; inside a selected group or frame each stroked layer is outlined in place, and stroked text becomes groups of glyph outlines (#1524).
diff --git a/changes/1527/fixed.md b/changes/1527/fixed.md
new file mode 100644
index 000000000..dc1a33751
--- /dev/null
+++ b/changes/1527/fixed.md
@@ -0,0 +1 @@
+- SVG and PDF exports keep inside and outside strokes on their side of the outline, and SVG export sets text on the lines and baselines the canvas draws, wrapped paragraphs included (#1520, #1521).
diff --git a/packages/core/src/canvas/boolean.ts b/packages/core/src/canvas/boolean.ts
index 6266717f7..721ce5cd4 100644
--- a/packages/core/src/canvas/boolean.ts
+++ b/packages/core/src/canvas/boolean.ts
@@ -1,6 +1,6 @@
import type { Canvas, Path, PathBuilder, PathOp } from 'canvaskit-wasm'
-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import type { SceneGraph, SceneNode, Stroke } from '@open-pencil/scene-graph'
import type { GroupFitOptions } from '@open-pencil/scene-graph/group-bounds'
import { getTextOutlineSupport } from '#core/text/outlines'
@@ -62,13 +62,14 @@ export function canMakeBooleanSourceNode(node: SceneNode, graph: SceneGraph): bo
})
}
-function baseShapePath(r: SkiaRenderer, node: SceneNode): Path | null {
+/** A layer's shape in its own box: its outline, a line's stroke, or text's glyph outlines. */
+export function baseShapePath(r: SkiaRenderer, node: SceneNode): Path | null {
if (node.type === 'TEXT') return textNodeToOutlinePath(r, node)
if (node.type === 'LINE') return makeLineStrokeOutline(r, node)
return r.makeNodeShapePath(node)
}
-function nodeHasVisibleFill(node: SceneNode): boolean {
+export function nodeHasVisibleFill(node: SceneNode): boolean {
return node.fills.some((fill) => fill.visible)
}
@@ -76,17 +77,50 @@ export function nodeHasVisibleStroke(node: SceneNode): boolean {
return node.strokes.some((stroke) => stroke.visible && stroke.weight > 0)
}
-function addVisibleStrokeOutlines(target: PathBuilder, source: Path, node: SceneNode): void {
+/**
+ * The area a stroke paints along `source`, as the canvas draws it: centred on the path, or, on a
+ * layer whose outline it keeps to, twice its weight cut to inside or outside the outline. Vectors
+ * stroke their paths centred whatever the alignment, as the canvas draws them.
+ */
+function strokeArea(r: SkiaRenderer, source: Path, node: SceneNode, stroke: Stroke): Path | null {
+ const aligned = stroke.align !== 'CENTER' && node.type !== 'VECTOR'
+ const outline = source.makeStroked({ width: aligned ? stroke.weight * 2 : stroke.weight })
+ if (!outline || !aligned) return outline
+ const op = stroke.align === 'INSIDE' ? r.ck.PathOp.Intersect : r.ck.PathOp.Difference
+ const area = r.ck.Path.MakeFromOp(outline, source, op)
+ outline.delete()
+ // An op's result fills even-odd; turned to non-zero, it keeps its holes when added to others.
+ const winding = area?.makeAsWinding() ?? null
+ area?.delete()
+ return winding
+}
+
+/** The area every visible stroke of `node` paints along `source`, or null when none paints. */
+export function strokeAreaPath(r: SkiaRenderer, source: Path, node: SceneNode): Path | null {
+ const builder = new r.ck.PathBuilder()
+ addVisibleStrokeOutlines(r, builder, source, node)
+ const path = builder.detachAndDelete()
+ if (!path.isEmpty()) return path
+ path.delete()
+ return null
+}
+
+function addVisibleStrokeOutlines(
+ r: SkiaRenderer,
+ target: PathBuilder,
+ source: Path,
+ node: SceneNode
+): void {
for (const stroke of node.strokes) {
if (!stroke.visible || stroke.weight <= 0) continue
- const outline = source.makeStroked({ width: stroke.weight })
- if (!outline) continue
- target.addPath(outline)
- outline.delete()
+ const area = strokeArea(r, source, node, stroke)
+ if (!area) continue
+ target.addPath(area)
+ area.delete()
}
}
-function canContainFlattenableChildren(node: SceneNode): boolean {
+export function canContainFlattenableChildren(node: SceneNode): boolean {
return (
node.type === 'GROUP' ||
node.type === 'FRAME' ||
@@ -127,7 +161,7 @@ function containerSourcePath(r: SkiaRenderer, node: SceneNode, graph: SceneGraph
const ownPath = baseShapePath(r, node)
if (ownPath) {
if (nodeHasVisibleFill(node)) path.addPath(ownPath)
- addVisibleStrokeOutlines(path, ownPath, node)
+ addVisibleStrokeOutlines(r, path, ownPath, node)
ownPath.delete()
hasPath = true
}
@@ -169,64 +203,11 @@ export function makeBooleanSourcePath(
if (!nodeHasVisibleStroke(node)) return path
const combined = new r.ck.PathBuilder()
combined.addPath(path)
- addVisibleStrokeOutlines(combined, path, node)
+ addVisibleStrokeOutlines(r, combined, path, node)
path.delete()
return combined.detachAndDelete()
}
-export function hasVisibleStrokeSourceNode(node: SceneNode, graph: SceneGraph): boolean {
- if (nodeHasVisibleStroke(node)) return true
- if (!canContainFlattenableChildren(node)) return false
- return node.childIds.some((childId) => {
- const child = graph.getNode(childId)
- return child?.visible === true && hasVisibleStrokeSourceNode(child, graph)
- })
-}
-
-export function makeStrokeOutlinePath(
- r: SkiaRenderer,
- node: SceneNode,
- graph: SceneGraph
-): Path | null {
- if (!canMakeBooleanSourcePath(node)) return null
- if (canContainFlattenableChildren(node)) {
- const path = new r.ck.PathBuilder()
- let hasPath = false
- if (nodeHasVisibleStroke(node)) {
- const ownPath = baseShapePath(r, node)
- if (ownPath) {
- addVisibleStrokeOutlines(path, ownPath, node)
- ownPath.delete()
- hasPath = true
- }
- }
- hasPath ||=
- appendVisibleChildPaths(
- r,
- graph,
- node,
- path,
- (child) => makeStrokeOutlinePath(r, child, graph),
- false
- ) ?? false
- if (hasPath) return path.detachAndDelete()
- path.delete()
- return null
- }
-
- if (!nodeHasVisibleStroke(node)) return null
- const path =
- node.type === 'BOOLEAN_OPERATION'
- ? makeBooleanOperationPath(r, node, graph)
- : baseShapePath(r, node)
- if (!path) return null
- if (node.type === 'LINE') return path
- const outline = new r.ck.PathBuilder()
- addVisibleStrokeOutlines(outline, path, node)
- path.delete()
- return outline.detachAndDelete()
-}
-
function transformedShapePath(r: SkiaRenderer, child: SceneNode, graph: SceneGraph): Path | null {
const path = makeBooleanSourcePath(r, child, graph)
if (!path) return null
diff --git a/packages/core/src/canvas/flatten.ts b/packages/core/src/canvas/flatten.ts
index ca0d102c6..9d85452a8 100644
--- a/packages/core/src/canvas/flatten.ts
+++ b/packages/core/src/canvas/flatten.ts
@@ -2,7 +2,7 @@ import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { copyFills } from '@open-pencil/scene-graph/copy'
import { parseSVGPath } from '@open-pencil/scene-graph/parse-path'
-import { makeBooleanSourcePath, makeStrokeOutlinePath, nodePathTransform } from './boolean'
+import { makeBooleanSourcePath, nodePathTransform } from './boolean'
import type { SkiaRenderer } from './renderer'
export type VectorFlattenProps = Pick<
@@ -64,13 +64,3 @@ export function flattenNodesToVectorProps(
makeBooleanSourcePath(r, node, g)
)
}
-
-export function outlineStrokeNodesToVectorProps(
- renderer: SkiaRenderer,
- graph: SceneGraph,
- nodes: SceneNode[]
-): VectorFlattenProps | null {
- return nodesToVectorProps(renderer, graph, nodes, (r, g, node) =>
- makeStrokeOutlinePath(r, node, g)
- )
-}
diff --git a/packages/core/src/canvas/index.ts b/packages/core/src/canvas/index.ts
index 7fb525f01..a089ed11e 100644
--- a/packages/core/src/canvas/index.ts
+++ b/packages/core/src/canvas/index.ts
@@ -1,14 +1,12 @@
+export { canMakeBooleanSourceNode, canMakeBooleanSourcePath, nodeHasVisibleStroke } from './boolean'
+export { flattenNodesToVectorProps, type VectorFlattenProps } from './flatten'
export {
- canMakeBooleanSourceNode,
- canMakeBooleanSourcePath,
- hasVisibleStrokeSourceNode,
- nodeHasVisibleStroke
-} from './boolean'
-export {
- flattenNodesToVectorProps,
- outlineStrokeNodesToVectorProps,
- type VectorFlattenProps
-} from './flatten'
+ canOutlineStroke,
+ layersToOutline,
+ outlineStrokeLayer,
+ type OutlinedLayer,
+ type OutlinePiece
+} from './outline-stroke'
export {
distanceToGuideSegment,
getGuideScreenSegment,
diff --git a/packages/core/src/canvas/outline-stroke.ts b/packages/core/src/canvas/outline-stroke.ts
new file mode 100644
index 000000000..1214e7189
--- /dev/null
+++ b/packages/core/src/canvas/outline-stroke.ts
@@ -0,0 +1,207 @@
+import type { Path } from 'canvaskit-wasm'
+import { omit, pick } from 'es-toolkit/object'
+
+import type { Fill, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import { getNodeLocalMatrix, localTransformFromWorld } from '@open-pencil/scene-graph/coordinate'
+import { copyFills } from '@open-pencil/scene-graph/copy'
+import Matrix from '@open-pencil/scene-graph/matrix'
+import { parseSVGPath } from '@open-pencil/scene-graph/parse-path'
+
+import {
+ baseShapePath,
+ canContainFlattenableChildren,
+ canMakeBooleanSourcePath,
+ makeBooleanOperationPath,
+ nodeHasVisibleFill,
+ nodeHasVisibleStroke,
+ strokeAreaPath
+} from './boolean'
+import type { SkiaRenderer } from './renderer'
+import { textGlyphPaths } from './text/outlines'
+
+/**
+ * A layer Outline stroke makes in place of another: a vector, or for text a group holding one
+ * vector per glyph. Placement is in the original layer's parent.
+ */
+export interface OutlinePiece {
+ type: 'VECTOR' | 'GROUP'
+ props: Partial<SceneNode>
+ children: Partial<SceneNode>[]
+}
+
+/** What a layer becomes: its fill as a shape of its own, if it has one, under its stroke. */
+export interface OutlinedLayer {
+ fill: OutlinePiece | null
+ stroke: OutlinePiece
+}
+
+/** What the outlines keep of the layer they replace, as Figma's do. */
+const KEPT_FIELDS = [
+ 'opacity',
+ 'blendMode',
+ 'effects',
+ 'visible',
+ 'locked',
+ 'horizontalConstraint',
+ 'verticalConstraint',
+ 'layoutPositioning'
+] as const
+
+/** A layer's strokes as fills, which paint what the strokes painted. */
+function strokePaints(node: SceneNode): Fill[] {
+ return node.strokes.map((stroke) =>
+ omit(stroke, ['weight', 'align', 'cap', 'join', 'dashPattern'])
+ )
+}
+
+interface Box {
+ x: number
+ y: number
+ width: number
+ height: number
+}
+
+function boundsOf(paths: readonly Path[]): Box | null {
+ let [left, top, right, bottom] = [Infinity, Infinity, -Infinity, -Infinity]
+ for (const path of paths) {
+ const [l, t, r, b] = path.getBounds()
+ left = Math.min(left, l)
+ top = Math.min(top, t)
+ right = Math.max(right, r)
+ bottom = Math.max(bottom, b)
+ }
+ if (!(right > left) || !(bottom > top)) return null
+ return { x: left, y: top, width: right - left, height: bottom - top }
+}
+
+/** A path as a vector network, moved so `box` starts at the origin. */
+function networkIn(r: SkiaRenderer, path: Path, box: Box): SceneNode['vectorNetwork'] {
+ const builder = new r.ck.PathBuilder()
+ builder.addPath(path, r.ck.Matrix.translated(-box.x, -box.y))
+ const moved = builder.detachAndDelete()
+ const network = parseSVGPath(moved.toSVGString())
+ moved.delete()
+ return network
+}
+
+/**
+ * A box of the layer's own axes as a layer in its parent: turned and mirrored with the layer, so
+ * the outline lies where the layer drew it.
+ */
+function placedLike(node: SceneNode, box: Box): Partial<SceneNode> {
+ const world = Matrix.multiply(getNodeLocalMatrix(node), Matrix.translated(box.x, box.y))
+ const sized = { ...node, type: 'VECTOR' as const, width: box.width, height: box.height }
+ const placement = localTransformFromWorld(sized, world, Matrix.identity())
+ return { ...placement, width: box.width, height: box.height }
+}
+
+/**
+ * Paths in the layer's own axes as what replaces it: one vector, or for text a group of glyph
+ * vectors named `childName`. Null when the paths cover nothing.
+ */
+function pieceOf(
+ r: SkiaRenderer,
+ node: SceneNode,
+ paths: readonly Path[],
+ name: string,
+ childName: string,
+ fills: Fill[]
+): OutlinePiece | null {
+ const box = boundsOf(paths)
+ if (!box) return null
+ const props = { ...structuredClone(pick(node, KEPT_FIELDS)), ...placedLike(node, box), name }
+ if (node.type !== 'TEXT') {
+ const [path] = paths
+ return {
+ type: 'VECTOR',
+ props: { ...props, fills: copyFills(fills), vectorNetwork: networkIn(r, path, box) },
+ children: []
+ }
+ }
+ const children = paths.flatMap((path) => {
+ const own = boundsOf([path])
+ if (!own) return []
+ return [
+ {
+ name: childName,
+ x: own.x - box.x,
+ y: own.y - box.y,
+ width: own.width,
+ height: own.height,
+ fills: copyFills(fills),
+ vectorNetwork: networkIn(r, path, own)
+ }
+ ]
+ })
+ return { type: 'GROUP', props, children }
+}
+
+/** The shapes a layer is drawn from: text by glyph, anything else as one path. */
+function sourcePaths(r: SkiaRenderer, node: SceneNode, graph: SceneGraph): Path[] {
+ if (node.type === 'TEXT') return textGlyphPaths(r, node) ?? []
+ // A boolean is drawn as the shape its operation makes of its children.
+ const path =
+ node.type === 'BOOLEAN_OPERATION'
+ ? makeBooleanOperationPath(r, node, graph)
+ : baseShapePath(r, node)
+ return path ? [path] : []
+}
+
+/** Whether Outline stroke turns this layer itself into outlines. */
+export function canOutlineStroke(node: SceneNode): boolean {
+ return canMakeBooleanSourcePath(node) && nodeHasVisibleStroke(node)
+}
+
+/**
+ * A layer's stroke as Figma's Outline stroke leaves it: "<name> (Stroke)", filled with the
+ * stroke's paints where the stroke is drawn, over "<name>", its fill, when it has one. Both keep
+ * the layer's turn, opacity, and effects. Null when the stroke covers nothing.
+ */
+export function outlineStrokeLayer(
+ r: SkiaRenderer,
+ node: SceneNode,
+ graph: SceneGraph
+): OutlinedLayer | null {
+ if (!canOutlineStroke(node)) return null
+ const sources = sourcePaths(r, node, graph)
+ try {
+ // A line's shape is already its stroke.
+ const strokes =
+ node.type === 'LINE'
+ ? sources.map((path) => path.copy())
+ : sources.flatMap((path) => strokeAreaPath(r, path, node) ?? [])
+ const stroke = pieceOf(r, node, strokes, `${node.name} (Stroke)`, 'Stroke', strokePaints(node))
+ for (const path of strokes) path.delete()
+ if (!stroke) return null
+ const fill =
+ node.type !== 'LINE' && nodeHasVisibleFill(node)
+ ? pieceOf(r, node, sources, node.name, 'Vector', node.fills)
+ : null
+ return { fill, stroke }
+ } finally {
+ for (const path of sources) path.delete()
+ }
+}
+
+/**
+ * The layers Outline stroke turns into outlines: each selected layer with a stroke, and inside a
+ * selected group or frame every stroked layer it holds, the frame keeping its own stroke, as in
+ * Figma. An instance's layers belong to its component and are left alone.
+ */
+export function layersToOutline(
+ selected: readonly SceneNode[],
+ graph: Pick<SceneGraph, 'getChildren'>
+): SceneNode[] {
+ const found = new Map<string, SceneNode>()
+ const visit = (node: SceneNode, selectedItself: boolean) => {
+ if (!node.visible && !selectedItself) return
+ if (canContainFlattenableChildren(node)) {
+ if (node.type === 'INSTANCE') return
+ for (const child of graph.getChildren(node.id)) visit(child, false)
+ return
+ }
+ if (canOutlineStroke(node)) found.set(node.id, node)
+ }
+ for (const node of selected) visit(node, true)
+ return [...found.values()]
+}
diff --git a/packages/core/src/canvas/text/outlines.ts b/packages/core/src/canvas/text/outlines.ts
index 7c9bffd14..0f6527904 100644
--- a/packages/core/src/canvas/text/outlines.ts
+++ b/packages/core/src/canvas/text/outlines.ts
@@ -28,6 +28,20 @@ function shapedOutlines(r: SkiaRenderer, node: SceneNode): TextOutlineGlyph[] |
return outlines
}
+/** Each glyph the text draws as a path of its own, in the text's box. */
+export function textGlyphPaths(r: SkiaRenderer, node: SceneNode): Path[] | null {
+ const glyphs = shapedOutlines(r, node) ?? textNodeToOutlineLayout(node)?.glyphs
+ if (!glyphs) return null
+ return glyphs.flatMap((glyph) => {
+ const path = new r.ck.PathBuilder()
+ for (const command of glyph.commands) appendOutlineCommand(path, command, glyph.x, glyph.y)
+ const detached = path.detachAndDelete()
+ if (!detached.isEmpty()) return [detached]
+ detached.delete()
+ return []
+ })
+}
+
export function textNodeToOutlinePath(r: SkiaRenderer, node: SceneNode): Path | null {
const glyphs = shapedOutlines(r, node) ?? textNodeToOutlineLayout(node)?.glyphs
if (!glyphs) return null
diff --git a/packages/core/src/editor/clipboard/export.ts b/packages/core/src/editor/clipboard/export.ts
index d26d4603a..2368ebccf 100644
--- a/packages/core/src/editor/clipboard/export.ts
+++ b/packages/core/src/editor/clipboard/export.ts
@@ -1,17 +1,17 @@
import { selectionToJSX } from '@open-pencil/design-jsx'
import type { EditorContext } from '#core/editor/types'
-import { renderNodesToSVG } from '#core/io/formats/svg'
+import { renderNodesToLaidOutSVG } from '#core/io/formats/svg/text/layout'
export function createClipboardExportActions(ctx: EditorContext) {
function copySelectionAsText(ids: string[]): string {
return ids.map((id) => ctx.graph.getNode(id)?.name ?? id).join('\n')
}
- function copySelectionAsSVG(ids: string[]): string | null {
+ function copySelectionAsSVG(ids: string[]): Promise<string | null> {
const nodeIds =
ids.length > 0 ? ids : ctx.graph.getChildren(ctx.state.currentPageId).map((n) => n.id)
- return renderNodesToSVG(ctx.graph, ctx.state.currentPageId, nodeIds)
+ return renderNodesToLaidOutSVG(ctx.graph, ctx.state.currentPageId, nodeIds)
}
function copySelectionAsJSX(ids: string[]): string | null {
diff --git a/packages/core/src/editor/structure.ts b/packages/core/src/editor/structure.ts
index 716799f3c..f3c27646a 100644
--- a/packages/core/src/editor/structure.ts
+++ b/packages/core/src/editor/structure.ts
@@ -14,12 +14,10 @@ import {
type BooleanOperation
} from './structure/boolean'
import { wrapSelectionInContainer as wrapSelectionInContainerImpl } from './structure/container-wrap'
-import {
- flattenSelected as flattenSelectedImpl,
- outlineStrokeSelected as outlineStrokeSelectedImpl
-} from './structure/flatten'
+import { flattenSelected as flattenSelectedImpl } from './structure/flatten'
import { ungroupSelected as ungroupImpl } from './structure/group/ungroup'
import { createLayerTypeActions } from './structure/layer-type'
+import { outlineStrokeSelected as outlineStrokeSelectedImpl } from './structure/outline-stroke'
import {
defaultNodeName,
previewRenamedNodes,
diff --git a/packages/core/src/editor/structure/flatten.ts b/packages/core/src/editor/structure/flatten.ts
index 934bfaf85..dd08b00b5 100644
--- a/packages/core/src/editor/structure/flatten.ts
+++ b/packages/core/src/editor/structure/flatten.ts
@@ -1,7 +1,7 @@
import type { SceneNode } from '@open-pencil/scene-graph'
-import { canMakeBooleanSourceNode, hasVisibleStrokeSourceNode } from '#core/canvas/boolean'
-import { flattenNodesToVectorProps, outlineStrokeNodesToVectorProps } from '#core/canvas/flatten'
+import { canMakeBooleanSourceNode } from '#core/canvas/boolean'
+import { flattenNodesToVectorProps } from '#core/canvas/flatten'
import { restoreSubtree, snapshotSubtree } from '#core/editor/history/subtree'
import type { EditorContext } from '#core/editor/types'
@@ -72,12 +72,3 @@ export function flattenSelected(
return vector.id
}
-
-export function outlineStrokeSelected(ctx: EditorContext, selectedNodes: SceneNode[]) {
- return flattenSelected(ctx, selectedNodes, {
- label: 'Outline stroke',
- canFlattenNode: (node) =>
- canMakeBooleanSourceNode(node, ctx.graph) && hasVisibleStrokeSourceNode(node, ctx.graph),
- vectorPropsFactory: outlineStrokeNodesToVectorProps
- })
-}
diff --git a/packages/core/src/editor/structure/outline-stroke.ts b/packages/core/src/editor/structure/outline-stroke.ts
new file mode 100644
index 000000000..3c1fe2aee
--- /dev/null
+++ b/packages/core/src/editor/structure/outline-stroke.ts
@@ -0,0 +1,142 @@
+import type { SceneNode } from '@open-pencil/scene-graph'
+
+import {
+ layersToOutline,
+ outlineStrokeLayer,
+ type OutlinePiece,
+ type OutlinedLayer
+} from '#core/canvas/outline-stroke'
+import { restoreSubtree, snapshotSubtree } from '#core/editor/history/subtree'
+import { fitEnclosingGroupsWithUndo } from '#core/editor/structure/group/bounds'
+import type { EditorContext } from '#core/editor/types'
+
+/** A layer to outline, where it sits, and what it becomes. */
+interface Outlining {
+ node: SceneNode
+ parentId: string
+ index: number
+ snapshot: Map<string, SceneNode>
+ outlined: OutlinedLayer
+}
+
+/** Where a layer Outline stroke made sits, to put it back on redo. */
+interface Made {
+ id: string
+ parentId: string
+ index: number
+ snapshot: Map<string, SceneNode>
+}
+
+/** Creates a piece in `parentId` at `index`, with a group's glyph vectors inside it. */
+function createPiece(ctx: EditorContext, piece: OutlinePiece, parentId: string, index: number) {
+ const node = ctx.graph.createNode(piece.type, parentId, piece.props)
+ for (const child of piece.children) ctx.graph.createNode('VECTOR', node.id, child)
+ ctx.graph.insertChildAt(node.id, parentId, index)
+ return node.id
+}
+
+/** Restores snapshots taken in one parent, lowest index first so each lands where it was. */
+function restoreAt(ctx: EditorContext, entries: readonly Made[]) {
+ for (const { id, parentId, index, snapshot } of entries.toSorted((a, b) => a.index - b.index)) {
+ const root = snapshot.get(id)
+ if (!root) continue
+ restoreSubtree(ctx.graph, root, parentId, snapshot)
+ ctx.graph.insertChildAt(id, parentId, index)
+ }
+}
+
+/**
+ * Figma's Outline stroke: every stroked layer is replaced, where it was, by its fill as a shape
+ * of its own under its stroke as one, both selected. Undo puts the layers back.
+ */
+export function outlineStrokeSelected(
+ ctx: EditorContext,
+ selectedNodes: SceneNode[]
+): string[] | null {
+ const renderer = ctx.getRenderer()
+ if (!renderer) return null
+ const plan: Outlining[] = []
+ for (const node of layersToOutline(selectedNodes, ctx.graph)) {
+ const parent = node.parentId ? ctx.graph.getNode(node.parentId) : undefined
+ const outlined = parent ? outlineStrokeLayer(renderer, node, ctx.graph) : null
+ if (!parent || !outlined) continue
+ plan.push({
+ node,
+ parentId: parent.id,
+ index: parent.childIds.indexOf(node.id),
+ snapshot: snapshotSubtree(ctx.graph, node.id),
+ outlined
+ })
+ }
+ if (plan.length === 0) return null
+
+ const madeIds: string[] = []
+ for (const { node, parentId, outlined } of plan) {
+ const index = ctx.graph.getNode(parentId)?.childIds.indexOf(node.id) ?? 0
+ const fill = outlined.fill ? createPiece(ctx, outlined.fill, parentId, index) : null
+ const stroke = createPiece(ctx, outlined.stroke, parentId, index + (fill ? 1 : 0))
+ ctx.graph.deleteNode(node.id)
+ if (fill) madeIds.push(fill)
+ madeIds.push(stroke)
+ }
+ const made: Made[] = madeIds.flatMap((id) => {
+ const parentId = ctx.graph.getNode(id)?.parentId
+ if (!parentId) return []
+ const index = ctx.graph.getNode(parentId)?.childIds.indexOf(id) ?? 0
+ return [{ id, parentId, index, snapshot: snapshotSubtree(ctx.graph, id) }]
+ })
+ const parentIds = new Set(plan.map((entry) => entry.parentId))
+ const prevSelection = new Set(ctx.state.selectedIds)
+ for (const parentId of parentIds) ctx.runLayoutForNode(parentId)
+ ctx.setSelectedIds(new Set(madeIds))
+
+ // Groups around the outlines fit them, which can reach past the layers they replace, in the
+ // same undo step.
+ ctx.undo.runBatch('Outline stroke', () => {
+ pushOutlineUndo(ctx, { plan, made, madeIds, parentIds, prevSelection })
+ fitEnclosingGroupsWithUndo(ctx, parentIds)
+ })
+ return madeIds
+}
+
+/** The undo step that puts the outlined layers back, and redo that outlines them again. */
+function pushOutlineUndo(
+ ctx: EditorContext,
+ {
+ plan,
+ made,
+ madeIds,
+ parentIds,
+ prevSelection
+ }: {
+ plan: readonly Outlining[]
+ made: readonly Made[]
+ madeIds: readonly string[]
+ parentIds: ReadonlySet<string>
+ prevSelection: ReadonlySet<string>
+ }
+) {
+ ctx.undo.push({
+ label: 'Outline stroke',
+ forward: () => {
+ for (const { node } of plan) ctx.graph.deleteNode(node.id)
+ restoreAt(ctx, made)
+ for (const parentId of parentIds) ctx.runLayoutForNode(parentId)
+ ctx.setSelectedIds(new Set(madeIds))
+ },
+ inverse: () => {
+ for (const { id } of made) ctx.graph.deleteNode(id)
+ restoreAt(
+ ctx,
+ plan.map(({ node, parentId, index, snapshot }) => ({
+ id: node.id,
+ parentId,
+ index,
+ snapshot
+ }))
+ )
+ for (const parentId of parentIds) ctx.runLayoutForNode(parentId)
+ ctx.setSelectedIds(new Set(prevSelection))
+ }
+ })
+}
diff --git a/packages/core/src/io/formats.ts b/packages/core/src/io/formats.ts
index a769bc6c4..4a3790c4c 100644
--- a/packages/core/src/io/formats.ts
+++ b/packages/core/src/io/formats.ts
@@ -20,7 +20,6 @@ import type { DrawIOExportTarget } from './formats/drawio/export'
import { exportFigFile, parseFigFile } from './formats/fig'
import type { PPTXExportOptions } from './formats/pptx'
import { headlessRenderNodes, renderNodesToImage, type RasterExportFormat } from './formats/raster'
-import { renderNodesToSVG } from './formats/svg'
import { extractExportGraph, findPageId } from './subgraph'
import type {
ExportRequest,
@@ -413,7 +412,13 @@ export const svgFormat: IOFormatAdapter<'svg'> = {
async exportContent(request, options?: SVGExportOptions) {
const target = resolveExportNodes(request)
if (!target) throw new Error('Nothing to export')
- const data = renderNodesToSVG(request.graph, target.pageId, target.nodeIds, options)
+ const { renderNodesToLaidOutSVG } = await import('./formats/svg/text/layout')
+ const data = await renderNodesToLaidOutSVG(
+ request.graph,
+ target.pageId,
+ target.nodeIds,
+ options
+ )
if (!data) throw new Error('Nothing to export')
return {
format: 'svg',
diff --git a/packages/core/src/io/formats/svg/export.ts b/packages/core/src/io/formats/svg/export.ts
index bb8ab3778..c5429c398 100644
--- a/packages/core/src/io/formats/svg/export.ts
+++ b/packages/core/src/io/formats/svg/export.ts
@@ -23,7 +23,6 @@ import {
hasRadius,
roundedRectPath,
arcPath,
- shapeWithTextDetailsPath,
shapeWithTextOutlinePath,
regionSVGPaths,
looseSegments
@@ -42,6 +41,7 @@ import { arrowHeadElements, openPathElements, vectorArrowHeads } from './arrows'
import type { SVGExportContext, SVGFontAlias } from './defs'
import { svg, renderSVGNode } from './node'
import type { SVGNode } from './node'
+import { alignedStroke, alignedStrokeElement, shapeWithTextDetailElements } from './strokes'
import { renderTextNode } from './text/export'
import type { SVGTextLayout } from './text/lines'
@@ -228,17 +228,10 @@ function shapeWithTextElements(
strokeAttrs: Record<string, string | number | undefined>,
ctx: SVGExportContext
): SVGNode[] {
- const outline = shapeWithTextOutlinePath(node)
- const elements = [svg('path', { d: outline, ...common })]
- const details = strokeAttrs.stroke ? shapeWithTextDetailsPath(node) : null
- if (details) {
- const clipId = nextDefId(ctx, 'clip')
- ctx.defs.push(svg('clipPath', { id: clipId }, svg('path', { d: outline })))
- elements.push(
- svg('path', { d: details, fill: 'none', ...strokeAttrs, 'clip-path': `url(#${clipId})` })
- )
- }
- return elements
+ return [
+ svg('path', { d: shapeWithTextOutlinePath(node), ...common }),
+ ...shapeWithTextDetailElements(node, strokeAttrs, ctx)
+ ]
}
// --- Main recursive renderer ---
@@ -328,6 +321,35 @@ function hasPathLevelFills(node: SceneNode): boolean {
}
function buildShapeChildren(
+ node: SceneNode,
+ visibleFills: Fill[],
+ fillAttr: string | null,
+ fillOpacity: number | undefined,
+ strokeAttrs: Record<string, string | number | undefined>,
+ visibleStrokes: Stroke[],
+ ctx: SVGExportContext
+): SVGNode[] {
+ const aligned = hasPathLevelFills(node) ? null : alignedStroke(node, visibleStrokes[0])
+ if (!aligned) {
+ return fillAndStrokeElements(
+ node,
+ visibleFills,
+ fillAttr,
+ fillOpacity,
+ strokeAttrs,
+ visibleStrokes.length,
+ ctx
+ )
+ }
+ // The fill goes as it is, and the stroke over it inside or outside the outline.
+ return [
+ ...fillAndStrokeElements(node, visibleFills, fillAttr, fillOpacity, {}, 0, ctx),
+ ...alignedStrokeElement(node, aligned, strokeAttrs, ctx),
+ ...(node.type === 'SHAPE_WITH_TEXT' ? shapeWithTextDetailElements(node, strokeAttrs, ctx) : [])
+ ]
+}
+
+function fillAndStrokeElements(
node: SceneNode,
visibleFills: Fill[],
fillAttr: string | null,
@@ -425,7 +447,7 @@ function renderNode(node: SceneNode, ctx: SVGExportContext): SVGNode | null {
fillAttr,
fillOpacity,
strokeAttrs,
- visibleStrokes.length,
+ visibleStrokes,
ctx
)
diff --git a/packages/core/src/io/formats/svg/strokes.ts b/packages/core/src/io/formats/svg/strokes.ts
new file mode 100644
index 000000000..89a718e8d
--- /dev/null
+++ b/packages/core/src/io/formats/svg/strokes.ts
@@ -0,0 +1,92 @@
+import type { SceneNode, Stroke } from '@open-pencil/scene-graph'
+
+import type { SVGExportContext } from './defs'
+import { nextDefId } from './defs'
+import { svg, type SVGNode } from './node'
+import { nodeOutlinePath, round, shapeWithTextDetailsPath, shapeWithTextOutlinePath } from './paths'
+
+type Attrs = Record<string, string | number | undefined>
+
+/**
+ * The closed outline an aligned stroke follows, as path data in the layer's box: a FigJam shape's,
+ * an ellipse, polygon or star, or a box with its corners for any other layer. Null for lines,
+ * arcs, and vectors, whose strokes the canvas centres on their paths.
+ */
+function closedOutlinePath(node: SceneNode): string | null {
+ switch (node.type) {
+ case 'LINE':
+ case 'VECTOR':
+ case 'BOOLEAN_OPERATION':
+ return null
+ case 'SHAPE_WITH_TEXT':
+ return shapeWithTextOutlinePath(node)
+ case 'ELLIPSE':
+ return node.arcData ? null : nodeOutlinePath(node)
+ case 'POLYGON':
+ case 'STAR':
+ return nodeOutlinePath(node)
+ default:
+ return nodeOutlinePath({ ...node, type: 'RECTANGLE' })
+ }
+}
+
+/** The stroke an aligned stroke paints, when it is inside or outside a closed outline. */
+export function alignedStroke(node: SceneNode, stroke: Stroke | undefined): Stroke | null {
+ if (!stroke || stroke.align === 'CENTER') return null
+ return closedOutlinePath(node) === null ? null : stroke
+}
+
+/**
+ * A stroke inside or outside the layer's outline, as the canvas draws it: centred at twice its
+ * weight and clipped to the outline, or to everything around it.
+ */
+export function alignedStrokeElement(
+ node: SceneNode,
+ stroke: Stroke,
+ strokeAttrs: Attrs,
+ ctx: SVGExportContext
+): SVGNode[] {
+ const outline = closedOutlinePath(node)
+ if (outline === null) return []
+ const clipId = nextDefId(ctx, 'clip')
+ if (stroke.align === 'INSIDE') {
+ ctx.defs.push(svg('clipPath', { id: clipId }, svg('path', { d: outline })))
+ } else {
+ // A box wide enough for the stroke, its mitred tips included, with the outline cut out of it.
+ // The doubled stroke mitres out to its weight times the miter limit.
+ const margin = stroke.weight * Math.max(2, node.strokeMiterLimit)
+ const left = round(-margin)
+ const top = round(-margin)
+ const right = round(node.width + margin)
+ const bottom = round(node.height + margin)
+ const around = `M${left} ${top}H${right}V${bottom}H${left}Z`
+ ctx.defs.push(
+ svg('clipPath', { id: clipId }, svg('path', { d: around + outline, 'clip-rule': 'evenodd' }))
+ )
+ }
+ return [
+ svg('path', {
+ d: outline,
+ fill: 'none',
+ ...strokeAttrs,
+ 'stroke-width': round(stroke.weight * 2),
+ 'clip-path': `url(#${clipId})`
+ })
+ ]
+}
+
+/**
+ * A FigJam shape's inner lines, such as a database's front rim, stroked as the canvas strokes
+ * them: at the stroke's own weight whatever its alignment, ending where the outline does.
+ */
+export function shapeWithTextDetailElements(
+ node: SceneNode,
+ strokeAttrs: Attrs,
+ ctx: SVGExportContext
+): SVGNode[] {
+ const details = strokeAttrs.stroke ? shapeWithTextDetailsPath(node) : null
+ if (!details) return []
+ const clipId = nextDefId(ctx, 'clip')
+ ctx.defs.push(svg('clipPath', { id: clipId }, svg('path', { d: shapeWithTextOutlinePath(node) })))
+ return [svg('path', { d: details, fill: 'none', ...strokeAttrs, 'clip-path': `url(#${clipId})` })]
+}
diff --git a/packages/core/src/io/formats/svg/text/layout.ts b/packages/core/src/io/formats/svg/text/layout.ts
new file mode 100644
index 000000000..9248598d3
--- /dev/null
+++ b/packages/core/src/io/formats/svg/text/layout.ts
@@ -0,0 +1,22 @@
+import type { SceneGraph } from '@open-pencil/scene-graph'
+
+import { withPDFTextLayout } from '#core/io/formats/pdf/prepare'
+import { renderNodesToSVG, type SVGExportOptions } from '#core/io/formats/svg/export'
+import { prepareGraphFonts } from '#core/text/prepare'
+
+/**
+ * Layers as SVG with their text set as the canvas sets it: the fonts it draws with loaded, each
+ * line on the baseline the canvas gives it, and wrapped paragraphs kept wrapped, as PDF export
+ * sets them.
+ */
+export async function renderNodesToLaidOutSVG(
+ graph: SceneGraph,
+ pageId: string,
+ nodeIds: string[],
+ options: SVGExportOptions = {}
+): Promise<string | null> {
+ await prepareGraphFonts(graph, nodeIds)
+ return withPDFTextLayout(async (textLayout) =>
+ renderNodesToSVG(graph, pageId, nodeIds, { textLayout, ...options })
+ )
+}
diff --git a/packages/core/src/tools/vector/export.ts b/packages/core/src/tools/vector/export.ts
index 5e23b60bf..1447941b5 100644
--- a/packages/core/src/tools/vector/export.ts
+++ b/packages/core/src/tools/vector/export.ts
@@ -71,11 +71,11 @@ export const exportSVG = defineTool({
exposure: { webmcp: false },
input: v.strictObject({ ...exportInputs }),
execute: async (figma, args) => {
- const { renderNodesToSVG } = await import('#core/io/formats/svg')
+ const { renderNodesToLaidOutSVG } = await import('#core/io/formats/svg/text/layout')
const pageId = figma.currentPageId
const ids =
args.ids && args.ids.length > 0 ? args.ids : figma.currentPage.children.map((node) => node.id)
- const svg = renderNodesToSVG(figma.graph, pageId, ids)
+ const svg = await renderNodesToLaidOutSVG(figma.graph, pageId, ids)
if (!svg) return { error: 'No visible nodes to export' }
return { svg }
}
diff --git a/packages/core/tests/editor/structure/flatten.test.ts b/packages/core/tests/editor/structure/flatten.test.ts
index c6e02a8f0..f2a8a31a8 100644
--- a/packages/core/tests/editor/structure/flatten.test.ts
+++ b/packages/core/tests/editor/structure/flatten.test.ts
@@ -82,78 +82,6 @@ describe('flattenSelected', () => {
expect(editor.graph.getNode(second.id)).toBeUndefined()
})
- test('outlines visible strokes into a vector path', async () => {
- const { editor } = await createEditorWithRenderer()
- const pageId = editor.state.currentPageId
- const rect = editor.graph.createNode('RECTANGLE', pageId, {
- x: 20,
- y: 30,
- width: 40,
- height: 30,
- fills: [{ type: 'SOLID', color: TRANSPARENT, opacity: 1, visible: true }],
- strokes: [
- { type: 'SOLID', color: BLACK, weight: 8, opacity: 1, visible: true, align: 'CENTER' }
- ]
- })
-
- editor.select([rect.id])
- editor.outlineStrokeSelected()
-
- const [vectorId] = [...editor.state.selectedIds]
- const vector = editor.graph.getNode(vectorId)
- expect(vector?.type).toBe('VECTOR')
- expect(vector?.name).toBe('Outline stroke')
- expect(vector?.x).toBe(16)
- expect(vector?.y).toBe(26)
- expect(vector?.width).toBe(48)
- expect(vector?.height).toBe(38)
- expect(vector?.vectorNetwork?.vertices.length).toBeGreaterThan(0)
- expect(editor.graph.getNode(rect.id)).toBeUndefined()
- })
-
- test('outlines stroked descendants inside groups', async () => {
- const { editor } = await createEditorWithRenderer()
- const pageId = editor.state.currentPageId
- const rect = editor.graph.createNode('RECTANGLE', pageId, {
- x: 20,
- y: 30,
- width: 40,
- height: 30,
- fills: [{ type: 'SOLID', color: TRANSPARENT, opacity: 1, visible: true }],
- strokes: [
- { type: 'SOLID', color: BLACK, weight: 8, opacity: 1, visible: true, align: 'CENTER' }
- ]
- })
- editor.select([rect.id])
- editor.groupSelected()
-
- editor.outlineStrokeSelected()
-
- const [vectorId] = [...editor.state.selectedIds]
- const vector = editor.graph.getNode(vectorId)
- expect(vector?.type).toBe('VECTOR')
- expect(vector?.name).toBe('Outline stroke')
- expect(vector?.vectorNetwork?.vertices.length).toBeGreaterThan(0)
- })
-
- test('does not outline fill-only shapes as strokes', async () => {
- const { editor } = await createEditorWithRenderer()
- const pageId = editor.state.currentPageId
- const rect = editor.graph.createNode('RECTANGLE', pageId, {
- x: 20,
- y: 30,
- width: 40,
- height: 30,
- strokes: []
- })
-
- editor.select([rect.id])
- const result = editor.outlineStrokeSelected()
-
- expect(result).toBeNull()
- expect(editor.graph.getNode(rect.id)?.type).toBe('RECTANGLE')
- })
-
test('outlines loaded text through the shared text outline path', async () => {
await loadInterRegular()
const { editor } = await createEditorWithRenderer()
diff --git a/packages/core/tests/editor/structure/outline-stroke.test.ts b/packages/core/tests/editor/structure/outline-stroke.test.ts
new file mode 100644
index 000000000..a0c444b83
--- /dev/null
+++ b/packages/core/tests/editor/structure/outline-stroke.test.ts
@@ -0,0 +1,340 @@
+import { afterEach, describe, expect, test } from 'bun:test'
+
+import { createEditor } from '@open-pencil/core'
+import { SkiaRenderer } from '@open-pencil/core/canvas'
+import { initCanvasKit } from '@open-pencil/core/io/formats/raster'
+import { fontManager } from '@open-pencil/core/text'
+import { vectorNetworkToPath } from '@open-pencil/core/vector'
+import type { Effect, SceneNode, Stroke } from '@open-pencil/scene-graph'
+import type { Color } from '@open-pencil/scene-graph/primitives'
+
+// Figma's Outline stroke (⇧⌘O), measured live: each stroked layer becomes its fill, "<name>", under
+// "<name> (Stroke)", painted with the stroke where it is drawn; both keep the layer's turn,
+// opacity, and effects.
+
+const cleanups: (() => void)[] = []
+
+afterEach(() => {
+ for (const cleanup of cleanups.splice(0)) cleanup()
+})
+
+async function createEditorWithRenderer() {
+ const ck = await initCanvasKit()
+ const surface = ck.MakeSurface(200, 200)
+ if (!surface) throw new Error('Could not create CanvasKit surface')
+ const renderer = new SkiaRenderer(ck, surface)
+ const editor = createEditor()
+ editor.setCanvasKit(ck, renderer)
+ cleanups.push(() => {
+ editor.dispose()
+ renderer.destroy()
+ })
+ return editor
+}
+
+const RED: Color = { r: 1, g: 0, b: 0, a: 1 }
+const BLUE: Color = { r: 0, g: 0, b: 1, a: 1 }
+const solid = (color: Color) => ({ type: 'SOLID' as const, color, opacity: 1, visible: true })
+const stroke = (align: Stroke['align'] = 'INSIDE'): Stroke => ({
+ ...solid(RED),
+ weight: 4,
+ align
+})
+
+/** Each selected layer's name, type, box, and fill colours, in layer order. */
+function selected(editor: Awaited<ReturnType<typeof createEditorWithRenderer>>) {
+ return [...editor.state.selectedIds]
+ .map((id) => editor.graph.getNode(id))
+ .filter((node): node is SceneNode => node !== undefined)
+ .map((node) => ({
+ name: node.name,
+ type: node.type,
+ parent: editor.graph.getNode(node.parentId ?? '')?.type,
+ box: [node.x, node.y, node.width, node.height].map((n) => Math.round(n * 100) / 100),
+ fills: node.fills.map((fill) => (fill.type === 'SOLID' ? fill.color : null))
+ }))
+}
+
+describe('outlineStrokeSelected', () => {
+ test('replaces a stroked shape with its fill under its stroke, both selected', async () => {
+ const editor = await createEditorWithRenderer()
+ const pageId = editor.state.currentPageId
+ const box = editor.graph.createNode('RECTANGLE', pageId, {
+ name: 'Box',
+ x: 50,
+ y: 50,
+ width: 100,
+ height: 100,
+ fills: [solid(BLUE)],
+ strokes: [stroke()]
+ })
+ editor.select([box.id])
+ editor.outlineStrokeSelected()
+
+ expect(editor.graph.getNode(box.id)).toBeUndefined()
+ expect(selected(editor)).toEqual([
+ { name: 'Box', type: 'VECTOR', parent: 'CANVAS', box: [50, 50, 100, 100], fills: [BLUE] },
+ {
+ name: 'Box (Stroke)',
+ type: 'VECTOR',
+ parent: 'CANVAS',
+ box: [50, 50, 100, 100],
+ fills: [RED]
+ }
+ ])
+ // The fill sits under the stroke, where the shape was.
+ const children = editor.graph.getChildren(pageId).map((node) => node.name)
+ expect(children).toEqual(['Box', 'Box (Stroke)'])
+ })
+
+ test('outlines a stroke where it is drawn: inside, centred, or outside the box', async () => {
+ const outlined = async (align: Stroke['align']) => {
+ const editor = await createEditorWithRenderer()
+ const rect = editor.graph.createNode('RECTANGLE', editor.state.currentPageId, {
+ x: 50,
+ y: 50,
+ width: 100,
+ height: 100,
+ fills: [],
+ strokes: [stroke(align)]
+ })
+ editor.select([rect.id])
+ editor.outlineStrokeSelected()
+ return selected(editor).map((layer) => layer.box)
+ }
+ expect(await outlined('INSIDE')).toEqual([[50, 50, 100, 100]])
+ expect(await outlined('CENTER')).toEqual([[48, 48, 104, 104]])
+ expect(await outlined('OUTSIDE')).toEqual([[46, 46, 108, 108]])
+ })
+
+ test('leaves the shape uncovered by an outside stroke’s outline', async () => {
+ const editor = await createEditorWithRenderer()
+ const ellipse = editor.graph.createNode('ELLIPSE', editor.state.currentPageId, {
+ width: 120,
+ height: 70,
+ fills: [],
+ strokes: [stroke('OUTSIDE')]
+ })
+ editor.select([ellipse.id])
+ editor.outlineStrokeSelected()
+ const outline = editor.graph.getNode([...editor.state.selectedIds][0] ?? '')
+ const network = outline?.vectorNetwork
+ if (!outline || !network) throw new Error('Expected an outline')
+ const ck = await initCanvasKit()
+ const [path] = vectorNetworkToPath(ck, network)
+ // The ellipse's centre and a point on the ring, in the outline's own box.
+ expect(path?.contains(60 - outline.x, 35 - outline.y)).toBe(false)
+ expect(path?.contains(60 - outline.x, -2 - outline.y)).toBe(true)
+ path?.delete()
+ })
+
+ test('keeps the layer’s turn, opacity, and effects on both outlines', async () => {
+ const editor = await createEditorWithRenderer()
+ const shadow: Effect = {
+ type: 'DROP_SHADOW',
+ color: { r: 0, g: 0, b: 0, a: 0.5 },
+ offset: { x: 2, y: 2 },
+ radius: 4,
+ spread: 0,
+ visible: true
+ }
+ const ellipse = editor.graph.createNode('ELLIPSE', editor.state.currentPageId, {
+ name: 'Dot',
+ width: 100,
+ height: 60,
+ rotation: 30,
+ opacity: 0.5,
+ effects: [shadow],
+ fills: [solid(BLUE)],
+ strokes: [stroke('OUTSIDE')]
+ })
+ editor.select([ellipse.id])
+ editor.outlineStrokeSelected()
+ const [fill, outline] = [...editor.state.selectedIds].map((id) => editor.graph.getNode(id))
+ for (const layer of [fill, outline]) {
+ expect(layer?.rotation).toBeCloseTo(30)
+ expect(layer?.opacity).toBe(0.5)
+ expect(layer?.effects).toEqual([shadow])
+ }
+ // Figma's outline of this stroke is 108 × 68, turned with the ellipse.
+ expect([outline?.width ?? 0, outline?.height ?? 0].map(Math.round)).toEqual([108, 68])
+ })
+
+ test('outlines each layer of a selection and inside a group or frame in place', async () => {
+ const editor = await createEditorWithRenderer()
+ const pageId = editor.state.currentPageId
+ const loose = editor.graph.createNode('RECTANGLE', pageId, {
+ name: 'Loose',
+ fills: [],
+ strokes: [stroke()]
+ })
+ const inGroup = editor.graph.createNode('RECTANGLE', pageId, {
+ name: 'Grouped',
+ fills: [solid(BLUE)],
+ strokes: [stroke()]
+ })
+ editor.select([inGroup.id])
+ editor.groupSelected()
+ const group = editor.graph.getNode(inGroup.parentId ?? '')
+ const frame = editor.graph.createNode('FRAME', pageId, {
+ name: 'Card',
+ width: 160,
+ height: 100,
+ fills: [solid(BLUE)],
+ strokes: [stroke()]
+ })
+ editor.graph.createNode('RECTANGLE', frame.id, {
+ name: 'Inner',
+ fills: [],
+ strokes: [stroke()]
+ })
+
+ editor.select([loose.id, group?.id ?? '', frame.id])
+ editor.outlineStrokeSelected()
+
+ // A stroke-only layer leaves only its stroke; the group stays; the frame keeps its own stroke.
+ expect(selected(editor).map((layer) => `${layer.name} in ${layer.parent}`)).toEqual([
+ 'Loose (Stroke) in CANVAS',
+ 'Grouped in GROUP',
+ 'Grouped (Stroke) in GROUP',
+ 'Inner (Stroke) in FRAME'
+ ])
+ expect(editor.graph.getNode(frame.id)?.strokes).toHaveLength(1)
+ })
+
+ test('turns stroked text into a group of glyph outlines for its fill and its stroke', async () => {
+ const inter = await fontManager.fetchBundledFont('/InterVariable.ttf')
+ if (!inter) throw new Error('Expected the bundled Inter')
+ await fontManager.markLoaded('Inter', 'Regular', inter)
+ const editor = await createEditorWithRenderer()
+ const text = editor.graph.createNode('TEXT', editor.state.currentPageId, {
+ name: 'Hi',
+ text: 'Hi',
+ fontFamily: 'Inter',
+ fontSize: 40,
+ width: 40,
+ height: 48,
+ fills: [solid(BLUE)],
+ strokes: [{ ...stroke('CENTER'), weight: 2 }]
+ })
+ editor.select([text.id])
+ editor.outlineStrokeSelected()
+
+ const groups = [...editor.state.selectedIds].map((id) => editor.graph.getNode(id))
+ expect(groups.map((group) => [group?.type, group?.name])).toEqual([
+ ['GROUP', 'Hi'],
+ ['GROUP', 'Hi (Stroke)']
+ ])
+ const glyphs = groups.map((group) =>
+ editor.graph.getChildren(group?.id ?? '').map((glyph) => glyph.name)
+ )
+ expect(glyphs).toEqual([
+ ['Vector', 'Vector'],
+ ['Stroke', 'Stroke']
+ ])
+ })
+
+ test('outlines a boolean’s combined shape, not its box', async () => {
+ const editor = await createEditorWithRenderer()
+ const pageId = editor.state.currentPageId
+ const boolean = editor.graph.createNode('BOOLEAN_OPERATION', pageId, {
+ name: 'Overlap',
+ booleanOperation: 'INTERSECT',
+ width: 150,
+ height: 150,
+ fills: [solid(BLUE)],
+ strokes: [stroke()]
+ })
+ for (const at of [0, 50]) {
+ editor.graph.createNode('RECTANGLE', boolean.id, {
+ x: at,
+ y: at,
+ width: 100,
+ height: 100,
+ fills: [solid(BLUE)]
+ })
+ }
+ editor.select([boolean.id])
+ editor.outlineStrokeSelected()
+ // The two squares meet in 50 × 50, which an inside stroke stays within.
+ expect(selected(editor).map((layer) => layer.box)).toEqual([
+ [50, 50, 50, 50],
+ [50, 50, 50, 50]
+ ])
+ })
+
+ test('fits the group around outlines that reach past the layer, and undo refits it back', async () => {
+ const editor = await createEditorWithRenderer()
+ const pageId = editor.state.currentPageId
+ const rect = editor.graph.createNode('RECTANGLE', pageId, {
+ x: 50,
+ y: 50,
+ width: 100,
+ height: 100,
+ fills: [],
+ strokes: [stroke('OUTSIDE')]
+ })
+ editor.select([rect.id])
+ editor.groupSelected()
+ const groupId = rect.parentId ?? ''
+ const box = () => {
+ const group = editor.graph.getNode(groupId)
+ return [group?.x, group?.y, group?.width, group?.height]
+ }
+ expect(box()).toEqual([50, 50, 100, 100])
+
+ editor.outlineStrokeSelected()
+ expect(box()).toEqual([46, 46, 108, 108])
+
+ editor.undo.undo()
+ expect(box()).toEqual([50, 50, 100, 100])
+ editor.undo.redo()
+ expect(box()).toEqual([46, 46, 108, 108])
+ })
+
+ test('leaves fill-only shapes alone', async () => {
+ const editor = await createEditorWithRenderer()
+ const rect = editor.graph.createNode('RECTANGLE', editor.state.currentPageId, {
+ fills: [solid(BLUE)],
+ strokes: []
+ })
+ editor.select([rect.id])
+ expect(editor.outlineStrokeSelected()).toBeNull()
+ expect(editor.graph.getNode(rect.id)?.type).toBe('RECTANGLE')
+ })
+
+ test('undo puts the layers back and redo outlines them again', async () => {
+ const editor = await createEditorWithRenderer()
+ const pageId = editor.state.currentPageId
+ const before = editor.graph.createNode('RECTANGLE', pageId, { name: 'Before' })
+ const first = editor.graph.createNode('RECTANGLE', pageId, {
+ name: 'First',
+ fills: [solid(BLUE)],
+ strokes: [stroke()]
+ })
+ const second = editor.graph.createNode('ELLIPSE', pageId, {
+ name: 'Second',
+ fills: [],
+ strokes: [stroke()]
+ })
+ const after = editor.graph.createNode('RECTANGLE', pageId, { name: 'After' })
+ const names = () => editor.graph.getChildren(pageId).map((node) => node.name)
+
+ editor.select([first.id, second.id])
+ editor.outlineStrokeSelected()
+ const outlined = ['Before', 'First', 'First (Stroke)', 'Second (Stroke)', 'After']
+ expect(names()).toEqual(outlined)
+
+ editor.undo.undo()
+ expect(editor.graph.getNode(pageId)?.childIds).toEqual([
+ before.id,
+ first.id,
+ second.id,
+ after.id
+ ])
+ expect(editor.state.selectedIds).toEqual(new Set([first.id, second.id]))
+
+ editor.undo.redo()
+ expect(names()).toEqual(outlined)
+ })
+})
diff --git a/packages/core/tests/io/formats/svg/strokes.test.ts b/packages/core/tests/io/formats/svg/strokes.test.ts
new file mode 100644
index 000000000..00e3443f9
--- /dev/null
+++ b/packages/core/tests/io/formats/svg/strokes.test.ts
@@ -0,0 +1,79 @@
+import { describe, expect, test } from 'bun:test'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+
+import { renderNodesToSVG } from '@open-pencil/core/io/formats/svg'
+import { SceneGraph, type SceneNode, type Stroke } from '@open-pencil/scene-graph'
+
+const stroke = (align: Stroke['align']): Stroke => ({
+ type: 'SOLID',
+ color: { r: 0.7, g: 0.7, b: 0.7, a: 1 },
+ opacity: 1,
+ visible: true,
+ weight: 2,
+ align
+})
+
+/** The SVG for one 200 × 120 layer of `type` with a 2 px stroke aligned `align`. */
+function exported(type: 'RECTANGLE' | 'ELLIPSE' | 'FRAME', align: Stroke['align']): string {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const props: Partial<SceneNode> = {
+ width: 200,
+ height: 120,
+ cornerRadius: type === 'ELLIPSE' ? 0 : 12,
+ fills: [{ type: 'SOLID', color: { r: 1, g: 1, b: 1, a: 1 }, opacity: 1, visible: true }],
+ strokes: [stroke(align)]
+ }
+ const node = graph.createNode(type, page, props)
+ return expectDefined(renderNodesToSVG(graph, page, [node.id], { xmlDeclaration: false }))
+}
+
+/** The clip path an element names, by its id. */
+function clipOf(svg: string, element: string): string {
+ const id = expectDefined(/clip-path="url\(#([^)]+)\)"/.exec(element))[1]
+ return expectDefined(new RegExp(`<clipPath id="${id}">([\\s\\S]*?)</clipPath>`).exec(svg))[1]
+}
+
+describe('aligned strokes exported to SVG', () => {
+ test('an inside stroke stays in the box: twice its weight, clipped to the outline', () => {
+ const svg = exported('FRAME', 'INSIDE')
+ const stroked = expectDefined(/<path [^>]*stroke="#B3B3B3"[^>]*>/.exec(svg))[0]
+ expect(stroked).toContain('stroke-width="4"')
+ const outline = expectDefined(/ d="([^"]+)"/.exec(stroked))[1]
+ expect(clipOf(svg, stroked)).toContain(`d="${outline}"`)
+ // The fill is drawn without a stroke of its own.
+ expect(svg).toMatch(/<rect [^>]*fill="#FFFFFF"(?![^>]*stroke=)[^>]*\/>/)
+ })
+
+ test('an outside stroke keeps out of the box: clipped to everything around the outline', () => {
+ const svg = exported('ELLIPSE', 'OUTSIDE')
+ const stroked = expectDefined(/<path [^>]*stroke="#B3B3B3"[^>]*>/.exec(svg))[0]
+ expect(stroked).toContain('stroke-width="4"')
+ expect(clipOf(svg, stroked)).toContain('clip-rule="evenodd"')
+ })
+
+ test('a centred stroke is drawn on the shape at its own weight', () => {
+ const svg = exported('RECTANGLE', 'CENTER')
+ expect(svg).toMatch(/<rect [^>]*stroke="#B3B3B3" stroke-width="2"/)
+ expect(svg).not.toContain('clip-path')
+ })
+
+ test('an outside stroke’s clip reaches as far as its mitred tips', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const star = graph.createNode('STAR', page, {
+ width: 100,
+ height: 100,
+ pointCount: 5,
+ starInnerRadius: 0.2,
+ strokeMiterLimit: 10,
+ strokes: [{ ...stroke('OUTSIDE'), weight: 4 }]
+ })
+ const svg = expectDefined(renderNodesToSVG(graph, page, [star.id], { xmlDeclaration: false }))
+ const stroked = expectDefined(/<path [^>]*stroke="#B3B3B3"[^>]*>/.exec(svg))[0]
+ // A miter of the doubled stroke reaches its weight, 4, times the miter limit past the tip.
+ const [, left] = expectDefined(/d="M(-?[\d.]+) /.exec(clipOf(svg, stroked)))
+ expect(Number(left)).toBeLessThanOrEqual(-40)
+ })
+})
diff --git a/packages/core/tests/io/formats/svg/text/layout.test.ts b/packages/core/tests/io/formats/svg/text/layout.test.ts
new file mode 100644
index 000000000..3243dc000
--- /dev/null
+++ b/packages/core/tests/io/formats/svg/text/layout.test.ts
@@ -0,0 +1,41 @@
+import { beforeAll, expect, test } from 'bun:test'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+import { pixelLength } from '@open-pencil/scene-graph/text'
+
+import { BUILTIN_IO_FORMATS, IORegistry } from '#core/io'
+import { fontManager } from '#core/text/fonts'
+
+const SENTENCE = 'A sentence long enough that it has to wrap onto a second line.'
+
+beforeAll(async () => {
+ const inter = expectDefined(await fontManager.fetchBundledFont('/InterVariable.ttf'), 'Inter')
+ await fontManager.markLoaded('Inter', 'Regular', inter)
+})
+
+test('an SVG export sets text on the canvas baselines, a wrapped paragraph on its lines', async () => {
+ const graph = new SceneGraph()
+ const pageId = graph.getPages()[0].id
+ const node = graph.createNode('TEXT', pageId, {
+ text: SENTENCE,
+ fontFamily: 'Inter',
+ fontSize: 13,
+ lineHeight: pixelLength(24),
+ width: 230,
+ height: 48,
+ textAutoResize: 'HEIGHT'
+ })
+ const io = new IORegistry(BUILTIN_IO_FORMATS)
+ const result = await io.exportContent('svg', {
+ graph,
+ target: { scope: 'node', nodeId: node.id }
+ })
+ if (typeof result.data !== 'string') throw new Error('Expected SVG markup')
+ const baselines = [...result.data.matchAll(/<tspan [^>]*y="([\d.]+)"/g)].map(([, y]) => Number(y))
+ // Two 24 px lines, each baseline below half the leading and the font's ascent, not at 13.
+ expect(baselines).toHaveLength(2)
+ expect(baselines[0]).toBeGreaterThan(13)
+ expect(baselines[1] - baselines[0]).toBeCloseTo(24)
+})
diff --git a/packages/vue/src/editor/selection-capabilities/use.ts b/packages/vue/src/editor/selection-capabilities/use.ts
index 301d7b0d9..a89488e0e 100644
--- a/packages/vue/src/editor/selection-capabilities/use.ts
+++ b/packages/vue/src/editor/selection-capabilities/use.ts
@@ -1,6 +1,6 @@
import { computed, shallowRef } from 'vue'
-import { canMakeBooleanSourceNode, hasVisibleStrokeSourceNode } from '@open-pencil/core/canvas'
+import { canMakeBooleanSourceNode, layersToOutline } from '@open-pencil/core/canvas'
import { useEditorEvent } from '#vue/editor/events/use'
import { useSelectionState } from '#vue/editor/selection-state/use'
@@ -61,17 +61,9 @@ export function useSelectionCapabilities() {
nodes.every((node) => node.type === 'TEXT' && canMakeBooleanSourceNode(node, editor.graph))
)
}),
- canOutlineStroke: useSceneComputed(() => {
- const nodes = editor.getSelectedNodes()
- return (
- nodes.length > 0 &&
- nodes.every(
- (node) =>
- hasVisibleStrokeSourceNode(node, editor.graph) &&
- canMakeBooleanSourceNode(node, editor.graph)
- )
- )
- }),
+ canOutlineStroke: useSceneComputed(
+ () => layersToOutline(editor.getSelectedNodes(), editor.graph).length > 0
+ ),
canGoToMainComponent: computed(() => selection.isInstance.value),
canCreateInstance: computed(() => selectedNode.value?.type === 'COMPONENT'),
canCreateSlot: selection.canCreateSlot,
diff --git a/src/app/editor/canvas/menu/context.ts b/src/app/editor/canvas/menu/context.ts
index 6b62a9d1e..832bc20c1 100644
--- a/src/app/editor/canvas/menu/context.ts
+++ b/src/app/editor/canvas/menu/context.ts
@@ -55,7 +55,9 @@ function copyAction(
actions.clipboardWrite(editor.copySelectionAsText(actions.ids()), 'text')
)
case 'copy-as-svg':
- return runAsync(() => actions.clipboardWrite(editor.copySelectionAsSVG(actions.ids()), 'SVG'))
+ return runAsync(async () =>
+ actions.clipboardWrite(await editor.copySelectionAsSVG(actions.ids()), 'SVG')
+ )
case 'copy-as-png':
return runAsync(actions.copyAsPNG)
case 'copy-as-jsx':