AI-native design editor. Open-source Figma alternative.
fix(pen): place turned, mirrored, and grouped layers as pen.dev draws them (#1411)
Danila Poyarkovb550dc7f1f52
diff --git a/changes/1411/fixed.md b/changes/1411/fixed.mdnew file mode 100644index 000000000..fe35f3e9f--- /dev/null+++ b/changes/1411/fixed.md@@ -0,0 +1 @@+- Turned, mirrored, and grouped layers of `.pen` files land where pen.dev draws them, polygons keep their sides, ellipses their arcs and rings, and paths their view box and even-odd fill.diff --git a/packages/core/src/io/formats.ts b/packages/core/src/io/formats.tsindex a454d95db..0cdbdda18 100644--- a/packages/core/src/io/formats.ts+++ b/packages/core/src/io/formats.ts@@ -228,12 +228,14 @@ export const penFormat: IOFormatAdapter<'pen'> = {},async readDocument(input) {const text = new TextDecoder().decode(input.data)- const graph = parsePenFile(text)// A .pen file stores its layout intent, not the sizes and positions it implies.- layoutAuthoredNodes(- graph,- graph.getPages().map((page) => page.id)- )+ const graph = parsePenFile(text, {+ layout: (target) =>+ layoutAuthoredNodes(+ target,+ target.getPages().map((page) => page.id)+ )+ })return { graph, sourceFormat: 'pen' }}}diff --git a/packages/core/tests/io/formats/pen/layout.test.ts b/packages/core/tests/io/formats/pen/layout.test.tsindex be6d1bafe..f6f3d9b1e 100644--- a/packages/core/tests/io/formats/pen/layout.test.ts+++ b/packages/core/tests/io/formats/pen/layout.test.ts@@ -2,16 +2,19 @@ import { describe, expect, test } from 'bun:test'import { layoutAuthoredNodes } from '@open-pencil/core/layout'import { parsePenFile, type PenDocument, type PenNode } from '@open-pencil/pen'+import { getNodeLocalMatrix } from '@open-pencil/scene-graph/coordinate'+import Matrix from '@open-pencil/scene-graph/matrix'function parseLayoutDocument(children: PenNode[]) {const document: PenDocument = { version: '2.17', children }- const graph = parsePenFile(JSON.stringify(document))- // As the .pen reader lays out what it reads.- layoutAuthoredNodes(- graph,- graph.getPages().map((page) => page.id)- )- return graph+ // As Core's .pen reader lays out what it reads.+ return parsePenFile(JSON.stringify(document), {+ layout: (graph) =>+ layoutAuthoredNodes(+ graph,+ graph.getPages().map((page) => page.id)+ )+ })}function fixedChild(id: string): PenNode {@@ -252,3 +255,28 @@ describe('parsePenFile — text without a width', () => {expect([...graph.getAllNodes()].find((node) => node.type === 'TEXT')?.width).toBe(0)})})++describe('parsePenFile — turned layers sized by layout', () => {+ test('turns auto-width text about its corner after laying it out', () => {+ const graph = parseLayoutDocument([+ {+ id: 'free',+ type: 'frame',+ layout: 'none',+ width: 400,+ height: 300,+ children: [{ id: 'label', type: 'text', x: 100, y: 200, rotation: 90, content: 'Revenue', fontSize: 14 }]+ }+ ])+ const label = graph.getNode('label')+ if (!label) throw new Error('label missing')+ expect(label.width).toBeGreaterThan(0)+ const [cornerX, cornerY] = Matrix.mapPoints(getNodeLocalMatrix(label), [0, 0])+ expect(cornerX).toBeCloseTo(100)+ expect(cornerY).toBeCloseTo(200)+ // Turned a quarter counter-clockwise, the text runs upwards from its corner.+ const [endX, endY] = Matrix.mapPoints(getNodeLocalMatrix(label), [label.width, 0])+ expect(endX).toBeCloseTo(100)+ expect(endY).toBeCloseTo(200 - label.width)+ })+})diff --git a/packages/pen/src/convert.ts b/packages/pen/src/convert.tsindex 8e9ee421e..01fed9640 100644--- a/packages/pen/src/convert.ts+++ b/packages/pen/src/convert.ts@@ -141,6 +141,8 @@ export function mapNodeType(pen: PenNode): NodeType {if (pen.type === 'frame') return pen.reusable ? 'COMPONENT' : 'FRAME'if (pen.type === 'rectangle') return 'RECTANGLE'if (pen.type === 'ellipse') return 'ELLIPSE'+ if (pen.type === 'polygon') return 'POLYGON'+ if (pen.type === 'group') return 'GROUP'if (pen.type === 'text' || pen.type === 'icon_font') return 'TEXT'if (pen.type === 'path') return 'VECTOR'if (pen.type === 'ref') return 'INSTANCE'diff --git a/packages/pen/src/geometry.ts b/packages/pen/src/geometry.tsnew file mode 100644index 000000000..d7311f62e--- /dev/null+++ b/packages/pen/src/geometry.ts@@ -0,0 +1,59 @@+import type { ArcData, VectorNetwork } from '@open-pencil/scene-graph'+import { parseSVGPath } from '@open-pencil/scene-graph/parse-path'++import type { PenNode } from './schema'+import { resolveNumber, type VarContext } from './variables'++const DEGREES = Math.PI / 180++/**+ * An ellipse's arc. pen.dev measures `startAngle` counter-clockwise from the right and sweeps+ * counter-clockwise for a positive `sweepAngle`; the scene graph measures clockwise.+ */+export function ellipseArc(pen: PenNode, ctx: VarContext): ArcData | null {+ if (pen.innerRadius === undefined && pen.startAngle === undefined && pen.sweepAngle === undefined)+ return null+ const start = resolveNumber(pen.startAngle, ctx)+ const sweep = Math.max(-360, Math.min(360, resolveNumber(pen.sweepAngle, ctx, 360)))+ return {+ startingAngle: -start * DEGREES,+ endingAngle: -(start + sweep) * DEGREES,+ innerRadius: Math.max(0, Math.min(1, resolveNumber(pen.innerRadius, ctx)))+ }+}++type ViewBox = [x: number, y: number, width: number, height: number]++function networkBounds(network: VectorNetwork): ViewBox {+ let [minX, minY, maxX, maxY] = [Infinity, Infinity, -Infinity, -Infinity]+ for (const { x, y } of network.vertices) {+ minX = Math.min(minX, x)+ minY = Math.min(minY, y)+ maxX = Math.max(maxX, x)+ maxY = Math.max(maxY, y)+ }+ return [minX, minY, maxX - minX, maxY - minY]+}++/**+ * A path's geometry in its box. `viewBox` is the region of the path's coordinates that fills the+ * box; without one, the geometry's own bounds do. An axis the geometry has no extent on is not+ * scaled, so a straight line keeps its place.+ */+export function pathNetwork(pen: PenNode, width: number, height: number): VectorNetwork | null {+ if (!pen.geometry) return null+ const network = parseSVGPath(pen.geometry, pen.fillRule === 'evenodd' ? 'EVENODD' : 'NONZERO')+ if (network.vertices.length === 0) return network+ const [vx, vy, vw, vh] = pen.viewBox ?? networkBounds(network)+ const sx = vw > 0 ? width / vw : 1+ const sy = vh > 0 ? height / vh : 1+ for (const vertex of network.vertices) {+ vertex.x = (vertex.x - vx) * sx+ vertex.y = (vertex.y - vy) * sy+ }+ for (const segment of network.segments) {+ segment.tangentStart = { x: segment.tangentStart.x * sx, y: segment.tangentStart.y * sy }+ segment.tangentEnd = { x: segment.tangentEnd.x * sx, y: segment.tangentEnd.y * sy }+ }+ return network+}diff --git a/packages/pen/src/placement.ts b/packages/pen/src/placement.tsnew file mode 100644index 000000000..48cdbdf25--- /dev/null+++ b/packages/pen/src/placement.ts@@ -0,0 +1,84 @@+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import { localTransformFromWorld } from '@open-pencil/scene-graph/coordinate'+import { fitEnclosingGroups } from '@open-pencil/scene-graph/group-bounds'+import Matrix from '@open-pencil/scene-graph/matrix'+import type { Vector } from '@open-pencil/scene-graph/primitives'++/**+ * Where pen.dev puts a layer: at `x`, `y` in its parent, turned `rotation` degrees+ * counter-clockwise and then mirrored, both about that corner. The scene graph turns clockwise and+ * mirrors about a layer's centre, so a layer's position depends on its final size and is set after+ * layout. Measured against pen.dev 2.21 renders of turned, mirrored, and grouped layers.+ */+export interface PenPlacement {+ x: number+ y: number+ rotation: number+ flipX: boolean+ flipY: boolean+}++export function isPlain(placement: PenPlacement): boolean {+ return placement.rotation === 0 && !placement.flipX && !placement.flipY+}++function inFlow(graph: SceneGraph, node: SceneNode): boolean {+ const parent = node.parentId ? graph.getNode(node.parentId) : undefined+ return !!parent && parent.layoutMode !== 'NONE' && node.layoutPositioning !== 'ABSOLUTE'+}++/** Sets a layer's position and turn so it lands where pen.dev draws it; `offset` is where its box starts in pen.dev's. */+function place(+ graph: SceneGraph,+ node: SceneNode,+ placement: PenPlacement,+ offset: Vector = { x: 0, y: 0 }+) {+ const world = Matrix.multiply(+ Matrix.translated(placement.x, placement.y),+ Matrix.rotated((-placement.rotation * Math.PI) / 180),+ Matrix.scaled(placement.flipX ? -1 : 1, placement.flipY ? -1 : 1),+ Matrix.translated(offset.x, offset.y)+ )+ const local = localTransformFromWorld(+ { ...node, flipX: placement.flipX },+ world,+ Matrix.identity()+ )+ if (!local) return+ // Auto layout places the layers in its flow; only their turn and mirroring carry over.+ if (inFlow(graph, node)) graph.updateNode(node.id, { ...local, x: node.x, y: node.y })+ else graph.updateNode(node.id, local)+}++/**+ * Places every turned or mirrored layer, which the reader builds upright. Then each group, inner+ * ones first, is fitted to its placed layers and placed itself; its box starts at its layers'+ * bounds, wherever pen.dev's starts. `groupIds` is in reading order.+ */+export function placeLayers(+ graph: SceneGraph,+ placements: ReadonlyMap<string, PenPlacement>,+ groupIds: readonly string[]+): void {+ const groups = new Set(groupIds)+ for (const [id, placement] of placements) {+ const node = graph.getNode(id)+ if (node && !groups.has(id) && !isPlain(placement)) place(graph, node, placement)+ }++ const origins = new Map<string, Vector>()+ for (const id of groupIds) {+ const group = graph.getNode(id)+ if (group) origins.set(id, { x: group.x, y: group.y })+ }+ // Reading order lists a group before the groups inside it, so reversed it is innermost first.+ for (const id of groupIds.toReversed()) {+ fitEnclosingGroups(graph, [id])+ const node = graph.getNode(id)+ const origin = origins.get(id)+ const placement = placements.get(id)+ if (!node || !origin || !placement || isPlain(placement)) continue+ place(graph, node, placement, { x: node.x - origin.x, y: node.y - origin.y })+ }+}diff --git a/packages/pen/src/read.ts b/packages/pen/src/read.tsindex 815fe0008..9e3a958cc 100644--- a/packages/pen/src/read.ts+++ b/packages/pen/src/read.ts@@ -5,13 +5,11 @@ import {type AxisSizingMode,type LayoutMode,type LayoutSizing,- type SceneNode,- type VectorNetwork+ type SceneNode} from '@open-pencil/scene-graph'import { copyEffects, copyFills, copyStrokes } from '@open-pencil/scene-graph/copy'import { populateInstanceChildren } from '@open-pencil/scene-graph/instances'import { fillSizingFields } from '@open-pencil/scene-graph/layout'-import { parseSVGPath } from '@open-pencil/scene-graph/parse-path'import {applyCornerRadius,@@ -26,7 +24,9 @@ import {parseSize} from './convert'import { convertEffects } from './effects'+import { ellipseArc, pathNetwork } from './geometry'import { applyStroke, convertPaints, strokeFields } from './paints'+import { isPlain, placeLayers, type PenPlacement } from './placement'import { penFileSchema, type PenNode, type PenOverride } from './schema'import {bindIfVar,@@ -37,32 +37,25 @@ import {type VarContext} from './variables'-function scaleVectorNetwork(vn: VectorNetwork, targetW: number, targetH: number): void {- if (vn.vertices.length === 0) return- let minX = Infinity- let maxX = -Infinity- let minY = Infinity- let maxY = -Infinity- for (const v of vn.vertices) {- minX = Math.min(minX, v.x)- maxX = Math.max(maxX, v.x)- minY = Math.min(minY, v.y)- maxY = Math.max(maxY, v.y)- }- const vnW = maxX - minX- const vnH = maxY - minY- if (vnW < 0.01 || vnH < 0.01) return- const sx = targetW / vnW- const sy = targetH / vnH- if (Math.abs(sx - 1) < 0.01 && Math.abs(sy - 1) < 0.01) return- for (const v of vn.vertices) {- v.x = (v.x - minX) * sx- v.y = (v.y - minY) * sy- }- for (const s of vn.segments) {- s.tangentStart = { x: s.tangentStart.x * sx, y: s.tangentStart.y * sy }- s.tangentEnd = { x: s.tangentEnd.x * sx, y: s.tangentEnd.y * sy }- }+/** Options for reading a document. */+export interface PenReadOptions {+ /**+ * Lays out the graph's auto layout and text, as `layoutAuthoredNodes` in Core does. Turned and+ * mirrored layers are placed after it, since where they land depends on their final size.+ */+ layout?(graph: SceneGraph): void+}++/** What reading one document builds up. */+interface Build {+ graph: SceneGraph+ ctx: VarContext+ componentIds: Map<string, string>+ penSources: Map<string, PenNode>+ /** pen.dev's placement of each turned or mirrored layer, and of every group. */+ placements: Map<string, PenPlacement>+ /** Groups in reading order. */+ groupIds: string[]}function resolveFontFamily(raw: string | undefined, ctx: VarContext): string {@@ -71,6 +64,17 @@ function resolveFontFamily(raw: string | undefined, ctx: VarContext): string {return raw}+function penPlacement(pen: PenOverride, ctx: VarContext, base?: PenPlacement): PenPlacement {+ return {+ x: pen.x ?? base?.x ?? 0,+ y: pen.y ?? base?.y ?? 0,+ rotation: pen.rotation === undefined ? (base?.rotation ?? 0) : resolveNumber(pen.rotation, ctx),+ flipX: pen.flipX === undefined ? (base?.flipX ?? false) : resolveBoolean(pen.flipX, ctx),+ flipY: pen.flipY === undefined ? (base?.flipY ?? false) : resolveBoolean(pen.flipY, ctx)+ }+}++/** A layer's own fields; it is built upright and placed once laid out. */function buildBaseOverrides(pen: PenNode, ctx: VarContext): Partial<SceneNode> {return {id: pen.id,@@ -79,9 +83,6 @@ function buildBaseOverrides(pen: PenNode, ctx: VarContext): Partial<SceneNode> {y: pen.y ?? 0,visible: resolveBoolean(pen.enabled, ctx),opacity: resolveNumber(pen.opacity, ctx, 1),- rotation: resolveNumber(pen.rotation, ctx),- flipX: resolveBoolean(pen.flipX, ctx, false),- flipY: resolveBoolean(pen.flipY, ctx, false),clipsContent: resolveBoolean(pen.clip, ctx, false),boundVariables: {}}@@ -189,14 +190,8 @@ function applyRefVisuals(if (pen.cornerRadius === undefined) applyCornerRadius(node, compPen.cornerRadius, ctx)}-function applyRefProps(- node: SceneNode,- pen: PenNode,- graph: SceneGraph,- componentIds: Map<string, string>,- penSources: Map<string, PenNode>,- ctx: VarContext-): void {+function applyRefProps(node: SceneNode, pen: PenNode, build: Build): void {+ const { graph, componentIds, penSources, ctx } = buildif (!pen.ref) returnconst componentId = componentIds.get(pen.ref) ?? pen.refnode.componentId = componentId@@ -208,19 +203,13 @@ function applyRefProps(applyRefVisuals(node, pen, penSources.get(pen.ref), ctx)}-function applyAllRefProps(- penNodes: PenNode[],- graph: SceneGraph,- componentIds: Map<string, string>,- penSources: Map<string, PenNode>,- ctx: VarContext-): void {+function applyAllRefProps(penNodes: PenNode[], build: Build): void {for (const pen of penNodes) {if (pen.type === 'ref') {- const node = graph.getNode(pen.id)- if (node) applyRefProps(node, pen, graph, componentIds, penSources, ctx)+ const node = build.graph.getNode(pen.id)+ if (node) applyRefProps(node, pen, build)}- if (pen.children) applyAllRefProps(pen.children, graph, componentIds, penSources, ctx)+ if (pen.children) applyAllRefProps(pen.children, build)}}@@ -230,14 +219,8 @@ function applyTheme(theme: Record<string, string>, ctx: VarContext): void {}// eslint-disable-next-line complexity -- .pen node mapping touches many format-specific fields-function createSceneNode(- pen: PenNode,- parentId: string,- graph: SceneGraph,- ctx: VarContext,- componentIds: Map<string, string>,- penSources: Map<string, PenNode>-): string | null {+function createSceneNode(pen: PenNode, parentId: string, build: Build): string | null {+ const { graph, ctx } = buildif (pen.type === 'prompt') return nullif (pen.theme) applyTheme(pen.theme, ctx)@@ -259,6 +242,9 @@ function createSceneNode(}const node = graph.createNode(mapNodeType(pen), parentId, overrides)+ const placement = penPlacement(pen, ctx)+ if (pen.type === 'group') build.groupIds.push(node.id)+ if (pen.type === 'group' || !isPlain(placement)) build.placements.set(node.id, placement)node.fills = convertPaints(pen.fill, 'fills', ctx, node)applyStroke(node, strokeFields(pen), ctx)@@ -269,10 +255,11 @@ function createSceneNode(// Text without a width resizes to its content, which laying out the document measures.if (isTextLike) applyTextProps(node, pen, ctx)- if (pen.type === 'path' && pen.geometry) {- const vectorNetwork = parseSVGPath(pen.geometry)- node.vectorNetwork = vectorNetwork- scaleVectorNetwork(vectorNetwork, node.width, node.height)+ if (pen.type === 'ellipse') node.arcData = ellipseArc(pen, ctx)+ if (pen.type === 'polygon') node.pointCount = Math.max(3, resolveNumber(pen.polygonCount, ctx, 3))+ if (pen.type === 'path') {+ const network = pathNetwork(pen, node.width, node.height)+ if (network) node.vectorNetwork = network}if (parentLayout !== 'NONE') {@@ -281,14 +268,12 @@ function createSceneNode(}if (pen.reusable) {- componentIds.set(pen.id, node.id)- penSources.set(pen.id, pen)+ build.componentIds.set(pen.id, node.id)+ build.penSources.set(pen.id, pen)}if (pen.children) {- for (const child of pen.children) {- createSceneNode(child, node.id, graph, ctx, componentIds, penSources)- }+ for (const child of pen.children) createSceneNode(child, node.id, build)}return node.id@@ -342,38 +327,42 @@ function findCloneByNameFallback(return matches.length === 1 ? matches[0] : undefined}-function applyOverrideProps(target: SceneNode, overrideData: PenOverride, ctx: VarContext): void {+function applyOverrideProps(target: SceneNode, overrideData: PenOverride, build: Build): void {+ const { ctx } = buildif (overrideData.fill !== undefined)target.fills = convertPaints(overrideData.fill, 'fills', ctx, target)if (overrideData.content !== undefined) target.text = overrideData.contentif (overrideData.x !== undefined) target.x = overrideData.xif (overrideData.y !== undefined) target.y = overrideData.y+ const base = build.placements.get(target.id)+ const placement = penPlacement(overrideData, ctx, base ?? { ...target, rotation: 0 })+ if (base || !isPlain(placement)) build.placements.set(target.id, placement)if (overrideData.enabled !== undefined) target.visible = resolveBoolean(overrideData.enabled, ctx)if (overrideData.width !== undefined)target.width = parseSize(overrideData.width, target.width, ctx).valueif (overrideData.height !== undefined)target.height = parseSize(overrideData.height, target.height, ctx).value- if (overrideData.rotation !== undefined)- target.rotation = resolveNumber(overrideData.rotation, ctx)if (overrideData.name !== undefined) target.name = overrideData.name}-function populateInstances(graph: SceneGraph): void {+/** Fills empty instances from their components; a copied layer keeps its source's placement. */+function populateInstances(build: Build): void {+ const { graph, placements } = buildfor (const node of graph.getAllNodes()) {- if (node.type === 'INSTANCE' && node.componentId && node.childIds.length === 0) {- const component = graph.getNode(node.componentId)- if (component) populateInstanceChildren(graph, node.id, node.componentId)+ if (node.type !== 'INSTANCE' || !node.componentId || node.childIds.length > 0) continue+ if (!graph.getNode(node.componentId)) continue+ populateInstanceChildren(graph, node.id, node.componentId)+ const copies = [...graph.getChildren(node.id)]+ for (const copy of copies) {+ const source = copy.componentId ? placements.get(copy.componentId) : undefined+ if (source && !placements.has(copy.id)) placements.set(copy.id, source)+ copies.push(...graph.getChildren(copy.id))}}}-function applyDescendantOverrides(- graph: SceneGraph,- pen: PenNode,- ctx: VarContext,- componentIds: Map<string, string>,- penSources: Map<string, PenNode>-): void {+function applyDescendantOverrides(pen: PenNode, build: Build): void {+ const { graph } = buildif (pen.type !== 'ref' || !pen.descendants) returnconst instanceNode = graph.getNode(pen.id)if (!instanceNode) return@@ -387,37 +376,22 @@ function applyDescendantOverrides(if (overrideData.children) {const toDelete = clone.childIds.slice()for (const childId of toDelete) graph.deleteNode(childId)- for (const child of overrideData.children) {- createSceneNode(child, clone.id, graph, ctx, componentIds, penSources)- }+ for (const child of overrideData.children) createSceneNode(child, clone.id, build)}- applyOverrideProps(clone, overrideData, ctx)+ applyOverrideProps(clone, overrideData, build)continue}if (overrideData.type && overrideData.id) {- createSceneNode(- overrideData as PenNode,- instanceNode.id,- graph,- ctx,- componentIds,- penSources- )+ createSceneNode(overrideData as PenNode, instanceNode.id, build)}}}-function walkAndApplyOverrides(- nodes: PenNode[],- graph: SceneGraph,- ctx: VarContext,- componentIds: Map<string, string>,- penSources: Map<string, PenNode>-): void {+function walkAndApplyOverrides(nodes: PenNode[], build: Build): void {for (const pen of nodes) {- applyDescendantOverrides(graph, pen, ctx, componentIds, penSources)- if (pen.children) walkAndApplyOverrides(pen.children, graph, ctx, componentIds, penSources)+ applyDescendantOverrides(pen, build)+ if (pen.children) walkAndApplyOverrides(pen.children, build)}}@@ -469,7 +443,16 @@ function fixInstanceWidths(graph: SceneGraph): void {}}-export function parsePenFile(json: string): SceneGraph {+/** Whether a group sits in an auto layout's flow, where fitting it changes the layout. */+function groupsInFlow(graph: SceneGraph, groupIds: readonly string[]): boolean {+ return groupIds.some((id) => {+ const group = graph.getNode(id)+ const parent = group?.parentId ? graph.getNode(group.parentId) : undefined+ return parent !== undefined && parent.layoutMode !== 'NONE'+ })+}++export function parsePenFile(json: string, options: PenReadOptions = {}): SceneGraph {const parsed = v.safeParse(penFileSchema, json)if (!parsed.success) {throw new Error(`Not a .pen document: ${v.summarize(parsed.issues)}`)@@ -482,23 +465,31 @@ export function parsePenFile(json: string): SceneGraph {}const ctx = buildVarContext(graph, doc.variables ?? {}, doc.themes ?? {})- const componentIds = new Map<string, string>()- const penSources = new Map<string, PenNode>()+ const build: Build = {+ graph,+ ctx,+ componentIds: new Map(),+ penSources: new Map(),+ placements: new Map(),+ groupIds: []+ }- collectComponentIds(doc.children, componentIds)+ collectComponentIds(doc.children, build.componentIds)const page = graph.addPage(doc.children[0]?.name ?? 'Page 1')- for (const child of doc.children) {- createSceneNode(child, page.id, graph, ctx, componentIds, penSources)- }+ for (const child of doc.children) createSceneNode(child, page.id, build)- applyAllRefProps(doc.children, graph, componentIds, penSources, ctx)- populateInstances(graph)- walkAndApplyOverrides(doc.children, graph, ctx, componentIds, penSources)- populateInstances(graph)+ applyAllRefProps(doc.children, build)+ populateInstances(build)+ walkAndApplyOverrides(doc.children, build)+ populateInstances(build)resolveThemeVariables(doc.children, graph, ctx)fixInstanceWidths(graph)+ options.layout?.(graph)+ placeLayers(graph, build.placements, build.groupIds)+ if (groupsInFlow(graph, build.groupIds)) options.layout?.(graph)+if (graph.getPages(true).length === 0) {graph.addPage('Page 1')}@@ -506,6 +497,6 @@ export function parsePenFile(json: string): SceneGraph {return graph}-export async function readPenFile(file: File): Promise<SceneGraph> {- return parsePenFile(await file.text())+export async function readPenFile(file: File, options?: PenReadOptions): Promise<SceneGraph> {+ return parsePenFile(await file.text(), options)}diff --git a/packages/pen/tests/geometry.test.ts b/packages/pen/tests/geometry.test.tsnew file mode 100644index 000000000..0ea5e4b50--- /dev/null+++ b/packages/pen/tests/geometry.test.ts@@ -0,0 +1,178 @@+import { describe, expect, test } from 'bun:test'++import type { PenNode } from '@open-pencil/pen'+import type { SceneGraph } from '@open-pencil/scene-graph'+import { getNodeLocalMatrix } from '@open-pencil/scene-graph/coordinate'+import Matrix from '@open-pencil/scene-graph/matrix'+import type { Vector } from '@open-pencil/scene-graph/primitives'++import { expectDefined, getNodeOrThrow } from './helpers/assert'+import { parseDocument } from './helpers/document'++function nodeIn(children: PenNode[], id: string) {+ return getNodeOrThrow(+ parseDocument([+ { id: 'page', type: 'frame', layout: 'none', width: 600, height: 400, children }+ ]),+ id+ )+}++/** Where a layer's local point lands in its parent, the way the renderer draws it. */+function pointInParent(graph: SceneGraph, id: string, x: number, y: number) {+ const [px, py] = Matrix.mapPoints(getNodeLocalMatrix(getNodeOrThrow(graph, id)), [x, y])+ return { x: px, y: py }+}++function expectPoint(actual: Vector, x: number, y: number) {+ expect(actual.x).toBeCloseTo(x, 6)+ expect(actual.y).toBeCloseTo(y, 6)+}++const rect = (id: string, fields: Partial<PenNode>): PenNode => ({+ id,+ type: 'rectangle',+ width: 100,+ height: 60,+ ...fields+})++describe('parsePenFile — shapes', () => {+ test('reads an ellipse arc, counter-clockwise in pen.dev and clockwise in the scene graph', () => {+ const node = nodeIn(+ [+ {+ id: 'arc',+ type: 'ellipse',+ width: 100,+ height: 80,+ startAngle: 30,+ sweepAngle: 200,+ innerRadius: 0.4+ }+ ],+ 'arc'+ )+ expect(node.arcData?.startingAngle).toBeCloseTo((-30 * Math.PI) / 180)+ expect(node.arcData?.endingAngle).toBeCloseTo((-230 * Math.PI) / 180)+ expect(node.arcData?.innerRadius).toBe(0.4)+ })++ test('keeps a whole ellipse without arc data', () => {+ expect(+ nodeIn([{ id: 'oval', type: 'ellipse', width: 100, height: 80 }], 'oval').arcData+ ).toBeNull()+ })++ test('reads polygons with their side count and corner radius', () => {+ const node = nodeIn(+ [{ id: 'pent', type: 'polygon', width: 100, height: 80, polygonCount: 5, cornerRadius: 10 }],+ 'pent'+ )+ expect(node.type).toBe('POLYGON')+ expect(node.pointCount).toBe(5)+ expect(node.cornerRadius).toBe(10)+ })++ test('maps a path view box onto the layer box instead of stretching the geometry', () => {+ const node = nodeIn(+ [+ {+ id: 'tri',+ type: 'path',+ width: 100,+ height: 80,+ geometry: 'M0 0 L50 0 L50 50 Z',+ viewBox: [0, 0, 100, 100]+ }+ ],+ 'tri'+ )+ const xs = expectDefined(node.vectorNetwork).vertices.map((vertex) => vertex.x)+ const ys = expectDefined(node.vectorNetwork).vertices.map((vertex) => vertex.y)+ expect(Math.max(...xs)).toBeCloseTo(50)+ expect(Math.max(...ys)).toBeCloseTo(40)+ })++ test('keeps an even-odd fill rule', () => {+ const node = nodeIn(+ [+ {+ id: 'ring',+ type: 'path',+ width: 100,+ height: 80,+ fillRule: 'evenodd',+ geometry: 'M0 0H100V80H0Z M25 20H75V60H25Z'+ }+ ],+ 'ring'+ )+ expect(+ expectDefined(node.vectorNetwork).regions.every((region) => region.windingRule === 'EVENODD')+ ).toBe(true)+ })+})++// Measured on pen.dev 2.21: a layer turns counter-clockwise about its x, y corner, and mirrors+// about that corner in its own axes, after turning.+describe('parsePenFile — turned and mirrored layers', () => {+ function graphOf(children: PenNode[]) {+ return parseDocument([+ { id: 'page', type: 'frame', layout: 'none', width: 600, height: 400, children }+ ])+ }++ test('turns a layer counter-clockwise about its top-left corner', () => {+ const graph = graphOf([rect('turned', { x: 60, y: 40, rotation: 30 })])+ const cos = Math.cos(Math.PI / 6)+ expectPoint(pointInParent(graph, 'turned', 0, 0), 60, 40)+ expectPoint(pointInParent(graph, 'turned', 100, 0), 60 + 100 * cos, 40 - 50)+ })++ test('mirrors a layer about its corner, in its own axes', () => {+ const graph = graphOf([rect('mirrored', { x: 220, y: 40, rotation: 30, flipX: true })])+ const node = getNodeOrThrow(graph, 'mirrored')+ expect(node.flipX).toBe(true)+ expectPoint(pointInParent(graph, 'mirrored', 0, 0), 220, 40)+ // The local right edge lands to the left of the corner.+ expectPoint(+ pointInParent(graph, 'mirrored', 100, 0),+ 220 - 100 * Math.cos(Math.PI / 6),+ 40 + 50+ )+ })++ test('mirrors an upright layer to the left of its x', () => {+ const graph = graphOf([rect('flipped', { x: 340, y: 40, flipX: true })])+ expectPoint(pointInParent(graph, 'flipped', 0, 0), 340, 40)+ expect(getNodeOrThrow(graph, 'flipped').x).toBeCloseTo(240)+ })++ test('fits a group to its layers and turns it about its own origin', () => {+ const graph = graphOf([+ {+ id: 'group',+ type: 'group',+ x: 80,+ y: 180,+ rotation: 20,+ children: [+ rect('a', { x: 10, y: 5, width: 80, height: 40 }),+ { id: 'b', type: 'ellipse', x: 90, y: 20, width: 30, height: 30 }+ ]+ }+ ])+ const group = getNodeOrThrow(graph, 'group')+ expect(group.type).toBe('GROUP')+ expect([group.width, group.height]).toEqual([110, 45])+ const angle = (20 * Math.PI) / 180+ // Layer a's corner sits at (10, 5) in the group's pen.dev space.+ const [ax, ay] = Matrix.mapPoints(+ Matrix.multiply(getNodeLocalMatrix(group), getNodeLocalMatrix(getNodeOrThrow(graph, 'a'))),+ [0, 0]+ )+ expect(ax).toBeCloseTo(80 + 10 * Math.cos(angle) + 5 * Math.sin(angle))+ expect(ay).toBeCloseTo(180 - 10 * Math.sin(angle) + 5 * Math.cos(angle))+ })+})