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