hazo_canvas
v1.16.6
Published
Reusable headless-first Konva canvas-editor package.
Readme
hazo_canvas
A headless-first, plugin-extensible Konva canvas editor, generalized from kinstripe's composer to serve print-composition (kinstripe) and diagram-flow (FlowForge) consumers. Ships a full editor controller (useCanvasEditor), Konva <Canvas> renderer, layers panel with selection and cascade-delete, PDF export, images adapter, and multiple layout engines.
Installation
npm install hazo_canvasPeer dependencies:
npm install hazo_core react react-dom hazo_ui
# hazo_connect is an optional peer — add it when the persistence runtime ships (Phase 1)What ships
| What | Exported from |
|---|---|
| Zod schemas: CanvasDocumentSchema, PageSchema, ElementSchema, LabelSchema, RunSchema, LayerSchema, GroupSchema | hazo_canvas/client and hazo_canvas |
| Inferred TypeScript types: CanvasDocument, Page, Element, Label, Run, Layer, Group | same |
| migrateDocument(raw: unknown): CanvasDocument | same |
| HazoCanvasError + HAZO_CANVAS_CODES | same |
| <Canvas> Konva renderer + useCanvasEditor controller | hazo_canvas |
| <LayersPanel>, <PropertiesPanel>, <Toolbar>, <CanvasControls> UI panels | hazo_canvas |
| <ExportPdfDialog> — DPI selector + PDF download via hazo_canvas/pdf | hazo_canvas |
| hazo_canvas/pdf — toPDF() server-side PDF adapter | hazo_canvas/pdf |
| hazo_canvas/images-adapter — HazoImageProvider over hazo_files + hazo_images | hazo_canvas/images-adapter |
| hazo_canvas/layout-dagre — tree/DAG layout (requires dagre peer) | hazo_canvas/layout-dagre |
| hazo_canvas/layout-sankey — Sankey flow layout (requires d3-sankey peer) | hazo_canvas/layout-sankey |
| hazo_canvas/layout-network — force-directed graph layout (requires d3-force peer) | hazo_canvas/layout-network |
| hazo_canvas/layout-timeline — time-axis layout for timeline, roadmap, gantt, swimlane, business (requires d3-scale + d3-time peers) | hazo_canvas/layout-timeline |
| hazo_canvas/layout-core — createSeededRng, runTwiceIdentical, determinism primitives | hazo_canvas/client |
| hazo_canvas_documents DDL (Postgres + SQLite) | db_setup_postgres.sql / db_setup_sqlite.sql |
| Config sample | config/hazo_canvas_config.ini.sample |
Usage
Import the model and migration shim from the client-safe entry point:
import {
CanvasDocumentSchema,
migrateDocument,
type CanvasDocument,
} from 'hazo_canvas/client';
// Validate a raw document (e.g. parsed from a database TEXT/JSONB column):
const result = CanvasDocumentSchema.safeParse(raw);
if (!result.success) {
console.error(result.error.issues);
} else {
const doc: CanvasDocument = result.data;
}
// Or use the migration dispatcher (validates + handles future version bumps):
const doc: CanvasDocument = migrateDocument(raw);migrateDocument throws HazoCanvasError (HAZO_CANVAS_INVALID_DOCUMENT or HAZO_CANVAS_UNSUPPORTED_VERSION) on failure, so it is safe to call inside a try/catch or a Next.js route handler.
Data model
All coordinates and sizes are in px throughout the model. Unit conversion (e.g. mm for PDF export) happens only at export boundaries.
CanvasDocument
version: 1
id: string
title: string
pages: Page[] — at least one page required
createdAt: string — ISO 8601
updatedAt: string — ISO 8601
Page
id: string
kind: 'canvas' — discriminator for future page-type extensions
size: { width, height } — px
elements: Element[] — shapes and images
labels: Label[] — text blocks (kept separate for z-order flexibility)
layers: Layer[]
groups: Group[]
Element
id, type (open string), x, y, width, height — required
rotation?, zIndex?, opacity?, fill?, stroke?, strokeWidth?
points? — line/arrow control points (px)
imageFileId? — hazo_files reference for source image
blurredFileId? — hazo_files reference for blur-processed variant
blur?, crop? — px
hidden?, locked?, name?, layerId?, groupId?
...any plugin fields survive via .passthrough()
built-in type values: image | rect | ellipse | circle | line | arrow | star
Label
id, lines: Run[][] — array of paragraphs, each a Run array
font?, sizePct?, align?, x?, y?, rotation?
zIndex?, hidden?, name?, layerId?
Run (inline text span)
text, bold?, italic?, underline?, color?, font?, sizePct?
Layer
id, name, hidden?, locked?
Group
id, elementIds: string[]Database
Run the migration for your database dialect once during setup.
PostgreSQL (production / staging)
CREATE TABLE IF NOT EXISTS hazo_canvas_documents (
id UUID NOT NULL PRIMARY KEY DEFAULT gen_random_uuid(),
title TEXT NOT NULL DEFAULT '',
document JSONB NOT NULL DEFAULT '{}',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);Full file: db_setup_postgres.sql (package root)
SQLite (local dev / test-app)
CREATE TABLE IF NOT EXISTS hazo_canvas_documents (
id TEXT NOT NULL PRIMARY KEY,
title TEXT NOT NULL DEFAULT '',
document TEXT NOT NULL DEFAULT '{}', -- JSON-serialized CanvasDocument
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);Full file: db_setup_sqlite.sql (package root)
The document column stores the complete serialized CanvasDocument. Consumers manage reads/writes directly; CRUD helpers and autosave are Phase 3+.
Layout engines
All layout engines are server-only subpath exports. They take an explicit graph in and return geometry out — the consumer maps results onto CanvasDocument elements via state updates.
hazo_canvas/layout-dagre — tree/DAG layout
// npm install dagre (optional peer)
import { layoutTree } from 'hazo_canvas/layout-dagre';
const { positions } = layoutTree(
[{ id: 'root', width: 120, height: 40 }, { id: 'a', width: 100, height: 40 }],
[{ source: 'root', target: 'a' }],
{ direction: 'TB', nodeSep: 20, rankSep: 40 },
);
// positions: Array<{ id, x, y }> — top-left pxhazo_canvas/layout-sankey — Sankey flow layout
// npm install d3-sankey (optional peer)
import { layoutSankey } from 'hazo_canvas/layout-sankey';
const { nodes, links } = layoutSankey(
[{ id: 'revenue' }, { id: 'salaries' }, { id: 'profit' }],
[
{ source: 'revenue', target: 'salaries', value: 40 },
{ source: 'revenue', target: 'profit', value: 30 },
],
{ width: 600, height: 400, nodeWidth: 24, nodePadding: 8, nodeAlign: 'justify' },
);
// nodes: Array<{ id, x, y, width, height }> — top-left px, heights derived from flow
// links: Array<{ source, target, value, width, sourceX, sourceY, targetX, targetY }>
// Draw ribbons as horizontal cubics between (sourceX,sourceY) and (targetX,targetY) with the given width.Throws HazoCanvasError(LAYOUT_PEER_MISSING) if d3-sankey is not installed. Throws LAYOUT_INVALID_GRAPH for non-positive link values, dangling node IDs, or cycles.
hazo_canvas/layout-timeline — time-axis layout (reused by 5 graph kinds)
Used by timeline, roadmap, gantt, swimlane, and business graph kinds.
// npm install d3-scale d3-time (optional peers)
import { layoutTimeline } from 'hazo_canvas/layout-timeline';
const { nodes, axis } = layoutTimeline(
[
{ id: 'kickoff', time: 0 },
{ id: 'phase1', start: 100, end: 400, lane: 'Development' },
{ id: 'launch', time: 500 },
],
{ width: 800, height: 200, laneHeight: 32, tickCount: 4, orientation: 'horizontal' },
);
// nodes: Array<{ id, x, y, width, height, lane, kind: 'point'|'interval' }>
// axis: { domain, range, ticks: [{ value, position, label }] }Graph element kinds
The graph element type supports 9 graphKind values. All emit ChildShape[] via graphResultToChildren. Rendering is Soft Modern: rounded nodes, soft drop shadow, pastel fills, medium-weight labels.
| Kind | Layout engine | Description |
|---|---|---|
| dagre | layout-dagre | Directed acyclic graph / tree (TB, LR, etc.) |
| sankey | layout-sankey | Flow diagram with gradient/colored/grey ribbons |
| network | layout-network | Force-directed graph (force or radial style) |
| timeline | layout-timeline | Horizontal/vertical event timeline with bars/milestones |
| roadmap | layout-timeline | Point events as alternating above/below cards on an axis |
| gantt | layout-timeline | Lane-grouped interval bars (pill shape) with lane backgrounds |
| swimlane | layout-timeline | Full-width shaded lane bands with colored interval bars |
| business | layout-timeline | Dashed-axis quarterly pins (ringed ellipses) with header+body cards |
| legend | layout-legend | Color swatch legend with label column |
Each kind has a matching form (DagreForm, SankeyForm, NetworkForm, TimelineForm, TimelineFamilyForm for roadmap/gantt/swimlane/business, LegendForm) and a starter dataset from getDefaultInputs(kind).
hazo_canvas/layout-core — determinism primitives (isomorphic)
import { createSeededRng, runTwiceIdentical, LAYOUT_DETERMINISM_CONTRACT } from 'hazo_canvas/client';
const rng = createSeededRng(42); // mulberry32 — deterministic [0,1)
const isDet = runTwiceIdentical(myLayoutFn, input); // true if fn is deterministicRoadmap
Phase 2 (4/5 done): arrange, PDF adapter, layout-dagre, images-adapter. renderToSVG deferred (OQ-1).
Phase 3 — Collaboration: Yjs awareness, CRDT binding, <PresenceAvatars/>, auth seam.
Phase 4 (2/4 done): layout-sankey + deterministic guarantee done. layout-network and layout-timeline pending.
Phase 5 — kinstripe migration: compositor state + data migration, behavioral parity, cutover.
License
MIT
