Canvas
Module CanvasEngine (Packages/NavigatorKit/Sources/CanvasEngine): the editing model, geometry, attachments and
exports of a canvas. It imports NavigatorCore, Persistence, Foundation and CryptoKit only — no UI framework. The
SwiftUI/AppKit/UIKit canvas view (not part of this module) renders what the editor describes and forwards gestures.
Pieces
| Type | Role |
|---|---|
CanvasEditor (struct) |
All editing operations over one CanvasDocument, selection, viewport, hit-testing, undo/redo |
CanvasRect, CanvasHandle, CanvasEdge |
Geometry |
CanvasRouter, CanvasRoute |
Connection curves |
CanvasSpatialIndex |
Uniform-grid culling index |
CanvasAttachmentStore (actor) |
Image/PDF files on disk |
CanvasAutosaver (actor) |
Debounced saving through database.canvases |
CanvasExport |
JSON, Markdown outline, render plan for PNG/PDF |
Editing model
CanvasEditor is a value type; the UI owns one per open canvas (@State/@Observable wrapper) and reads
document, selection, revision.
- Cards:
addCard,removeCards/removeSelection,duplicate,setContent,setTint,setTitle. - Move:
move(_:by:snap:)for one-shot moves (arrow keys);beginDrag+updateDrag(session, translation:)for gestures. The translation is the total since the gesture began. With snapping the group's top-left corner lands on the grid and every card gets the same translation: a group never deforms. - Resize:
resize(_:handle:translation:from:coalescingKey:)(eight handles). The dragged edges snap, the opposite edges stay put, the size stays withinminimumCardSize … maximumCardSize(120×80 … 4000×4000 by default). - Z-order:
bringToFront,sendToBack,bringForward,sendBackward. OnlyzIndexchanges; the order ofdocument.cardsis never used for stacking except to break ties. - Alignment / distribution:
align(six modes, ≥ 2 cards, relative to the group's bounding box),distribute(horizontal/vertical, ≥ 3 cards, equal gaps, outer cards fixed). - Connections:
connect(from:to:label:)throws for a self-link, an unknown card or a duplicate. A connection is directed and identified by its(from, to)pair (A→B and B→A may both exist). Removing a card removes its connections in the same undo step. Labels are trimmed and capped at 200 characters. - Selection:
select(_:mode:),select(in:rule:mode:)(marquee, intersect or contain),selectAll,clearSelection. - Viewport:
pan(byView:),zoom(to:around:viewSize:),zoom(by:…),zoomToFit(viewSize:padding:ids:),visibleRect(viewSize:),canvasPoint(fromView:),viewPoint(fromCanvas:). View transform:view = (canvas − center) × scale + viewSize / 2. Zoom keeps the canvas point under the anchor fixed:center′ = p − (anchor − viewSize/2) / scale′withpthe canvas point under the anchor before the zoom. Scale is clamped to 0.1 … 4; zoom-to-fit never magnifies beyond 1:1. - Hit-testing:
hitTest(_:)returns.handle(selected cards only),.card(front-most),.connectionor.empty. Handle size (14 pt) and connection tolerance (6 pt) are screen distances, divided by the scale. - Limits: 20 000 cards, 50 000 connections, coordinates within ±1 000 000 (clamped), finite numbers only.
Undo and redo
Every change of cards, connections or title goes through one commit path that records an invertible delta (removed
cards with their array index, inserted cards with theirs, before/after of modified cards, before/after connection
list, before/after title). Undo restores the document exactly, including the order of cards. Undo also restores
the selection that was active. The stack is bounded (undoLimit, 200 by default); a new edit clears redo. Edits
that change nothing record nothing. Updates sharing a coalescingKey (a drag session, a resize gesture, typing the
title) merge into one step; breakUndoCoalescing() ends a run.
Not undoable, by design: viewport and selection changes (view state). updatedAt is not touched by the editor;
CanvasAutosaver stamps it when saving.
validate() lists broken invariants (duplicate ids, non-finite geometry, size out of bounds, dangling/self/duplicate
connections, invalid viewport, unsafe attachment path). The test suite applies 8 × 400 random operations and checks
after each one that the document is valid, then that undoing step by step returns every intermediate document and
finally the initial one.
Connection routing
CanvasRouter.route picks the edges from the dominant axis between the card centres (right→left, left→right,
bottom→top, top→bottom), anchors the curve at the edge midpoints and extends the two control points along the edge
normals by half the gap, clamped to 40 … 300. The renderer strokes the cubic Bézier start, control1, control2, end;
labelPoint is the curve's midpoint; polyline(segments:) flattens it. Routing does not avoid other cards.
Culling
visibleCards(in:): linear scan, back to front.CanvasSpatialIndex: uniform grid (512-unit cells) built once perrevision; cards covering more than 64 cells go to a short list scanned linearly.visibleCards(in:index:)gives the same result as the scan (tested on random documents).
Measured on the development Mac (Apple Silicon, macOS 27), 5 000 random cards over a 40 000 × 40 000 area, viewport
1920 × 1080, swift test:
| Operation | Debug build | Release build |
|---|---|---|
| Linear scan | ≈ 1.1 ms | ≈ 0.12 ms |
| Grid index query | ≈ 10 µs | ≈ 1 µs |
| Grid index build | ≈ 9.6 ms | ≈ 0.8 ms |
| One undoable move of one card | ≈ 4.7 ms | ≈ 1.0 ms |
The linear scan is already far below a frame at 5 000 cards; the index matters when culling runs several times per frame. The cost of an edit is dominated by the copy-and-compare of the card array (O(n) per command).
Attachments
CanvasAttachmentStore(root:) stores files as <root>/<canvas id>/<sha256 hex>.<ext>.
- The type is decided by magic bytes (PNG, JPEG, GIF, WebP, HEIC/HEIF, TIFF, PDF). File names, extensions and MIME types are never consulted. Anything else (SVG, HTML, executables…) is refused.
- Limits: 25 MiB per image, 100 MiB per PDF, 1 GiB per canvas (configurable). A file's size is checked before it is read.
- A name is accepted only if it is 64 lowercase hex digits, a dot and a known extension: no separator, no
.., no escape can pass (isSafeRelativePath). Documents carrying any other path fail validation and JSON import. removeOrphans(of:)deletes stored files no card refers to — call it when a canvas is closed (undo could still bring a card back while it is open).removeAll(of:)when a canvas is deleted.
Only the first bytes are inspected: the store does not decode the image or the PDF. The renderer must use the system decoders (ImageIO, PDFKit) and tolerate files that fail to decode.
Saving and exporting
CanvasAutosaver.schedule(document)after each edit; the newest version is written after 800 ms of calm;flush()writes immediately. A failed save stays queued and is reported bylastError/ thrown byflush().CanvasExport.json→{"format":"orix.canvas","version":1,"exportedAt":…,"document":…}(ISO 8601 dates: sub-second precision is not kept).document(fromJSON:assigningNewIDs:)rejects foreign files, other versions and invalid documents as a whole. Attachment files are not embedded in the JSON.CanvasExport.markdownOutline→ title, one bullet per card in reading order, outgoing connections as sub-bullets.CanvasExport.renderPlan→ output size, cards back to front and connection curves in output coordinates. The module does not rasterise: the UI draws the plan into aCGContext/ImageRenderer.
Not verified / not done
- No UI exists in this module; gestures, rendering, accessibility of the canvas view and PNG/PDF rasterisation are the UI layer's work and are untested here.
- The benchmark numbers come from one machine; nothing was measured on an iPhone or iPad.
- Image and PDF content is not decoded or sanitised here.
- A canvas with a
spaceIDthat is not stored (ghost or deleted space) cannot be saved: the store refuses it.