@niccolofanton/corkboard 0.1.0 → 0.2.1

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/CHANGELOG.md CHANGED
@@ -2,6 +2,107 @@
2
2
 
3
3
  All notable changes to this project are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project follows [Semantic Versioning](https://semver.org/).
4
4
 
5
+ ## [0.2.1]
6
+
7
+ ### Fixed
8
+
9
+ - A two-finger horizontal trackpad swipe could still trigger the browser's back/forward gesture. The host now sets `overscroll-behavior: none`, a live board holds `overscroll-behavior-x: none` on the page root (ref-counted across boards, restored on `dispose()`), and the embed "Done" button now consumes wheel events instead of only stopping them.
10
+
11
+ ## [0.2.0]
12
+
13
+ ### Breaking
14
+
15
+ - The root entry is a small designed API: `Corkboard`, `CorkboardError`, the themes, `DEFAULTS`, `MIN_SCALE`, `MAX_SCALE`, `parseEmbedUrl`, `normalizeEmbedUrl` and the types a host needs. `Stage`, `Store`, `Interaction`, the video and embed layers and the pure layout and snapping functions moved to `@niccolofanton/corkboard/unstable` (no semver guarantee).
16
+ - `board.store` and `board.stage` are private: use `getInternals(board)` from `/unstable`. `board.camera`, `board.layout`, `board.embeds` and `board.interaction` are typed as the interfaces `CameraApi`, `LayoutApi`, `EmbedsApi` (`live`, `interacting`, `info`, `interact`, `exitInteract`) and `InteractionApi` (`setPanMode`); `CameraApi` and `LayoutApi` are no longer classes.
17
+ - The `change` event is the net difference per card id: `added`, `removed` and `updated` never share an id (add then remove cancels, remove then add is one update, add then update is one add), `updated` is `{ el, prev, props }[]` (it was an array of cards; `props` compares each top-level field with `Object.is`), a batch with no net change emits nothing. It carries `source` (`'user' | 'api' | 'load' | 'system' | string`) and, when the draw order changed other than by an append, `order: { moved: { id, prevBelow, nextBelow }[] }`: anchors (the card directly below each moved card before and after), the minimal set of cards to take out and put back, not whole id lists. A removed card is in it, so an undo restores its depth.
18
+ - Removed from the root: `setVideo`, `setVideoPaused`, `playing`, `videoBudget` (now `board.video`), `setEmbeds` (`board.embeds.setOptions`), `clearSelection` (`select([])`), `arrangeTargets`, `CorkboardOptions.overlays` (`addOverlay` in `/unstable`), `DebugStats` (now `/unstable`, and `BoardStats.debug` is `@experimental`). `snapping` returns a copy.
19
+ - `screenRect(id)`, `bounds(ids?)` and `embeds.info(id)` return `undefined` when there is nothing to return (`bounds` no longer returns a unit rect on an empty board). A lookup miss is `undefined`; a "none right now" field is `null`.
20
+ - `camera.set` throws `'invalid'` for a non-finite `tx` / `ty` or a `scale` <= 0, and the `camera` option for anything but `0 < minScale <= maxScale` (no silent fallback).
21
+ - `stats()` returns a typed, grouped `BoardStats` (`textures`, `render`, `debug`, `embeds`, `video`) instead of a flat record; `embedsLive` / `embedsMaxLive` are `embeds.live` / `embeds.maxLive`, and the old timing series are `render.tickMs` / `cpuMs` / `gpuMs` percentiles.
22
+ - `all()` returns the cards in draw order, bottom first.
23
+ - `Card.media.thumbhash` (0.1: `Element`) is stored as a base64 string: `add`, `update` and `applyChange` convert a `Uint8Array`, so cards and `change` payloads are JSON-safe. `Card.media` is the new `CardMedia`; `CardMediaInput`, the input, still takes bytes or base64. `add` and `update` copy `media`.
24
+ - `interaction.commit: false` writes nothing to the board: no lift of the dragged card, no delete, no move. `transform` (with the new `toFront`) and `delete` are proposals for the host to apply (controlled mode, documented in the API reference). With `commit` on, `delete` fires after the removal.
25
+ - `update(id, { data: undefined })` with an own `data` key clears `data` (it used to keep it).
26
+ - `add` and `update` validate their input (0.1 stored whatever it got) and throw `CorkboardError('invalid')` (NaN, a size <= 0, a duplicate id, an embed with both or neither of `url` / `html`...); `loadSnapshot` and `applyChange` apply the same rules. Every method but `off` and the getters throws `CorkboardError('disposed')` after `dispose()`. `Corkboard.create` rejects with `CorkboardError('unsupported')` without WebGL2.
27
+ - A snippet frame that loads another document is given its `srcdoc` back; 3 such navigations within 10 s block the card (poster, `error` event, `embeds.info(id).blocked`) until its content changes. Best effort against accidents (a link clicked in interact mode), not a security boundary.
28
+ - The snippet preview cache is `corkboard-previews-v2`, keyed by SHA-256; opening the default cache deletes the v1 one. Persistent previews need `crypto.subtle` (otherwise memory only).
29
+ - The pure layout `ArrangeOpts` (`{ gap }`) is `ArrangeGapOptions`, so `ArrangeOptions` means one thing.
30
+ - Public types renamed, no aliases (the old `Element` and `MediaSource` shadowed the DOM globals in a consumer's module). The declarations (root and `/unstable`) show only the new names:
31
+
32
+ | 0.1 | 0.2 |
33
+ |---|---|
34
+ | `Element`, `ElementId`, `ElementInit`, `ElementPatch`, `ElementKind`, `ElementProp`, `ElementUpdate` | `Card`, `CardId`, `CardInit`, `CardPatch`, `CardKind`, `CardProp`, `CardUpdate` |
35
+ | `ElementMedia` (stored), `MediaSource` (input) | `CardMedia`, `CardMediaInput` |
36
+ | `SnapshotElement`, `SnapshotElementInput` | `SnapshotCard`, `SnapshotCardInput` |
37
+ | `CameraOptions` (`animate`, `padding` of `fit` / `zoomTo` / `center`) | `CameraMoveOptions`; the `camera` create option is typed `CameraRange` (new) |
38
+ | the inline `{ x, y, w, h }` of `screenRect` and `transform.rects` | `Box` (new, unit-neutral: screen px for `screenRect`, world px for `transform.rects`; `Rect` stays the world `{ x0, y0, x1, y1 }`) |
39
+ | `Box` of `/unstable` (`{ minX, minY, maxX, maxY }`, world px) | `Aabb` (frees `Box` for the root x/y/w/h type) |
40
+
41
+ - Every list of ids takes `CardId | readonly CardId[]`: `remove`, `bringToFront` and `sendToBack` already did; now `select`, `bounds`, `camera.fit` and every `board.layout` method do too. `setOrder` needs the full list as an array. A value of another type throws `CorkboardError('invalid')` (`board.select('id')` used to throw `ids.filter is not a function`).
42
+ - Options are validated, at `create` and in every setter, with `CorkboardError('invalid')` naming the option: `setTheme('blue')` (was a raw `TypeError`) and `create({ theme: 'blue' })` (was accepted), `video.setOptions({ maxPlaying: NaN })`, `embeds.setOptions({ maxLive: -1 })`, `textures.budgetBytes: -1`, enum values, booleans, a `Theme` with a missing field. Numbers must be finite and in range; `Infinity` only where "no cap" is documented (the `embeds` limits, `video.maxPlaying`). API reference: which options are create-only (`textures`, `cspSafe`, `nonce`, `gpuTimer`, `signal`, `interaction` on / off) and which can change later.
43
+ - `stats().embeds.maxLive` caps the new `stats().embeds.active` (active frames), not `live` (active + parked, as before); its documentation said otherwise. The demo HUD shows `active/maxLive`.
44
+ - `board.embeds.parked`, `culled`, `frozen`, `loading`, `animating`, `animatingBudget`, `maxLive`, `freezeThreshold` and `previewsPending` (members of the 0.1 layer object) are `board.stats().embeds.*` (counts; the id sets are in `getInternals(board).embeds`).
45
+
46
+ ### Added
47
+
48
+ - `CorkboardError` (`code`: `'disposed' | 'unsupported' | 'invalid'`) and `Corkboard.isSupported()`.
49
+ - Save and load (the board had none in 0.1): `getSnapshot({ camera? })` returns a `BoardSnapshot`, `loadSnapshot(snapshot, { camera? })` replaces the board with it (all or nothing, at most one `change` event with `source: 'load'`); `SNAPSHOT_VERSION`. A snapshot from a newer corkboard than the build reads is refused; `loadSnapshot` follows the change rules (same ids become updates, unchanged cards are not reported) and checks cards with the same rules as `add`. Snapshots share no object with the board (`media` is copied; `data` stays by reference).
50
+ - `batch(fn, { source? })`: one `change` event for everything `fn` does, tagged with `source` (the outermost named one wins; `'load'` wins over any). Library-initiated writes are `'system'`: skip them in an undo stack, do not broadcast them. If `fn` throws, its error is the one rethrown.
51
+ - Z-order: `bringToFront(ids)`, `sendToBack(ids)`, `setOrder(ids)`, and `change.order` so an undo can restore depth.
52
+ - `board.applyChange(change, { invert?, source?, conflict? })` and the pure `invertChange(change)`: undo, redo and sync from the `change` payload (the `Change` type), in one batch. Removals, exact upserts of added cards, raw field writes (no size derived from the media; `data` cleared), then the draw order from the anchors. Inverted changes skip fields edited since; sources `'apply'` and `'undo'`; `ChangeSource`, `OrderChange`, `OrderMove`, `CardMedia` and `BoardSnapshotInput` are exported. A fuzz test undoes and redoes random operation sequences, and keeps two boards in sync through JSON.
53
+ - Namespaces: `board.video` (`playing`, `budget`, `paused`, `setPaused`, `setOptions`), `board.embeds.setOptions`, `board.interaction.setOptions` (never alters a running gesture), `camera.setRange(min, max)`.
54
+ - `addOverlay(board, factory)` in `/unstable`: DOM overlays at any time after `create`, with a disposer.
55
+ - Argument checks on the whole API: `board.layout` options (`gap`, `width`, `columns`, `duration`...) and `align` / `distribute` modes, `camera.center` / `zoomBy` / `zoomTo` / `fit` / coordinate conversions, `inRect`, `setGrid`, `setSnapping` throw `'invalid'` for a NaN, a negative or a wrong type before anything moves (`layout.tidy(ids, { gap: NaN })` wrote NaN positions that `loadSnapshot(getSnapshot())` then rejected; `masonry({ width: -50 })` stored a negative width). Whatever writes a card (layout, a drag, a resize, the embed layer) refuses a NaN or infinite position, a rotation that is not finite and a size <= 0; a layout is all or nothing. A fuzz test runs random layout calls, with bad options too.
56
+ - Root types `CameraRange`, `CameraMoveOptions`, `Box`, `AlignMode`, `SnippetNetwork`, `PreviewCacheMode`, `TextureOptions` and `VideoApi`.
57
+ - A listener that throws (`change` or any other event) is reported with `console.error` and no longer stops the other listeners or the board's own bookkeeping; the public `change` goes out after the internal subscribers.
58
+ - Events: `error` (`BoardErrorEvent`: a picture, worker, video or embed that failed), `contextLost`, `contextRestored`, `render` (`{ cpuMs, gpuMs }` per rendered frame).
59
+ - Options: `signal` (cancel a pending `create`, for React StrictMode), `nonce` (for a nonce-based `style-src`; the injected styles are shared by the boards on a document and removed with the last one).
60
+ - Embed security options: `snippetNetwork` (`'images'` | `'none'`), `isolatedHosts`, `previewCache: { persistent: true, name }`; `Corkboard.clearPreviewCache(name?)`; `resolve` and `resolveTimeoutMs` through `embeds.setOptions`.
61
+ - `@niccolofanton/corkboard/unstable` and `getInternals(board)`.
62
+ - JSDoc on every public type, so IDE hovers work on the published declarations.
63
+ - A Playwright smoke test on real WebGL (`pnpm test:e2e`), and a CI matrix over the pinned and the latest Pixi 8.x.
64
+
65
+ ### Fixed
66
+
67
+ - A drag is ONE `change` event: the lift at drag start no longer writes to the store (the card is drawn on top while held, and the move and the bring-to-front are committed together on release; a cancelled drag writes nothing).
68
+ - `loadSnapshot` keeps the board's `data` object when the loaded one is structurally equal (as it already did for `media`): loading the same JSON twice emits nothing. A hand-written snapshot needs only `id`, `x`, `y`, `w`, `h` and `media`: `kind` and the rest default as in `add`. A `load` change carries `order` too, so undoing it restores the depth.
69
+ - The documented `embeds.info(id)?.poster` example did not compile (`ResolvedEmbed.posters` is an array); the docs now use the `embedResolved` event's `poster` or `posters[0]`.
70
+ - The decode worker's Blob is made when the first worker starts, not when the library is imported. Importing only `parseEmbedUrl` or the themes no longer pulls in the board or Pixi.
71
+ - The Pixi render group flag the texture retirement forces a batch rebuild with is only set when it exists; otherwise a child is added to and removed from the world.
72
+ - The texture upload uses Pixi's public API when the private members it leans on are missing (a Pixi minor renaming them).
73
+ - A dead decode worker no longer stalls its cards: its in-flight jobs move to the other workers, and with none left the failure is reported once.
74
+ - `Stage.create` honours the `signal` after each await and releases what it made; `Stage.dispose` runs every step even if one throws (the texture manager and the Pixi app are always released).
75
+ - A failed `Stage.create` or `Corkboard.create` gives everything back (canvas, GL context, ticker, workers, overlay root); a constructor step that fails no longer leaks the stage, and a dispose step that throws no longer skips the others.
76
+ - Pixi falling back to WebGPU, a 2D canvas or a WebGL1 context is a clear `'unsupported'` error.
77
+ - `Store.add` is all or nothing on a duplicate id; many updates to one card in a batch fold in linear time.
78
+ - The public texture-upload fallback (used when Pixi's private members are missing) wrote atlas cells and generated mipmaps on the active texture unit instead of the page's, so after a batch that used several units a card could show another card's picture. The page is now unbound and rebound on unit 0 before every upload; the e2e suite adds cards in rounds with different colours on both upload paths and checks every card's pixels.
79
+ - Moving the board in the DOM reloads a snippet's frame; that is detected by the iframe getting a new window and never counts as a navigation.
80
+ - `embeds.info(id)` returns `frameable: false, blocked: true` for a blocked snippet (new `ResolvedEmbed.blocked`), cleared when the card's content changes.
81
+ - `isolatedHosts` entries are normalised (host or URL, `*.` / leading dot, port, IDN, trailing dot, IPv6). IP literals match exactly and are never a suffix (`0.1` no longer isolates `127.0.0.1`). Entries that are not a host throw `CorkboardError('invalid')` from `create` / `setOptions`.
82
+ - The embed layer's automatic resize from a resolver's aspect is a `'system'` change.
83
+ - The generated placeholder of an HTML snippet is grey, without a glyph.
84
+ - A write made inside a `change` listener reaches the later listeners after the change that caused it, not before: `Store` and the board's emitter deliver one event at a time, in order, and queue what a listener emits (a listener forwarding changes to a peer used to see `[update, add]`).
85
+ - `applyChange` refuses a change that repeats an id in `added`, in `removed` or in `updated`, or has an id both added and removed, with `'invalid'` and nothing changed (it used to remove, emit, then throw). With `invert: true` the inverse is what is validated: the `removed` cards as whole cards and the `prev` values that would land; a malformed change is a `CorkboardError('invalid')`, never a `TypeError`.
86
+ - `deepEqual` (used to keep the board's own `media` / `data` objects) reads own keys only, so `{}` and `{ constructor: 'x' }` differ (`loadSnapshot` dropped such a `data` key), and compares shared or self-referencing values in time linear in their size.
87
+ - `media.thumbhash` validation rejects padded base64 that does not decode (`"AA="`, `"AAA=="`).
88
+ - A card added while a drag holds others draws below them (it used to share the held card's rank). Disposing the interaction layer, or `loadSnapshot`, during a drag cancels it: no stale lift or pin, and the release no longer writes the old position over the loaded board.
89
+ - Removing many cards one id at a time in one `batch` no longer costs a pass over the whole draw order each (50k cards, 3k removals: 2.6 s to 0.02 s).
90
+
91
+ ### Docs and tooling
92
+
93
+ - The 0.1.0 entry and the README claimed a rotate gesture; there is none (`rot` is data only).
94
+ - API reference: a navigating snippet gets its `srcdoc` back and is blocked after 3 strikes in 10 s (it said "destroyed on the first reload"); the migration guide lists only what 0.1 had; the Overlays section describes `addOverlay` for DOM synced to the camera instead of pointing at `src/`; migration rows for the `board.embeds.*` counters and the type renames. The demo's version badge is read from `package.json`.
95
+ - HTML-EMBEDS: Security section rewritten (navigation guard, `csp` attribute, advisory `snippetNetwork`, separate-origin isolation as future work).
96
+ - Release hygiene: `test:e2e` always builds a separate e2e bundle (`dist-e2e`) first. The test hook `__corkboardForcePublicUpload` is compiled out of the published bundle (`__CORKBOARD_TEST__`) and no longer declared as a `global` in the published types (it was a local cast already); `check:package` fails if either the `.js` or the `.d.ts` files carry it. `prepublishOnly` also runs `check:package` and the e2e suite. The CI e2e job runs on Chromium and Firefox, with both Pixi versions.
97
+
98
+ ### Security
99
+
100
+ - Snippets: `snippetNetwork: 'none'` is best effort. It blocks subresource requests (images, fonts, `fetch`...), but a snippet can still navigate its own frame (`location.href = 'https://x/?…'`) and that request always leaves; `'none'` is advisory. On engines other than Chromium a hostile snippet can run another page in its frame, outside the snippet CSP; only serving snippets from a separate origin would isolate them (future work). Snapshot replies over 2 MB are dropped.
101
+ - Snippets: in Chromium the iframe carries the snippet CSP in its `csp` attribute (Embedded Enforcement), so a page a snippet navigates to is not run unless it sends `Allow-CSP-From`.
102
+ - `isolatedHosts` removes `allow-same-origin` for chosen hosts. The same-origin guard (this one and the own-origin one) looks only at the URL a frame starts with: a redirect or a link followed in interact mode can leave it.
103
+ - The persistent preview cache key is a SHA-256 (it was a 64-bit hash).
104
+ - Documented: a `srcdoc` snippet inherits the host page's CSP; `worker-src blob:` / `textures.workerUrl`, `cspSafe` and `nonce` cover a strict CSP.
105
+
5
106
  ## [0.1.0]
6
107
 
7
108
  First release, published as `@niccolofanton/corkboard`.
@@ -14,7 +115,7 @@ First release, published as `@niccolofanton/corkboard`.
14
115
  - Video cards: a WebGL poster plus a `<video>` element synced to the camera, with a play pool (`always` / `hover` / `off`) that adapts to the frame rate.
15
116
  - Embed cards for YouTube, Vimeo, Spotify, CodePen, Figma, any page or a snippet of HTML: a poster sprite that becomes a sandboxed iframe at a virtual 720p / 1080p screen, with live / parked / culled lifecycle, runtime posters and snapshots.
16
117
  - Auto layout (masonry, tidy grid, align, distribute, equal width) with animated transitions.
17
- - Interaction: selection and marquee, drag, resize and rotate, smart-guide and dot-grid snapping, keyboard shortcuts, hand tool.
118
+ - Interaction: selection and marquee, drag and resize, smart-guide and dot-grid snapping, keyboard shortcuts, hand tool.
18
119
  - Typed events (`selection`, `hover`, `click`, `dblclick`, `transform`, `gesture`, `delete`, `change`, `camera`, `cameraSettled`, `embedInteract`, `embedLive`, `embedResolved`) and a `stats()` API.
19
120
  - Extension points: custom element kinds (views and DOM overlays), light / dark theme, optional CSP-safe mode.
20
121
  - Single bundled `dist/index.d.ts` that resolves under `node16`, `nodenext` and `bundler` module resolution.
package/README.md CHANGED
@@ -1,12 +1,23 @@
1
1
  # Corkboard
2
2
 
3
+ [![npm](https://img.shields.io/npm/v/@niccolofanton/corkboard)](https://www.npmjs.com/package/@niccolofanton/corkboard)
4
+ [![CI](https://github.com/niccolofanton/corkboard/actions/workflows/ci.yml/badge.svg)](https://github.com/niccolofanton/corkboard/actions/workflows/ci.yml)
5
+ [![license](https://img.shields.io/npm/l/@niccolofanton/corkboard)](LICENSE)
6
+
3
7
  ![Corkboard](docs/preview.gif)
4
8
 
5
- Corkboard is a framework-agnostic TypeScript library that puts an infinite WebGL canvas of image, video and embed cards on screen, built on Pixi v8 and extracted from a moodboard app. It is meant for large boards on an ordinary laptop, so most of the work is in not doing work: the render loop is on demand and sits at 0 requestAnimationFrame callbacks while nothing moves, and an rbush index culls cards outside the view.
9
+ An infinite WebGL canvas of image, video and embed cards, built on Pixi v8. Framework-agnostic TypeScript, made for
10
+ boards of thousands of cards on an ordinary laptop.
6
11
 
7
- Pictures go through a level-of-detail pipeline that starts at a ThumbHash, moves to a shared atlas, and ends in per-card textures with baked rounded corners, all decoded in workers and kept under an LRU memory budget. A video card is its poster in WebGL plus a `<video>` element synced to the camera; an embed (YouTube, Vimeo, Spotify, CodePen, Figma, any page or a snippet of HTML) is a poster sprite that becomes a sandboxed iframe, laid out at a virtual 720p or 1080p screen and scaled down, only when it is large on screen or selected. Auto layout (masonry, tidy grid, align, distribute) animates cards to their new places, and dragging snaps to smart guides or to the dot grid.
12
+ - **Fast by not working:** on-demand render loop (idle at 0 rAF callbacks), viewport culling, level-of-detail textures
13
+ decoded in workers under a memory budget.
14
+ - **Video and embeds:** videos play over their WebGL poster; YouTube, Vimeo, Spotify, CodePen, Figma, any page or a
15
+ snippet of HTML become sandboxed live iframes, loaded in chunks, frozen to a snapshot when too small to read.
16
+ - **Layout and editing:** masonry, tidy grid, align and distribute with animated transitions; selection, drag, resize,
17
+ smart guides and grid snapping.
18
+ - **Production bits:** `getSnapshot()` / `loadSnapshot()`, net-diff `change` events with a draw order, `applyChange` / `invertChange` for undo, redo and sync, a typed `error` event, `Corkboard.isSupported()`.
8
19
 
9
- **Live: [corkboard.niccolofanton.dev](https://corkboard.niccolofanton.dev)**
20
+ **Live demo: [corkboard.niccolofanton.dev](https://corkboard.niccolofanton.dev)**
10
21
 
11
22
  ## Install
12
23
 
@@ -14,11 +25,7 @@ Pictures go through a level-of-detail pipeline that starts at a ThumbHash, moves
14
25
  npm i @niccolofanton/corkboard pixi.js
15
26
  ```
16
27
 
17
- `pixi.js` (^8.22.0) is a peer dependency: one copy, shared with your app. The package is ESM-only (`import`, no
18
- `require`), ships its own TypeScript declarations, and is tree-shakeable (`sideEffects: false`).
19
-
20
- Browser support: any browser with WebGL2. Snapshots of HTML embeds (see [Embeds](#embeds)) are not available in Safari,
21
- where the frame simply stays live.
28
+ `pixi.js` ^8.22.0 is a peer dependency. ESM only, types included. Needs WebGL2.
22
29
 
23
30
  ## Quick start
24
31
 
@@ -30,6 +37,8 @@ async function main(): Promise<void> {
30
37
  board.add([
31
38
  { media: { src: 'https://picsum.photos/seed/1/480/600', aspect: 1.25 } },
32
39
  { media: { src: 'https://picsum.photos/seed/2/480/270', video: 'https://example.com/clip.mp4' } },
40
+ { media: { embed: { url: 'https://youtu.be/dQw4w9WgXcQ' } } },
41
+ { media: { embed: { html: '<button onclick="this.textContent++">0</button>' } } },
33
42
  ]);
34
43
  board.layout.tidy();
35
44
  board.camera.fit();
@@ -38,147 +47,49 @@ async function main(): Promise<void> {
38
47
  void main();
39
48
  ```
40
49
 
41
- `Corkboard.create` is async (it starts the WebGL renderer). A top-level `await` works too where your build target allows it
42
- (Vite's default target does not: set `build.target: 'es2022'`).
43
-
44
- Pictures are read by a decode worker with `fetch`, so they need CORS headers. Videos only need to be playable by `<video>`.
45
-
46
- ## Bundlers & CSP
47
-
48
- The decode worker is inlined in the library and started from a blob URL, so it works under any bundler or dev server (no
49
- asset URL to resolve, no `optimizeDeps` setting). A page whose CSP has no `worker-src blob:` (or `child-src blob:` /
50
- `script-src blob:` as the fallback) can serve the worker itself instead: the package exports it as
51
- `@niccolofanton/corkboard/decode.worker.js`. Pass its URL as `textures.workerUrl`:
52
-
53
- ```ts
54
- import workerUrl from '@niccolofanton/corkboard/decode.worker.js?url'; // Vite (types from vite/client); any bundler that gives you the file's URL
55
- await Corkboard.create(el, { textures: { workerUrl } });
50
+ - Pictures are fetched by a worker, so they need CORS headers.
51
+ - `Corkboard.create` is async; a top-level `await` also works if your build target allows it (Vite: `build.target: 'es2022'`).
52
+ - Embeds don't take pointer events: double-click (or Enter) to interact, Esc to leave. A known provider needs no setup;
53
+ for titles, thumbnails and framing checks of other pages, pass `embeds.resolve` (see the [API reference](docs/API.md#embeds)).
54
+
55
+ ## React
56
+
57
+ ```tsx
58
+ useEffect(() => {
59
+ const ctl = new AbortController(); // cancels a create() that StrictMode unmounts mid-flight
60
+ let board: Corkboard | undefined;
61
+ Corkboard.create(ref.current!, { signal: ctl.signal })
62
+ .then((b) => (board = b))
63
+ .catch((e) => { if (!ctl.signal.aborted) console.error(e); });
64
+ return () => { ctl.abort(); board?.dispose(); };
65
+ }, []);
56
66
  ```
57
67
 
58
- For a CSP without `unsafe-eval`, also pass `cspSafe: true` (Pixi's `unsafe-eval` build).
59
-
60
- ## API
61
-
62
- - `Corkboard.create(host, options)`: `theme`, `grid`, `snapping`, `interaction`, `video`, `embeds`, `textures`, `overlays`, `camera`, `cspSafe`.
63
- - Cards: `add(init | init[])`, `update(id, patch)`, `remove(ids)`, `clear()`, `get(id)`, `all()`, `size`, `inRect(rect)`, `bounds(ids?)`.
64
- - Selection: `selection`, `select(ids)`, `selectAll()`, `clearSelection()`.
65
- - `board.layout`: `tidy(ids?, opts)`, `masonry(ids?, opts)`, `align(mode, ids?)`, `distribute(axis, ids?)`, `equalWidth(ids?)`.
66
- - `board.camera`: `get()`, `set(cam)`, `fit(ids?)`, `zoomTo(rect)`, `zoomBy(k)`, `actual()`, `center(x, y, scale?)`, `visible()`, `screenToWorld`, `worldToScreen`.
67
- - Settings: `setTheme`, `setGrid`, `setSnapping({ guides, grid })`, `setVideo({ mode: 'always' | 'hover' | 'off', loop, muted, minPlayPx, maxPlaying, maxPlayingTouch })`, `setVideoPaused`, `setEmbeds({ maxLive, maxLiveTouch, maxMounted, maxOffscreen, cullMargin, minLivePx, minLiveScale, maxLoading, freezePx, maxAnimating, adaptive, resolution, arbitrarySameOrigin, autoplay, previewWorkers, previewCache })`.
68
- - Events (`board.on(type, fn)` returns an unsubscribe): `selection`, `hover`, `click`, `dblclick`, `transform`, `gesture`, `delete`, `change`, `camera`, `cameraSettled`, `embedInteract`, `embedLive`, `embedResolved`.
69
- - `stats()`, `dispose()`. The pure layout and snapping functions, `Store`, `Stage` and `Interaction` are exported too.
70
-
71
- - `textures`: `budgetBytes`, `workers`, `workerUrl`, `uploadBudgetMs`, `overscan`, `softCanvas`.
72
- - `camera`: `minScale`, `maxScale` (default 0.05..4). A board much wider than the screen that must fit whole needs a lower minimum.
73
- - `interaction`: `select`, `emptyDrag`, `keyboard`, `commit`, and for a host that draws its own chrome `marquee: false` (a drag
74
- on empty canvas always pans), `keepSelectionOnPan` (a pan keeps the selection, a click that does not move clears it) and
75
- `selectionOutline: false` (the canvas draws no selection outline or handles). `board.interaction.setPanMode(true)` is a hand
76
- tool: a left-button drag pans from anywhere, over a card included, like holding Space.
77
- - `video` (`mode: 'always'`): a card plays on its own only if its long side is at least `minPlayPx` CSS px on screen
78
- (default 160), and at most `maxPlaying` play at once (default 8; `maxPlayingTouch`, default 2, on touch), the biggest and
79
- most central first. Smaller or surplus cards stay a thumbnail, so a zoomed-out board opens no streams. The pool shares the
80
- frame budget of the embeds: a slow window (under 40 fps) cuts the cap to 60% of what plays (at least 1, the most visible
81
- clips keep playing) and two smooth ones in a row give 50% back, up to `maxPlaying`. `board.videoBudget` is the cap now.
82
- - `camera.fit()` on a host that has no size yet (hidden tab, pane not laid out) waits for the first real size and then
83
- centres, unless the camera was moved meanwhile.
84
- - Keyboard shortcuts act only while the board itself has focus, never for keys typed in an `<input>` inside the host.
85
-
86
- A card is `{ media: { src, video?, sizes?, aspect?, thumbhash?, color? }, x?, y?, w?, h?, rot?, radius?, locked?, aspectLocked?, data? }`.
87
- Cards with no `x` / `y` are placed on a free spot near what is on screen (a given `x` or `y` alone is kept, and an embed
88
- without `w` is 400 wide).
89
-
90
- ## Embeds
68
+ ## Strict CSP
69
+
70
+ - `worker-src blob:`, or serve the bundled worker and pass `textures.workerUrl` (below).
71
+ - No `unsafe-eval`: `cspSafe: true`. Nonce-based `style-src`: `nonce`.
72
+ - `img-src data: blob:` for snapshots and previews. HTML snippets (`srcdoc`) inherit the page's CSP.
91
73
 
92
74
  ```ts
93
- const board = await Corkboard.create(el, {
94
- embeds: { maxLive: 12, resolve: async (url) => (await fetch(`/api/embed?url=${url}`)).json() },
95
- });
96
- board.add({ media: { embed: { url: 'https://youtu.be/dQw4w9WgXcQ' } } }); // nothing else to set up
97
- board.add({ media: { embed: { url: 'https://example.com/post', title: 'A post' }, aspect: 0.75 } });
98
- board.add({ media: { embed: { html: '<button onclick="this.textContent=1">0</button>' } } }); // a snippet
75
+ import workerUrl from '@niccolofanton/corkboard/decode.worker.js?url'; // Vite; any bundler that gives you a file URL
76
+ await Corkboard.create(el, { textures: { workerUrl }, cspSafe: true, nonce });
99
77
  ```
100
78
 
101
- - `media.embed` is `{ url }` or `{ html }` (+ `title`). `media.aspect` is height / width, as everywhere; a known provider has its own.
102
- `media.src` is the poster: leave it out and the board resolves one (the card is a textured sprite like any other).
103
- What the board generates (tile, fetched thumbnail, snapshot, preview) is a runtime picture on the stage
104
- (`stage.setPosterOverride`), never written to your store: no `change` event, nothing dead to save, and swapping one poster
105
- for another keeps the old one on screen until the new one has decoded (no flash of the placeholder).
106
- - Poster, first hit wins: your `src`; `embeds.resolve(url)` (`{ poster?, iframeSrc?, aspect?, title?, frameable? }`); YouTube
107
- thumbnails; a generated tile (host, title, glyph, themed). oEmbed titles / thumbnails, `og:image`, screenshots and
108
- `X-Frame-Options` probing need a server: do them behind `resolve` and cache the result. `frameable: false` makes a bookmark
109
- card (never live, a double-click opens the URL in a new tab).
110
- - Live iframe: any card in view (`minLivePx` and `minLiveScale` are opt-in floors, 0 by default) or selected, camera still, at
111
- most `maxLive` at once (12, or 3 on touch), the biggest on screen first. Frames mount in chunks (`maxLoading`, default 6, at a
112
- time, nearest the centre first). It is laid out at world size and moved with the camera as one CSS matrix. A frame that stops
113
- qualifying is parked (inert, still showing its last frame) rather than destroyed; `maxMounted` frames (24, or 6 on touch) stay
114
- in all, and the least valuable parked ones are destroyed past that.
115
- - Culling: a mounted iframe whose card leaves the view (plus a `cullMargin` of 50 % of the viewport on each side) is hidden at
116
- once (`display: none`, so it stops rendering but keeps its state) and shows again the moment the card returns. A loaded
117
- snippet is snapshotted on the way out so its last frame is the poster. At most `maxOffscreen` hidden frames are kept (64, or
118
- 12 on touch), the most recently seen first; the rest are destroyed when the camera settles.
119
- - Freezing: a mounted frame whose card gets smaller than `freezePx` on screen (default 140 CSS px, short side; 0 turns it
120
- off; raised up to 4x while the page stays slow with the animating budget at its floor, `board.embeds.freezeThreshold`) and is not selected or in interact mode stops costing anything. A snippet is asked (by a small script injected ahead
121
- of its HTML) for a snapshot of its own document, current animation state included; that image becomes the card's poster
122
- and the frame is hidden (`display: none`, alive, so it resumes where it was). A YouTube or Vimeo player is paused through
123
- its postMessage API (it keeps showing the current video frame) and played again afterwards. Both come back above 1.4x
124
- `freezePx`, when selected, or on interact. Parked and culled snippets are paused (animations and `requestAnimationFrame`),
125
- parked and culled videos too. A snapshot that fails (a tainted canvas, Safari) leaves the frame live. `board.embeds.frozen`.
126
- - Animating budget: of the mounted frames that are on screen, not parked, culled or frozen, the ones that can be paused
127
- (snippets, YouTube / Vimeo players that may be playing) are ranked (interacting, selected, biggest on screen, nearest the
128
- centre) and only the first N animate; the rest are paused and keep showing their last frame. Mounting is not affected.
129
- `maxAnimating` is the ceiling (default `Infinity`); with `adaptive` (default `true`) the board's frame-rate monitor lowers N
130
- to 70% of what animates (min 6) after a second under 40 fps and raises it by a quarter + 2 after two seconds in a row over
131
- 55 fps, up to the ceiling. The monitor does not run a rAF loop all the time: it samples in short bursts (4 one-second
132
- windows at most, or until two in a row agree) started by anything that can change the load (camera settled, frames mounted,
133
- destroyed, frozen or thawed, a budget moved) and by a 10 s heartbeat while something renders in a visible tab, then stops so
134
- the page can idle. Pages that cannot be paused (plain URLs, Spotify, CodePen, Figma) take no slot. `board.embeds.animating`,
135
- `board.embeds.animatingBudget`.
136
- - Previews: an HTML snippet card that has not been live shows a generated tile until `embeds.previewWorkers` hidden frames
137
- (default 3, 0 turns it off) render it in the background (nearest the view first, camera still, 400 ms in) and its poster
138
- becomes a real picture of the snippet. They take no live or loading slot. Pictures are cached by a hash of the snippet,
139
- in memory and, with `embeds.previewCache: 'persistent'` (opt-in, default `'memory'`: it leaves pictures of the snippets on the
140
- visitor's disk), in Cache Storage (at most 1000, the oldest dropped first) so a reload shows them at once.
141
- `board.embeds.previewsPending`.
142
- - Resolution: a live page is laid out at a virtual screen with the card's aspect, then scaled onto the card, so it shows
143
- its desktop layout at any card size. `embeds.resolution` is `'720p'` (default: short side 720 CSS px, a 16:9 card is a
144
- 1280 x 720 page), `'1080p'` (1920 x 1080), a number (the short side) or `'native'` (the card's world size: a 400 px card
145
- is a 400 px wide page). `media.embed.resolution` overrides it per card; `setEmbeds({ resolution })` changes it live.
146
- - It does not take pointer events: pan, zoom, select and drag work over it. Double-click (or Enter on a selected card) enters
147
- interact mode; Done, Esc or a click outside ends it (`embedInteract`). Keys and wheel inside a cross-origin frame never reach
148
- the page.
149
- - Sandbox, computed at render time and never stored: allowlisted providers get `allow-scripts allow-same-origin allow-forms
150
- allow-popups allow-presentation`; other URLs the same minus `allow-presentation`; snippets run in `srcdoc` with `allow-scripts`
151
- only plus a CSP (no network). Only http(s) URLs load. A snippet has no storage and cannot reach the page.
152
- The allowlist is the exact embed URLs the built-in parsers emit (`youtube-nocookie.com/embed/`, `player.vimeo.com/video/`,
153
- `open.spotify.com/embed/`, `codepen.io/<user>/embed/`, `figma.com/embed`), not whole hosts.
154
- - Arbitrary URLs keep `allow-same-origin` because many sites break without their own cookies and storage. The risk: the
155
- sandbox flags survive navigation inside the frame, so a link followed in interact mode loads the next site with scripts
156
- and its real origin (it still cannot reach your page; a frame on your own origin never gets the flag). To give those frames
157
- an opaque origin instead, pass `embeds: { arbitrarySameOrigin: false }` (also `setEmbeds`).
158
- - A `blob:` `media.src` on an embed card (an old saved board) is treated as absent, since it died with its page: a fresh poster
159
- is made for it and `embedResolved.poster` never reports a blob. A host's https / data: `media.src` stays the poster of a
160
- tile or fetched thumbnail; a snapshot or preview of a snippet, which is the real picture, goes over it. Neither is written
161
- to `media.src`. Persist `embedResolved.poster` (an https URL), not blobs, when you save a board.
162
- - Live state: `board.embeds.live`, `board.embeds.interacting`, `board.embeds.interact(id)`, `board.embeds.info(id)`.
163
-
164
- ## Adding an element kind
165
-
166
- `ElementKind` (`src/types.ts`) is a union. A new kind is one view in `src/render/views/registry.ts` and, if it needs live DOM,
167
- one `Overlay` (`src/overlay.ts`) passed through `options.overlays`.
168
-
169
79
  ## Docs
170
80
 
171
- - [docs/HANDOFF.md](docs/HANDOFF.md): how the renderer works (stage, culling, LOD textures, atlas, video, layout, snapping, perf budget, lessons learned).
172
- - [docs/HTML-EMBEDS.md](docs/HTML-EMBEDS.md): research on HTML / iframe cards in a WebGL canvas and the design chosen.
81
+ - [API reference](docs/API.md): methods, options, events, errors, embeds, migrating from 0.1.
82
+ - [HTML embeds](docs/HTML-EMBEDS.md): how embeds are loaded, culled, frozen and paused (§11), and the research behind it.
83
+ - [Renderer handoff](docs/HANDOFF.md): stage, culling, LOD textures, atlas, video, layout, snapping, performance.
84
+ - `@niccolofanton/corkboard/unstable`: the building blocks (stage, store, layout and snapping functions, `getInternals`), no semver guarantee.
173
85
 
174
86
  ## Development
175
87
 
176
88
  ```sh
177
- pnpm install # pnpm 10.11.1 (see packageManager); pixi.js is a devDependency here
178
- pnpm dev # the demo (600 cards)
89
+ pnpm install
90
+ pnpm dev # demo
179
91
  pnpm test
180
- pnpm typecheck
181
- pnpm build # dist/: library, bundled index.d.ts, decode.worker.js
92
+ pnpm build # dist/: library, bundled types, decode worker
182
93
  ```
183
94
 
184
95
  ## License