@fieldnotes/core 0.60.0 → 0.62.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,705 +1,706 @@
1
- # @fieldnotes/core
2
-
3
- A lightweight, framework-agnostic infinite canvas SDK for the web — with first-class support for embedding interactive HTML elements.
4
-
5
- ## Features
6
-
7
- - **Infinite canvas** — pan, zoom, pinch-to-zoom
8
- - **Freehand drawing** — pencil tool with stroke smoothing and pressure-sensitive width
9
- - **Sticky notes** — editable text notes with customizable colors
10
- - **Arrows** — curved bezier arrows with element binding
11
- - **Shapes** — rectangles, ellipses with fill and stroke
12
- - **Text** — standalone text elements with font size and alignment
13
- - **Images** — drag & drop or programmatic placement (canvas-rendered for proper layer ordering)
14
- - **HTML embedding** — add any DOM element as a fully interactive canvas citizen
15
- - **Layers** — named layers with visibility, locking, and absolute ordering
16
- - **Select & multi-select** — click, drag box, move, resize (layer-aware)
17
- - **Undo / redo** — full history stack with configurable depth
18
- - **State serialization** — export/import JSON snapshots with automatic migration
19
- - **Grids** — square and hex grid overlays for D&D maps and alignment
20
- - **Export** — PNG export with scale, padding, background, and element filter options
21
- - **Performance instrumentation** — `getRenderStats()` and `logPerformance()` for frame timing
22
- - **Touch & tablet** — Pointer Events API, pinch-to-zoom, two-finger pan, stylus pressure
23
- - **Zero dependencies** — vanilla TypeScript, no framework required
24
- - **Tree-shakeable** — ESM + CJS output
25
-
26
- ## Install
27
-
28
- ```bash
29
- npm install @fieldnotes/core
30
- ```
31
-
32
- ## Quick Start
33
-
34
- ```typescript
35
- import {
36
- Viewport,
37
- HandTool,
38
- SelectTool,
39
- PencilTool,
40
- EraserTool,
41
- ArrowTool,
42
- NoteTool,
43
- } from '@fieldnotes/core';
44
-
45
- // Mount on any container element
46
- const viewport = new Viewport(document.getElementById('canvas'), {
47
- background: { pattern: 'dots', spacing: 24 },
48
- });
49
-
50
- // Register tools
51
- viewport.toolManager.register(new HandTool());
52
- viewport.toolManager.register(new SelectTool());
53
- viewport.toolManager.register(new PencilTool({ color: '#1a1a1a', width: 2 }));
54
- viewport.toolManager.register(new EraserTool());
55
- viewport.toolManager.register(new ArrowTool({ color: '#1a1a1a', width: 2 }));
56
- viewport.toolManager.register(new NoteTool());
57
-
58
- // Activate a tool
59
- viewport.setTool('select');
60
-
61
- // Clean up when done
62
- viewport.destroy();
63
- ```
64
-
65
- Your container element needs a defined size (width/height). The canvas fills its container.
66
-
67
- ## Embedding HTML Elements
68
-
69
- The main differentiator — embed any DOM node as a fully interactive canvas element:
70
-
71
- ```typescript
72
- const card = document.createElement('div');
73
- card.innerHTML = '<h3>My Card</h3><button>Click me</button>';
74
-
75
- // Buttons, inputs, links — everything works
76
- card.querySelector('button').addEventListener('click', () => {
77
- console.log('Clicked inside the canvas!');
78
- });
79
-
80
- const elementId = viewport.addHtmlElement(card, { x: 100, y: 200 }, { w: 250, h: 150 });
81
- ```
82
-
83
- HTML elements pan, zoom, resize, and interleave by layer/`zIndex` with canvas-rendered content. They
84
- use a **two-mode interaction model**:
85
-
86
- - **Default** — the element can be selected, dragged, and resized like any other element
87
- - **Double-click** — enters interact mode, making buttons, inputs, and links work
88
- - **Escape** or **click outside** — exits interact mode
89
-
90
- You can also exit interact mode programmatically:
91
-
92
- ```typescript
93
- viewport.stopInteracting();
94
- ```
95
-
96
- ## Adding Images
97
-
98
- ```typescript
99
- // Programmatic
100
- viewport.addImage('https://example.com/photo.jpg', { x: 0, y: 0 });
101
- viewport.addImage('/assets/map.png', { x: 0, y: 0 }, { w: 800, h: 600 });
102
-
103
- // Drag & drop is handled automatically — drop images onto the canvas
104
- ```
105
-
106
- > **Important: Use URLs, not base64 data URLs.** Images are stored inline in the serialized state. A single base64-encoded photo can be 2-5MB, which will blow past the `localStorage` ~5MB quota and make JSON exports impractical. Upload images to your server or CDN and use the URL. For offline/local-first apps, store blobs in IndexedDB and reference them by URL.
107
-
108
- ## Adding Shapes
109
-
110
- ```typescript
111
- // Default: a centered 100×100 rectangle
112
- const id = viewport.addShape();
113
-
114
- // Override shape, size, position, and colors
115
- viewport.addShape({
116
- shape: 'ellipse',
117
- size: { w: 200, h: 120 },
118
- position: { x: 0, y: 0 },
119
- strokeColor: '#1d4ed8',
120
- fillColor: '#dbeafe',
121
- strokeWidth: 2,
122
- });
123
- ```
124
-
125
- `addShape(opts?): string` creates a shape in a single undo step, selects the new shape, and returns its id. With no options it places a 100×100 rectangle centered in the current viewport — a keyboard-friendly path to shape creation.
126
-
127
- ## Grids
128
-
129
- Add square or hex grid overlays — useful for D&D combat maps, alignment, or graph paper backgrounds. Grids always render on top of images and other layer elements.
130
-
131
- ```typescript
132
- // Add a hex grid
133
- viewport.addGrid({
134
- gridType: 'hex',
135
- hexOrientation: 'pointy', // 'pointy' | 'flat'
136
- cellSize: 40,
137
- strokeColor: '#cccccc',
138
- strokeWidth: 1,
139
- opacity: 0.5,
140
- });
141
-
142
- // Update grid properties
143
- viewport.updateGrid({ cellSize: 50, strokeColor: '#aaaaaa' });
144
-
145
- // Remove grid
146
- viewport.removeGrid();
147
- ```
148
-
149
- ## Image Export
150
-
151
- Export the canvas as a PNG image:
152
-
153
- ```typescript
154
- const blob = await viewport.exportImage({
155
- scale: 2, // pixel density (default 2)
156
- padding: 20, // world-space padding around content (default 0)
157
- background: '#fff', // fill color (default '#ffffff')
158
- filter: (el) => el.type !== 'html', // optional per-element filter
159
- imageTimeoutMs: 10_000, // maximum wait per image
160
- maxDimension: 16_384, // maximum output width or height
161
- maxPixels: 67_108_864, // maximum output pixel count
162
- onAssetError: ({ elementId, src, reason }) => {
163
- console.warn(`Could not export ${elementId} (${reason}): ${src}`);
164
- },
165
- });
166
- ```
167
-
168
- Remote images are requested with anonymous CORS using their original URLs; failures are omitted from
169
- the result and reported through `onAssetError` when supplied.
170
-
171
- Application-owned HTML embeds require an explicit rasterization hook. Return a ready canvas-compatible
172
- image source; Field Notes applies the element's size, rotation, paint order, and layer opacity in both
173
- PNG and SVG exports:
174
-
175
- ```typescript
176
- const options = {
177
- htmlTimeoutMs: 10_000,
178
- renderHtml: async (element) => {
179
- const node = document.querySelector(`[data-element-id="${element.id}"]`);
180
- return node ? rasterizeToCanvas(node) : null; // application or library implementation
181
- },
182
- onHtmlError: ({ elementId, reason }) => {
183
- console.warn(`Could not export HTML element ${elementId}: ${reason}`);
184
- },
185
- };
186
-
187
- const png = await viewport.exportImage(options);
188
- const svg = await viewport.exportSVG(options);
189
- ```
190
-
191
- Without `renderHtml`, embeds remain omitted and can be observed through `onHtmlError`.
192
-
193
- ## Performance Monitoring
194
-
195
- ```typescript
196
- // Get a snapshot of render stats
197
- const stats = viewport.getRenderStats();
198
- // { fps, avgFrameMs, p95FrameMs, lastGridMs, frameCount }
199
-
200
- // Log stats to console every 2 seconds (returns stop function)
201
- const stop = viewport.logPerformance(2000);
202
- // [FieldNotes] fps=60 frame=1.2ms p95=2.1ms grid=0.1ms
203
- stop(); // stop logging
204
- ```
205
-
206
- ## Camera Control
207
-
208
- ```typescript
209
- const { camera } = viewport;
210
-
211
- camera.pan(100, 50); // pan by offset
212
- camera.moveTo(0, 0); // jump to position
213
- camera.setZoom(2); // set zoom level
214
- camera.zoomAt(1.5, { x: 400, y: 300 }); // zoom toward screen point
215
-
216
- const world = camera.screenToWorld({ x: e.clientX, y: e.clientY });
217
- const screen = camera.worldToScreen({ x: 0, y: 0 });
218
-
219
- camera.onChange(() => {
220
- /* camera moved */
221
- });
222
- ```
223
-
224
- ## Element Store
225
-
226
- Direct access to canvas elements:
227
-
228
- ```typescript
229
- const { store } = viewport;
230
-
231
- const all = store.getAll(); // sorted by zIndex
232
- const el = store.getById('some-id');
233
- const strokes = store.getElementsByType('stroke');
234
-
235
- store.update('some-id', { locked: true });
236
- store.remove('some-id');
237
-
238
- store.on('add', (el) => console.log('added', el));
239
- store.on('remove', (el) => console.log('removed', el));
240
- store.on('update', ({ previous, current }) => {
241
- /* ... */
242
- });
243
- ```
244
-
245
- ## Undo / Redo
246
-
247
- ```typescript
248
- viewport.undo();
249
- viewport.redo();
250
-
251
- viewport.history.canUndo; // boolean
252
- viewport.history.canRedo; // boolean
253
- viewport.history.onChange(() => {
254
- /* update UI */
255
- });
256
- ```
257
-
258
- ## Layers
259
-
260
- Organize elements into named layers with visibility, lock, and ordering controls. All elements on a higher layer render above all elements on a lower layer, regardless of individual z-index.
261
-
262
- ```typescript
263
- const { layerManager } = viewport;
264
-
265
- // Create layers
266
- const background = layerManager.activeLayer; // "Layer 1" exists by default
267
- layerManager.renameLayer(background.id, 'Map');
268
- const tokens = layerManager.createLayer('Tokens');
269
- const notes = layerManager.createLayer('Notes');
270
-
271
- // Set active layer — new elements are created on the active layer
272
- layerManager.setActiveLayer(tokens.id);
273
-
274
- // Visibility and locking
275
- layerManager.setLayerVisible(background.id, false); // hide
276
- layerManager.setLayerLocked(background.id, true); // prevent selection/editing
277
-
278
- // Move elements between layers
279
- layerManager.moveElementToLayer(elementId, notes.id);
280
-
281
- // Reorder layers
282
- layerManager.reorderLayer(tokens.id, 5); // higher order = renders on top
283
-
284
- // Query
285
- layerManager.getLayers(); // sorted by order
286
- layerManager.isLayerVisible(id);
287
- layerManager.isLayerLocked(id);
288
-
289
- // Listen for changes
290
- layerManager.on('change', () => {
291
- /* update UI */
292
- });
293
- ```
294
-
295
- Locked layers prevent selection, erasing, and arrow binding on their elements. Hidden layers are invisible and non-interactive. The active layer cannot be hidden or locked — if you try, it automatically switches to the next available layer.
296
-
297
- ## State Serialization
298
-
299
- ```typescript
300
- // Save
301
- const json = viewport.exportJSON();
302
- localStorage.setItem('canvas', json);
303
-
304
- // Load
305
- viewport.loadJSON(localStorage.getItem('canvas'));
306
- ```
307
-
308
- > **Note:** Serialized state includes all layers and element `layerId` assignments. States saved before layers were introduced are automatically migrated — elements are placed on a default "Layer 1".
309
-
310
- > **Two equivalent pairs:** `exportJSON()` / `loadJSON()` work with strings and are the
311
- > canonical choice for persistence. `exportState()` / `loadState()` work with in-memory
312
- > `CanvasState` objects, skipping the JSON round-trip — this is what `AutoSave` uses. The
313
- > module-level `exportState` / `parseState` functions are no longer exported; use the
314
- > `Viewport` methods.
315
-
316
- ## Tool Switching
317
-
318
- ```typescript
319
- viewport.setTool('pencil');
320
- viewport.setTool('hand');
321
-
322
- viewport.toolManager.onChange((toolName) => {
323
- console.log('switched to', toolName);
324
- });
325
- ```
326
-
327
- ## Keyboard shortcuts
328
-
329
- Defaults (remappable): `Delete`/`Backspace` delete · `Escape` deselect · `mod+Z` undo ·
330
- `mod+Y`/`mod+Shift+Z` redo · `mod+A` select all · `mod+C/V/D` copy/paste/duplicate ·
331
- `[`/`]` z-order (with `mod` = to back/front) · `Shift+1` zoom-to-fit · `mod+=` zoom in ·
332
- `mod+-` zoom out · `mod+0` reset zoom to 100% · arrows nudge
333
- (`Shift` = one grid cell) · tool keys `V` select, `H` hand, `P` pencil, `E` eraser,
334
- `A` arrow, `N` note, `T` text, `S` shape, `M` measure, `G` template.
335
-
336
- `mod` = Ctrl or Cmd. Shortcuts fire only while the canvas has focus (click it once);
337
- pass `shortcuts: { scope: 'window' }` for page-wide handling.
338
-
339
- ```ts
340
- const viewport = new Viewport(el, {
341
- shortcuts: {
342
- bindings: {
343
- duplicate: 'mod+shift+d', // remap
344
- 'tool:pencil': ['p', 'b'], // multiple bindings
345
- copy: null, // disable
346
- 'tool:my-custom-tool': 'f', // any registered tool works
347
- },
348
- },
349
- });
350
-
351
- viewport.shortcuts.rebind('undo', 'mod+u');
352
- viewport.shortcuts.disable('select-all');
353
- viewport.shortcuts.reset(); // back to defaults
354
- viewport.shortcuts.getBindings(); // current table — render a settings UI
355
- ```
356
-
357
- ## Changing Tool Options at Runtime
358
-
359
- All drawing tools support `setOptions()` for changing color, width, and other settings without re-creating the tool:
360
-
361
- ```typescript
362
- // Get a tool by name (type-safe with generics)
363
- const pencil = viewport.toolManager.getTool<PencilTool>('pencil');
364
- const arrow = viewport.toolManager.getTool<ArrowTool>('arrow');
365
- const note = viewport.toolManager.getTool<NoteTool>('note');
366
-
367
- // Change colors
368
- pencil?.setOptions({ color: '#ff0000' });
369
- arrow?.setOptions({ color: '#ff0000' });
370
- note?.setOptions({ backgroundColor: '#e8f5e9' });
371
-
372
- // Change stroke width
373
- pencil?.setOptions({ width: 5 });
374
- arrow?.setOptions({ width: 3 });
375
- ```
376
-
377
- ### Stroke Smoothing
378
-
379
- The pencil tool automatically smooths freehand strokes using Ramer-Douglas-Peucker point simplification and Catmull-Rom curve fitting. You can control the smoothing tolerance:
380
-
381
- ```typescript
382
- new PencilTool({
383
- smoothing: 1.5, // default — higher = smoother, lower = more detail
384
- });
385
-
386
- // Or at runtime
387
- pencil?.setOptions({ smoothing: 3 });
388
- ```
389
-
390
- ### Pressure-Sensitive Width
391
-
392
- When using a stylus (Apple Pencil, Surface Pen), stroke width varies based on pressure automatically. The `width` option sets the **maximum** width at full pressure. Mouse input uses a default pressure of 0.5 for consistent-width strokes.
393
-
394
- Stroke points include pressure data in the `StrokePoint` type:
395
-
396
- ```typescript
397
- interface StrokePoint {
398
- x: number;
399
- y: number;
400
- pressure: number; // 0-1
401
- }
402
- ```
403
-
404
- ## Custom Tools
405
-
406
- Implement the `Tool` interface to create your own tools:
407
-
408
- ```typescript
409
- import type { Tool, ToolContext, PointerState } from '@fieldnotes/core';
410
-
411
- const myTool: Tool = {
412
- name: 'my-tool',
413
-
414
- onPointerDown(state: PointerState, ctx: ToolContext) {
415
- const world = ctx.camera.screenToWorld({ x: state.x, y: state.y });
416
- // state.pressure is available for stylus input (0-1)
417
- },
418
-
419
- onPointerMove(state: PointerState, ctx: ToolContext) {
420
- // called during drag
421
- },
422
-
423
- onPointerUp(state: PointerState, ctx: ToolContext) {
424
- // finalize action
425
- ctx.store.add(myElement);
426
- ctx.requestRender();
427
- },
428
-
429
- // Optional
430
- onActivate(ctx) {
431
- ctx.setCursor?.('crosshair');
432
- },
433
- onDeactivate(ctx) {
434
- ctx.setCursor?.('default');
435
- },
436
- renderOverlay(canvasCtx) {
437
- /* draw preview on canvas */
438
- },
439
- };
440
-
441
- viewport.toolManager.register(myTool);
442
- viewport.setTool('my-tool');
443
- ```
444
-
445
- ## Configuration
446
-
447
- ### Viewport Options
448
-
449
- ```typescript
450
- new Viewport(container, {
451
- camera: {
452
- minZoom: 0.1, // default: 0.1
453
- maxZoom: 10, // default: 10
454
- },
455
- background: {
456
- pattern: 'dots', // 'dots' | 'grid' | 'none' (default: 'dots')
457
- spacing: 24, // grid spacing in px (default: 24)
458
- color: '#d0d0d0', // dot/line color (default: '#d0d0d0')
459
- },
460
- // Called for every drop; replaces the built-in image-drop handling
461
- onDrop: (event, worldPosition) => {
462
- /* handle drop */
463
- },
464
- // Called when an image element fails to load; failed images render a gray
465
- // placeholder. Falls back to console.warn when unset.
466
- onImageError: ({ src, elementIds }) => {
467
- /* handle broken image */
468
- },
469
- });
470
- ```
471
-
472
- ### ViewportOptions reference
473
-
474
- - `camera?: CameraOptions` — `minZoom` / `maxZoom` (defaults `0.1` / `10`).
475
- - `background?: BackgroundOptions` — `pattern`, `spacing`, `color`.
476
- - `fontSizePresets?: FontSizePreset[]` — custom font-size steps for the note toolbar.
477
- - `toolbar?: boolean` — show/hide the note formatting toolbar (default `true`).
478
- - `placeholder?: string` — placeholder text shown in empty notes.
479
- - `shortcuts?: ShortcutOptions` — seed the keyboard shortcut table with custom bindings.
480
- - `onHtmlElementMount?`called after `loadState` for HTML elements that need content injected.
481
- - `onDrop?` — called for every drop event; replaces the built-in image-drop handling.
482
- - `onImageError?` — called when an image element fails to load.
483
- - `panBufferMargin?: number` (default `256`) CSS-pixel margin cached beyond the viewport so
484
- small pans re-composite instead of re-rasterizing the layers and grid. Larger = more pan
485
- reuse, more memory per layer. Set `0` to disable (exact-viewport caches) on memory-tight hosts.
486
-
487
- ### Tool Options
488
-
489
- ```typescript
490
- new PencilTool({ color: '#ff0000', width: 3, smoothing: 1.5 });
491
- new EraserTool({ radius: 30 }); // radius is screen pixels (converted to world units per zoom); mode: 'partial' (default) splits strokes at the erased span; mode: 'stroke' deletes the whole stroke
492
- new ArrowTool({ color: '#333', width: 2 });
493
- ```
494
-
495
- `PencilTool` also accepts `opacity` (0–1), `blendMode` (`'source-over'` | `'multiply'`), and `name` — so a highlighter tool is just a named pencil variant with multiply blending:
496
-
497
- ```typescript
498
- // Register a highlighter alongside the standard pencil
499
- viewport.toolManager.register(
500
- new PencilTool({
501
- name: 'highlighter',
502
- color: '#facc15',
503
- width: 12,
504
- opacity: 0.4,
505
- blendMode: 'multiply',
506
- }),
507
- );
508
- viewport.setTool('highlighter');
509
- ```
510
-
511
- `ShapeTool` supports a `'line'` shape kind that draws a straight segment between two points. Hold **Shift** while drawing to snap to 45° increments. Lines are hit-tested by proximity to the segment, and `ShapeElement.flip` records which diagonal of the bounding box the line runs along. When a line is selected, it shows two endpoint drag-handles instead of bounding-box resize handles — drag one endpoint to reshape the line while the other stays anchored.
512
-
513
- ### Arrow Labels
514
-
515
- Arrows support an optional `label` string, rendered as a pill at the curve midpoint. Pass it at creation or double-click an arrow on the canvas to add or edit the label inline.
516
-
517
- ```typescript
518
- createArrow({ from: { x: 0, y: 0 }, to: { x: 200, y: 0 }, label: 'depends on' });
519
- new NoteTool({ backgroundColor: '#fff9c4', size: { w: 200, h: 150 } });
520
- new ImageTool({ size: { w: 400, h: 300 } });
521
- ```
522
-
523
- ## Element Types
524
-
525
- All elements share a base shape:
526
-
527
- ```typescript
528
- interface BaseElement {
529
- id: string;
530
- type: string;
531
- position: { x: number; y: number };
532
- zIndex: number;
533
- locked: boolean;
534
- layerId: string;
535
- }
536
- ```
537
-
538
- | Type | Key Fields |
539
- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
540
- | `stroke` | `points: StrokePoint[]`, `color`, `width`, `opacity` |
541
- | `note` | `size`, `text`, `backgroundColor`, `textColor` |
542
- | `arrow` | `from`, `to`, `bend`, `color`, `width`, `fromBinding`, `toBinding` |
543
- | `image` | `size`, `src` |
544
- | `shape` | `size`, `shape` (`rectangle` \| `ellipse` \| `line`), `strokeColor`, `fillColor`, `flip` (`boolean` — which bbox diagonal a line runs along) |
545
- | `text` | `size`, `text`, `fontSize`, `color`, `textAlign` |
546
- | `grid` | `gridType` (`square` \| `hex`), `hexOrientation`, `cellSize`, `strokeColor`, `opacity` |
547
- | `html` | `size` |
548
-
549
- ## Styling the Selection
550
-
551
- A normalized `ElementStyle` interface lets you read and apply visual properties across all element types through a single, consistent shape. The `SelectTool` emits a selection-change event; `Viewport` exposes four methods that together cover reactive UIs.
552
-
553
- ### `ElementStyle` interface
554
-
555
- ```typescript
556
- interface ElementStyle {
557
- color?: string; // stroke color / text color
558
- fillColor?: string; // fill / background color
559
- strokeWidth?: number; // line width in world-space units
560
- opacity?: number; // 0–1
561
- fontSize?: number; // px
562
- }
563
- ```
564
-
565
- #### Mapping across element types
566
-
567
- | `ElementStyle` field | `stroke` | `arrow` | `shape` | `note` | `text` |
568
- | -------------------- | --------- | ------- | ------------- | ----------------- | ---------- |
569
- | `color` | `color` | `color` | `strokeColor` | `textColor` | `color` |
570
- | `fillColor` | | | `fillColor` | `backgroundColor` | |
571
- | `strokeWidth` | `width` | `width` | `strokeWidth` | — | — |
572
- | `opacity` | `opacity` | | | — | — |
573
- | `fontSize` | | — | — | (via toolbar) | `fontSize` |
574
-
575
- ### Conversion helpers
576
-
577
- ```typescript
578
- import { styleToPatch, getElementStyle } from '@fieldnotes/core';
579
-
580
- // ElementStyle → element-specific patch object
581
- const patch = styleToPatch(element, { color: '#e00', strokeWidth: 3 });
582
- store.update(element.id, patch);
583
-
584
- // element → normalized ElementStyle
585
- const style = getElementStyle(element);
586
- ```
587
-
588
- ### Viewport methods
589
-
590
- - **`viewport.getSelectedIds()`** — returns the current selection as a referentially-stable array (the same array reference is reused across calls when the selection has not changed — safe for `useSyncExternalStore` equality checks).
591
- - **`viewport.onSelectionChange(listener)`** — subscribes to selection changes; returns an unsubscribe function. The listener receives the new stable id array.
592
- - **`viewport.getSelectionStyle()`** — returns an `ElementStyle` containing only the properties that are identical across every selected element. Properties that differ are omitted.
593
- - **`viewport.applyStyleToSelection(style)`** — applies the given `ElementStyle` to all selected elements in a single undo step.
594
-
595
- ### `SelectTool.onSelectionChange`
596
-
597
- ```typescript
598
- const selectTool = viewport.toolManager.getTool<SelectTool>('select');
599
- selectTool?.onSelectionChange((ids) => {
600
- console.log('selected:', ids);
601
- });
602
- ```
603
-
604
- ### Example
605
-
606
- ```typescript
607
- // Apply a red stroke to everything currently selected — one undo step
608
- viewport.applyStyleToSelection({ color: '#ff0000' });
609
-
610
- // Read back the shared style for a UI color picker
611
- const style = viewport.getSelectionStyle();
612
- // style.color is defined only if all selected elements share the same color
613
-
614
- // React to selection changes
615
- const unsub = viewport.onSelectionChange((ids) => {
616
- setSelectedIds(ids); // ids is referentially stable — safe for deps arrays
617
- });
618
- // call unsub() to unsubscribe
619
- ```
620
-
621
- ## Aligning the Selection
622
-
623
- Two methods on `Viewport` let you snap or space selected elements in one undo step.
624
-
625
- - **`viewport.alignSelection(edge)`** — `edge`: `AlignEdge` = `'left' | 'center-x' | 'right' | 'top' | 'middle' | 'bottom'`; aligns every selected element to the corresponding edge or center of the selection's bounding box. Needs 2+ selected elements. Locked elements anchor the bounding box without moving.
626
- - **`viewport.distributeSelection(axis)`** — `axis`: `DistributeAxis` = `'horizontal' | 'vertical'`; evenly spaces selected elements' centers along the axis. Needs 3+ selected elements. Locked elements anchor the span without moving.
627
-
628
- ```typescript
629
- viewport.alignSelection('left'); // flush left edges
630
- viewport.alignSelection('center-x'); // center on vertical axis
631
- viewport.alignSelection('middle'); // center on horizontal axis
632
- viewport.distributeSelection('horizontal'); // equal horizontal spacing
633
- ```
634
-
635
- Grids are ignored by both operations.
636
-
637
- ## Smart Alignment Guides
638
-
639
- Call `viewport.setSmartGuides(true)` to enable drag-time alignment snapping. While dragging a selection, its edges and centers snap to the edges and centers of nearby visible elements (within 6 screen pixels), and guide lines are drawn at each matched alignment. Smart guides replace grid snapping for the duration of the drag; the result is still committed as a single undo step.
640
-
641
- ```typescript
642
- viewport.setSmartGuides(true); // enable
643
- viewport.setSmartGuides(false); // disable (default)
644
- ```
645
-
646
- ## Grouping
647
-
648
- Group elements so they select, move, delete, z-order, and align as a single unit.
649
-
650
- - **`viewport.groupSelection()`** — groups the current selection under a new id.
651
- - **`viewport.ungroupSelection()`** — dissolves any groups in the current selection.
652
-
653
- Each is one undo step. Selecting any member selects its whole group, so to edit a single member individually, ungroup first. Pasting or duplicating a group keeps the copies grouped under a fresh id.
654
-
655
- ```typescript
656
- viewport.groupSelection(); // Ctrl/Cmd+G
657
- viewport.ungroupSelection(); // Ctrl/Cmd+Shift+G
658
- ```
659
-
660
- The shortcuts are rebindable as `group` and `ungroup`.
661
-
662
- ## Rotation
663
-
664
- Select a single element and a rotate handle appears above the selection box. Drag it to rotate the element about its center; hold **Shift** to snap to 15° increments. Notes, text, images, HTML embeds, shapes, and strokes can all be rotated.
665
-
666
- Hit-testing, marquee selection, and resize are all rotation-aware: resizing a rotated element keeps the opposite corner fixed in the element's local frame. Rotation is reflected in PNG export and round-trips through serialization (`rotation?` on elements, stored in radians).
667
-
668
- ## Context menu & lock
669
-
670
- Right-click (desktop) or touch long-press (tablet) opens a context menu over the canvas with Cut/Copy/Paste/Duplicate/Delete, z-order (to front / forward / backward / to back), and Lock/Unlock. The menu is core-provided (plain DOM) and selects the element under the pointer if it isn't already selected. Opt out with `new Viewport(el, { contextMenu: false })`.
671
-
672
- Lock with **`viewport.toggleLockSelection()`** or **Ctrl/Cmd+Shift+L**; a lock badge appears on the selection. Locked elements stay selectable but can't be moved, resized, or rotated. **Ctrl/Cmd+X** cuts the selection. The shortcuts are rebindable as `toggle-lock` and `cut`.
673
-
674
- You can drive any menu action programmatically with **`viewport.runAction(name)`** (e.g. `'cut'`, `'paste'`, `'toggle-lock'`), and **`viewport.canPaste()`** reports whether the clipboard has content.
675
-
676
- ## Built-in Interactions
677
-
678
- | Input | Action |
679
- | -------------------- | ------------------- |
680
- | Scroll wheel | Zoom |
681
- | Middle-click drag | Pan |
682
- | Space + drag | Pan |
683
- | Two-finger pinch | Zoom |
684
- | Two-finger drag | Pan |
685
- | Delete / Backspace | Remove selected |
686
- | Ctrl+Z / Cmd+Z | Undo |
687
- | Ctrl+Shift+Z / Cmd+Y | Redo |
688
- | Double-click note | Edit text |
689
- | Double-click HTML | Enter interact mode |
690
- | Escape | Exit interact mode |
691
-
692
- ## Browser Support
693
-
694
- Works in all modern browsers supporting Pointer Events API and HTML5 Canvas.
695
-
696
- ## Versioning
697
-
698
- `@fieldnotes/core` and `@fieldnotes/react` are versioned independently. The react
699
- package's `peerDependencies` declare the compatible core range. Pre-1.0, minor
700
- versions may contain breaking changes. The core peer range is bounded at the next major rather than per-minor; if a core minor
701
- ever breaks the wrapper, a coordinated react release raises the lower bound.
702
-
703
- ## License
704
-
705
- MIT
1
+ # @fieldnotes/core
2
+
3
+ A lightweight, framework-agnostic infinite canvas SDK for the web — with first-class support for embedding interactive HTML elements.
4
+
5
+ ## Features
6
+
7
+ - **Infinite canvas** — pan, zoom, pinch-to-zoom
8
+ - **Freehand drawing** — pencil tool with stroke smoothing and pressure-sensitive width
9
+ - **Sticky notes** — editable text notes with customizable colors
10
+ - **Arrows** — curved bezier arrows with element binding
11
+ - **Shapes** — rectangles, ellipses with fill and stroke
12
+ - **Text** — standalone text elements with font size and alignment
13
+ - **Images** — drag & drop or programmatic placement (canvas-rendered for proper layer ordering)
14
+ - **HTML embedding** — add any DOM element as a fully interactive canvas citizen
15
+ - **Canvas-routed HTML painters** — register a painter to draw `html` elements on the canvas (screen, minimap, and export) instead of the DOM, with typed element activation events
16
+ - **Layers** — named layers with visibility, locking, and absolute ordering
17
+ - **Select & multi-select** — click, drag box, move, resize (layer-aware)
18
+ - **Undo / redo** — full history stack with configurable depth
19
+ - **State serialization** — export/import JSON snapshots with automatic migration
20
+ - **Grids** — square and hex grid overlays for D&D maps and alignment
21
+ - **Export** — PNG export with scale, padding, background, and element filter options
22
+ - **Performance instrumentation** — `getRenderStats()` and `logPerformance()` for frame timing
23
+ - **Touch & tablet** — Pointer Events API, pinch-to-zoom, two-finger pan, stylus pressure
24
+ - **Zero dependencies** — vanilla TypeScript, no framework required
25
+ - **Tree-shakeable** — ESM + CJS output
26
+
27
+ ## Install
28
+
29
+ ```bash
30
+ npm install @fieldnotes/core
31
+ ```
32
+
33
+ ## Quick Start
34
+
35
+ ```typescript
36
+ import {
37
+ Viewport,
38
+ HandTool,
39
+ SelectTool,
40
+ PencilTool,
41
+ EraserTool,
42
+ ArrowTool,
43
+ NoteTool,
44
+ } from '@fieldnotes/core';
45
+
46
+ // Mount on any container element
47
+ const viewport = new Viewport(document.getElementById('canvas'), {
48
+ background: { pattern: 'dots', spacing: 24 },
49
+ });
50
+
51
+ // Register tools
52
+ viewport.toolManager.register(new HandTool());
53
+ viewport.toolManager.register(new SelectTool());
54
+ viewport.toolManager.register(new PencilTool({ color: '#1a1a1a', width: 2 }));
55
+ viewport.toolManager.register(new EraserTool());
56
+ viewport.toolManager.register(new ArrowTool({ color: '#1a1a1a', width: 2 }));
57
+ viewport.toolManager.register(new NoteTool());
58
+
59
+ // Activate a tool
60
+ viewport.setTool('select');
61
+
62
+ // Clean up when done
63
+ viewport.destroy();
64
+ ```
65
+
66
+ Your container element needs a defined size (width/height). The canvas fills its container.
67
+
68
+ ## Embedding HTML Elements
69
+
70
+ The main differentiator — embed any DOM node as a fully interactive canvas element:
71
+
72
+ ```typescript
73
+ const card = document.createElement('div');
74
+ card.innerHTML = '<h3>My Card</h3><button>Click me</button>';
75
+
76
+ // Buttons, inputs, links — everything works
77
+ card.querySelector('button').addEventListener('click', () => {
78
+ console.log('Clicked inside the canvas!');
79
+ });
80
+
81
+ const elementId = viewport.addHtmlElement(card, { x: 100, y: 200 }, { w: 250, h: 150 });
82
+ ```
83
+
84
+ HTML elements pan, zoom, resize, and interleave by layer/`zIndex` with canvas-rendered content. They
85
+ use a **two-mode interaction model**:
86
+
87
+ - **Default** — the element can be selected, dragged, and resized like any other element
88
+ - **Double-click** — enters interact mode, making buttons, inputs, and links work
89
+ - **Escape** or **click outside** — exits interact mode
90
+
91
+ You can also exit interact mode programmatically:
92
+
93
+ ```typescript
94
+ viewport.stopInteracting();
95
+ ```
96
+
97
+ ## Adding Images
98
+
99
+ ```typescript
100
+ // Programmatic
101
+ viewport.addImage('https://example.com/photo.jpg', { x: 0, y: 0 });
102
+ viewport.addImage('/assets/map.png', { x: 0, y: 0 }, { w: 800, h: 600 });
103
+
104
+ // Drag & drop is handled automatically — drop images onto the canvas
105
+ ```
106
+
107
+ > **Important: Use URLs, not base64 data URLs.** Images are stored inline in the serialized state. A single base64-encoded photo can be 2-5MB, which will blow past the `localStorage` ~5MB quota and make JSON exports impractical. Upload images to your server or CDN and use the URL. For offline/local-first apps, store blobs in IndexedDB and reference them by URL.
108
+
109
+ ## Adding Shapes
110
+
111
+ ```typescript
112
+ // Default: a centered 100×100 rectangle
113
+ const id = viewport.addShape();
114
+
115
+ // Override shape, size, position, and colors
116
+ viewport.addShape({
117
+ shape: 'ellipse',
118
+ size: { w: 200, h: 120 },
119
+ position: { x: 0, y: 0 },
120
+ strokeColor: '#1d4ed8',
121
+ fillColor: '#dbeafe',
122
+ strokeWidth: 2,
123
+ });
124
+ ```
125
+
126
+ `addShape(opts?): string` creates a shape in a single undo step, selects the new shape, and returns its id. With no options it places a 100×100 rectangle centered in the current viewport — a keyboard-friendly path to shape creation.
127
+
128
+ ## Grids
129
+
130
+ Add square or hex grid overlays — useful for D&D combat maps, alignment, or graph paper backgrounds. Grids always render on top of images and other layer elements.
131
+
132
+ ```typescript
133
+ // Add a hex grid
134
+ viewport.addGrid({
135
+ gridType: 'hex',
136
+ hexOrientation: 'pointy', // 'pointy' | 'flat'
137
+ cellSize: 40,
138
+ strokeColor: '#cccccc',
139
+ strokeWidth: 1,
140
+ opacity: 0.5,
141
+ });
142
+
143
+ // Update grid properties
144
+ viewport.updateGrid({ cellSize: 50, strokeColor: '#aaaaaa' });
145
+
146
+ // Remove grid
147
+ viewport.removeGrid();
148
+ ```
149
+
150
+ ## Image Export
151
+
152
+ Export the canvas as a PNG image:
153
+
154
+ ```typescript
155
+ const blob = await viewport.exportImage({
156
+ scale: 2, // pixel density (default 2)
157
+ padding: 20, // world-space padding around content (default 0)
158
+ background: '#fff', // fill color (default '#ffffff')
159
+ filter: (el) => el.type !== 'html', // optional per-element filter
160
+ imageTimeoutMs: 10_000, // maximum wait per image
161
+ maxDimension: 16_384, // maximum output width or height
162
+ maxPixels: 67_108_864, // maximum output pixel count
163
+ onAssetError: ({ elementId, src, reason }) => {
164
+ console.warn(`Could not export ${elementId} (${reason}): ${src}`);
165
+ },
166
+ });
167
+ ```
168
+
169
+ Remote images are requested with anonymous CORS using their original URLs; failures are omitted from
170
+ the result and reported through `onAssetError` when supplied.
171
+
172
+ Application-owned HTML embeds require an explicit rasterization hook. Return a ready canvas-compatible
173
+ image source; Field Notes applies the element's size, rotation, paint order, and layer opacity in both
174
+ PNG and SVG exports:
175
+
176
+ ```typescript
177
+ const options = {
178
+ htmlTimeoutMs: 10_000,
179
+ renderHtml: async (element) => {
180
+ const node = document.querySelector(`[data-element-id="${element.id}"]`);
181
+ return node ? rasterizeToCanvas(node) : null; // application or library implementation
182
+ },
183
+ onHtmlError: ({ elementId, reason }) => {
184
+ console.warn(`Could not export HTML element ${elementId}: ${reason}`);
185
+ },
186
+ };
187
+
188
+ const png = await viewport.exportImage(options);
189
+ const svg = await viewport.exportSVG(options);
190
+ ```
191
+
192
+ Without `renderHtml`, embeds remain omitted and can be observed through `onHtmlError`.
193
+
194
+ ## Performance Monitoring
195
+
196
+ ```typescript
197
+ // Get a snapshot of render stats
198
+ const stats = viewport.getRenderStats();
199
+ // { fps, avgFrameMs, p95FrameMs, lastGridMs, frameCount }
200
+
201
+ // Log stats to console every 2 seconds (returns stop function)
202
+ const stop = viewport.logPerformance(2000);
203
+ // [FieldNotes] fps=60 frame=1.2ms p95=2.1ms grid=0.1ms
204
+ stop(); // stop logging
205
+ ```
206
+
207
+ ## Camera Control
208
+
209
+ ```typescript
210
+ const { camera } = viewport;
211
+
212
+ camera.pan(100, 50); // pan by offset
213
+ camera.moveTo(0, 0); // jump to position
214
+ camera.setZoom(2); // set zoom level
215
+ camera.zoomAt(1.5, { x: 400, y: 300 }); // zoom toward screen point
216
+
217
+ const world = camera.screenToWorld({ x: e.clientX, y: e.clientY });
218
+ const screen = camera.worldToScreen({ x: 0, y: 0 });
219
+
220
+ camera.onChange(() => {
221
+ /* camera moved */
222
+ });
223
+ ```
224
+
225
+ ## Element Store
226
+
227
+ Direct access to canvas elements:
228
+
229
+ ```typescript
230
+ const { store } = viewport;
231
+
232
+ const all = store.getAll(); // sorted by zIndex
233
+ const el = store.getById('some-id');
234
+ const strokes = store.getElementsByType('stroke');
235
+
236
+ store.update('some-id', { locked: true });
237
+ store.remove('some-id');
238
+
239
+ store.on('add', (el) => console.log('added', el));
240
+ store.on('remove', (el) => console.log('removed', el));
241
+ store.on('update', ({ previous, current }) => {
242
+ /* ... */
243
+ });
244
+ ```
245
+
246
+ ## Undo / Redo
247
+
248
+ ```typescript
249
+ viewport.undo();
250
+ viewport.redo();
251
+
252
+ viewport.history.canUndo; // boolean
253
+ viewport.history.canRedo; // boolean
254
+ viewport.history.onChange(() => {
255
+ /* update UI */
256
+ });
257
+ ```
258
+
259
+ ## Layers
260
+
261
+ Organize elements into named layers with visibility, lock, and ordering controls. All elements on a higher layer render above all elements on a lower layer, regardless of individual z-index.
262
+
263
+ ```typescript
264
+ const { layerManager } = viewport;
265
+
266
+ // Create layers
267
+ const background = layerManager.activeLayer; // "Layer 1" exists by default
268
+ layerManager.renameLayer(background.id, 'Map');
269
+ const tokens = layerManager.createLayer('Tokens');
270
+ const notes = layerManager.createLayer('Notes');
271
+
272
+ // Set active layer — new elements are created on the active layer
273
+ layerManager.setActiveLayer(tokens.id);
274
+
275
+ // Visibility and locking
276
+ layerManager.setLayerVisible(background.id, false); // hide
277
+ layerManager.setLayerLocked(background.id, true); // prevent selection/editing
278
+
279
+ // Move elements between layers
280
+ layerManager.moveElementToLayer(elementId, notes.id);
281
+
282
+ // Reorder layers
283
+ layerManager.reorderLayer(tokens.id, 5); // higher order = renders on top
284
+
285
+ // Query
286
+ layerManager.getLayers(); // sorted by order
287
+ layerManager.isLayerVisible(id);
288
+ layerManager.isLayerLocked(id);
289
+
290
+ // Listen for changes
291
+ layerManager.on('change', () => {
292
+ /* update UI */
293
+ });
294
+ ```
295
+
296
+ Locked layers prevent selection, erasing, and arrow binding on their elements. Hidden layers are invisible and non-interactive. The active layer cannot be hidden or locked — if you try, it automatically switches to the next available layer.
297
+
298
+ ## State Serialization
299
+
300
+ ```typescript
301
+ // Save
302
+ const json = viewport.exportJSON();
303
+ localStorage.setItem('canvas', json);
304
+
305
+ // Load
306
+ viewport.loadJSON(localStorage.getItem('canvas'));
307
+ ```
308
+
309
+ > **Note:** Serialized state includes all layers and element `layerId` assignments. States saved before layers were introduced are automatically migrated — elements are placed on a default "Layer 1".
310
+
311
+ > **Two equivalent pairs:** `exportJSON()` / `loadJSON()` work with strings and are the
312
+ > canonical choice for persistence. `exportState()` / `loadState()` work with in-memory
313
+ > `CanvasState` objects, skipping the JSON round-trip this is what `AutoSave` uses. The
314
+ > module-level `exportState` / `parseState` functions are no longer exported; use the
315
+ > `Viewport` methods.
316
+
317
+ ## Tool Switching
318
+
319
+ ```typescript
320
+ viewport.setTool('pencil');
321
+ viewport.setTool('hand');
322
+
323
+ viewport.toolManager.onChange((toolName) => {
324
+ console.log('switched to', toolName);
325
+ });
326
+ ```
327
+
328
+ ## Keyboard shortcuts
329
+
330
+ Defaults (remappable): `Delete`/`Backspace` delete · `Escape` deselect · `mod+Z` undo ·
331
+ `mod+Y`/`mod+Shift+Z` redo · `mod+A` select all · `mod+C/V/D` copy/paste/duplicate ·
332
+ `[`/`]` z-order (with `mod` = to back/front) · `Shift+1` zoom-to-fit · `mod+=` zoom in ·
333
+ `mod+-` zoom out · `mod+0` reset zoom to 100% · arrows nudge
334
+ (`Shift` = one grid cell) · tool keys `V` select, `H` hand, `P` pencil, `E` eraser,
335
+ `A` arrow, `N` note, `T` text, `S` shape, `M` measure, `G` template.
336
+
337
+ `mod` = Ctrl or Cmd. Shortcuts fire only while the canvas has focus (click it once);
338
+ pass `shortcuts: { scope: 'window' }` for page-wide handling.
339
+
340
+ ```ts
341
+ const viewport = new Viewport(el, {
342
+ shortcuts: {
343
+ bindings: {
344
+ duplicate: 'mod+shift+d', // remap
345
+ 'tool:pencil': ['p', 'b'], // multiple bindings
346
+ copy: null, // disable
347
+ 'tool:my-custom-tool': 'f', // any registered tool works
348
+ },
349
+ },
350
+ });
351
+
352
+ viewport.shortcuts.rebind('undo', 'mod+u');
353
+ viewport.shortcuts.disable('select-all');
354
+ viewport.shortcuts.reset(); // back to defaults
355
+ viewport.shortcuts.getBindings(); // current table — render a settings UI
356
+ ```
357
+
358
+ ## Changing Tool Options at Runtime
359
+
360
+ All drawing tools support `setOptions()` for changing color, width, and other settings without re-creating the tool:
361
+
362
+ ```typescript
363
+ // Get a tool by name (type-safe with generics)
364
+ const pencil = viewport.toolManager.getTool<PencilTool>('pencil');
365
+ const arrow = viewport.toolManager.getTool<ArrowTool>('arrow');
366
+ const note = viewport.toolManager.getTool<NoteTool>('note');
367
+
368
+ // Change colors
369
+ pencil?.setOptions({ color: '#ff0000' });
370
+ arrow?.setOptions({ color: '#ff0000' });
371
+ note?.setOptions({ backgroundColor: '#e8f5e9' });
372
+
373
+ // Change stroke width
374
+ pencil?.setOptions({ width: 5 });
375
+ arrow?.setOptions({ width: 3 });
376
+ ```
377
+
378
+ ### Stroke Smoothing
379
+
380
+ The pencil tool automatically smooths freehand strokes using Ramer-Douglas-Peucker point simplification and Catmull-Rom curve fitting. You can control the smoothing tolerance:
381
+
382
+ ```typescript
383
+ new PencilTool({
384
+ smoothing: 1.5, // default — higher = smoother, lower = more detail
385
+ });
386
+
387
+ // Or at runtime
388
+ pencil?.setOptions({ smoothing: 3 });
389
+ ```
390
+
391
+ ### Pressure-Sensitive Width
392
+
393
+ When using a stylus (Apple Pencil, Surface Pen), stroke width varies based on pressure automatically. The `width` option sets the **maximum** width at full pressure. Mouse input uses a default pressure of 0.5 for consistent-width strokes.
394
+
395
+ Stroke points include pressure data in the `StrokePoint` type:
396
+
397
+ ```typescript
398
+ interface StrokePoint {
399
+ x: number;
400
+ y: number;
401
+ pressure: number; // 0-1
402
+ }
403
+ ```
404
+
405
+ ## Custom Tools
406
+
407
+ Implement the `Tool` interface to create your own tools:
408
+
409
+ ```typescript
410
+ import type { Tool, ToolContext, PointerState } from '@fieldnotes/core';
411
+
412
+ const myTool: Tool = {
413
+ name: 'my-tool',
414
+
415
+ onPointerDown(state: PointerState, ctx: ToolContext) {
416
+ const world = ctx.camera.screenToWorld({ x: state.x, y: state.y });
417
+ // state.pressure is available for stylus input (0-1)
418
+ },
419
+
420
+ onPointerMove(state: PointerState, ctx: ToolContext) {
421
+ // called during drag
422
+ },
423
+
424
+ onPointerUp(state: PointerState, ctx: ToolContext) {
425
+ // finalize action
426
+ ctx.store.add(myElement);
427
+ ctx.requestRender();
428
+ },
429
+
430
+ // Optional
431
+ onActivate(ctx) {
432
+ ctx.setCursor?.('crosshair');
433
+ },
434
+ onDeactivate(ctx) {
435
+ ctx.setCursor?.('default');
436
+ },
437
+ renderOverlay(canvasCtx) {
438
+ /* draw preview on canvas */
439
+ },
440
+ };
441
+
442
+ viewport.toolManager.register(myTool);
443
+ viewport.setTool('my-tool');
444
+ ```
445
+
446
+ ## Configuration
447
+
448
+ ### Viewport Options
449
+
450
+ ```typescript
451
+ new Viewport(container, {
452
+ camera: {
453
+ minZoom: 0.1, // default: 0.1
454
+ maxZoom: 10, // default: 10
455
+ },
456
+ background: {
457
+ pattern: 'dots', // 'dots' | 'grid' | 'none' (default: 'dots')
458
+ spacing: 24, // grid spacing in px (default: 24)
459
+ color: '#d0d0d0', // dot/line color (default: '#d0d0d0')
460
+ },
461
+ // Called for every drop; replaces the built-in image-drop handling
462
+ onDrop: (event, worldPosition) => {
463
+ /* handle drop */
464
+ },
465
+ // Called when an image element fails to load; failed images render a gray
466
+ // placeholder. Falls back to console.warn when unset.
467
+ onImageError: ({ src, elementIds }) => {
468
+ /* handle broken image */
469
+ },
470
+ });
471
+ ```
472
+
473
+ ### ViewportOptions reference
474
+
475
+ - `camera?: CameraOptions` — `minZoom` / `maxZoom` (defaults `0.1` / `10`).
476
+ - `background?: BackgroundOptions` — `pattern`, `spacing`, `color`.
477
+ - `fontSizePresets?: FontSizePreset[]` — custom font-size steps for the note toolbar.
478
+ - `toolbar?: boolean` — show/hide the note formatting toolbar (default `true`).
479
+ - `placeholder?: string` — placeholder text shown in empty notes.
480
+ - `shortcuts?: ShortcutOptions` seed the keyboard shortcut table with custom bindings.
481
+ - `onHtmlElementMount?` — called after `loadState` for HTML elements that need content injected.
482
+ - `onDrop?` — called for every drop event; replaces the built-in image-drop handling.
483
+ - `onImageError?` called when an image element fails to load.
484
+ - `panBufferMargin?: number` (default `256`) — CSS-pixel margin cached beyond the viewport so
485
+ small pans re-composite instead of re-rasterizing the layers and grid. Larger = more pan
486
+ reuse, more memory per layer. Set `0` to disable (exact-viewport caches) on memory-tight hosts.
487
+
488
+ ### Tool Options
489
+
490
+ ```typescript
491
+ new PencilTool({ color: '#ff0000', width: 3, smoothing: 1.5 });
492
+ new EraserTool({ radius: 30 }); // radius is screen pixels (converted to world units per zoom); mode: 'partial' (default) splits strokes at the erased span; mode: 'stroke' deletes the whole stroke
493
+ new ArrowTool({ color: '#333', width: 2 });
494
+ ```
495
+
496
+ `PencilTool` also accepts `opacity` (0–1), `blendMode` (`'source-over'` | `'multiply'`), and `name` — so a highlighter tool is just a named pencil variant with multiply blending:
497
+
498
+ ```typescript
499
+ // Register a highlighter alongside the standard pencil
500
+ viewport.toolManager.register(
501
+ new PencilTool({
502
+ name: 'highlighter',
503
+ color: '#facc15',
504
+ width: 12,
505
+ opacity: 0.4,
506
+ blendMode: 'multiply',
507
+ }),
508
+ );
509
+ viewport.setTool('highlighter');
510
+ ```
511
+
512
+ `ShapeTool` supports a `'line'` shape kind that draws a straight segment between two points. Hold **Shift** while drawing to snap to 45° increments. Lines are hit-tested by proximity to the segment, and `ShapeElement.flip` records which diagonal of the bounding box the line runs along. When a line is selected, it shows two endpoint drag-handles instead of bounding-box resize handles — drag one endpoint to reshape the line while the other stays anchored.
513
+
514
+ ### Arrow Labels
515
+
516
+ Arrows support an optional `label` string, rendered as a pill at the curve midpoint. Pass it at creation or double-click an arrow on the canvas to add or edit the label inline.
517
+
518
+ ```typescript
519
+ createArrow({ from: { x: 0, y: 0 }, to: { x: 200, y: 0 }, label: 'depends on' });
520
+ new NoteTool({ backgroundColor: '#fff9c4', size: { w: 200, h: 150 } });
521
+ new ImageTool({ size: { w: 400, h: 300 } });
522
+ ```
523
+
524
+ ## Element Types
525
+
526
+ All elements share a base shape:
527
+
528
+ ```typescript
529
+ interface BaseElement {
530
+ id: string;
531
+ type: string;
532
+ position: { x: number; y: number };
533
+ zIndex: number;
534
+ locked: boolean;
535
+ layerId: string;
536
+ }
537
+ ```
538
+
539
+ | Type | Key Fields |
540
+ | -------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
541
+ | `stroke` | `points: StrokePoint[]`, `color`, `width`, `opacity` |
542
+ | `note` | `size`, `text`, `backgroundColor`, `textColor` |
543
+ | `arrow` | `from`, `to`, `bend`, `color`, `width`, `fromBinding`, `toBinding` |
544
+ | `image` | `size`, `src` |
545
+ | `shape` | `size`, `shape` (`rectangle` \| `ellipse` \| `line`), `strokeColor`, `fillColor`, `flip` (`boolean` — which bbox diagonal a line runs along) |
546
+ | `text` | `size`, `text`, `fontSize`, `color`, `textAlign` |
547
+ | `grid` | `gridType` (`square` \| `hex`), `hexOrientation`, `cellSize`, `strokeColor`, `opacity` |
548
+ | `html` | `size` |
549
+
550
+ ## Styling the Selection
551
+
552
+ A normalized `ElementStyle` interface lets you read and apply visual properties across all element types through a single, consistent shape. The `SelectTool` emits a selection-change event; `Viewport` exposes four methods that together cover reactive UIs.
553
+
554
+ ### `ElementStyle` interface
555
+
556
+ ```typescript
557
+ interface ElementStyle {
558
+ color?: string; // stroke color / text color
559
+ fillColor?: string; // fill / background color
560
+ strokeWidth?: number; // line width in world-space units
561
+ opacity?: number; // 0–1
562
+ fontSize?: number; // px
563
+ }
564
+ ```
565
+
566
+ #### Mapping across element types
567
+
568
+ | `ElementStyle` field | `stroke` | `arrow` | `shape` | `note` | `text` |
569
+ | -------------------- | --------- | ------- | ------------- | ----------------- | ---------- |
570
+ | `color` | `color` | `color` | `strokeColor` | `textColor` | `color` |
571
+ | `fillColor` | | — | `fillColor` | `backgroundColor` | — |
572
+ | `strokeWidth` | `width` | `width` | `strokeWidth` | — | — |
573
+ | `opacity` | `opacity` | — | — | | |
574
+ | `fontSize` | — | — | — | (via toolbar) | `fontSize` |
575
+
576
+ ### Conversion helpers
577
+
578
+ ```typescript
579
+ import { styleToPatch, getElementStyle } from '@fieldnotes/core';
580
+
581
+ // ElementStyle element-specific patch object
582
+ const patch = styleToPatch(element, { color: '#e00', strokeWidth: 3 });
583
+ store.update(element.id, patch);
584
+
585
+ // element normalized ElementStyle
586
+ const style = getElementStyle(element);
587
+ ```
588
+
589
+ ### Viewport methods
590
+
591
+ - **`viewport.getSelectedIds()`** — returns the current selection as a referentially-stable array (the same array reference is reused across calls when the selection has not changed — safe for `useSyncExternalStore` equality checks).
592
+ - **`viewport.onSelectionChange(listener)`** — subscribes to selection changes; returns an unsubscribe function. The listener receives the new stable id array.
593
+ - **`viewport.getSelectionStyle()`** — returns an `ElementStyle` containing only the properties that are identical across every selected element. Properties that differ are omitted.
594
+ - **`viewport.applyStyleToSelection(style)`** — applies the given `ElementStyle` to all selected elements in a single undo step.
595
+
596
+ ### `SelectTool.onSelectionChange`
597
+
598
+ ```typescript
599
+ const selectTool = viewport.toolManager.getTool<SelectTool>('select');
600
+ selectTool?.onSelectionChange((ids) => {
601
+ console.log('selected:', ids);
602
+ });
603
+ ```
604
+
605
+ ### Example
606
+
607
+ ```typescript
608
+ // Apply a red stroke to everything currently selected — one undo step
609
+ viewport.applyStyleToSelection({ color: '#ff0000' });
610
+
611
+ // Read back the shared style for a UI color picker
612
+ const style = viewport.getSelectionStyle();
613
+ // style.color is defined only if all selected elements share the same color
614
+
615
+ // React to selection changes
616
+ const unsub = viewport.onSelectionChange((ids) => {
617
+ setSelectedIds(ids); // ids is referentially stable — safe for deps arrays
618
+ });
619
+ // call unsub() to unsubscribe
620
+ ```
621
+
622
+ ## Aligning the Selection
623
+
624
+ Two methods on `Viewport` let you snap or space selected elements in one undo step.
625
+
626
+ - **`viewport.alignSelection(edge)`** — `edge`: `AlignEdge` = `'left' | 'center-x' | 'right' | 'top' | 'middle' | 'bottom'`; aligns every selected element to the corresponding edge or center of the selection's bounding box. Needs 2+ selected elements. Locked elements anchor the bounding box without moving.
627
+ - **`viewport.distributeSelection(axis)`** — `axis`: `DistributeAxis` = `'horizontal' | 'vertical'`; evenly spaces selected elements' centers along the axis. Needs 3+ selected elements. Locked elements anchor the span without moving.
628
+
629
+ ```typescript
630
+ viewport.alignSelection('left'); // flush left edges
631
+ viewport.alignSelection('center-x'); // center on vertical axis
632
+ viewport.alignSelection('middle'); // center on horizontal axis
633
+ viewport.distributeSelection('horizontal'); // equal horizontal spacing
634
+ ```
635
+
636
+ Grids are ignored by both operations.
637
+
638
+ ## Smart Alignment Guides
639
+
640
+ Call `viewport.setSmartGuides(true)` to enable drag-time alignment snapping. While dragging a selection, its edges and centers snap to the edges and centers of nearby visible elements (within 6 screen pixels), and guide lines are drawn at each matched alignment. Smart guides replace grid snapping for the duration of the drag; the result is still committed as a single undo step.
641
+
642
+ ```typescript
643
+ viewport.setSmartGuides(true); // enable
644
+ viewport.setSmartGuides(false); // disable (default)
645
+ ```
646
+
647
+ ## Grouping
648
+
649
+ Group elements so they select, move, delete, z-order, and align as a single unit.
650
+
651
+ - **`viewport.groupSelection()`** — groups the current selection under a new id.
652
+ - **`viewport.ungroupSelection()`** — dissolves any groups in the current selection.
653
+
654
+ Each is one undo step. Selecting any member selects its whole group, so to edit a single member individually, ungroup first. Pasting or duplicating a group keeps the copies grouped under a fresh id.
655
+
656
+ ```typescript
657
+ viewport.groupSelection(); // Ctrl/Cmd+G
658
+ viewport.ungroupSelection(); // Ctrl/Cmd+Shift+G
659
+ ```
660
+
661
+ The shortcuts are rebindable as `group` and `ungroup`.
662
+
663
+ ## Rotation
664
+
665
+ Select a single element and a rotate handle appears above the selection box. Drag it to rotate the element about its center; hold **Shift** to snap to 15° increments. Notes, text, images, HTML embeds, shapes, and strokes can all be rotated.
666
+
667
+ Hit-testing, marquee selection, and resize are all rotation-aware: resizing a rotated element keeps the opposite corner fixed in the element's local frame. Rotation is reflected in PNG export and round-trips through serialization (`rotation?` on elements, stored in radians).
668
+
669
+ ## Context menu & lock
670
+
671
+ Right-click (desktop) or touch long-press (tablet) opens a context menu over the canvas with Cut/Copy/Paste/Duplicate/Delete, z-order (to front / forward / backward / to back), and Lock/Unlock. The menu is core-provided (plain DOM) and selects the element under the pointer if it isn't already selected. Opt out with `new Viewport(el, { contextMenu: false })`.
672
+
673
+ Lock with **`viewport.toggleLockSelection()`** or **Ctrl/Cmd+Shift+L**; a lock badge appears on the selection. Locked elements stay selectable but can't be moved, resized, or rotated. **Ctrl/Cmd+X** cuts the selection. The shortcuts are rebindable as `toggle-lock` and `cut`.
674
+
675
+ You can drive any menu action programmatically with **`viewport.runAction(name)`** (e.g. `'cut'`, `'paste'`, `'toggle-lock'`), and **`viewport.canPaste()`** reports whether the clipboard has content.
676
+
677
+ ## Built-in Interactions
678
+
679
+ | Input | Action |
680
+ | -------------------- | ------------------- |
681
+ | Scroll wheel | Zoom |
682
+ | Middle-click drag | Pan |
683
+ | Space + drag | Pan |
684
+ | Two-finger pinch | Zoom |
685
+ | Two-finger drag | Pan |
686
+ | Delete / Backspace | Remove selected |
687
+ | Ctrl+Z / Cmd+Z | Undo |
688
+ | Ctrl+Shift+Z / Cmd+Y | Redo |
689
+ | Double-click note | Edit text |
690
+ | Double-click HTML | Enter interact mode |
691
+ | Escape | Exit interact mode |
692
+
693
+ ## Browser Support
694
+
695
+ Works in all modern browsers supporting Pointer Events API and HTML5 Canvas.
696
+
697
+ ## Versioning
698
+
699
+ `@fieldnotes/core` and `@fieldnotes/react` are versioned independently. The react
700
+ package's `peerDependencies` declare the compatible core range. Pre-1.0, minor
701
+ versions may contain breaking changes. The core peer range is bounded at the next major rather than per-minor; if a core minor
702
+ ever breaks the wrapper, a coordinated react release raises the lower bound.
703
+
704
+ ## License
705
+
706
+ MIT