AI-native design editor. Open-source Figma alternative.
feat: open draw.io diagrams as FigJam shapes and connectors (#1446)
Danila Poyarkovd63b4af7b4ad
diff --git a/AGENTS.md b/AGENTS.mdindex 2f18406e0..36fc70a13 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -13,7 +13,7 @@ This file holds the repository map and the rules that apply everywhere. Rules fo| `packages/drawio` | draw.io model, reader and writer for `.drawio`/`.dio` files and the diagrams draw.io PNG and SVG exports embed; no SceneGraph | — || `packages/kiwi` | SceneGraph-independent Kiwi schema/runtime, codecs, containers, parse helpers | `packages/fig/AGENTS.md` || `packages/fig` | `.fig` archives, SceneGraph conversion, metadata policy, component/instance interpretation, Figma clipboard | `packages/fig/AGENTS.md` |-| `packages/core` | Renderer, layout, editor, Figma API, tools, clipboard, vector conversion, document I/O; depends on scene-graph and the format packages (pen, kiwi, fig, dom-css, design-jsx); no browser DOM | `packages/core/AGENTS.md` |+| `packages/core` | Renderer, layout, editor, Figma API, tools, clipboard, vector conversion, document I/O; depends on scene-graph and the format packages (pen, drawio, kiwi, fig, dom-css, design-jsx); no browser DOM | `packages/core/AGENTS.md` || `packages/dom-css` | DOM/CSS/HTML/JSX/Tailwind projection and browser/headless adapters; depends only on scene-graph and emit, and takes engine services such as web-font resolution as injected options | `packages/dom-css/AGENTS.md` || `packages/emit` | Source emission for exporters: ESTree and JSX builders, template filling, and esrap printing, with the literal rules that keep exported strings from being reinterpreted | — || `packages/design-jsx` | OpenPencil design JSX: elements, paint/effect helpers, variables, schema and authoring reference, JSX export, and a renderer that takes icons, SVG, and layout as injected services | `packages/design-jsx/AGENTS.md` |diff --git a/bun.lock b/bun.lockindex 64d8521b0..8d71a4b46 100644--- a/bun.lock+++ b/bun.lock@@ -262,6 +262,7 @@"@iconify/utils": "^3.1.4","@open-pencil/design-jsx": "workspace:*","@open-pencil/dom-css": "workspace:*",+ "@open-pencil/drawio": "workspace:*","@open-pencil/fig": "workspace:*","@open-pencil/kiwi": "workspace:*","@open-pencil/pen": "workspace:*",@@ -284,6 +285,7 @@"nanoevents": "^9.1.0","ofetch": "^1.5.1","opentype.js": "^2.0.0",+ "parse5": "^8.0.1","pixelmatch": "^7.2.0","pptxgenjs": "^4.0.1","rbush": "^4.0.1",diff --git a/changes/1446/added.md b/changes/1446/added.mdnew file mode 100644index 000000000..f689ee79d--- /dev/null+++ b/changes/1446/added.md@@ -0,0 +1 @@+- draw.io diagrams open: `.drawio` and `.dio` files and draw.io's editable PNG and SVG exports become pages of FigJam shapes with text and connectors joined to them, keeping their colours, labels, arrowheads, bend points, layers, and containers.diff --git a/changes/1446/fixed.md b/changes/1446/fixed.mdnew file mode 100644index 000000000..12fd7da4d--- /dev/null+++ b/changes/1446/fixed.md@@ -0,0 +1 @@+- A connector's loose end no longer moves when the group holding it resizes around its other layers.diff --git a/packages/core/package.json b/packages/core/package.jsonindex 12591797f..15a993843 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -180,6 +180,7 @@"@iconify/utils": "^3.1.4","@open-pencil/design-jsx": "workspace:*","@open-pencil/dom-css": "workspace:*",+ "@open-pencil/drawio": "workspace:*","@open-pencil/fig": "workspace:*","@open-pencil/kiwi": "workspace:*","@open-pencil/pen": "workspace:*",@@ -202,6 +203,7 @@"nanoevents": "^9.1.0","ofetch": "^1.5.1","opentype.js": "^2.0.0",+ "parse5": "^8.0.1","pixelmatch": "^7.2.0","pptxgenjs": "^4.0.1","rbush": "^4.0.1",diff --git a/packages/core/src/io/formats.ts b/packages/core/src/io/formats.tsindex 6d2f4798d..33ff9993f 100644--- a/packages/core/src/io/formats.ts+++ b/packages/core/src/io/formats.ts@@ -1,4 +1,5 @@import { sceneNodeToJSX, selectionToJSX } from '@open-pencil/design-jsx'+import { isDrawioExportFileName } from '@open-pencil/drawio'import {buildPenGraph,isDataURL,@@ -305,6 +306,44 @@ export const penFormat: IOFormatAdapter<'pen'> = {}}+export const drawioFormat: IOFormatAdapter<'drawio'> = {+ id: 'drawio',+ label: 'draw.io Diagram',+ role: 'interchange-document',+ category: 'document',+ extensions: ['drawio', 'dio'],+ mimeTypes: ['application/vnd.jgraph.mxfile'],+ support: {+ readDocument: true+ },+ // A draw.io PNG or SVG export opens as its diagram when its name says it is one.+ matchesFile(fileName, mimeType) {+ const ext = lowerExt(fileName)+ return (+ ext === 'drawio' ||+ ext === 'dio' ||+ isDrawioExportFileName(fileName) ||+ mimeType === 'application/vnd.jgraph.mxfile'+ )+ },+ async readDocument(input) {+ const { readDrawioBytes } = await import('@open-pencil/drawio')+ const { drawioToSceneGraph } = await import('./formats/drawio')+ const file = readDrawioBytes(input.data)+ if (!file) throw new Error('This file holds no draw.io diagram')+ if (file.unreadable.length > 0) {+ throw new Error(`Could not read the draw.io pages ${file.unreadable.join(', ')}`)+ }+ const graph = drawioToSceneGraph(file)+ // draw.io stores label text, not the sizes it lays out to.+ layoutAuthoredNodes(+ graph,+ graph.getPages().map((page) => page.id)+ )+ return { graph, sourceFormat: 'drawio' }+ }+}+export const pngFormat = rasterFormat('PNG')export const jpgFormat = rasterFormat('JPG')export const webpFormat = rasterFormat('WEBP')@@ -487,6 +526,7 @@ export const tailwindJSXFormat: IOFormatAdapter<'tailwind-jsx'> = {export const BUILTIN_IO_FORMATS = [figFormat,penFormat,+ drawioFormat,pngFormat,jpgFormat,webpFormat,diff --git a/packages/core/src/io/formats/drawio/edges.ts b/packages/core/src/io/formats/drawio/edges.tsnew file mode 100644index 000000000..d54a2b816--- /dev/null+++ b/packages/core/src/io/formats/drawio/edges.ts@@ -0,0 +1,277 @@+import type { DrawioCell, DrawioStyle } from '@open-pencil/drawio'+import type {+ ConnectorControlPoint,+ ConnectorEndpoint,+ ConnectorLabelPosition,+ ConnectorLineType,+ ConnectorMagnet,+ SceneGraph,+ SceneNode,+ StrokeCap+} from '@open-pencil/scene-graph'+import {+ boundEndpoint,+ connectorRoute,+ connectorSublayers,+ createConnector,+ curveControlPoints,+ curveMidpoint,+ dragCurve,+ freeEndpoint,+ layoutConnector+} from '@open-pencil/scene-graph/connectors'+import type { Vector } from '@open-pencil/scene-graph/primitives'++import { readLabel } from './label'+import { dashOf, labelFields, labelFormat, lineColor } from './paint'++/** Edge styles that route at right angles, as FigJam's elbowed connectors do. */+const ELBOW_STYLES = new Set([+ 'orthogonalEdgeStyle',+ 'elbowEdgeStyle',+ 'entityRelationEdgeStyle',+ 'segmentEdgeStyle',+ 'isometricEdgeStyle'+])++/**+ * The line type an edge draws: curved when `curved=1`, elbowed for a right-angled edge style or+ * an edge bent through points of its own, and straight otherwise.+ */+function lineTypeOf(edge: DrawioCell): ConnectorLineType {+ const { values } = edge.style+ if (values.curved === '1') return 'CURVED'+ if (ELBOW_STYLES.has(values.edgeStyle ?? '') || edge.geometry.points.length > 0) return 'ELBOWED'+ return 'STRAIGHT'+}++/**+ * draw.io arrowheads and the FigJam ends that draw them: a filled triangle is FigJam's triangle+ * arrow (its "triangle" end points back, as a reversed one), an open one its line arrow.+ */+const CAPS = new Map<string, StrokeCap>([+ ['none', 'NONE'],+ ['classic', 'ARROW_EQUILATERAL'],+ ['classicThin', 'ARROW_EQUILATERAL'],+ ['block', 'ARROW_EQUILATERAL'],+ ['blockThin', 'ARROW_EQUILATERAL'],+ ['open', 'ARROW_LINES'],+ ['openThin', 'ARROW_LINES'],+ ['openAsync', 'ARROW_LINES'],+ ['async', 'ARROW_LINES'],+ ['oval', 'CIRCLE_FILLED'],+ ['diamond', 'DIAMOND_FILLED'],+ ['diamondThin', 'DIAMOND_FILLED']+])++/** An end's cap: `startArrow` is none and `endArrow` classic unless the style says otherwise. */+function capOf(style: DrawioStyle, key: 'startArrow' | 'endArrow'): StrokeCap {+ const arrow = style.values[key] ?? (key === 'endArrow' ? 'classic' : 'none')+ const fill = style.values[key === 'endArrow' ? 'endFill' : 'startFill']+ const cap = CAPS.get(arrow) ?? 'ARROW_LINES'+ // An unfilled triangle draws as FigJam's open arrow.+ return fill === '0' && cap === 'ARROW_EQUILATERAL' ? 'ARROW_LINES' : cap+}++/**+ * Where a label sits along an edge: draw.io keeps it `x` of the way from -1 at the source to 1 at+ * the target, or in the middle.+ */+export function labelPositionOf(x: number): ConnectorLabelPosition | null {+ if (x === 0) return null+ return {+ section: x < 0 ? 'MIDDLE_TO_START' : 'MIDDLE_TO_END',+ offset: Math.min(1, Math.abs(x)),+ offAxis: 'NONE'+ }+}++/** A drawn edge, made before the layers its ends join, so it keeps its place in the order. */+export interface PendingEdge {+ connector: SceneNode+ edge: DrawioCell+ /** Labels draw.io keeps as cells of the edge, which the connector's label takes in turn. */+ labels: DrawioCell[]+}++/**+ * Makes the connector an edge draws, in `parentId`, its ends free until `bindEdge` joins them.+ * Its line takes the edge's colour, width and dash.+ */+export function createEdge(+ graph: SceneGraph,+ parentId: string,+ edge: DrawioCell,+ labels: DrawioCell[]+): PendingEdge {+ const { style } = edge+ const connector = createConnector(+ graph,+ parentId,+ {+ start: freeEndpoint(0, 0),+ end: freeEndpoint(0, 0),+ lineType: lineTypeOf(edge),+ startCap: capOf(style, 'startArrow'),+ endCap: capOf(style, 'endArrow')+ },+ { visible: edge.visible }+ )+ const line = connectorSublayers(graph, connector)?.line+ const color = lineColor(style)+ const stroke = line?.strokes.at(0)+ if (line && stroke) {+ const weight = Number.parseFloat(style.values.strokeWidth ?? '1') || 1+ const dashPattern = dashOf(style, weight)+ graph.updateNode(line.id, {+ strokes: color ? [{ ...stroke, color: { ...color }, weight, dashPattern }] : [],+ strokeWeight: weight,+ dashPattern+ })+ }+ return { connector, edge, labels }+}++/**+ * An end of an edge: bound to the layer `cellId` drew, where `exitX`/`exitY` (or `entryX`/+ * `entryY`) put it as shares of the layer's box, or by the side it picks; free at the point the+ * edge stores when it joins nothing.+ */+/**+ * The side of `box` that faces `toward`, as an edge bent through a point leaves or enters by the+ * side that point lies beyond; null for a point over the box.+ */+function sideFacing(+ box: Pick<SceneNode, 'x' | 'y' | 'width' | 'height'>,+ toward: Vector+): ConnectorMagnet | null {+ if (toward.x > box.x + box.width) return 'RIGHT'+ if (toward.x < box.x) return 'LEFT'+ if (toward.y < box.y) return 'TOP'+ if (toward.y > box.y + box.height) return 'BOTTOM'+ return null+}++function endpointOf(+ graph: SceneGraph,+ layerOf: (cellId: string) => string | undefined,+ edge: DrawioCell,+ end: 'source' | 'target',+ straight: boolean+): ConnectorEndpoint {+ const cellId = edge[end]+ const nodeId = cellId ? layerOf(cellId) : undefined+ const node = nodeId ? graph.getNode(nodeId) : undefined+ if (node) {+ const prefix = end === 'source' ? 'exit' : 'entry'+ const x = Number.parseFloat(edge.style.values[`${prefix}X`] ?? '')+ const y = Number.parseFloat(edge.style.values[`${prefix}Y`] ?? '')+ if (Number.isFinite(x) && Number.isFinite(y)) {+ return {+ nodeId: node.id,+ magnet: 'NONE',+ position: { x: x * node.width, y: y * node.height }+ }+ }+ const { points } = edge.geometry+ const toward = end === 'source' ? points.at(0) : points.at(-1)+ // Both share the edge's parent's axes when the layer is a sibling of the edge.+ const facing =+ toward && node.parentId === layerOf(edge.parent) ? sideFacing(node, toward) : null+ return boundEndpoint(node.id, straight ? 'CENTER' : (facing ?? 'AUTO'))+ }+ const point = end === 'source' ? edge.geometry.sourcePoint : edge.geometry.targetPoint+ return freeEndpoint(point?.x ?? 0, point?.y ?? 0)+}++/**+ * The control lines an elbow takes to run through an edge's bend points in turn: across to each+ * point, then along to it, starting square to the side the connector leaves by.+ */+function elbowThrough(points: Vector[], leavesAcross: boolean): ConnectorControlPoint[] {+ const controls: ConnectorControlPoint[] = []+ for (const point of points) {+ const vertical: ConnectorControlPoint = { position: { ...point }, direction: 'VERTICAL' }+ const horizontal: ConnectorControlPoint = { position: { ...point }, direction: 'HORIZONTAL' }+ // A connector leaving sideways runs across to the point first.+ const pair = leavesAcross ? [vertical, horizontal] : [horizontal, vertical]+ for (const control of pair) {+ const last = controls.at(-1)+ if (last?.direction === control.direction) {+ last.position = control.position+ continue+ }+ controls.push(control)+ }+ }+ return controls+}++/**+ * Joins a connector's ends to the layers its edge connects, routes it through the edge's bend+ * points, and gives it the edge's label where draw.io placed it. Labels beyond the first come+ * back for the caller to draw as text.+ */+export function bindEdge(+ graph: SceneGraph,+ { connector, edge, labels }: PendingEdge,+ layerOf: (cellId: string) => string | undefined+): DrawioCell[] {+ const straight = connector.connectorLineType === 'STRAIGHT'+ graph.updateNode(connector.id, {+ connectorStart: endpointOf(graph, layerOf, edge, 'source', straight),+ connectorEnd: endpointOf(graph, layerOf, edge, 'target', straight)+ })+ const own = edge.value ? [edge] : []+ const all = [...own, ...labels]+ const label = all.at(0)+ const extra = all.slice(1)+ const parts = connectorSublayers(graph, connector)+ // The label takes the edge's font even while empty, ready to be typed into.+ if (parts) graph.updateNode(parts.label.id, labelFields(edge.style))+ if (label && parts) {+ const format = labelFormat(label.style)+ const read = readLabel(label.value, label.style.values.html === '1', format)+ graph.updateNode(parts.label.id, {+ ...labelFields(label.style, format),+ text: read.text,+ styleRuns: read.runs+ })+ const at = label === edge ? edge.geometry.x : label.geometry.x+ graph.updateNode(connector.id, { connectorLabelPosition: labelPositionOf(at) })+ }+ layoutConnector(graph, connector)+ routeThroughPoints(graph, connector, edge.geometry.points)+ return extra+}++/** Bends an elbow or a curve through an edge's points, in the connector's parent's axes. */+function routeThroughPoints(graph: SceneGraph, connector: SceneNode, points: Vector[]) {+ if (points.length === 0) return+ const node = graph.getNode(connector.id)+ const route = node ? connectorRoute(graph, node) : null+ if (!node || !route) return+ const local = (point: Vector) => ({ x: point.x - node.x, y: point.y - node.y })+ if (node.connectorLineType === 'CURVED') {+ const curve = route.pieces.at(0)+ if (!curve) return+ // The curve bends so its middle passes the middle bend point.+ const through = points[Math.floor(points.length / 2)]+ const middle = curveMidpoint(curve)+ const [first, second] = dragCurve(curveControlPoints(curve), {+ x: through.x - middle.x,+ y: through.y - middle.y+ })+ graph.updateNode(node.id, { connectorCurveHandles: [local(first), local(second)] })+ } else {+ const across = route.sides[0] === 'LEFT' || route.sides[0] === 'RIGHT'+ graph.updateNode(node.id, {+ connectorControlPoints: elbowThrough(points, across).map((control) => ({+ ...control,+ position: local(control.position)+ }))+ })+ }+ const updated = graph.getNode(node.id)+ if (updated) layoutConnector(graph, updated)+}diff --git a/packages/core/src/io/formats/drawio/index.ts b/packages/core/src/io/formats/drawio/index.tsnew file mode 100644index 000000000..b85a874b9--- /dev/null+++ b/packages/core/src/io/formats/drawio/index.ts@@ -0,0 +1,185 @@+import type { DrawioCell, DrawioFile, DrawioPage } from '@open-pencil/drawio'+import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'+import { connectorRoute, placeConnectorLabel } from '@open-pencil/scene-graph/connectors'+import { createShapeWithText } from '@open-pencil/scene-graph/generated'+import { fitEnclosingGroups } from '@open-pencil/scene-graph/group-bounds'++import { bindEdge, createEdge, labelPositionOf, type PendingEdge } from './edges'+import { readLabel } from './label'+import { labelFields, labelFormat, shapePaint } from './paint'+import { shapeName, vertexKind } from './shapes'++/** A cell's label as text and runs, in the cell's own style. */+function labelOf(cell: DrawioCell) {+ const format = labelFormat(cell.style)+ return { format, ...readLabel(cell.value, cell.style.values.html === '1', format) }+}++/** The first line of a label, as a layer's name. */+function nameOf(text: string, fallback: string): string {+ return text.split('\n')[0]?.trim() || fallback+}++/** Builds one draw.io page's cells into `pageId`, in draw.io's drawing order. */+class PageBuilder {+ /** The layer each draw.io cell or layer became. */+ private readonly layers = new Map<string, string>()+ private readonly edges: PendingEdge[] = []+ private readonly groups: string[] = []++ constructor(+ private readonly graph: SceneGraph,+ private readonly page: DrawioPage,+ private readonly pageId: string+ ) {}++ build() {+ const { graph, page, pageId } = this+ // One layer draws straight onto the page; several each become a group named after it, as+ // does a single layer that is hidden or locked, so it stays so.+ for (const [index, layer] of page.layers.entries()) {+ if (page.layers.length === 1 && layer.visible && !layer.locked) {+ this.layers.set(layer.id, pageId)+ continue+ }+ const group = graph.createNode('GROUP', pageId, {+ name: layer.name || `Layer ${index + 1}`,+ visible: layer.visible,+ locked: layer.locked+ })+ this.layers.set(layer.id, group.id)+ this.groups.push(group.id)+ }+ const parents = new Set(page.cells.map((cell) => cell.parent))+ const labelsOf = new Map<string, DrawioCell[]>()+ const edgeIds = new Set(+ page.cells.filter((cell) => cell.kind === 'edge').map((cell) => cell.id)+ )+ for (const cell of page.cells) {+ // A vertex inside an edge is one of its labels.+ if (edgeIds.has(cell.parent)) {+ const labels = labelsOf.get(cell.parent) ?? []+ labels.push(cell)+ labelsOf.set(cell.parent, labels)+ }+ }+ const cells = new Map(page.cells.map((cell) => [cell.id, cell]))+ const placing = new Set<string>()+ const place = (cell: DrawioCell) => {+ if (edgeIds.has(cell.parent) || this.layers.has(cell.id) || placing.has(cell.id)) return+ placing.add(cell.id)+ // A cell listed before its parent, as draw.io's format allows, waits for the parent.+ const parent = cells.get(cell.parent)+ if (parent) place(parent)+ const parentId = this.layers.get(cell.parent) ?? pageId+ if (cell.kind === 'edge') {+ const pending = createEdge(graph, parentId, cell, labelsOf.get(cell.id) ?? [])+ this.layers.set(cell.id, pending.connector.id)+ this.edges.push(pending)+ return+ }+ const node = this.vertex(cell, parentId, parents.has(cell.id))+ this.layers.set(cell.id, node.id)+ }+ for (const cell of page.cells) place(cell)+ const layerOf = (cellId: string) => this.layers.get(cellId)+ for (const pending of this.edges) {+ for (const extra of bindEdge(graph, pending, layerOf)) this.edgeText(pending, extra)+ }+ // Groups fit around what they hold, the innermost first.+ for (const id of this.groups.toReversed()) fitEnclosingGroups(graph, [id])+ }++ private vertex(cell: DrawioCell, parentId: string, hasChildren: boolean): SceneNode {+ const { graph } = this+ const { x, y, width, height } = cell.geometry+ const kind = vertexKind(cell.style, hasChildren)+ const label = labelOf(cell)+ const box = { x, y, width, height, visible: cell.visible }+ if (kind.type === 'TEXT') {+ return graph.createNode('TEXT', parentId, {+ ...box,+ name: nameOf(label.text, 'Text'),+ ...labelFields(cell.style, label.format),+ text: label.text,+ styleRuns: label.runs,+ textAutoResize: 'NONE'+ })+ }+ if (kind.type === 'SECTION') {+ return graph.createNode('SECTION', parentId, {+ ...box,+ ...shapePaint(cell.style),+ name: nameOf(label.text, 'Section')+ })+ }+ if (kind.type === 'GROUP') {+ const group = graph.createNode('GROUP', parentId, {+ ...box,+ name: nameOf(label.text, 'Group')+ })+ this.groups.push(group.id)+ return group+ }+ // A shape turned a quarter swaps its sides, about the centre of the box it fills.+ const quarter = Math.abs(kind.rotation) === 90+ const placed = quarter+ ? { x: x + (width - height) / 2, y: y + (height - width) / 2, width: height, height: width }+ : { x, y, width, height }+ const known = shapeName(cell.style)+ return createShapeWithText(+ graph,+ parentId,+ {+ ...placed,+ visible: cell.visible,+ rotation: kind.rotation,+ shapeWithTextType: kind.shape,+ // draw.io sized it, so it keeps its size, as a FigJam shape whose height was set does.+ shapeTruncates: true,+ ...shapePaint(cell.style),+ // A stencil FigJam has no shape for keeps its name, so it can be found and replaced.+ name: kind.stencil ? known : nameOf(label.text, 'Shape with text')+ },+ { ...labelFields(cell.style, label.format), text: label.text, styleRuns: label.runs }+ )+ }++ /** A label beyond an edge's first, as text where draw.io placed it along the edge. */+ private edgeText({ connector }: PendingEdge, cell: DrawioCell) {+ const { graph } = this+ const node = graph.getNode(connector.id)+ const route = node ? connectorRoute(graph, node) : null+ if (!node?.parentId || !route) return+ const label = labelOf(cell)+ const size = { width: cell.geometry.width, height: cell.geometry.height }+ const plate = placeConnectorLabel(route.pieces, size, labelPositionOf(cell.geometry.x))?.plate+ const offset = cell.geometry.offset ?? { x: 0, y: 0 }+ graph.createNode('TEXT', node.parentId, {+ x: (plate?.x ?? 0) + offset.x,+ y: (plate?.y ?? 0) + offset.y,+ visible: cell.visible,+ name: nameOf(label.text, 'Text'),+ ...labelFields(cell.style, label.format),+ text: label.text,+ styleRuns: label.runs,+ textAutoResize: 'WIDTH_AND_HEIGHT'+ })+ }+}++/**+ * A draw.io file as layers: each page a page, its shapes FigJam shapes with text, its edges+ * connectors joined to them, its layers groups when there are several, in draw.io's drawing order.+ * Text sizes are left for layout, which measures them once fonts load.+ */+export function drawioToSceneGraph(file: DrawioFile): SceneGraph {+ const graph = new SceneGraph()+ const first = graph.getPages().at(0)+ for (const [index, page] of file.pages.entries()) {+ const pageNode = index === 0 && first ? first : graph.addPage(page.name)+ if (index === 0) graph.updateNode(pageNode.id, { name: page.name })+ new PageBuilder(graph, page, pageNode.id).build()+ }+ return graph+}diff --git a/packages/core/src/io/formats/drawio/label.ts b/packages/core/src/io/formats/drawio/label.tsnew file mode 100644index 000000000..6bab04a5c--- /dev/null+++ b/packages/core/src/io/formats/drawio/label.ts@@ -0,0 +1,141 @@+import { parseFragment, type DefaultTreeAdapterTypes } from 'parse5'++import type { CharacterStyleOverride, StyleRun } from '@open-pencil/scene-graph'+import { tryParseColor } from '@open-pencil/scene-graph/color'+import type { Color } from '@open-pencil/scene-graph/primitives'++/** How a stretch of a label looks: the cell's style, as tags inside the label change it. */+export interface LabelFormat {+ bold: boolean+ italic: boolean+ underline: boolean+ size: number+ color: Color+ family: string+}++/** A label's text, with runs where its tags make it look other than the cell's style. */+export interface Label {+ text: string+ runs: StyleRun[]+}++type Node = DefaultTreeAdapterTypes.ChildNode+type Element = DefaultTreeAdapterTypes.Element++/** Tags that start their text on a line of its own. */+const BLOCK_TAGS = new Set(['div', 'p', 'li', 'tr', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'])++function attribute(element: Element, name: string): string | null {+ return element.attrs.find((attr) => attr.name === name)?.value ?? null+}++/** The CSS declarations of an inline `style`, by property. */+function declarations(css: string): Map<string, string> {+ const result = new Map<string, string>()+ for (const part of css.split(';')) {+ const colon = part.indexOf(':')+ if (colon > 0)+ result.set(part.slice(0, colon).trim().toLowerCase(), part.slice(colon + 1).trim())+ }+ return result+}++/** A stretch's format as an HTML tag changes it: `<b>`, `<i>`, `<u>`, and `<font>`. */+function tagFormat(element: Element, format: LabelFormat): LabelFormat {+ const next = { ...format }+ const tag = element.tagName+ if (tag === 'b' || tag === 'strong') next.bold = true+ if (tag === 'i' || tag === 'em') next.italic = true+ if (tag === 'u') next.underline = true+ if (tag === 'font') {+ next.color = tryParseColor(attribute(element, 'color') ?? '') ?? next.color+ next.family = attribute(element, 'face')?.split(',')[0]?.trim() || next.family+ }+ return next+}++/** A stretch's format as an element's inline CSS changes it. */+function cssFormat(css: Map<string, string>, format: LabelFormat): LabelFormat {+ const next = { ...format }+ const size = css.get('font-size') ?? ''+ if (size.endsWith('px') && Number.isFinite(Number.parseFloat(size))) {+ next.size = Number.parseFloat(size)+ }+ next.color = tryParseColor(css.get('color') ?? '') ?? next.color+ const weight = css.get('font-weight')+ if (weight) next.bold = weight === 'bold' || Number.parseInt(weight, 10) >= 600+ const style = css.get('font-style')+ if (style) next.italic = style === 'italic'+ const decoration = css.get('text-decoration') ?? css.get('text-decoration-line')+ if (decoration) next.underline = decoration.includes('underline')+ const family = css.get('font-family')?.split(',')[0]?.replace(/["']/g, '').trim()+ if (family) next.family = family+ return next+}++function formatOf(element: Element, format: LabelFormat): LabelFormat {+ return cssFormat(declarations(attribute(element, 'style') ?? ''), tagFormat(element, format))+}++/** What a stretch's format changes from the cell's, as a run's style. */+function override(format: LabelFormat, base: LabelFormat): CharacterStyleOverride | null {+ const style: CharacterStyleOverride = {}+ if (format.bold !== base.bold) style.fontWeight = format.bold ? 700 : 400+ if (format.italic !== base.italic) style.italic = format.italic+ if (format.underline !== base.underline) {+ style.textDecoration = format.underline ? 'UNDERLINE' : 'NONE'+ }+ if (format.size !== base.size) style.fontSize = format.size+ if (format.family !== base.family) style.fontFamily = format.family+ const { r, g, b, a } = format.color+ const c = base.color+ if (r !== c.r || g !== c.g || b !== c.b || a !== c.a) {+ style.fills = [{ type: 'SOLID', color: { ...format.color }, opacity: 1, visible: true }]+ }+ return Object.keys(style).length > 0 ? style : null+}++/**+ * A cell's label as text and style runs. An HTML label, as `html=1` makes it, reads as a browser+ * would show it: its whitespace collapsed, a line for each `<br>` and block, and the bold,+ * italic, underline, size, colour and font its tags give a stretch. A plain label is its text.+ */+export function readLabel(value: string, html: boolean, base: LabelFormat): Label {+ if (!html) return { text: value, runs: [] }+ let text = ''+ const runs: StyleRun[] = []+ const lineBreak = () => {+ if (text !== '' && !text.endsWith('\n')) text += '\n'+ }+ const visit = (node: Node, format: LabelFormat) => {+ if (node.nodeName === '#text' && 'value' in node) {+ let piece = node.value.replace(/[ \t\r\n]+/g, ' ')+ if (text === '' || text.endsWith('\n') || text.endsWith(' ')) piece = piece.replace(/^ /, '')+ if (!piece) return+ const style = override(format, base)+ if (style) runs.push({ start: text.length, length: piece.length, style })+ text += piece+ return+ }+ if (!('tagName' in node)) return+ if (node.tagName === 'br') {+ text += '\n'+ return+ }+ const block = BLOCK_TAGS.has(node.tagName)+ if (block) lineBreak()+ const inner = formatOf(node, format)+ for (const child of node.childNodes) visit(child, inner)+ if (block) lineBreak()+ }+ for (const node of parseFragment(value).childNodes) visit(node, base)+ // A line break the last block adds ends nothing.+ const trimmed = text.replace(/[ \n]+$/, '')+ return {+ text: trimmed,+ runs: runs+ .map((run) => ({ ...run, length: Math.min(run.length, trimmed.length - run.start) }))+ .filter((run) => run.length > 0)+ }+}diff --git a/packages/core/src/io/formats/drawio/paint.ts b/packages/core/src/io/formats/drawio/paint.tsnew file mode 100644index 000000000..9b76649f0--- /dev/null+++ b/packages/core/src/io/formats/drawio/paint.ts@@ -0,0 +1,116 @@+import { styleNumber, type DrawioStyle } from '@open-pencil/drawio'+import type { Fill, SceneNode, Stroke } from '@open-pencil/scene-graph'+import { tryParseColor } from '@open-pencil/scene-graph/color'+import { BLACK, WHITE } from '@open-pencil/scene-graph/constants'+import type { Color } from '@open-pencil/scene-graph/primitives'++import type { LabelFormat } from './label'++/**+ * The font draw.io draws with when a style names none. draw.io's own default, Helvetica, is not a+ * font every system has, so its labels take the editor's default font instead.+ */+export const DEFAULT_FONT_FAMILY = 'Inter'+/** draw.io's default label size. */+const DEFAULT_FONT_SIZE = 12++/** A colour a style sets: `none` for none, `default` for draw.io's default, otherwise CSS. */+function styleColor(style: DrawioStyle, key: string, fallback: Color | null): Color | null {+ const value = style.values[key]+ if (value === undefined || value === 'default') return fallback+ if (value === 'none') return null+ return tryParseColor(value) ?? fallback+}++/** A 0–100 opacity a style sets, as a fraction. */+function opacity(style: DrawioStyle, key: string): number {+ return Math.min(1, Math.max(0, styleNumber(style, key, 100) / 100))+}++function solid(color: Color, alpha: number): Fill {+ return { type: 'SOLID', color: { ...color }, opacity: alpha, visible: true }+}++/**+ * A vertex's fill and outline as a style draws them: white and black, one pixel wide, by default,+ * as draw.io draws a new shape, dashed by `dashPattern` or, with `dashed=1`, draw.io's 3-on-3 dash+ * scaled by the width.+ */+export function shapePaint(style: DrawioStyle): Partial<SceneNode> {+ const fill = styleColor(style, 'fillColor', WHITE)+ const stroke = styleColor(style, 'strokeColor', BLACK)+ const weight = styleNumber(style, 'strokeWidth', 1)+ const dashPattern = dashOf(style, weight)+ const strokes: Stroke[] = stroke+ ? [+ {+ ...solid(stroke, opacity(style, 'strokeOpacity')),+ weight,+ align: 'CENTER',+ dashPattern+ }+ ]+ : []+ return {+ fills: fill ? [solid(fill, opacity(style, 'fillOpacity'))] : [],+ strokes,+ strokeWeight: weight,+ strokeAlign: 'CENTER',+ dashPattern,+ opacity: opacity(style, 'opacity')+ }+}++/** The dash a style draws its line with: `dashPattern` in widths, or 3-on-3 for `dashed=1`. */+export function dashOf(style: DrawioStyle, weight: number): number[] {+ if (style.values.dashed !== '1') return []+ const pattern = (style.values.dashPattern ?? '3 3')+ .split(/\s+/)+ .map(Number.parseFloat)+ .filter((n) => Number.isFinite(n) && n > 0)+ return pattern.map((n) => n * weight)+}++/** The colour of an edge's line: `strokeColor`, black by default. */+export function lineColor(style: DrawioStyle): Color | null {+ return styleColor(style, 'strokeColor', BLACK)+}++/** How a cell's label looks before the tags inside it change it. */+export function labelFormat(style: DrawioStyle): LabelFormat {+ const fontStyle = styleNumber(style, 'fontStyle', 0)+ return {+ // fontStyle is a bit set: bold, italic, underline.+ bold: (fontStyle & 1) !== 0,+ italic: (fontStyle & 2) !== 0,+ underline: (fontStyle & 4) !== 0,+ size: styleNumber(style, 'fontSize', DEFAULT_FONT_SIZE),+ color: styleColor(style, 'fontColor', BLACK) ?? BLACK,+ family: style.values.fontFamily?.split(',')[0]?.trim() || DEFAULT_FONT_FAMILY+ }+}++const HORIZONTAL = new Map<string, SceneNode['textAlignHorizontal']>([+ ['left', 'LEFT'],+ ['center', 'CENTER'],+ ['right', 'RIGHT']+])+const VERTICAL = new Map<string, SceneNode['textAlignVertical']>([+ ['top', 'TOP'],+ ['middle', 'CENTER'],+ ['bottom', 'BOTTOM']+])++/** A label's text fields: its font, size, colour, and alignment, centred by default. */+export function labelFields(style: DrawioStyle, format = labelFormat(style)): Partial<SceneNode> {+ return {+ fontFamily: format.family,+ fontWeight: format.bold ? 700 : 400,+ italic: format.italic,+ fontSize: format.size,+ textDecoration: format.underline ? 'UNDERLINE' : 'NONE',+ fills: [solid(format.color, 1)],+ textAlignHorizontal: HORIZONTAL.get(style.values.align ?? 'center') ?? 'CENTER',+ textAlignVertical: VERTICAL.get(style.values.verticalAlign ?? 'middle') ?? 'CENTER'+ }+}diff --git a/packages/core/src/io/formats/drawio/shapes.ts b/packages/core/src/io/formats/drawio/shapes.tsnew file mode 100644index 000000000..e4644a5da--- /dev/null+++ b/packages/core/src/io/formats/drawio/shapes.ts@@ -0,0 +1,113 @@+import type { DrawioStyle } from '@open-pencil/drawio'+import type { ShapeWithTextType } from '@open-pencil/scene-graph/shape-with-text'++/** What a draw.io vertex becomes: a FigJam shape, text, a section around its cells, or a group. */+export type VertexKind =+ /** A FigJam shape, turned clockwise by `rotation` degrees about its centre. */+ | { type: 'SHAPE_WITH_TEXT'; shape: ShapeWithTextType; rotation: number; stencil: boolean }+ | { type: 'TEXT' }+ | { type: 'SECTION' }+ | { type: 'GROUP' }++/**+ * draw.io shapes, by their `shape` value or stylesheet name, and the FigJam shapes with text that+ * draw them. Flowchart stencils map to the FigJam flowchart shape of the same meaning.+ */+const SHAPES = new Map<string, ShapeWithTextType>([+ ['rectangle', 'SQUARE'],+ ['label', 'SQUARE'],+ ['ellipse', 'ELLIPSE'],+ ['doubleEllipse', 'ELLIPSE'],+ ['rhombus', 'DIAMOND'],+ ['triangle', 'TRIANGLE_UP'],+ ['parallelogram', 'PARALLELOGRAM_RIGHT'],+ ['trapezoid', 'TRAPEZOID'],+ ['hexagon', 'HEXAGON'],+ ['cylinder', 'ENG_DATABASE'],+ ['cylinder3', 'ENG_DATABASE'],+ ['datastore', 'ENG_DATABASE'],+ ['document', 'DOCUMENT_SINGLE'],+ ['process', 'PREDEFINED_PROCESS'],+ ['manualInput', 'MANUAL_INPUT'],+ ['internalStorage', 'INTERNAL_STORAGE'],+ ['step', 'CHEVRON'],+ ['note', 'ENG_FILE'],+ ['folder', 'ENG_FOLDER'],+ ['cross', 'PLUS'],+ ['singleArrow', 'ARROW_RIGHT'],+ ['callout', 'SPEECH_BUBBLE'],+ ['sumEllipse', 'SUMMING_JUNCTION'],+ ['orEllipse', 'OR'],+ ['mxgraph.flowchart.process', 'SQUARE'],+ ['mxgraph.flowchart.decision', 'DIAMOND'],+ ['mxgraph.flowchart.terminator', 'ROUNDED_RECTANGLE'],+ ['mxgraph.flowchart.start_1', 'ELLIPSE'],+ ['mxgraph.flowchart.start_2', 'ELLIPSE'],+ ['mxgraph.flowchart.on-page_reference', 'ELLIPSE'],+ ['mxgraph.flowchart.data', 'PARALLELOGRAM_RIGHT'],+ ['mxgraph.flowchart.database', 'ENG_DATABASE'],+ ['mxgraph.flowchart.stored_data', 'ENG_DATABASE'],+ ['mxgraph.flowchart.direct_data', 'ENG_QUEUE'],+ ['mxgraph.flowchart.document', 'DOCUMENT_SINGLE'],+ ['mxgraph.flowchart.multi-document', 'DOCUMENT_MULTIPLE'],+ ['mxgraph.flowchart.predefined_process', 'PREDEFINED_PROCESS'],+ ['mxgraph.flowchart.manual_input', 'MANUAL_INPUT'],+ ['mxgraph.flowchart.internal_storage', 'INTERNAL_STORAGE'],+ ['mxgraph.flowchart.summing_function', 'SUMMING_JUNCTION'],+ ['mxgraph.flowchart.or', 'OR'],+ ['mxgraph.flowchart.extract_or_measurement', 'TRIANGLE_UP'],+ ['mxgraph.flowchart.merge_or_storage', 'TRIANGLE_DOWN'],+ ['mxgraph.basic.pentagon', 'PENTAGON'],+ ['mxgraph.basic.octagon2', 'OCTAGON'],+ ['mxgraph.basic.star', 'STAR'],+ ['mxgraph.basic.plus', 'PLUS'],+ ['mxgraph.basic.rectCallout', 'SPEECH_BUBBLE'],+ ['mxgraph.basic.oval_callout', 'SPEECH_BUBBLE']+])++/** Stylesheet names that pick a shape, as `ellipse` in `ellipse;whiteSpace=wrap;` does. */+const SHAPE_NAMES = new Set([...SHAPES.keys(), 'text', 'swimlane', 'group', 'image'])++/** The shape a style draws: its `shape`, else the stylesheet style it names, else a rectangle. */+export function shapeName(style: DrawioStyle): string {+ return style.values.shape ?? style.names.find((name) => SHAPE_NAMES.has(name)) ?? 'rectangle'+}++/** Which way `direction` points, in degrees anticlockwise from pointing right. */+const DIRECTION_TURN = new Map([+ ['east', 0],+ ['north', 90],+ ['west', 180],+ ['south', -90]+])++/**+ * What a vertex becomes. Text stays text; a swimlane, or a vertex its style makes a container,+ * becomes a section holding its cells; a group stays a group. A shape draw.io turns by+ * `direction` keeps its turn. Any other shape, a stencil FigJam has no shape for among them,+ * becomes a rectangle, named after the stencil so it can be found.+ */+export function vertexKind(style: DrawioStyle, hasChildren: boolean): VertexKind {+ const name = shapeName(style)+ if (name === 'text') return { type: 'TEXT' }+ if (name === 'swimlane' || (hasChildren && style.values.container === '1')) {+ return { type: 'SECTION' }+ }+ if (name === 'group' || (hasChildren && !SHAPES.has(name))) return { type: 'GROUP' }+ let shape = SHAPES.get(name) ?? 'SQUARE'+ const direction = style.values.direction ?? 'east'+ let rotation = 0+ if (shape === 'TRIANGLE_UP' && name === 'triangle') {+ // draw.io's triangle points right; FigJam's points up and turns, clockwise for a positive+ // rotation, to point elsewhere.+ rotation = 90 - (DIRECTION_TURN.get(direction) ?? 0)+ if (rotation === 180) {+ shape = 'TRIANGLE_DOWN'+ rotation = 0+ }+ } else if (shape === 'ARROW_RIGHT' && direction === 'west') shape = 'ARROW_LEFT'+ else if (shape === 'PARALLELOGRAM_RIGHT' && style.values.flipH === '1') {+ shape = 'PARALLELOGRAM_LEFT'+ } else if (shape === 'SQUARE' && style.values.rounded === '1') shape = 'ROUNDED_RECTANGLE'+ return { type: 'SHAPE_WITH_TEXT', shape, rotation, stencil: !SHAPES.has(name) }+}diff --git a/packages/core/tests/io/formats/drawio/import.test.ts b/packages/core/tests/io/formats/drawio/import.test.tsnew file mode 100644index 000000000..e37d047f9--- /dev/null+++ b/packages/core/tests/io/formats/drawio/import.test.ts@@ -0,0 +1,255 @@+import { describe, expect, test } from 'bun:test'++import { expectDefined } from '#core-tests/helpers/assert'++import { BUILTIN_IO_FORMATS, IORegistry } from '#core/io'++import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import { connectorSublayers } from '@open-pencil/scene-graph/connectors'+import { shapeWithTextLabel } from '@open-pencil/scene-graph/generated'++const io = new IORegistry(BUILTIN_IO_FORMATS)++/** A draw.io file whose first page holds `cells` on draw.io's default layer. */+function file(cells: string, layers = '<mxCell id="1" parent="0"/>') {+ return `<mxfile><diagram id="p" name="Flow"><mxGraphModel><root><mxCell id="0"/>${layers}${cells}</root></mxGraphModel></diagram></mxfile>`+}++const vertex = (id: string, style: string, [x, y, w, h]: number[], value = '', parent = '1') =>+ `<mxCell id="${id}" value="${value}" style="${style}" vertex="1" parent="${parent}"><mxGeometry x="${x}" y="${y}" width="${w}" height="${h}" as="geometry"/></mxCell>`++async function read(source: string, name = 'flow.drawio') {+ const { graph } = await io.readDocument({ name, data: new TextEncoder().encode(source) })+ return graph+}++function onPage(graph: SceneGraph): SceneNode[] {+ return graph.getChildren(graph.getPages()[0].id)+}++function byName(graph: SceneGraph, name: string): SceneNode {+ return expectDefined([...graph.getAllNodes()].find((node) => node.name === name), name)+}++describe('opening draw.io files', () => {+ test('takes .drawio and .dio files and draw.io’s editable PNG and SVG exports', () => {+ const format = expectDefined(io.getFormat('drawio'))+ for (const name of ['flow.drawio', 'flow.dio', 'flow.drawio.png', 'flow.drawio.svg']) {+ expect({ name, matches: format.matchesFile?.(name) }).toEqual({ name, matches: true })+ }+ expect(format.matchesFile?.('photo.png')).toBe(false)+ })++ test('refuses a file with no diagram, and one with pages it cannot read', async () => {+ await expect(read('<svg xmlns="http://www.w3.org/2000/svg"/>', 'a.drawio.svg')).rejects.toThrow(+ 'no draw.io diagram'+ )+ await expect(+ read(`<mxfile><diagram id="x" name="Broken">%%%</diagram></mxfile>`)+ ).rejects.toThrow('Broken')+ })+})++describe('draw.io shapes', () => {+ test('become FigJam shapes with text of the same kind, sized and painted as drawn', async () => {+ const graph = await read(+ file(+ vertex('a', 'rounded=1;whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;strokeWidth=2;', [40, 60, 120, 60], 'Start') ++ vertex('b', 'rhombus;whiteSpace=wrap;html=1;fillColor=none;dashed=1;', [280, 40, 100, 100], '<b>Ok</b>?') ++ vertex('c', 'shape=cylinder3;whiteSpace=wrap;html=1;', [280, 240, 80, 100], 'Store') ++ vertex('d', 'shape=mxgraph.aws4.lambda;', [600, 40, 60, 60], 'Lambda')+ )+ )+ expect(+ onPage(graph).map((node) => [node.type, node.shapeWithTextType, node.x, node.y, node.width, node.height])+ ).toEqual([+ ['SHAPE_WITH_TEXT', 'ROUNDED_RECTANGLE', 40, 60, 120, 60],+ ['SHAPE_WITH_TEXT', 'DIAMOND', 280, 40, 100, 100],+ ['SHAPE_WITH_TEXT', 'ENG_DATABASE', 280, 240, 80, 100],+ // A stencil FigJam has no shape for draws as a rectangle named after it.+ ['SHAPE_WITH_TEXT', 'SQUARE', 600, 40, 60, 60]+ ])+ const [start, decision, , stencil] = onPage(graph)+ expect(start.fills[0]?.color).toMatchObject({ r: 0xda / 255, g: 0xe8 / 255, b: 0xfc / 255 })+ expect(start.strokes[0]).toMatchObject({ weight: 2, color: { r: 0x6c / 255 } })+ expect(decision.fills).toEqual([])+ expect(decision.dashPattern).toEqual([3, 3])+ expect(stencil.name).toBe('mxgraph.aws4.lambda')+ const label = expectDefined(shapeWithTextLabel(graph, decision))+ expect(label).toMatchObject({ text: 'Ok?', fontSize: 12, fontFamily: 'Inter' })+ expect(label.styleRuns).toEqual([{ start: 0, length: 2, style: { fontWeight: 700 } }])+ })++ test('a triangle points the way draw.io points it', async () => {+ const graph = await read(+ file(+ vertex('r', 'triangle;whiteSpace=wrap;', [500, 40, 60, 80]) ++ vertex('s', 'triangle;direction=south;', [600, 40, 80, 60])+ )+ )+ const [right, down] = onPage(graph)+ // Turned a quarter about the centre of the box it fills.+ expect([right.shapeWithTextType, right.rotation, right.x, right.y, right.width, right.height]).toEqual(['TRIANGLE_UP', 90, 490, 50, 80, 60])+ expect([down.shapeWithTextType, down.rotation]).toEqual(['TRIANGLE_DOWN', 0])+ })++ test('text stays text, and a swimlane is a section around its cells', async () => {+ const graph = await read(+ file(+ vertex('t', 'text;html=1;align=left;verticalAlign=top;fontSize=20;fontColor=#ff0000;', [40, 20, 200, 30], 'Title') ++ vertex('lane', 'swimlane;whiteSpace=wrap;html=1;', [40, 100, 300, 200], 'Team') ++ vertex('in', 'whiteSpace=wrap;html=1;', [20, 40, 100, 50], 'Task', 'lane')+ )+ )+ const title = byName(graph, 'Title')+ expect(title).toMatchObject({ type: 'TEXT', text: 'Title', fontSize: 20, textAlignHorizontal: 'LEFT', textAlignVertical: 'TOP' })+ expect(title.fills[0]?.color).toMatchObject({ r: 1, g: 0, b: 0 })+ const lane = byName(graph, 'Team')+ expect(lane).toMatchObject({ type: 'SECTION', x: 40, y: 100, width: 300, height: 200 })+ expect(graph.getChildren(lane.id).map((node) => [node.name, node.x, node.y])).toEqual([['Task', 20, 40]])+ })+})++describe('draw.io edges', () => {+ const shapes =+ vertex('a', 'whiteSpace=wrap;', [40, 60, 120, 60], 'A') ++ vertex('b', 'whiteSpace=wrap;', [400, 60, 120, 60], 'B') ++ vertex('c', 'whiteSpace=wrap;', [400, 260, 120, 60], 'C')++ test('become connectors joined to their shapes, with draw.io’s line, ends, and label', async () => {+ const graph = await read(+ file(+ shapes ++ `<mxCell id="e" value="goes" style="edgeStyle=orthogonalEdgeStyle;endArrow=open;startArrow=oval;strokeColor=#ff0000;strokeWidth=2;dashed=1;" edge="1" parent="1" source="a" target="b"><mxGeometry relative="1" as="geometry"/></mxCell>` ++ `<mxCell id="f" value="" style="endArrow=block;endFill=0;exitX=1;exitY=0.25;entryX=0;entryY=0.5;" edge="1" parent="1" source="a" target="c"><mxGeometry relative="1" as="geometry"/></mxCell>` ++ `<mxCell id="g" value="" style="curved=1;" edge="1" parent="1" source="b"><mxGeometry relative="1" as="geometry"><mxPoint x="700" y="300" as="targetPoint"/></mxGeometry></mxCell>`+ )+ )+ const [goes, exits, loose] = onPage(graph).filter((node) => node.type === 'CONNECTOR')+ expect(goes).toMatchObject({+ connectorLineType: 'ELBOWED',+ connectorStartCap: 'CIRCLE_FILLED',+ connectorEndCap: 'ARROW_LINES',+ connectorStart: { nodeId: byName(graph, 'A').id, magnet: 'AUTO' },+ connectorEnd: { nodeId: byName(graph, 'B').id, magnet: 'AUTO' }+ })+ const parts = expectDefined(connectorSublayers(graph, goes))+ expect(parts.label.text).toBe('goes')+ expect(parts.line.strokes[0]).toMatchObject({ weight: 2, color: { r: 1, g: 0, b: 0 }, dashPattern: [6, 6] })+ // exitX/exitY pin an end to a point of its shape; an unfilled triangle is an open arrow.+ expect(exits).toMatchObject({+ connectorLineType: 'STRAIGHT',+ connectorEndCap: 'ARROW_LINES',+ connectorStart: { magnet: 'NONE', position: { x: 120, y: 15 } },+ connectorEnd: { magnet: 'NONE', position: { x: 0, y: 30 } }+ })+ // draw.io's default arrowhead is a filled triangle, FigJam's triangle arrow.+ expect(loose).toMatchObject({+ connectorLineType: 'CURVED',+ connectorEndCap: 'ARROW_EQUILATERAL',+ connectorEnd: { nodeId: null, position: { x: 700, y: 300 } }+ })+ })++ test('bent through points leave and enter by the sides facing them and run through them', async () => {+ const graph = await read(+ file(+ shapes ++ `<mxCell id="e" style="edgeStyle=orthogonalEdgeStyle;" edge="1" parent="1" source="b" target="c"><mxGeometry relative="1" as="geometry"><Array as="points"><mxPoint x="600" y="90"/><mxPoint x="600" y="290"/></Array></mxGeometry></mxCell>`+ )+ )+ const connector = expectDefined(onPage(graph).find((node) => node.type === 'CONNECTOR'))+ expect([connector.connectorStart?.magnet, connector.connectorEnd?.magnet]).toEqual(['RIGHT', 'RIGHT'])+ const { line } = expectDefined(connectorSublayers(graph, connector))+ const points = (line.vectorNetwork?.vertices ?? []).map((v) => [connector.x + line.x + v.x, connector.y + line.y + v.y])+ expect(points.some(([x]) => x === 600)).toBe(true)+ expect(points.at(0)?.[0]).toBeGreaterThan(520)+ })++ test('take the labels draw.io keeps along them, where it keeps them', async () => {+ const graph = await read(+ file(+ shapes ++ `<mxCell id="e" value="" style="" edge="1" parent="1" source="a" target="b"><mxGeometry relative="1" as="geometry"/></mxCell>` ++ `<mxCell id="l1" value="first" style="edgeLabel;html=1;" vertex="1" connectable="0" parent="e"><mxGeometry x="-0.5" relative="1" as="geometry"/></mxCell>` ++ `<mxCell id="l2" value="second" style="edgeLabel;html=1;" vertex="1" connectable="0" parent="e"><mxGeometry x="0.5" relative="1" as="geometry"/></mxCell>`+ )+ )+ const connector = expectDefined(onPage(graph).find((node) => node.type === 'CONNECTOR'))+ expect(connector.connectorLabelPosition).toEqual({ section: 'MIDDLE_TO_START', offset: 0.5, offAxis: 'NONE' })+ expect(connectorSublayers(graph, connector)?.label.text).toBe('first')+ // A second label draws as text by the edge.+ expect(byName(graph, 'second').type).toBe('TEXT')+ })++ test('keep a hidden extra label hidden', async () => {+ const graph = await read(+ file(+ shapes ++ `<mxCell id="e" value="shown" style="" edge="1" parent="1" source="a" target="b"><mxGeometry relative="1" as="geometry"/></mxCell>` ++ `<mxCell id="l" value="hidden" style="edgeLabel;" vertex="1" parent="e" visible="0"><mxGeometry x="0.5" relative="1" as="geometry"/></mxCell>`+ )+ )+ expect(byName(graph, 'hidden').visible).toBe(false)+ })+})++test('style values named like built-in object members fall back as unknown values do', async () => {+ const graph = await read(+ file(+ vertex('a', 'triangle;direction=constructor;align=constructor;verticalAlign=toString;', [0, 0, 80, 60], 'A') ++ vertex('b', '', [200, 0, 80, 60], 'B') ++ `<mxCell id="e" style="endArrow=constructor;startArrow=valueOf;" edge="1" parent="1" source="a" target="b"><mxGeometry relative="1" as="geometry"/></mxCell>`+ )+ )+ const shape = byName(graph, 'A')+ // An unknown direction points east, as draw.io's default does: FigJam's triangle turned a quarter.+ expect(shape.rotation).toBe(90)+ const connector = expectDefined(onPage(graph).find((node) => node.type === 'CONNECTOR'))+ expect([connector.connectorStartCap, connector.connectorEndCap]).toEqual(['ARROW_LINES', 'ARROW_LINES'])+ const label = expectDefined([...graph.getAllNodes()].find((node) => node.type === 'TEXT' && node.text === 'A'))+ expect([label.textAlignHorizontal, label.textAlignVertical]).toEqual(['CENTER', 'CENTER'])+})++describe('draw.io pages and layers', () => {+ test('each page is a page, each of several layers a group, in draw.io’s order', async () => {+ const graph = await read(+ `<mxfile><diagram id="p1" name="One"><mxGraphModel><root><mxCell id="0"/><mxCell id="1" parent="0"/><mxCell id="2" value="Notes" parent="0" visible="0"/>${vertex('a', '', [0, 0, 50, 50], 'Below')}${vertex('b', '', [100, 0, 50, 50], 'Hidden note', '2')}${vertex('c', '', [200, 0, 50, 50], 'Above')}</root></mxGraphModel></diagram><diagram id="p2" name="Two"><mxGraphModel><root><mxCell id="0"/><mxCell id="1" parent="0"/></root></mxGraphModel></diagram></mxfile>`+ )+ expect(graph.getPages().map((page) => page.name)).toEqual(['One', 'Two'])+ const [base, notes] = onPage(graph)+ expect([base.type, base.name, notes.type, notes.name, notes.visible]).toEqual(['GROUP', 'Layer 1', 'GROUP', 'Notes', false])+ expect(graph.getChildren(base.id).map((node) => node.name)).toEqual(['Below', 'Above'])+ expect(graph.getChildren(notes.id).map((node) => node.name)).toEqual(['Hidden note'])+ })++ test('a single hidden or locked layer is a group that stays so', async () => {+ const graph = await read(file(vertex('a', '', [0, 0, 50, 50], 'Shape'), '<mxCell id="1" value="Only" style="locked=1;" parent="0" visible="0"/>'))+ const [layer] = onPage(graph)+ expect([layer.type, layer.name, layer.visible, layer.locked]).toEqual(['GROUP', 'Only', false, true])+ })++ test('a cell listed before its parent still lands inside it', async () => {+ const graph = await read(+ file(vertex('child', '', [10, 10, 40, 40], 'Child', 'g') + vertex('g', 'group;', [100, 100, 60, 60], '', '1'))+ )+ const child = byName(graph, 'Child')+ const group = expectDefined(graph.getNode(expectDefined(child.parentId)))+ expect(group.type).toBe('GROUP')+ expect([group.x + child.x, group.y + child.y]).toEqual([110, 110])+ })++ test('a free edge end stays where draw.io put it when its layer fits around its shapes', async () => {+ const graph = await read(+ file(+ vertex('a', '', [300, 300, 50, 50], 'A', '2') ++ `<mxCell id="e" style="" edge="1" parent="2" source="a"><mxGeometry relative="1" as="geometry"><mxPoint x="700" y="700" as="targetPoint"/></mxGeometry></mxCell>`,+ '<mxCell id="1" parent="0"/><mxCell id="2" parent="0"/>'+ )+ )+ const connector = expectDefined([...graph.getAllNodes()].find((node) => node.type === 'CONNECTOR'))+ const layer = expectDefined(graph.getNode(expectDefined(connector.parentId)))+ const end = expectDefined(connector.connectorEnd).position+ expect([layer.x + end.x, layer.y + end.y]).toEqual([700, 700])+ })+})diff --git a/packages/core/tests/io/formats/drawio/label.test.ts b/packages/core/tests/io/formats/drawio/label.test.tsnew file mode 100644index 000000000..0bacd238d--- /dev/null+++ b/packages/core/tests/io/formats/drawio/label.test.ts@@ -0,0 +1,30 @@+import { expect, test } from 'bun:test'++import { readLabel, type LabelFormat } from '#core/io/formats/drawio/label'++const BASE: LabelFormat = {+ bold: false,+ italic: false,+ underline: false,+ size: 12,+ color: { r: 0, g: 0, b: 0, a: 1 },+ family: 'Inter'+}++test('an HTML label reads as a browser shows it, with runs where its tags change the style', () => {+ const label = readLabel(+ '<div>Line one</div><div><b>Bold</b> and <i style="color:#ff0000">red</i><br>last & <span style="font-size:20px">big</span></div>',+ true,+ BASE+ )+ expect(label.text).toBe('Line one\nBold and red\nlast & big')+ expect(label.runs).toEqual([+ { start: 9, length: 4, style: { fontWeight: 700 } },+ { start: 18, length: 3, style: { italic: true, fills: [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }] } },+ { start: 29, length: 3, style: { fontSize: 20 } }+ ])+})++test('a plain label is its text, its markup included', () => {+ expect(readLabel('a <b> c', false, BASE)).toEqual({ text: 'a <b> c', runs: [] })+})diff --git a/packages/scene-graph/src/group-bounds.ts b/packages/scene-graph/src/group-bounds.tsindex 6b503d80a..944045cc1 100644--- a/packages/scene-graph/src/group-bounds.ts+++ b/packages/scene-graph/src/group-bounds.ts@@ -4,7 +4,9 @@ import { FITTED_CONTAINER_TYPES } from './node-defaults'import type { Rect, Vector } from './primitives'import type { SceneNode } from './types'-type Placement = Pick<SceneNode, 'x' | 'y' | 'width' | 'height'>+/** Where a layer sits, with a connector's ends, since a free end is in the parent's axes too. */+type Placement = Pick<SceneNode, 'x' | 'y' | 'width' | 'height'> &+ Partial<Pick<SceneNode, 'connectorStart' | 'connectorEnd'>>/** What `fitEnclosingGroups` changed, so a caller can undo and redo it. */export interface GroupFit {@@ -23,7 +25,23 @@ export interface GroupFitOptions {}function placement(node: SceneNode): Placement {- return { x: node.x, y: node.y, width: node.width, height: node.height }+ const box = { x: node.x, y: node.y, width: node.width, height: node.height }+ if (node.type !== 'CONNECTOR') return box+ return {+ ...box,+ connectorStart: structuredClone(node.connectorStart),+ connectorEnd: structuredClone(node.connectorEnd)+ }+}++/** A connector end moved by `dx`, `dy` when it is free, as its point is in the parent's axes. */+function shiftedEnd(+ end: SceneNode['connectorStart'],+ dx: number,+ dy: number+): SceneNode['connectorStart'] {+ if (end?.nodeId !== null) return end+ return { ...end, position: { x: end.position.x - dx, y: end.position.y - dy } }}/** Groups and booleans holding the parents, innermost first. */@@ -73,6 +91,17 @@ export function groupBounds(: { x: origin.x, y: origin.y, width: 0, height: 0 }}+/** A child moved back by the group's shift, a connector's free ends with it. */+function shiftedBack(child: SceneNode, dx: number, dy: number): Partial<SceneNode> {+ const moved = { x: child.x - dx, y: child.y - dy }+ if (child.type !== 'CONNECTOR') return moved+ return {+ ...moved,+ connectorStart: shiftedEnd(child.connectorStart, dx, dy),+ connectorEnd: shiftedEnd(child.connectorEnd, dx, dy)+ }+}+/** Moves the group to its children's bounds, shifting them back so they stay put. */function fitGroup(graph: SceneGraph,@@ -95,7 +124,7 @@ function fitGroup(}graph.updateNode(group.id, bounds)for (const child of children) {- graph.updateNode(child.id, { x: child.x - dx, y: child.y - dy })+ graph.updateNode(child.id, shiftedBack(child, dx, dy))}for (const node of [group, ...children]) {const current = graph.getNode(node.id)diff --git a/packages/scene-graph/tests/group-bounds.test.ts b/packages/scene-graph/tests/group-bounds.test.tsindex 44e1569f5..d507e0c8c 100644--- a/packages/scene-graph/tests/group-bounds.test.ts+++ b/packages/scene-graph/tests/group-bounds.test.ts@@ -1,7 +1,14 @@import { expect, test } from 'bun:test'import { SceneGraph } from '@open-pencil/scene-graph'-import { fitEnclosingGroups } from '@open-pencil/scene-graph/group-bounds'+import {+ boundEndpoint,+ connectorRoute,+ createConnector,+ freeEndpoint,+ layoutConnector+} from '@open-pencil/scene-graph/connectors'+import { fitEnclosingGroups, undoGroupFit } from '@open-pencil/scene-graph/group-bounds'// Live Figma 126: a group holding a rectangle, then a mask ellipse, then a larger rectangle// measures 0,0 150×150, and moving the masked rectangle leaves it unchanged.@@ -23,3 +30,30 @@ test('a group with a mask spans the layers below the mask and the mask', () => {fitEnclosingGroups(graph, [group.id])expect(bounds()).toEqual({ x: 0, y: 0, width: 150, height: 150 })})++test("a connector's free end stays put on the canvas as its group refits, and comes back on undo", () => {+ const graph = new SceneGraph()+ const group = graph.createNode('GROUP', graph.getPages()[0].id, { width: 400, height: 400 })+ const rect = graph.createNode('RECTANGLE', group.id, { width: 100, height: 100 })+ const connector = createConnector(graph, group.id, {+ start: boundEndpoint(rect.id),+ end: freeEndpoint(300, 300)+ })+ layoutConnector(graph, connector)+ fitEnclosingGroups(graph, [group.id])+ const freeEnd = () => {+ const at = graph.getNode(group.id) ?? group+ const node = graph.getNode(connector.id)+ const end = node ? connectorRoute(graph, node)?.end.point : undefined+ return end && { x: at.x + end.x, y: at.y + end.y }+ }+ expect(freeEnd()).toEqual({ x: 300, y: 300 })++ graph.updateNode(rect.id, { x: -100, y: -100 })+ const fit = fitEnclosingGroups(graph, [group.id])+ expect(graph.getNode(group.id)?.x).toBe(-100)+ expect(freeEnd()).toEqual({ x: 300, y: 300 })++ if (fit) undoGroupFit(graph, fit)+ expect(graph.getNode(connector.id)?.connectorEnd?.position).toEqual({ x: 300, y: 300 })+})diff --git a/tests/engine/tauri/file-actions.test.ts b/tests/engine/tauri/file-actions.test.tsindex 4ef8dd431..815c333b1 100644--- a/tests/engine/tauri/file-actions.test.ts+++ b/tests/engine/tauri/file-actions.test.ts@@ -17,7 +17,12 @@ describe('Tauri file actions', () => {expect(cmd).toBe('plugin:dialog|open')expect(args).toEqual({options: {- filters: [{ name: 'Design file', extensions: ['fig', 'pen', 'html', 'htm', 'xhtml'] }],+ filters: [+ {+ name: 'Design file',+ extensions: ['fig', 'pen', 'drawio', 'dio', 'html', 'htm', 'xhtml']+ }+ ],multiple: true}})