Skip to content

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

feat: save a design as a draw.io file (#1447)

Danila Poyarkov053b95435542
diff --git a/changes/1447/added.md b/changes/1447/added.md
new file mode 100644
index 000000000..8a4a89512
--- /dev/null
+++ b/changes/1447/added.md
@@ -0,0 +1 @@
+- Designs save as draw.io files: FigJam shapes, connectors, text, sections, frames, and groups as their draw.io counterparts, and anything else as an image, from the export menu for the document, a page, or a selection.
diff --git a/packages/core/src/io/formats.ts b/packages/core/src/io/formats.ts
index 33ff9993f..fd5f63029 100644
--- a/packages/core/src/io/formats.ts
+++ b/packages/core/src/io/formats.ts
@@ -1,5 +1,5 @@
import { sceneNodeToJSX, selectionToJSX } from '@open-pencil/design-jsx'
-import { isDrawioExportFileName } from '@open-pencil/drawio'
+import { isDrawIOExportFileName } from '@open-pencil/drawio'
import {
buildPenGraph,
isDataURL,
@@ -12,6 +12,7 @@ import type { SceneGraph } from '@open-pencil/scene-graph'
import { drawIcon, iconify, type IconData, type IconProvider } from '#core/icons'
import { layoutAuthoredNodes } from '#core/layout'
+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'
@@ -314,22 +315,28 @@ export const drawioFormat: IOFormatAdapter<'drawio'> = {
extensions: ['drawio', 'dio'],
mimeTypes: ['application/vnd.jgraph.mxfile'],
support: {
- readDocument: true
+ readDocument: true,
+ writeDocument: true,
+ exportDocument: true,
+ exportPage: true,
+ exportSelection: true,
+ exportNode: true
},
+ exportOptions: FIXED_SIZE_EXPORT,
// 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) ||
+ isDrawIOExportFileName(fileName) ||
mimeType === 'application/vnd.jgraph.mxfile'
)
},
async readDocument(input) {
- const { readDrawioBytes } = await import('@open-pencil/drawio')
+ const { readDrawIOBytes } = await import('@open-pencil/drawio')
const { drawioToSceneGraph } = await import('./formats/drawio')
- const file = readDrawioBytes(input.data)
+ 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(', ')}`)
@@ -341,6 +348,33 @@ export const drawioFormat: IOFormatAdapter<'drawio'> = {
graph.getPages().map((page) => page.id)
)
return { graph, sourceFormat: 'drawio' }
+ },
+ async writeDocument(graph) {
+ const pageIds = graph.getPages().map((page) => page.id)
+ return writeDrawIO(graph, { pageIds })
+ },
+ // A page or a selection goes as a one-page diagram; the document, every page.
+ async exportContent(request) {
+ if (request.target.scope === 'document') {
+ const pageIds = request.graph.getPages().map((page) => page.id)
+ return writeDrawIO(request.graph, { pageIds })
+ }
+ const target = resolveExportNodes(request)
+ if (!target) throw new Error('Nothing to export')
+ return writeDrawIO(request.graph, target)
+ }
+}
+
+/** Pages or layers as a draw.io file, loading the writer only when one is saved. */
+async function writeDrawIO(graph: SceneGraph, target: DrawIOExportTarget): Promise<ExportResult> {
+ const { writeDrawIOFile } = await import('@open-pencil/drawio')
+ const { sceneGraphToDrawIO } = await import('./formats/drawio')
+ return {
+ format: 'drawio',
+ mimeType: 'application/vnd.jgraph.mxfile',
+ extension: 'drawio',
+ data: writeDrawIOFile(sceneGraphToDrawIO(graph, target)),
+ encoding: 'utf8'
}
}
diff --git a/packages/core/src/io/formats/drawio/edges.ts b/packages/core/src/io/formats/drawio/edges.ts
index d54a2b816..288a38f2e 100644
--- a/packages/core/src/io/formats/drawio/edges.ts
+++ b/packages/core/src/io/formats/drawio/edges.ts
@@ -1,4 +1,4 @@
-import type { DrawioCell, DrawioStyle } from '@open-pencil/drawio'
+import type { DrawIOCell, DrawIOStyle } from '@open-pencil/drawio'
import type {
ConnectorControlPoint,
ConnectorEndpoint,
@@ -38,7 +38,7 @@ const ELBOW_STYLES = new Set([
* 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 {
+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'
@@ -65,7 +65,7 @@ const CAPS = new Map<string, StrokeCap>([
])
/** An end's cap: `startArrow` is none and `endArrow` classic unless the style says otherwise. */
-function capOf(style: DrawioStyle, key: 'startArrow' | 'endArrow'): StrokeCap {
+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'
@@ -89,9 +89,9 @@ export function labelPositionOf(x: number): ConnectorLabelPosition | null {
/** 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
+ edge: DrawIOCell
/** Labels draw.io keeps as cells of the edge, which the connector's label takes in turn. */
- labels: DrawioCell[]
+ labels: DrawIOCell[]
}
/**
@@ -101,8 +101,8 @@ export interface PendingEdge {
export function createEdge(
graph: SceneGraph,
parentId: string,
- edge: DrawioCell,
- labels: DrawioCell[]
+ edge: DrawIOCell,
+ labels: DrawIOCell[]
): PendingEdge {
const { style } = edge
const connector = createConnector(
@@ -155,7 +155,7 @@ function sideFacing(
function endpointOf(
graph: SceneGraph,
layerOf: (cellId: string) => string | undefined,
- edge: DrawioCell,
+ edge: DrawIOCell,
end: 'source' | 'target',
straight: boolean
): ConnectorEndpoint {
@@ -216,7 +216,7 @@ export function bindEdge(
graph: SceneGraph,
{ connector, edge, labels }: PendingEdge,
layerOf: (cellId: string) => string | undefined
-): DrawioCell[] {
+): DrawIOCell[] {
const straight = connector.connectorLineType === 'STRAIGHT'
graph.updateNode(connector.id, {
connectorStart: endpointOf(graph, layerOf, edge, 'source', straight),
diff --git a/packages/core/src/io/formats/drawio/export.ts b/packages/core/src/io/formats/drawio/export.ts
new file mode 100644
index 000000000..ff0c7a0cc
--- /dev/null
+++ b/packages/core/src/io/formats/drawio/export.ts
@@ -0,0 +1,573 @@
+import { fromUint8Array } from 'js-base64'
+
+import type {
+ DrawIOCell,
+ DrawIOFile,
+ DrawIOGeometry,
+ DrawIOPage,
+ DrawIOPoint,
+ DrawIOStyle
+} from '@open-pencil/drawio'
+import type { ConnectorEndpoint, SceneGraph, SceneNode, StrokeCap } from '@open-pencil/scene-graph'
+import { colorToHex } from '@open-pencil/scene-graph/color'
+import {
+ connectorRoute,
+ connectorRouteEnds,
+ connectorSublayers,
+ curveMidpoint
+} from '@open-pencil/scene-graph/connectors'
+import { getParentWorldMatrix } from '@open-pencil/scene-graph/coordinate'
+import {
+ isGeneratedFrame,
+ shapeWithTextLabel,
+ stickySublayers
+} from '@open-pencil/scene-graph/generated'
+import Matrix, { type Mat3 } from '@open-pencil/scene-graph/matrix'
+import type { Vector } from '@open-pencil/scene-graph/primitives'
+
+import { renderNodesToSVG } from '#core/io/formats/svg'
+
+import { DEFAULT_FONT_FAMILY } from './paint'
+import { drawioShapeValues } from './shapes'
+
+/** draw.io's id for its root cell and for its one layer, as it numbers new files. */
+const ROOT_ID = '0'
+const LAYER_ID = '1'
+
+const EMPTY_GEOMETRY: DrawIOGeometry = {
+ x: 0,
+ y: 0,
+ width: 0,
+ height: 0,
+ relative: false,
+ points: [],
+ sourcePoint: null,
+ targetPoint: null,
+ offset: null
+}
+
+function style(names: string[], values: Record<string, string | undefined>): DrawIOStyle {
+ return {
+ names,
+ values: Object.fromEntries(Object.entries(values).filter(([, v]) => v !== undefined))
+ }
+}
+
+function round(value: number): number {
+ return Math.round(value * 100) / 100
+}
+
+function box(node: SceneNode): DrawIOGeometry {
+ return {
+ ...EMPTY_GEOMETRY,
+ x: round(node.x),
+ y: round(node.y),
+ width: round(node.width),
+ height: round(node.height)
+ }
+}
+
+/**
+ * Carries a layer's parent's axes into the page's, for a selected layer whose parent is not
+ * written: draw.io places it on its one layer, which has the page's axes.
+ */
+interface ToPage {
+ matrix: Mat3
+ /** How far the parent turns its axes, in degrees. */
+ turn: number
+}
+
+function toPageOf(graph: SceneGraph, node: SceneNode, pageId: string): ToPage | null {
+ if (!node.parentId || node.parentId === pageId) return null
+ const matrix = getParentWorldMatrix(graph.getNode(node.parentId), graph)
+ const origin = Matrix.mapPoint(matrix, { x: 0, y: 0 })
+ const across = Matrix.mapPoint(matrix, { x: 1, y: 0 })
+ const turn = (Math.atan2(across.y - origin.y, across.x - origin.x) * 180) / Math.PI
+ return { matrix, turn }
+}
+
+/** Where a layer sits and how far it turns about its centre, in draw.io's axes. */
+interface Placed {
+ geometry: DrawIOGeometry
+ rotation: number
+}
+
+function placed(node: SceneNode, toPage: ToPage | null): Placed {
+ if (!toPage) return { geometry: box(node), rotation: node.rotation }
+ // draw.io turns a cell about its centre, as the layer turns, so the centre carries its place.
+ const centre = Matrix.mapPoint(toPage.matrix, {
+ x: node.x + node.width / 2,
+ y: node.y + node.height / 2
+ })
+ const rotation = ((((node.rotation + toPage.turn + 180) % 360) + 360) % 360) - 180
+ return {
+ geometry: {
+ ...box(node),
+ x: round(centre.x - node.width / 2),
+ y: round(centre.y - node.height / 2)
+ },
+ rotation
+ }
+}
+
+/** A turn as draw.io's `rotation` style value, which an unturned cell leaves out. */
+function rotationValue(rotation: number): string | undefined {
+ return rotation === 0 ? undefined : String(round(rotation))
+}
+
+const escapeHTML = (text: string) =>
+ text.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
+
+/** A layer's first visible solid fill, or the first stop of a gradient, as draw.io's colour. */
+function fillColor(node: SceneNode): string {
+ const fill = node.fills.find((paint) => paint.visible)
+ if (!fill) return 'none'
+ if (fill.type === 'SOLID') return colorToHex(fill.color)
+ const stop = fill.gradientStops?.at(0)
+ return stop ? colorToHex(stop.color) : 'none'
+}
+
+/** A layer's fill, outline, dash, and opacity as style pairs. */
+function paintValues(node: SceneNode): Record<string, string | undefined> {
+ const stroke = node.strokes.find((paint) => paint.visible)
+ const weight = stroke?.weight ?? node.strokeWeight
+ const dash = stroke?.dashPattern ?? node.dashPattern
+ return {
+ fillColor: fillColor(node),
+ strokeColor: stroke ? colorToHex(stroke.color) : 'none',
+ strokeWidth: stroke && weight !== 1 ? String(weight) : undefined,
+ dashed: dash.length > 0 ? '1' : undefined,
+ dashPattern: dash.length > 0 ? dash.map((n) => round(n / (weight || 1))).join(' ') : undefined,
+ opacity: node.opacity < 1 ? String(Math.round(node.opacity * 100)) : undefined
+ }
+}
+
+const ALIGN: Record<SceneNode['textAlignHorizontal'], string> = {
+ LEFT: 'left',
+ CENTER: 'center',
+ RIGHT: 'right',
+ JUSTIFIED: 'left'
+}
+const VERTICAL_ALIGN: Record<SceneNode['textAlignVertical'], string> = {
+ TOP: 'top',
+ CENTER: 'middle',
+ BOTTOM: 'bottom'
+}
+
+/** A text layer's font and alignment as a label's style pairs. */
+function fontValues(text: SceneNode): Record<string, string | undefined> {
+ const fill = text.fills.find((paint) => paint.visible && paint.type === 'SOLID')
+ const bits =
+ (text.fontWeight >= 600 ? 1 : 0) |
+ (text.italic ? 2 : 0) |
+ (text.textDecoration === 'UNDERLINE' ? 4 : 0)
+ return {
+ fontSize: String(text.fontSize),
+ // The font draw.io's default stands for on import goes back as that default.
+ fontFamily: text.fontFamily === DEFAULT_FONT_FAMILY ? undefined : text.fontFamily,
+ fontColor: fill ? colorToHex(fill.color) : undefined,
+ fontStyle: bits ? String(bits) : undefined,
+ align: ALIGN[text.textAlignHorizontal],
+ verticalAlign: VERTICAL_ALIGN[text.textAlignVertical]
+ }
+}
+
+/**
+ * A text layer's characters as an HTML label: each style run in a span that sets what it
+ * changes, and a line break for each new line.
+ */
+function labelHTML(text: SceneNode): string {
+ const { text: characters, styleRuns } = text
+ let html = ''
+ let at = 0
+ const plain = (to: number) => {
+ html += escapeHTML(characters.slice(at, to)).replaceAll('\n', '<br>')
+ at = to
+ }
+ for (const run of [...styleRuns].sort((a, b) => a.start - b.start)) {
+ plain(run.start)
+ const css: string[] = []
+ const { style: s } = run
+ if (s.fontWeight !== undefined) css.push(`font-weight: ${s.fontWeight}`)
+ if (s.italic !== undefined) css.push(`font-style: ${s.italic ? 'italic' : 'normal'}`)
+ if (s.textDecoration)
+ css.push(`text-decoration: ${s.textDecoration === 'UNDERLINE' ? 'underline' : 'none'}`)
+ if (s.fontSize !== undefined) css.push(`font-size: ${s.fontSize}px`)
+ if (s.fontFamily) css.push(`font-family: ${s.fontFamily}`)
+ const fill = s.fills?.find((paint) => paint.type === 'SOLID')
+ if (fill?.type === 'SOLID') css.push(`color: ${colorToHex(fill.color)}`)
+ const inner = escapeHTML(characters.slice(run.start, run.start + run.length)).replaceAll(
+ '\n',
+ '<br>'
+ )
+ html += css.length > 0 ? `<span style="${css.join('; ')}">${inner}</span>` : inner
+ at = run.start + run.length
+ }
+ plain(characters.length)
+ return html
+}
+
+/** A connector line's colour, width, and dash as an edge's style pairs. */
+function lineValues(line: SceneNode): Record<string, string | undefined> {
+ const stroke = line.strokes.find((paint) => paint.visible)
+ const weight = stroke?.weight ?? 1
+ const dash = stroke?.dashPattern ?? []
+ return {
+ strokeColor: stroke ? colorToHex(stroke.color) : 'none',
+ strokeWidth: weight !== 1 ? String(weight) : undefined,
+ dashed: dash.length > 0 ? '1' : undefined,
+ dashPattern: dash.length > 0 ? dash.map((n) => round(n / weight)).join(' ') : undefined
+ }
+}
+
+/** FigJam's ends and the draw.io arrowheads that draw them. */
+const ARROWS: Record<StrokeCap, string> = {
+ NONE: 'none',
+ ROUND: 'none',
+ SQUARE: 'none',
+ ARROW_LINES: 'open',
+ ARROW_EQUILATERAL: 'classic',
+ TRIANGLE_FILLED: 'classic',
+ DIAMOND_FILLED: 'diamond',
+ CIRCLE_FILLED: 'oval'
+}
+
+/** Where a side magnet pins an end, as shares of the layer's box. */
+const SIDE_POINTS: Partial<Record<ConnectorEndpoint['magnet'], [number, number]>> = {
+ TOP: [0.5, 0],
+ RIGHT: [1, 0.5],
+ BOTTOM: [0.5, 1],
+ LEFT: [0, 0.5]
+}
+
+/** Writes one page's layers as draw.io cells, in drawing order. */
+class PageWriter {
+ readonly cells: DrawIOCell[] = []
+ private readonly ids = new Map<string, string>()
+ /** Where each edge's line last ran from and to, in draw.io's axes. */
+ private readonly drawnEnds = new Map<string, { start: DrawIOPoint; end: DrawIOPoint }>()
+ private next = 2
+
+ constructor(
+ private readonly graph: SceneGraph,
+ private readonly pageId: string
+ ) {}
+
+ private idOf(nodeId: string): string {
+ let id = this.ids.get(nodeId)
+ if (!id) {
+ id = String(this.next++)
+ this.ids.set(nodeId, id)
+ }
+ return id
+ }
+
+ write(nodeIds: readonly string[]) {
+ // Every layer gets its id first, so an edge can name a layer drawn above it.
+ const assign = (id: string) => {
+ const node = this.graph.getNode(id)
+ if (!node) return
+ this.idOf(id)
+ if (!isGeneratedFrame(node)) for (const child of node.childIds) assign(child)
+ }
+ // A layer inside another chosen one goes with it, as a cell of its own or drawn in its picture.
+ const chosen = new Set(nodeIds)
+ const roots = nodeIds.filter((id) => {
+ const parentId = this.graph.getNode(id)?.parentId
+ return !parentId || !this.graph.closest(parentId, (node) => chosen.has(node.id))
+ })
+ for (const id of roots) assign(id)
+ for (const id of roots) {
+ const node = this.graph.getNode(id)
+ if (node) this.layer(node, LAYER_ID, toPageOf(this.graph, node, this.pageId))
+ }
+ this.freeStrandedEnds()
+ }
+
+ /**
+ * An edge end joined to a layer that has no cell, such as one left out of a selection or
+ * drawn inside a picture, goes as a free point where the line last ran.
+ */
+ private freeStrandedEnds() {
+ const written = new Set(this.cells.map((cell) => cell.id))
+ for (const cell of this.cells) {
+ const drawn = this.drawnEnds.get(cell.id)
+ if (!drawn) continue
+ if (!cell.source || !written.has(cell.source)) {
+ cell.source = null
+ cell.geometry.sourcePoint = drawn.start
+ }
+ if (!cell.target || !written.has(cell.target)) {
+ cell.target = null
+ cell.geometry.targetPoint = drawn.end
+ }
+ }
+ }
+
+ private push(
+ node: SceneNode,
+ parent: string,
+ cell: Omit<DrawIOCell, 'id' | 'parent' | 'visible' | 'attributes' | 'source' | 'target'> &
+ Partial<Pick<DrawIOCell, 'source' | 'target'>>
+ ) {
+ this.cells.push({
+ id: this.idOf(node.id),
+ parent,
+ visible: node.visible,
+ attributes: {},
+ source: null,
+ target: null,
+ ...cell
+ })
+ }
+
+ private children(node: SceneNode) {
+ for (const id of node.childIds) {
+ const child = this.graph.getNode(id)
+ if (child) this.layer(child, this.idOf(node.id), null)
+ }
+ }
+
+ private layer(node: SceneNode, parent: string, toPage: ToPage | null) {
+ const { geometry, rotation } = placed(node, toPage)
+ switch (node.type) {
+ case 'SHAPE_WITH_TEXT':
+ return this.shape(node, parent, toPage)
+ case 'TEXT':
+ return this.push(node, parent, {
+ kind: 'vertex',
+ value: labelHTML(node),
+ style: style(['text'], {
+ html: '1',
+ whiteSpace: 'wrap',
+ rotation: rotationValue(rotation),
+ ...fontValues(node)
+ }),
+ geometry
+ })
+ case 'STICKY': {
+ const body = stickySublayers(this.graph, node)?.body
+ return this.push(node, parent, {
+ kind: 'vertex',
+ value: body ? labelHTML(body) : '',
+ style: style([], {
+ whiteSpace: 'wrap',
+ html: '1',
+ ...paintValues(node),
+ strokeColor: 'none',
+ align: 'left',
+ verticalAlign: 'top',
+ spacing: '20',
+ rotation: rotationValue(rotation),
+ fontSize: body ? String(body.fontSize) : undefined
+ }),
+ geometry
+ })
+ }
+ case 'SECTION':
+ this.push(node, parent, {
+ kind: 'vertex',
+ value: escapeHTML(node.name),
+ style: style(['swimlane'], { html: '1', startSize: '30', ...paintValues(node) }),
+ geometry
+ })
+ return this.children(node)
+ case 'GROUP':
+ this.push(node, parent, {
+ kind: 'vertex',
+ value: '',
+ style: style(['group'], {}),
+ geometry
+ })
+ return this.children(node)
+ case 'FRAME':
+ this.push(node, parent, {
+ kind: 'vertex',
+ value: '',
+ style: style([], { container: '1', html: '1', ...paintValues(node) }),
+ geometry
+ })
+ return this.children(node)
+ case 'RECTANGLE':
+ case 'ELLIPSE':
+ return this.push(node, parent, {
+ kind: 'vertex',
+ value: '',
+ style: style(node.type === 'ELLIPSE' ? ['ellipse'] : [], {
+ rounded: node.cornerRadius > 0 ? '1' : undefined,
+ rotation: rotationValue(rotation),
+ ...paintValues(node)
+ }),
+ geometry
+ })
+ case 'CONNECTOR':
+ return this.edge(node, parent, toPage)
+ default:
+ return this.picture(node, parent, geometry)
+ }
+ }
+
+ private shape(node: SceneNode, parent: string, toPage: ToPage | null) {
+ const label = shapeWithTextLabel(this.graph, node)
+ const values: Record<string, string | undefined> = {
+ ...drawioShapeValues(node.shapeWithTextType),
+ whiteSpace: 'wrap',
+ html: '1',
+ ...paintValues(node),
+ ...(label ? fontValues(label) : {})
+ }
+ let { geometry, rotation } = placed(node, toPage)
+ // A triangle turned a quarter points the way draw.io's direction says, in the box it fills.
+ const quarter = Math.abs(rotation) === 90 && node.shapeWithTextType === 'TRIANGLE_UP'
+ if (quarter) {
+ values.direction = rotation === 90 ? 'east' : 'west'
+ geometry = {
+ ...geometry,
+ x: round(geometry.x + (node.width - node.height) / 2),
+ y: round(geometry.y + (node.height - node.width) / 2),
+ width: round(node.height),
+ height: round(node.width)
+ }
+ rotation = 0
+ }
+ values.rotation = rotationValue(rotation)
+ this.push(node, parent, {
+ kind: 'vertex',
+ value: label ? labelHTML(label) : '',
+ style: style([], values),
+ geometry
+ })
+ }
+
+ /** A layer draw.io has no cell for, drawn as the SVG image it exports as. */
+ private picture(node: SceneNode, parent: string, geometry: DrawIOGeometry) {
+ const svg = renderNodesToSVG(this.graph, this.pageId, [node.id])
+ if (!svg) return
+ const data = fromUint8Array(new TextEncoder().encode(svg))
+ this.push(node, parent, {
+ kind: 'vertex',
+ value: '',
+ // draw.io keeps a data URI in its style without `;base64`, which would end the value.
+ style: style([], { shape: 'image', image: `data:image/svg+xml,${data}`, aspect: 'fixed' }),
+ geometry
+ })
+ }
+
+ private end(
+ endpoint: ConnectorEndpoint | null,
+ prefix: 'exit' | 'entry'
+ ): Record<string, string> {
+ const node = endpoint?.nodeId ? this.graph.getNode(endpoint.nodeId) : undefined
+ if (!endpoint || !node) return {}
+ const side = SIDE_POINTS[endpoint.magnet]
+ const point: [number, number] | null =
+ side ??
+ (endpoint.magnet === 'NONE' || endpoint.magnet === 'ABSOLUTE'
+ ? [endpoint.position.x / (node.width || 1), endpoint.position.y / (node.height || 1)]
+ : null)
+ if (!point) return {}
+ return { [`${prefix}X`]: String(round(point[0])), [`${prefix}Y`]: String(round(point[1])) }
+ }
+
+ /**
+ * Where an edge's free ends sit, its bend points, and its label's place along it, with the
+ * points carried into draw.io's axes.
+ */
+ private edgeGeometry(node: SceneNode, toPage: ToPage | null): DrawIOGeometry {
+ const at = (point: Vector) => {
+ const mapped = toPage ? Matrix.mapPoint(toPage.matrix, point) : point
+ return { x: round(mapped.x), y: round(mapped.y) }
+ }
+ const drawn = connectorRouteEnds(this.graph, node)
+ if (drawn) {
+ this.drawnEnds.set(this.idOf(node.id), { start: at(drawn.start), end: at(drawn.end) })
+ }
+ const position = node.connectorLabelPosition
+ const along = position?.section === 'MIDDLE_TO_START' ? -position.offset : position?.offset
+ return {
+ ...EMPTY_GEOMETRY,
+ relative: true,
+ x: round(along ?? 0),
+ sourcePoint: !node.connectorStart?.nodeId && drawn ? at(drawn.start) : null,
+ targetPoint: !node.connectorEnd?.nodeId && drawn ? at(drawn.end) : null,
+ points: this.waypoints(node).map(at)
+ }
+ }
+
+ private edge(node: SceneNode, parent: string, toPage: ToPage | null) {
+ // A connector without its line and label is not one draw.io could draw.
+ const parts = connectorSublayers(this.graph, node)
+ if (!parts) return
+ const startId = node.connectorStart?.nodeId
+ const endId = node.connectorEnd?.nodeId
+ const lineType = node.connectorLineType
+ this.push(node, parent, {
+ kind: 'edge',
+ value: parts.label.text ? labelHTML(parts.label) : '',
+ style: style([], {
+ edgeStyle: lineType === 'ELBOWED' ? 'orthogonalEdgeStyle' : undefined,
+ rounded: lineType === 'ELBOWED' ? '1' : undefined,
+ curved: lineType === 'CURVED' ? '1' : undefined,
+ html: '1',
+ startArrow: ARROWS[node.connectorStartCap],
+ endArrow: ARROWS[node.connectorEndCap],
+ ...lineValues(parts.line),
+ ...this.end(node.connectorStart, 'exit'),
+ ...this.end(node.connectorEnd, 'entry'),
+ ...fontValues(parts.label)
+ }),
+ geometry: this.edgeGeometry(node, toPage),
+ source: startId ? (this.ids.get(startId) ?? null) : null,
+ target: endId ? (this.ids.get(endId) ?? null) : null
+ })
+ }
+
+ /**
+ * The points a dragged connector bends through, for draw.io to run its edge the same way: an
+ * elbow's corners, or the middle of a curve. A connector routing itself leaves draw.io to route.
+ */
+ private waypoints(node: SceneNode): Vector[] {
+ const route = connectorRoute(this.graph, node)
+ if (!route) return []
+ if (node.connectorLineType === 'CURVED' && node.connectorCurveHandles) {
+ const curve = route.pieces.at(0)
+ return curve ? [curveMidpoint(curve)] : []
+ }
+ if (node.connectorLineType !== 'ELBOWED' || node.connectorControlPoints.length === 0) return []
+ return route.pieces.slice(0, -1).map((piece) => piece.to)
+ }
+}
+
+/** One page of layers as a draw.io page, holding `nodeIds` or every layer on it. */
+function pageOf(graph: SceneGraph, pageId: string, nodeIds?: readonly string[]): DrawIOPage {
+ const page = graph.getNode(pageId)
+ const writer = new PageWriter(graph, pageId)
+ writer.write(nodeIds ?? page?.childIds ?? [])
+ return {
+ id: pageId,
+ name: page?.name ?? 'Page',
+ attributes: { grid: '1', gridSize: '10' },
+ rootId: ROOT_ID,
+ layers: [{ id: LAYER_ID, name: '', visible: true, locked: false }],
+ cells: writer.cells
+ }
+}
+
+/** What a draw.io export holds: whole pages, or some layers of one page. */
+export type DrawIOExportTarget =
+ | { pageIds: readonly string[] }
+ | { pageId: string; nodeIds: readonly string[] }
+
+/**
+ * Layers as a draw.io file: FigJam shapes as draw.io's shapes of the same meaning, connectors as
+ * edges joined to them, bent the way they were dragged, text as text, sections as swimlanes, and
+ * frames and groups as containers. A layer draw.io has no cell for goes as an SVG image of
+ * itself, so nothing is lost.
+ */
+export function sceneGraphToDrawIO(graph: SceneGraph, target: DrawIOExportTarget): DrawIOFile {
+ const pages =
+ 'pageIds' in target
+ ? target.pageIds.map((pageId) => pageOf(graph, pageId))
+ : [pageOf(graph, target.pageId, target.nodeIds)]
+ return { pages, unreadable: [] }
+}
diff --git a/packages/core/src/io/formats/drawio/index.ts b/packages/core/src/io/formats/drawio/index.ts
index b85a874b9..6d10e23cf 100644
--- a/packages/core/src/io/formats/drawio/index.ts
+++ b/packages/core/src/io/formats/drawio/index.ts
@@ -1,4 +1,4 @@
-import type { DrawioCell, DrawioFile, DrawioPage } from '@open-pencil/drawio'
+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'
@@ -10,7 +10,7 @@ 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) {
+function labelOf(cell: DrawIOCell) {
const format = labelFormat(cell.style)
return { format, ...readLabel(cell.value, cell.style.values.html === '1', format) }
}
@@ -29,7 +29,7 @@ class PageBuilder {
constructor(
private readonly graph: SceneGraph,
- private readonly page: DrawioPage,
+ private readonly page: DrawIOPage,
private readonly pageId: string
) {}
@@ -51,7 +51,7 @@ class PageBuilder {
this.groups.push(group.id)
}
const parents = new Set(page.cells.map((cell) => cell.parent))
- const labelsOf = new Map<string, DrawioCell[]>()
+ const labelsOf = new Map<string, DrawIOCell[]>()
const edgeIds = new Set(
page.cells.filter((cell) => cell.kind === 'edge').map((cell) => cell.id)
)
@@ -65,7 +65,7 @@ class PageBuilder {
}
const cells = new Map(page.cells.map((cell) => [cell.id, cell]))
const placing = new Set<string>()
- const place = (cell: DrawioCell) => {
+ 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.
@@ -90,7 +90,7 @@ class PageBuilder {
for (const id of this.groups.toReversed()) fitEnclosingGroups(graph, [id])
}
- private vertex(cell: DrawioCell, parentId: string, hasChildren: boolean): SceneNode {
+ 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)
@@ -146,7 +146,7 @@ class PageBuilder {
}
/** A label beyond an edge's first, as text where draw.io placed it along the edge. */
- private edgeText({ connector }: PendingEdge, cell: DrawioCell) {
+ private edgeText({ connector }: PendingEdge, cell: DrawIOCell) {
const { graph } = this
const node = graph.getNode(connector.id)
const route = node ? connectorRoute(graph, node) : null
@@ -173,7 +173,7 @@ class PageBuilder {
* 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 {
+export function drawioToSceneGraph(file: DrawIOFile): SceneGraph {
const graph = new SceneGraph()
const first = graph.getPages().at(0)
for (const [index, page] of file.pages.entries()) {
@@ -183,3 +183,5 @@ export function drawioToSceneGraph(file: DrawioFile): SceneGraph {
}
return graph
}
+
+export { sceneGraphToDrawIO } from './export'
diff --git a/packages/core/src/io/formats/drawio/paint.ts b/packages/core/src/io/formats/drawio/paint.ts
index 9b76649f0..978a09eef 100644
--- a/packages/core/src/io/formats/drawio/paint.ts
+++ b/packages/core/src/io/formats/drawio/paint.ts
@@ -1,4 +1,4 @@
-import { styleNumber, type DrawioStyle } from '@open-pencil/drawio'
+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'
@@ -15,7 +15,7 @@ export const DEFAULT_FONT_FAMILY = 'Inter'
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 {
+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
@@ -23,7 +23,7 @@ function styleColor(style: DrawioStyle, key: string, fallback: Color | null): Co
}
/** A 0–100 opacity a style sets, as a fraction. */
-function opacity(style: DrawioStyle, key: string): number {
+function opacity(style: DrawIOStyle, key: string): number {
return Math.min(1, Math.max(0, styleNumber(style, key, 100) / 100))
}
@@ -36,7 +36,7 @@ function solid(color: Color, alpha: number): Fill {
* 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> {
+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)
@@ -62,7 +62,7 @@ export function shapePaint(style: DrawioStyle): Partial<SceneNode> {
}
/** 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[] {
+export function dashOf(style: DrawIOStyle, weight: number): number[] {
if (style.values.dashed !== '1') return []
const pattern = (style.values.dashPattern ?? '3 3')
.split(/\s+/)
@@ -72,12 +72,12 @@ export function dashOf(style: DrawioStyle, weight: number): number[] {
}
/** The colour of an edge's line: `strokeColor`, black by default. */
-export function lineColor(style: DrawioStyle): Color | null {
+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 {
+export function labelFormat(style: DrawIOStyle): LabelFormat {
const fontStyle = styleNumber(style, 'fontStyle', 0)
return {
// fontStyle is a bit set: bold, italic, underline.
@@ -102,7 +102,7 @@ const VERTICAL = new Map<string, SceneNode['textAlignVertical']>([
])
/** A label's text fields: its font, size, colour, and alignment, centred by default. */
-export function labelFields(style: DrawioStyle, format = labelFormat(style)): Partial<SceneNode> {
+export function labelFields(style: DrawIOStyle, format = labelFormat(style)): Partial<SceneNode> {
return {
fontFamily: format.family,
fontWeight: format.bold ? 700 : 400,
diff --git a/packages/core/src/io/formats/drawio/shapes.ts b/packages/core/src/io/formats/drawio/shapes.ts
index e4644a5da..4acaf9ad8 100644
--- a/packages/core/src/io/formats/drawio/shapes.ts
+++ b/packages/core/src/io/formats/drawio/shapes.ts
@@ -1,4 +1,4 @@
-import type { DrawioStyle } from '@open-pencil/drawio'
+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. */
@@ -69,7 +69,7 @@ const SHAPES = new Map<string, ShapeWithTextType>([
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 {
+export function shapeName(style: DrawIOStyle): string {
return style.values.shape ?? style.names.find((name) => SHAPE_NAMES.has(name)) ?? 'rectangle'
}
@@ -87,7 +87,7 @@ const DIRECTION_TURN = new Map([
* `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 {
+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')) {
@@ -111,3 +111,45 @@ export function vertexKind(style: DrawioStyle, hasChildren: boolean): VertexKind
} else if (shape === 'SQUARE' && style.values.rounded === '1') shape = 'ROUNDED_RECTANGLE'
return { type: 'SHAPE_WITH_TEXT', shape, rotation, stencil: !SHAPES.has(name) }
}
+
+/**
+ * The draw.io style that draws each FigJam shape, the other way round: built-in shapes where
+ * draw.io has one, its flowchart and basic stencils otherwise. A shield, which draw.io has no
+ * shape for, goes as a rectangle.
+ */
+const DRAWIO_SHAPES: Record<ShapeWithTextType, Record<string, string>> = {
+ SQUARE: {},
+ ROUNDED_RECTANGLE: { rounded: '1' },
+ ELLIPSE: { shape: 'ellipse', perimeter: 'ellipsePerimeter' },
+ DIAMOND: { shape: 'rhombus', perimeter: 'rhombusPerimeter' },
+ TRIANGLE_UP: { shape: 'triangle', direction: 'north', perimeter: 'trianglePerimeter' },
+ TRIANGLE_DOWN: { shape: 'triangle', direction: 'south', perimeter: 'trianglePerimeter' },
+ PARALLELOGRAM_RIGHT: { shape: 'parallelogram', perimeter: 'parallelogramPerimeter' },
+ PARALLELOGRAM_LEFT: { shape: 'parallelogram', flipH: '1', perimeter: 'parallelogramPerimeter' },
+ ENG_DATABASE: { shape: 'cylinder3' },
+ ENG_QUEUE: { shape: 'mxgraph.flowchart.direct_data' },
+ ENG_FILE: { shape: 'note' },
+ ENG_FOLDER: { shape: 'folder' },
+ TRAPEZOID: { shape: 'trapezoid', perimeter: 'trapezoidPerimeter' },
+ PREDEFINED_PROCESS: { shape: 'process' },
+ SHIELD: {},
+ DOCUMENT_SINGLE: { shape: 'document' },
+ DOCUMENT_MULTIPLE: { shape: 'mxgraph.flowchart.multi-document' },
+ MANUAL_INPUT: { shape: 'manualInput' },
+ HEXAGON: { shape: 'hexagon', perimeter: 'hexagonPerimeter2' },
+ CHEVRON: { shape: 'step' },
+ PENTAGON: { shape: 'mxgraph.basic.pentagon' },
+ OCTAGON: { shape: 'mxgraph.basic.octagon2' },
+ STAR: { shape: 'mxgraph.basic.star' },
+ PLUS: { shape: 'cross' },
+ ARROW_LEFT: { shape: 'singleArrow', direction: 'west' },
+ ARROW_RIGHT: { shape: 'singleArrow' },
+ SUMMING_JUNCTION: { shape: 'sumEllipse', perimeter: 'ellipsePerimeter' },
+ OR: { shape: 'orEllipse', perimeter: 'ellipsePerimeter' },
+ SPEECH_BUBBLE: { shape: 'callout' },
+ INTERNAL_STORAGE: { shape: 'internalStorage' }
+}
+
+export function drawioShapeValues(shape: ShapeWithTextType): Record<string, string> {
+ return { ...DRAWIO_SHAPES[shape] }
+}
diff --git a/packages/core/tests/io/formats/drawio/export.test.ts b/packages/core/tests/io/formats/drawio/export.test.ts
new file mode 100644
index 000000000..cab9053a6
--- /dev/null
+++ b/packages/core/tests/io/formats/drawio/export.test.ts
@@ -0,0 +1,203 @@
+import { describe, expect, test } from 'bun:test'
+import { readFileSync } from 'node:fs'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+
+import { parseDrawIOFile } from '@open-pencil/drawio'
+import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
+import {
+ boundEndpoint,
+ connectorSublayers,
+ createConnector,
+ freeEndpoint
+} from '@open-pencil/scene-graph/connectors'
+import { createShapeWithText } from '@open-pencil/scene-graph/generated'
+
+import { BUILTIN_IO_FORMATS, IORegistry } from '#core/io'
+import type { ExportTarget } from '#core/io'
+
+const io = new IORegistry(BUILTIN_IO_FORMATS)
+
+/** A flowchart as draw.io saves it: shapes, text, elbowed, dashed, bent, and curved edges. */
+const ORDER_FLOW = readFileSync(new URL('order-flow.drawio', import.meta.url), 'utf8')
+
+async function read(source: string) {
+ return (await io.readDocument({ name: 'flow.drawio', data: new TextEncoder().encode(source) }))
+ .graph
+}
+
+async function write(graph: SceneGraph): Promise<string> {
+ const format = expectDefined(io.getFormat('drawio'))
+ const result = expectDefined(await format.writeDocument?.(graph))
+ if (typeof result.data !== 'string') throw new Error('Expected draw.io XML')
+ return result.data
+}
+
+/** The cells a draw.io export of `target` writes on its one page. */
+async function exported(graph: SceneGraph, target: ExportTarget) {
+ const result = await io.exportContent('drawio', { graph, target })
+ if (typeof result.data !== 'string') throw new Error('Expected draw.io XML')
+ const file = expectDefined(parseDrawIOFile(result.data))
+ return expectDefined(file.pages[0]).cells
+}
+
+/** A page with a rectangle and, in a group at 100, 100, a shape and a connector out of it. */
+function grouped() {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const rect = graph.createNode('RECTANGLE', page.id, { name: 'Alone', width: 40, height: 40 })
+ const group = graph.createNode('GROUP', page.id, {
+ name: 'Group',
+ x: 100,
+ y: 100,
+ width: 200,
+ height: 100
+ })
+ const shape = createShapeWithText(
+ graph,
+ group.id,
+ { name: 'Inner', x: 10, y: 20, width: 60, height: 40 },
+ {}
+ )
+ const connector = createConnector(graph, group.id, {
+ start: boundEndpoint(shape.id, 'RIGHT'),
+ end: freeEndpoint(180, 40)
+ })
+ return { graph, page, rect, group, shape, connector }
+}
+
+/** What a page holds, as a round trip should keep it. */
+function summary(graph: SceneGraph) {
+ const page = graph.getPages()[0]
+ const name = (id: string | null | undefined) => (id ? graph.getNode(id)?.name : null)
+ return graph.getChildren(page.id).map((node: SceneNode) =>
+ node.type === 'CONNECTOR'
+ ? {
+ type: node.type,
+ lineType: node.connectorLineType,
+ from: name(node.connectorStart?.nodeId),
+ to: name(node.connectorEnd?.nodeId),
+ caps: [node.connectorStartCap, node.connectorEndCap],
+ label: connectorSublayers(graph, node)?.label.text
+ }
+ : {
+ type: node.type,
+ kind: node.shapeWithTextType,
+ name: node.name,
+ box: [node.x, node.y, node.width, node.height].map(Math.round),
+ fill: node.fills[0]?.type === 'SOLID' ? node.fills[0].color : null
+ }
+ )
+}
+
+describe('saving a draw.io file', () => {
+ test('a diagram opened from draw.io saves to one that opens the same', async () => {
+ const opened = await read(ORDER_FLOW)
+ const saved = await write(opened)
+ expect(saved).toStartWith('<mxfile host="OpenPencil">')
+ expect(summary(await read(saved))).toEqual(summary(opened))
+ })
+
+ test('a dragged connector saves the corners it was dragged to, which draw.io runs through', async () => {
+ const opened = await read(ORDER_FLOW)
+ const file = expectDefined(parseDrawIOFile(await write(opened)))
+ const bent = expectDefined(file.pages[0]?.cells.find((cell) => cell.value === 'no'))
+ expect(bent.geometry.points).toContainEqual({ x: 420, y: 160 })
+ expect(bent.geometry.points).toContainEqual({ x: 530, y: 160 })
+ expect(bent.style.values.edgeStyle).toBe('orthogonalEdgeStyle')
+ })
+
+ test('a layer draw.io has no cell for goes as an SVG image of itself', async () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ graph.createNode('STAR', page.id, {
+ name: 'Star',
+ x: 10,
+ y: 20,
+ width: 40,
+ height: 40,
+ fills: [{ type: 'SOLID', color: { r: 1, g: 0.8, b: 0, a: 1 }, opacity: 1, visible: true }]
+ })
+ const connector = createConnector(graph, page.id, {
+ start: freeEndpoint(100, 100),
+ end: freeEndpoint(300, 100)
+ })
+ graph.updateNode(connector.id, { name: 'Loose' })
+ const [star, edge] = expectDefined(parseDrawIOFile(await write(graph))).pages[0]?.cells ?? []
+ expect(star.style.values.shape).toBe('image')
+ expect(star.style.values.image).toStartWith('data:image/svg+xml,')
+ expect(star.geometry).toMatchObject({ x: 10, y: 20, width: 40, height: 40 })
+ // A free connector keeps its ends as points.
+ expect(edge.geometry).toMatchObject({
+ sourcePoint: { x: 100, y: 100 },
+ targetPoint: { x: 300, y: 100 }
+ })
+ })
+
+ test('turned rectangles, ellipses, and text keep their turn', async () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ graph.createNode('RECTANGLE', page.id, { width: 40, height: 20, rotation: 30 })
+ graph.createNode('ELLIPSE', page.id, { width: 40, height: 20, rotation: -45 })
+ graph.createNode('TEXT', page.id, { width: 40, height: 20, rotation: 15, text: 'Turned' })
+ const cells = expectDefined(parseDrawIOFile(await write(graph))).pages[0]?.cells ?? []
+ expect(cells.map((cell) => cell.style.values.rotation)).toEqual(['30', '-45', '15'])
+ })
+
+ test('non-rectangular shapes name the outline edges attach to', async () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ for (const shapeWithTextType of ['ELLIPSE', 'DIAMOND', 'TRIANGLE_UP', 'HEXAGON'] as const) {
+ createShapeWithText(graph, page.id, { shapeWithTextType, width: 60, height: 40 }, {})
+ }
+ const cells = expectDefined(parseDrawIOFile(await write(graph))).pages[0]?.cells ?? []
+ expect(cells.map((cell) => cell.style.values.perimeter)).toEqual([
+ 'ellipsePerimeter',
+ 'rhombusPerimeter',
+ 'trianglePerimeter',
+ 'hexagonPerimeter2'
+ ])
+ })
+})
+
+describe('exporting part of a design as draw.io', () => {
+ test('a page holds that page’s layers, a node only itself', async () => {
+ const { graph, page, rect, group } = grouped()
+ const other = graph.addPage('Other')
+ graph.createNode('RECTANGLE', other.id, { width: 10, height: 10 })
+ expect((await exported(graph, { scope: 'page', pageId: page.id })).length).toBeGreaterThan(2)
+ const [only, ...rest] = await exported(graph, { scope: 'node', nodeId: rect.id })
+ expect([only?.geometry.width, rest.length]).toEqual([40, 0])
+ const selected = await exported(graph, { scope: 'selection', nodeIds: [rect.id, group.id] })
+ expect(selected.filter((cell) => cell.parent === '1')).toHaveLength(2)
+ await expect(exported(graph, { scope: 'selection', nodeIds: [] })).rejects.toThrow(
+ 'Nothing to export'
+ )
+ })
+
+ test('layers selected inside a group keep their place on the page', async () => {
+ const { graph, shape, connector } = grouped()
+ const cells = await exported(graph, { scope: 'selection', nodeIds: [shape.id, connector.id] })
+ const [vertex, edge] = cells
+ expect(vertex?.geometry).toMatchObject({ x: 110, y: 120, width: 60, height: 40 })
+ expect(edge?.geometry.targetPoint).toEqual({ x: 280, y: 140 })
+ })
+
+ test('a layer chosen with a group it is in is written once, inside the group', async () => {
+ const { graph, group, shape } = grouped()
+ const cells = await exported(graph, { scope: 'selection', nodeIds: [group.id, shape.id] })
+ const ids = cells.map((cell) => cell.id)
+ expect(new Set(ids).size).toBe(ids.length)
+ const groupCell = expectDefined(cells.find((cell) => cell.style.names.includes('group')))
+ expect(cells.filter((cell) => cell.parent === '1')).toEqual([groupCell])
+ })
+
+ test('an edge whose layer is left out keeps that end as a point where its line ran', async () => {
+ const { graph, connector } = grouped()
+ const [edge] = await exported(graph, { scope: 'selection', nodeIds: [connector.id] })
+ expect(edge?.source).toBeNull()
+ // Off the shape's right side, 10 + 60 across and 20 + 40 / 2 down in the group at 100, 100,
+ // by the gap a joined end leaves.
+ expect(edge?.geometry.sourcePoint).toEqual({ x: 176, y: 140 })
+ })
+})
diff --git a/packages/core/tests/io/formats/drawio/order-flow.drawio b/packages/core/tests/io/formats/drawio/order-flow.drawio
new file mode 100644
index 000000000..a22601f2b
--- /dev/null
+++ b/packages/core/tests/io/formats/drawio/order-flow.drawio
@@ -0,0 +1,14 @@
+<mxfile host="app.diagrams.net"><diagram id="flow" name="Order flow"><mxGraphModel dx="1000" dy="600" grid="1"><root>
+<mxCell id="0"/><mxCell id="1" parent="0"/>
+<mxCell id="start" value="Order placed" style="ellipse;whiteSpace=wrap;html=1;fillColor=#d5e8d4;strokeColor=#82b366;" vertex="1" parent="1"><mxGeometry x="40" y="40" width="140" height="70" as="geometry"/></mxCell>
+<mxCell id="check" value="In stock?" style="rhombus;whiteSpace=wrap;html=1;fillColor=#fff2cc;strokeColor=#d6b656;" vertex="1" parent="1"><mxGeometry x="260" y="25" width="120" height="100" as="geometry"/></mxCell>
+<mxCell id="ship" value="&lt;b&gt;Ship&lt;/b&gt; order" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;" vertex="1" parent="1"><mxGeometry x="460" y="45" width="140" height="60" as="geometry"/></mxCell>
+<mxCell id="db" value="Inventory" style="shape=cylinder3;whiteSpace=wrap;html=1;fillColor=#e1d5e7;strokeColor=#9673a6;" vertex="1" parent="1"><mxGeometry x="280" y="220" width="80" height="100" as="geometry"/></mxCell>
+<mxCell id="back" value="Back-order" style="shape=document;whiteSpace=wrap;html=1;fillColor=#f8cecc;strokeColor=#b85450;" vertex="1" parent="1"><mxGeometry x="460" y="220" width="140" height="80" as="geometry"/></mxCell>
+<mxCell id="note" value="Checked nightly" style="text;html=1;align=left;fontStyle=2;fontColor=#666666;" vertex="1" parent="1"><mxGeometry x="40" y="250" width="160" height="30" as="geometry"/></mxCell>
+<mxCell id="e1" style="edgeStyle=orthogonalEdgeStyle;html=1;" edge="1" parent="1" source="start" target="check"><mxGeometry relative="1" as="geometry"/></mxCell>
+<mxCell id="e2" value="yes" style="edgeStyle=orthogonalEdgeStyle;html=1;" edge="1" parent="1" source="check" target="ship"><mxGeometry relative="1" as="geometry"/></mxCell>
+<mxCell id="e3" value="no" style="edgeStyle=orthogonalEdgeStyle;html=1;" edge="1" parent="1" source="check" target="back"><mxGeometry relative="1" as="geometry"><Array as="points"><mxPoint x="420" y="160"/><mxPoint x="530" y="160"/></Array></mxGeometry></mxCell>
+<mxCell id="e4" style="endArrow=none;dashed=1;html=1;" edge="1" parent="1" source="check" target="db"><mxGeometry relative="1" as="geometry"/></mxCell>
+<mxCell id="e5" style="curved=1;endArrow=open;html=1;strokeColor=#b85450;" edge="1" parent="1" source="back" target="ship"><mxGeometry relative="1" as="geometry"><Array as="points"><mxPoint x="680" y="170"/></Array></mxGeometry></mxCell>
+</root></mxGraphModel></diagram></mxfile>
diff --git a/packages/drawio/src/embedded.ts b/packages/drawio/src/embedded.ts
index 79da1e266..afbc5e6e1 100644
--- a/packages/drawio/src/embedded.ts
+++ b/packages/drawio/src/embedded.ts
@@ -86,7 +86,7 @@ export function drawioRoot(bytes: Uint8Array, budget: InflateBudget): Element |
}
/** Whether a file name is draw.io's for an editable export, such as `flow.drawio.png`. */
-export function isDrawioExportFileName(fileName: string): boolean {
+export function isDrawIOExportFileName(fileName: string): boolean {
const name = fileName.toLowerCase()
return name.endsWith('.drawio.png') || name.endsWith('.drawio.svg')
}
diff --git a/packages/drawio/src/index.ts b/packages/drawio/src/index.ts
index 9d95de536..41408717a 100644
--- a/packages/drawio/src/index.ts
+++ b/packages/drawio/src/index.ts
@@ -1,30 +1,30 @@
import { drawioRoot } from './embedded'
import { inflateBudget } from './inflate'
-import type { DrawioFile } from './model'
-import { readDrawioRoot } from './read'
+import type { DrawIOFile } from './model'
+import { readDrawIORoot } from './read'
-export { isDrawioExportFileName } from './embedded'
+export { isDrawIOExportFileName } from './embedded'
export { MAX_INFLATED_BYTES } from './inflate'
export type {
- DrawioCell,
- DrawioFile,
- DrawioGeometry,
- DrawioLayer,
- DrawioPage,
- DrawioPoint,
- DrawioStyle
+ DrawIOCell,
+ DrawIOFile,
+ DrawIOGeometry,
+ DrawIOLayer,
+ DrawIOPage,
+ DrawIOPoint,
+ DrawIOStyle
} from './model'
-export { parseDrawioFile } from './read'
+export { parseDrawIOFile } from './read'
export { formatStyle, parseStyle, styleFlag, styleNumber } from './style'
-export { writeDrawioFile } from './write'
+export { writeDrawIOFile } from './write'
/**
* The draw.io file in `bytes`: a `.drawio` or `.dio` file, or the diagram a draw.io PNG or SVG
* export embeds. Null when the bytes hold no draw.io diagram. Everything the file unpacks, its
* compressed pages and image chunks together, shares one size limit.
*/
-export function readDrawioBytes(bytes: Uint8Array): DrawioFile | null {
+export function readDrawIOBytes(bytes: Uint8Array): DrawIOFile | null {
const budget = inflateBudget()
const root = drawioRoot(bytes, budget)
- return root ? readDrawioRoot(root, budget) : null
+ return root ? readDrawIORoot(root, budget) : null
}
diff --git a/packages/drawio/src/model.ts b/packages/drawio/src/model.ts
index 6738c8a3e..ec1800004 100644
--- a/packages/drawio/src/model.ts
+++ b/packages/drawio/src/model.ts
@@ -1,5 +1,5 @@
/** A point or offset, in the coordinates of the cell's parent. */
-export interface DrawioPoint {
+export interface DrawIOPoint {
x: number
y: number
}
@@ -10,37 +10,37 @@ export interface DrawioPoint {
* whose parent is an edge, as draw.io stores an edge label it moved, sits `x` of the way along the
* edge, from -1 at its source to 1 at its target, `y` across it, and `offset` from there.
*/
-export interface DrawioGeometry {
+export interface DrawIOGeometry {
x: number
y: number
width: number
height: number
relative: boolean
- points: DrawioPoint[]
- sourcePoint: DrawioPoint | null
- targetPoint: DrawioPoint | null
- offset: DrawioPoint | null
+ points: DrawIOPoint[]
+ sourcePoint: DrawIOPoint | null
+ targetPoint: DrawIOPoint | null
+ offset: DrawIOPoint | null
}
/**
* A `style` string: the names of stylesheet styles it starts from, such as `ellipse` or `text`,
* and its `key=value` pairs, both in the order written.
*/
-export interface DrawioStyle {
+export interface DrawIOStyle {
names: string[]
values: Partial<Record<string, string>>
}
/** A shape or a connecting edge, in the order draw.io draws them. */
-export interface DrawioCell {
+export interface DrawIOCell {
id: string
/** The cell or layer it belongs to. */
parent: string
kind: 'vertex' | 'edge'
/** The label: HTML when the style says `html=1`, plain text otherwise. */
value: string
- style: DrawioStyle
- geometry: DrawioGeometry
+ style: DrawIOStyle
+ geometry: DrawIOGeometry
visible: boolean
source: string | null
target: string | null
@@ -52,26 +52,26 @@ export interface DrawioCell {
}
/** One of a page's layers, bottom first: the cells whose parent it is draw on it. */
-export interface DrawioLayer {
+export interface DrawIOLayer {
id: string
name: string
visible: boolean
locked: boolean
}
-export interface DrawioPage {
+export interface DrawIOPage {
id: string
name: string
/** The model's own attributes, such as `grid` and `background`. */
attributes: Record<string, string>
/** The id of the cell at the root of the model, which the layers belong to. */
rootId: string
- layers: DrawioLayer[]
- cells: DrawioCell[]
+ layers: DrawIOLayer[]
+ cells: DrawIOCell[]
}
/** A draw.io file: its pages, and the names of those that could not be read. */
-export interface DrawioFile {
- pages: DrawioPage[]
+export interface DrawIOFile {
+ pages: DrawIOPage[]
unreadable: string[]
}
diff --git a/packages/drawio/src/read.ts b/packages/drawio/src/read.ts
index 45b932a16..af27286da 100644
--- a/packages/drawio/src/read.ts
+++ b/packages/drawio/src/read.ts
@@ -3,12 +3,12 @@ import { isValid, toUint8Array } from 'js-base64'
import { boundedInflate, inflateBudget, percentDecoded, type InflateBudget } from './inflate'
import type {
- DrawioCell,
- DrawioFile,
- DrawioGeometry,
- DrawioLayer,
- DrawioPage,
- DrawioPoint
+ DrawIOCell,
+ DrawIOFile,
+ DrawIOGeometry,
+ DrawIOLayer,
+ DrawIOPage,
+ DrawIOPoint
} from './model'
import { parseStyle, styleFlag } from './style'
import { attributesOf, childElements, parseXML } from './xml'
@@ -21,11 +21,11 @@ function number(element: Element, name: string, fallback = 0): number {
return Number.isFinite(value) ? value : fallback
}
-function pointOf(element: Element): DrawioPoint {
+function pointOf(element: Element): DrawIOPoint {
return { x: number(element, 'x'), y: number(element, 'y') }
}
-const NO_GEOMETRY: DrawioGeometry = {
+const NO_GEOMETRY: DrawIOGeometry = {
x: 0,
y: 0,
width: 0,
@@ -37,7 +37,7 @@ const NO_GEOMETRY: DrawioGeometry = {
offset: null
}
-function readGeometry(cell: Element): DrawioGeometry {
+function readGeometry(cell: Element): DrawIOGeometry {
const geometry = childElements(cell, 'mxGeometry').at(0)
if (!geometry) return structuredClone(NO_GEOMETRY)
const points = childElements(geometry, 'Array').find((e) => e.getAttribute('as') === 'points')
@@ -71,7 +71,7 @@ function cellElements(element: Element): CellElements | null {
return cell ? { cell, wrapper: element } : null
}
-function readCell({ cell, wrapper }: CellElements, id: string, parent: string): DrawioCell {
+function readCell({ cell, wrapper }: CellElements, id: string, parent: string): DrawIOCell {
const isEdge = cell.getAttribute('edge') === '1'
return {
id,
@@ -91,7 +91,7 @@ function readCell({ cell, wrapper }: CellElements, id: string, parent: string):
* A model's cells. Its root is the one cell without a parent, and its layers are the cells under
* the root that are neither shapes nor edges; draw.io names them `0` and `1` by default.
*/
-function readModel(model: Element, page: Pick<DrawioPage, 'id' | 'name'>): DrawioPage | null {
+function readModel(model: Element, page: Pick<DrawIOPage, 'id' | 'name'>): DrawIOPage | null {
const root = childElements(model, 'root').at(0)
if (!root) return null
const read: { elements: CellElements; id: string; parent: string | null }[] = []
@@ -102,8 +102,8 @@ function readModel(model: Element, page: Pick<DrawioPage, 'id' | 'name'>): Drawi
}
const rootId = read.find((entry) => !entry.parent)?.id
if (rootId === undefined) return null
- const layers: DrawioLayer[] = []
- const cells: DrawioCell[] = []
+ const layers: DrawIOLayer[] = []
+ const cells: DrawIOCell[] = []
for (const { elements, id, parent } of read) {
if (!parent) continue
const { cell } = elements
@@ -143,7 +143,7 @@ function readDiagram(
diagram: Element,
index: number,
budget: InflateBudget
-): DrawioPage | { unreadable: string } {
+): DrawIOPage | { unreadable: string } {
const name = diagram.getAttribute('name') || `Page ${index + 1}`
const page = { id: diagram.getAttribute('id') ?? `page-${index + 1}`, name }
let model = childElements(diagram, 'mxGraphModel').at(0) ?? null
@@ -160,19 +160,19 @@ function readDiagram(
* pages it could not read: damaged, or past what the file may unpack to. Null when the source
* is not a draw.io file.
*/
-export function parseDrawioFile(source: string, budget = inflateBudget()): DrawioFile | null {
+export function parseDrawIOFile(source: string, budget = inflateBudget()): DrawIOFile | null {
const root = parseXML(source)
- return root ? readDrawioRoot(root, budget) : null
+ return root ? readDrawIORoot(root, budget) : null
}
-/** The pages of a draw.io document from its parsed root, as `parseDrawioFile` reads them. */
-export function readDrawioRoot(root: Element, budget: InflateBudget): DrawioFile | null {
+/** The pages of a draw.io document from its parsed root, as `parseDrawIOFile` reads them. */
+export function readDrawIORoot(root: Element, budget: InflateBudget): DrawIOFile | null {
if (root.localName === 'mxGraphModel') {
const page = readModel(root, { id: 'page-1', name: 'Page 1' })
return page ? { pages: [page], unreadable: [] } : null
}
if (root.localName !== 'mxfile') return null
- const file: DrawioFile = { pages: [], unreadable: [] }
+ const file: DrawIOFile = { pages: [], unreadable: [] }
for (const [index, diagram] of childElements(root, 'diagram').entries()) {
const read = readDiagram(diagram, index, budget)
if ('unreadable' in read) file.unreadable.push(read.unreadable)
diff --git a/packages/drawio/src/style.ts b/packages/drawio/src/style.ts
index 6cb04bee7..7aeaa93e0 100644
--- a/packages/drawio/src/style.ts
+++ b/packages/drawio/src/style.ts
@@ -1,8 +1,8 @@
-import type { DrawioStyle } from './model'
+import type { DrawIOStyle } from './model'
/** A `style` string as its style names and its pairs. */
-export function parseStyle(style: string): DrawioStyle {
- const result: DrawioStyle = { names: [], values: {} }
+export function parseStyle(style: string): DrawIOStyle {
+ const result: DrawIOStyle = { names: [], values: {} }
for (const part of style.split(';')) {
const text = part.trim()
if (!text) continue
@@ -14,7 +14,7 @@ export function parseStyle(style: string): DrawioStyle {
}
/** A style as draw.io writes it: its names, then `key=value;` pairs, in order. */
-export function formatStyle({ names, values }: DrawioStyle): string {
+export function formatStyle({ names, values }: DrawIOStyle): string {
const pairs = Object.entries(values).flatMap(([key, value]) =>
value === undefined ? [] : [`${key}=${value}`]
)
@@ -22,12 +22,12 @@ export function formatStyle({ names, values }: DrawioStyle): string {
}
/** A number the style sets for `key`, or `fallback`. */
-export function styleNumber(style: DrawioStyle, key: string, fallback: number): number {
+export function styleNumber(style: DrawIOStyle, key: string, fallback: number): number {
const value = Number.parseFloat(style.values[key] ?? '')
return Number.isFinite(value) ? value : fallback
}
/** Whether the style turns `key` on, as `key=1` does. */
-export function styleFlag(style: DrawioStyle, key: string): boolean {
+export function styleFlag(style: DrawIOStyle, key: string): boolean {
return style.values[key] === '1'
}
diff --git a/packages/drawio/src/write.ts b/packages/drawio/src/write.ts
index ac27bb51b..f63902471 100644
--- a/packages/drawio/src/write.ts
+++ b/packages/drawio/src/write.ts
@@ -1,6 +1,6 @@
import { DOMImplementation, XMLSerializer, type Document, type Element } from '@xmldom/xmldom'
-import type { DrawioCell, DrawioFile, DrawioGeometry, DrawioPage, DrawioPoint } from './model'
+import type { DrawIOCell, DrawIOFile, DrawIOGeometry, DrawIOPage, DrawIOPoint } from './model'
import { formatStyle } from './style'
/** What the writer puts on `<mxfile>`, so draw.io knows who wrote it. */
@@ -10,7 +10,7 @@ function setNumber(element: Element, name: string, value: number) {
if (value !== 0) element.setAttribute(name, String(value))
}
-function point(document: Document, at: DrawioPoint, as?: string): Element {
+function point(document: Document, at: DrawIOPoint, as?: string): Element {
const element = document.createElement('mxPoint')
element.setAttribute('x', String(at.x))
element.setAttribute('y', String(at.y))
@@ -18,7 +18,7 @@ function point(document: Document, at: DrawioPoint, as?: string): Element {
return element
}
-function geometry(document: Document, value: DrawioGeometry): Element {
+function geometry(document: Document, value: DrawIOGeometry): Element {
const element = document.createElement('mxGeometry')
setNumber(element, 'x', value.x)
setNumber(element, 'y', value.y)
@@ -39,7 +39,7 @@ function geometry(document: Document, value: DrawioGeometry): Element {
}
/** A cell as draw.io writes it, wrapped in a `UserObject` when it carries attributes. */
-function cellElement(document: Document, cell: DrawioCell): Element {
+function cellElement(document: Document, cell: DrawIOCell): Element {
const element = document.createElement('mxCell')
const wrapped = Object.keys(cell.attributes).length > 0
if (!wrapped) {
@@ -63,7 +63,7 @@ function cellElement(document: Document, cell: DrawioCell): Element {
return wrapper
}
-function pageElement(document: Document, page: DrawioPage): Element {
+function pageElement(document: Document, page: DrawIOPage): Element {
const diagram = document.createElement('diagram')
diagram.setAttribute('id', page.id)
diagram.setAttribute('name', page.name)
@@ -93,7 +93,7 @@ function pageElement(document: Document, page: DrawioPage): Element {
* as draw.io itself saves by default, so the file diffs and reads as text. A file with pages that
* could not be read is refused, since writing it would drop them.
*/
-export function writeDrawioFile(file: DrawioFile): string {
+export function writeDrawIOFile(file: DrawIOFile): string {
if (file.unreadable.length > 0) {
throw new Error(`Could not write the draw.io pages ${file.unreadable.join(', ')}`)
}
diff --git a/packages/drawio/tests/read.test.ts b/packages/drawio/tests/read.test.ts
index ebc1aa9cf..adbc9fe15 100644
--- a/packages/drawio/tests/read.test.ts
+++ b/packages/drawio/tests/read.test.ts
@@ -3,7 +3,7 @@ import { describe, expect, test } from 'bun:test'
import { deflateSync } from 'fflate'
import { fromUint8Array } from 'js-base64'
-import { MAX_INFLATED_BYTES, parseDrawioFile, readDrawioBytes } from '@open-pencil/drawio'
+import { MAX_INFLATED_BYTES, parseDrawIOFile, readDrawIOBytes } from '@open-pencil/drawio'
/**
* A page as draw.io saves it: the root and default layer, a second hidden layer, a plain shape,
@@ -48,7 +48,7 @@ function compressed(model: string): string {
describe('reading a draw.io file', () => {
test('keeps each page’s layers, cells in drawing order, styles, and geometry', () => {
- const file = parseDrawioFile(`<mxfile host="drawio">${page('First')}</mxfile>`)
+ const file = parseDrawIOFile(`<mxfile host="drawio">${page('First')}</mxfile>`)
const [first] = file?.pages ?? []
expect(first).toMatchObject({
name: 'First',
@@ -86,15 +86,15 @@ describe('reading a draw.io file', () => {
})
test('reads a bare model and compressed pages', () => {
- expect(parseDrawioFile(MODEL)?.pages[0]?.cells).toHaveLength(5)
- const file = parseDrawioFile(
+ expect(parseDrawIOFile(MODEL)?.pages[0]?.cells).toHaveLength(5)
+ const file = parseDrawIOFile(
`<mxfile><diagram id="z" name="Packed">${compressed(MODEL)}</diagram></mxfile>`
)
expect(file?.pages[0]?.cells.map((cell) => cell.id)).toEqual(['a', 'b', 'e', 'l', 'hidden'])
})
test('names pages it cannot read, and reads the rest', () => {
- const file = parseDrawioFile(
+ const file = parseDrawIOFile(
`<mxfile>${page('Good')}<diagram id="bad" name="Broken">not base64 %%%</diagram></mxfile>`
)
expect(file?.pages.map((p) => p.name)).toEqual(['Good'])
@@ -102,8 +102,8 @@ describe('reading a draw.io file', () => {
})
test('is not fooled by other XML', () => {
- expect(parseDrawioFile('<svg xmlns="http://www.w3.org/2000/svg"/>')).toBeNull()
- expect(parseDrawioFile('not xml')).toBeNull()
+ expect(parseDrawIOFile('<svg xmlns="http://www.w3.org/2000/svg"/>')).toBeNull()
+ expect(parseDrawIOFile('not xml')).toBeNull()
})
test('stops unpacking once the whole file passes its limit, however many pages share it', () => {
@@ -116,7 +116,7 @@ describe('reading a draw.io file', () => {
{ length: 6 },
(_, i) => `<diagram id="p${i}" name="P${i}">${packed}</diagram>`
)
- const file = parseDrawioFile(`<mxfile>${pages.join('')}</mxfile>`)
+ const file = parseDrawIOFile(`<mxfile>${pages.join('')}</mxfile>`)
expect(file?.pages.length).toBeLessThan(6)
expect(file?.unreadable.length).toBeGreaterThan(0)
})
@@ -163,9 +163,9 @@ const EMBEDDED = encodeURIComponent(`<mxfile>${page('Embedded')}</mxfile>`)
describe('reading the diagram a draw.io export embeds', () => {
test('from a PNG’s text chunk', () => {
- const file = readDrawioBytes(pngWithText('mxfile', `<mxfile>${page('Embedded')}</mxfile>`))
+ const file = readDrawIOBytes(pngWithText('mxfile', `<mxfile>${page('Embedded')}</mxfile>`))
expect(file?.pages[0]?.name).toBe('Embedded')
- expect(readDrawioBytes(pngWithText('Software', 'paint.net'))).toBeNull()
+ expect(readDrawIOBytes(pngWithText('Software', 'paint.net'))).toBeNull()
})
test('from an SVG’s content attribute', () => {
@@ -174,33 +174,33 @@ describe('reading the diagram a draw.io export embeds', () => {
.replaceAll('"', '&quot;')
.replaceAll('<', '&lt;')
const svg = `<?xml version="1.0"?><svg xmlns="http://www.w3.org/2000/svg" content="${content}"><rect/></svg>`
- expect(readDrawioBytes(new TextEncoder().encode(svg))?.pages[0]?.name).toBe('Vector')
+ expect(readDrawIOBytes(new TextEncoder().encode(svg))?.pages[0]?.name).toBe('Vector')
expect(
- readDrawioBytes(new TextEncoder().encode('<svg xmlns="http://www.w3.org/2000/svg"/>'))
+ readDrawIOBytes(new TextEncoder().encode('<svg xmlns="http://www.w3.org/2000/svg"/>'))
).toBeNull()
})
test('from a PNG’s compressed and international text chunks', () => {
const zTXt = png(chunk('zTXt', concat([latin1('mxfile\0\0'), zlib(EMBEDDED)])))
- expect(readDrawioBytes(zTXt)?.pages[0]?.name).toBe('Embedded')
+ expect(readDrawIOBytes(zTXt)?.pages[0]?.name).toBe('Embedded')
// iTXt: keyword, compression flag and method, then empty language and translated keyword.
const packed = png(chunk('iTXt', concat([latin1('mxfile\0\x01\0\0\0'), zlib(EMBEDDED)])))
- expect(readDrawioBytes(packed)?.pages[0]?.name).toBe('Embedded')
+ expect(readDrawIOBytes(packed)?.pages[0]?.name).toBe('Embedded')
const plain = png(chunk('iTXt', latin1(`mxfile\0\0\0\0\0${EMBEDDED}`)))
- expect(readDrawioBytes(plain)?.pages[0]?.name).toBe('Embedded')
+ expect(readDrawIOBytes(plain)?.pages[0]?.name).toBe('Embedded')
})
test('says a damaged or cut short PNG cannot be read, rather than that it holds no diagram', () => {
const damaged = png(chunk('zTXt', latin1('mxfile\0\0not zlib')))
- expect(() => readDrawioBytes(damaged)).toThrow(
+ expect(() => readDrawIOBytes(damaged)).toThrow(
'Could not read the draw.io diagram in this image'
)
const whole = pngWithText('mxfile', `<mxfile>${page('Embedded')}</mxfile>`)
- expect(() => readDrawioBytes(whole.subarray(0, 40))).toThrow('cut short')
+ expect(() => readDrawIOBytes(whole.subarray(0, 40))).toThrow('cut short')
})
test('takes an SVG’s comments before its root in stride', () => {
const svg = `${'<!---->'.repeat(10_000)}x`
- expect(readDrawioBytes(new TextEncoder().encode(svg))).toBeNull()
+ expect(readDrawIOBytes(new TextEncoder().encode(svg))).toBeNull()
})
})
diff --git a/packages/drawio/tests/write.test.ts b/packages/drawio/tests/write.test.ts
index 2bf44e274..d98c9db0c 100644
--- a/packages/drawio/tests/write.test.ts
+++ b/packages/drawio/tests/write.test.ts
@@ -1,6 +1,6 @@
import { expect, test } from 'bun:test'
-import { parseDrawioFile, writeDrawioFile } from '@open-pencil/drawio'
+import { parseDrawIOFile, writeDrawIOFile } from '@open-pencil/drawio'
const MODEL = `<mxGraphModel grid="1"><root>
<mxCell id="0"/><mxCell id="1" parent="0"/>
@@ -27,19 +27,19 @@ const MODEL = `<mxGraphModel grid="1"><root>
</root></mxGraphModel>`
test('a written file reads back as the file it was written from', () => {
- const file = parseDrawioFile(`<mxfile><diagram id="p" name="Page">${MODEL}</diagram></mxfile>`)
+ const file = parseDrawIOFile(`<mxfile><diagram id="p" name="Page">${MODEL}</diagram></mxfile>`)
if (!file) throw new Error('Fixture did not read')
- const written = writeDrawioFile(file)
+ const written = writeDrawIOFile(file)
expect(written).toStartWith('<mxfile host="OpenPencil">')
// Saved uncompressed, as draw.io saves by default.
expect(written).toContain('<mxGraphModel grid="1"><root><mxCell id="0"/>')
- expect(parseDrawioFile(written)).toEqual(file)
+ expect(parseDrawIOFile(written)).toEqual(file)
})
test('a file with pages it could not read is not written, since they would be lost', () => {
- const file = parseDrawioFile(
+ const file = parseDrawIOFile(
`<mxfile><diagram id="p" name="Page">${MODEL}</diagram><diagram id="q" name="Broken">!</diagram></mxfile>`
)
if (!file) throw new Error('Fixture did not read')
- expect(() => writeDrawioFile(file)).toThrow('Could not write the draw.io pages Broken')
+ expect(() => writeDrawIOFile(file)).toThrow('Could not write the draw.io pages Broken')
})
diff --git a/tools/checks/package-quality/src/smoke/scenarios.ts b/tools/checks/package-quality/src/smoke/scenarios.ts
index ac8a44567..9299365ae 100644
--- a/tools/checks/package-quality/src/smoke/scenarios.ts
+++ b/tools/checks/package-quality/src/smoke/scenarios.ts
@@ -34,7 +34,7 @@ export const runtimeScenarios: RuntimeScenario[] = [
},
{
name: 'draw.io codec',
- code: 'const { parseDrawioFile, writeDrawioFile } = await import(\'@open-pencil/drawio\'); const file = parseDrawioFile(\'<mxGraphModel><root><mxCell id="0"/><mxCell id="1" parent="0"/><mxCell id="a" vertex="1" parent="1"/></root></mxGraphModel>\'); if (file?.pages[0]?.cells.length !== 1 || !writeDrawioFile(file).startsWith(\'<mxfile\')) throw new Error(\'draw.io package smoke failed\')'
+ code: 'const { parseDrawIOFile, writeDrawIOFile } = await import(\'@open-pencil/drawio\'); const file = parseDrawIOFile(\'<mxGraphModel><root><mxCell id="0"/><mxCell id="1" parent="0"/><mxCell id="a" vertex="1" parent="1"/></root></mxGraphModel>\'); if (file?.pages[0]?.cells.length !== 1 || !writeDrawIOFile(file).startsWith(\'<mxfile\')) throw new Error(\'draw.io package smoke failed\')'
},
{
name: 'Emit package',
diff --git a/tools/checks/package-quality/src/smoke/type-consumer.ts b/tools/checks/package-quality/src/smoke/type-consumer.ts
index 584b27828..c9c4bbebd 100644
--- a/tools/checks/package-quality/src/smoke/type-consumer.ts
+++ b/tools/checks/package-quality/src/smoke/type-consumer.ts
@@ -6,7 +6,7 @@ import { runCommand } from '@open-pencil/package-artifacts-tools'
const TYPE_CONSUMER = `import { createEditor, type Editor } from '@open-pencil/core'
import { Frame, type TreeNode } from '@open-pencil/design-jsx'
import { htmlToDesignDocument, type DesignDocument } from '@open-pencil/dom-css'
-import { parseDrawioFile, type DrawioFile } from '@open-pencil/drawio'
+import { parseDrawIOFile, type DrawIOFile } from '@open-pencil/drawio'
import { FIG_PACKAGE_STATUS, type FigContainerDocument } from '@open-pencil/fig'
import { FIG_KIWI_DEFAULT_VERSION, buildFigKiwi } from '@open-pencil/kiwi/fig/container'
import type { GUID as KiwiGUID } from '@open-pencil/kiwi/fig'
@@ -26,7 +26,7 @@ const maybeNode: SceneNode | undefined = graph.getPages()[0]
const penDocument: PenDocument = { version: '1', children: [] }
const figDocument: FigContainerDocument = { schemaDeflated: new Uint8Array([1]), dataRaw: new Uint8Array([2]) }
const kiwiGuid: KiwiGUID = { sessionID: 1, localID: 2 }
-const drawioFile: DrawioFile | null = parseDrawioFile('<mxfile/>')
+const drawioFile: DrawIOFile | null = parseDrawIOFile('<mxfile/>')
void editorFactory; void editor; void designDocument; void color; void vector; void maybeNode
void penDocument; void figDocument; void kiwiGuid; void FIG_PACKAGE_STATUS
void FIG_KIWI_DEFAULT_VERSION; void buildFigKiwi; void parsePenFile; void htmlToDesignDocument