@daasboard/embed 0.0.0-stage → 0.1.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/LICENSE +5 -0
- package/README.md +971 -2
- package/THIRD_PARTY_NOTICES.md +32 -0
- package/dist/assets/assetServiceStore.d.ts +51 -0
- package/dist/assets/assetServiceStore.js +658 -0
- package/dist/assets/clipboardAssets.d.ts +6 -0
- package/dist/assets/clipboardAssets.js +23 -0
- package/dist/boardUi.d.ts +34 -0
- package/dist/boardUi.js +122 -0
- package/dist/builtins.d.ts +19 -0
- package/dist/builtins.js +198 -0
- package/dist/contextMenu.d.ts +24 -0
- package/dist/contextMenu.js +114 -0
- package/dist/coordinates.d.ts +11 -0
- package/dist/coordinates.js +30 -0
- package/dist/createBoard.d.ts +2 -0
- package/dist/createBoard.js +1333 -0
- package/dist/document.d.ts +7 -0
- package/dist/document.js +86 -0
- package/dist/images/BoardImages.d.ts +53 -0
- package/dist/images/BoardImages.js +241 -0
- package/dist/images/preprocess.d.ts +27 -0
- package/dist/images/preprocess.js +196 -0
- package/dist/images/types.d.ts +90 -0
- package/dist/images/types.js +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +4 -0
- package/dist/types.d.ts +49 -0
- package/dist/types.js +1 -0
- package/dist/uiHost.d.ts +42 -0
- package/dist/uiHost.js +273 -0
- package/package.json +33 -3
package/README.md
CHANGED
|
@@ -1,3 +1,972 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @daasboard/embed
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`@daasboard/embed` mounts the renderer, editor and built-in UI inside an element in your application.
|
|
4
|
+
|
|
5
|
+
## Install from npm
|
|
6
|
+
|
|
7
|
+
Install one exact release across the packages your application uses (replace `<release>` with the owner's published version):
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
pnpm add --save-exact @daasboard/embed@<release> @daasboard/doc@<release> @daasboard/fonts@<release>
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
The embed installs its matching render-core, editor and UI dependencies. Add those packages directly at the same version only when your host imports them. Packages expose only their root index; internal source paths are not public entry points. They contain ES modules and TypeScript declarations. Node hosts and deployment scripts require Node 22.3 or later; the CanvasKit loader uses `process.getBuiltinModule`, introduced in Node 20.16 and 22.3. Public availability grants no license; see `LICENSE`.
|
|
14
|
+
|
|
15
|
+
Binary assets are separate from JavaScript. As a deployment step, copy the installed `@daasboard/fonts` directory into your public assets while preserving its relative paths, coverage manifests and OFL notices. Copy `canvaskit-wasm/bin/canvaskit.wasm` from the dependency resolved by `@daasboard/render-core`, then set `assets.canvasKitWasm` to its served URL. Use the exact binaries installed with the packages, never a CDN's latest build. With pnpm's strict dependency layout, a Node deployment script can locate them through their owning package:
|
|
16
|
+
|
|
17
|
+
```js
|
|
18
|
+
import { createRequire } from "node:module";
|
|
19
|
+
import { dirname, join } from "node:path";
|
|
20
|
+
import { cp, mkdir } from "node:fs/promises";
|
|
21
|
+
|
|
22
|
+
const host = createRequire(import.meta.url);
|
|
23
|
+
const embed = createRequire(host.resolve("@daasboard/embed"));
|
|
24
|
+
const render = createRequire(embed.resolve("@daasboard/render-core"));
|
|
25
|
+
const doc = createRequire(host.resolve("@daasboard/doc"));
|
|
26
|
+
await mkdir("public/assets", { recursive: true });
|
|
27
|
+
await cp(render.resolve("canvaskit-wasm/bin/canvaskit.wasm"),
|
|
28
|
+
"public/assets/canvaskit.wasm");
|
|
29
|
+
await cp(dirname(host.resolve("@daasboard/fonts/package.json")),
|
|
30
|
+
"public/assets/fonts", { recursive: true });
|
|
31
|
+
const loroBrowserWasm = join(dirname(dirname(doc.resolve("loro-crdt"))),
|
|
32
|
+
"browser", "loro_wasm_bg.wasm");
|
|
33
|
+
// The production bundler emits this matching Loro binary itself; do not rename
|
|
34
|
+
// its emitted URL. Deploy its wasm asset beside the emitted JavaScript.
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
The `createRequire` calls above locate files; import the packages themselves as ES modules.
|
|
38
|
+
|
|
39
|
+
A Vite host sets `assetsInclude: ["**/*.wasm"]` and builds for `es2022`; deploy Vite's emitted `loro_wasm_bg-*.wasm` alongside its JavaScript. Its production build retains Loro's browser entry, which loads wasm synchronously at import time, even for a `MemoryDocument`. webpack can remove unused Loro code from a `MemoryDocument` host. Serving the matching Loro wasm is the safe deployment instruction across bundlers. The `assets` option does not configure it. In plain Node, Loro loads its matching wasm from its installed package.
|
|
40
|
+
|
|
41
|
+
For Next.js 16, mount the board only in the browser: dynamically `import()` the packages inside an
|
|
42
|
+
effect, or use `next/dynamic` with `ssr: false` from a client component. A `"use client"` directive alone
|
|
43
|
+
does not prevent prerendering a static import; Loro's Node entry reads its wasm during import.
|
|
44
|
+
|
|
45
|
+
Both webpack and Turbopack need browser stubs for CanvasKit's Node-only `fs` and `path` branches.
|
|
46
|
+
For webpack, add `resolve.fallback: { fs: false, path: false }` only in client builds. For Turbopack,
|
|
47
|
+
use browser-only `resolveAlias` entries pointing to an empty module:
|
|
48
|
+
|
|
49
|
+
```js
|
|
50
|
+
// next.config.mjs
|
|
51
|
+
export default {
|
|
52
|
+
webpack(config, { isServer }) {
|
|
53
|
+
if (!isServer) {
|
|
54
|
+
config.resolve.fallback = { ...config.resolve.fallback, fs: false, path: false };
|
|
55
|
+
}
|
|
56
|
+
return config;
|
|
57
|
+
},
|
|
58
|
+
turbopack: {
|
|
59
|
+
resolveAlias: {
|
|
60
|
+
fs: { browser: "./empty.js" },
|
|
61
|
+
path: { browser: "./empty.js" },
|
|
62
|
+
},
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Create `empty.js` next to that config with `export default {};`. Keep the aliases limited to browser builds
|
|
68
|
+
so server rendering can use Node's real modules.
|
|
69
|
+
|
|
70
|
+
Use a versioned public font path and map both font and coverage files without changing their contents:
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
const fontUrl = (file: string, sha256: string) =>
|
|
74
|
+
`/assets/fonts/${file}?sha256=${sha256}`;
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
The SHA-256 verifies the fetched bytes and can also be used as an immutable cache key. Keep `THIRD_PARTY_NOTICES.md` and the installed dependencies' notices with redistributed bundles.
|
|
78
|
+
|
|
79
|
+
```ts
|
|
80
|
+
import { createBoard } from "@daasboard/embed";
|
|
81
|
+
import { LoroPageDoc } from "@daasboard/doc";
|
|
82
|
+
|
|
83
|
+
const page = LoroPageDoc.create(); // The application owns this adapter and any synchronization.
|
|
84
|
+
const board = await createBoard({
|
|
85
|
+
container: document.getElementById("board")!, // Give it an explicit CSS width and height.
|
|
86
|
+
document: page,
|
|
87
|
+
assets: {
|
|
88
|
+
canvasKitWasm: "/assets/canvaskit.wasm",
|
|
89
|
+
fontUrl: (file) => `/assets/fonts/${file}`,
|
|
90
|
+
},
|
|
91
|
+
ui: true,
|
|
92
|
+
readOnly: false,
|
|
93
|
+
});
|
|
94
|
+
board.focus();
|
|
95
|
+
// When the host unmounts:
|
|
96
|
+
board.dispose();
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
`createBoard(options)` resolves once CanvasKit is ready, the default Inter regular load attempt has
|
|
100
|
+
settled, the host's declared font faces have loaded, and the host wiring is ready. The default font
|
|
101
|
+
registry permits a failed Inter attempt to settle; a failed declared face rejects the mount.
|
|
102
|
+
The handle exposes `focus()`, `dispose()`, `clipboard`, `controller` as
|
|
103
|
+
`UiController`, `tools` as `UiTools`, `camera` with `zoom()`, `zoomTo()` and `onChange()`, and `ui`, the built-in
|
|
104
|
+
UI (below). These are the same narrowed, guarded services given to the built-in UI. The controller's `targets()`
|
|
105
|
+
and `subscribe()` report selection changes. A host with `ui: false` can drive its own controls through the handle:
|
|
106
|
+
|
|
107
|
+
```ts
|
|
108
|
+
board.tools.setTool("rect");
|
|
109
|
+
board.camera.zoomTo("fit");
|
|
110
|
+
const off = board.controller.subscribe(() => {
|
|
111
|
+
console.log(board.controller.targets());
|
|
112
|
+
});
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
Readiness does not wait for a rendered frame, so a hidden-tab mount can finish. Disposal is idempotent,
|
|
116
|
+
leaves the supplied adapter usable, and preserves the container's original children and inline styles.
|
|
117
|
+
A failed mount releases the resources it acquired. Pass `signal?: AbortSignal` to cancel a pending mount:
|
|
118
|
+
an already-aborted signal rejects at once, and an abort during initialization releases the partial board,
|
|
119
|
+
including its in-flight font fetches. Rejection preserves `signal.reason`: a normal `abort()` has an
|
|
120
|
+
`AbortError`, a timeout signal keeps its `TimeoutError`, and a caller-supplied reason is returned unchanged.
|
|
121
|
+
A shared CanvasKit initialization may finish after cancellation, but any renderer allocated for that
|
|
122
|
+
cancelled board is released. After mounting resolves, use `dispose()` to unmount.
|
|
123
|
+
|
|
124
|
+
The required `document` is a `DocumentAdapter`; it can be a local `LoroPageDoc`, a `MemoryDocument`, or
|
|
125
|
+
an adapter initialized and synchronized by the application. The board takes its own scene map/order,
|
|
126
|
+
subscribes to changes, and unsubscribes on disposal. Its optional `readonly carriesDescendants?: boolean`
|
|
127
|
+
capability enables automatic frame parenting when a move carries the object's descendants.
|
|
128
|
+
`LoroPageDoc` declares it true; `MemoryDocument` and adapters that omit it keep the flat behavior. There
|
|
129
|
+
is no `reparentOnDrop` option. The board opens no transport and writes no browser storage. Caller-owned
|
|
130
|
+
documents remain supported: hosts join a relay room with `connectRoom` from `@daasboard/doc` and pass
|
|
131
|
+
its page as `{ document }` (see [Joining a room](#joining-a-room)). The alternative
|
|
132
|
+
`{ boardId, token, transport }` remains unbuilt.
|
|
133
|
+
|
|
134
|
+
Serve the matching `canvaskit-wasm/bin/canvaskit.wasm` and the contents of
|
|
135
|
+
`@daasboard/fonts`, preserving relative font and `manifest/*.json` paths. `fontUrl` receives
|
|
136
|
+
the relative file and its SHA-256, so applications can use a CDN, hashed asset map or bundler URLs.
|
|
137
|
+
There are no Vite imports in the package. The first `createBoard` load declares the shared CanvasKit wasm
|
|
138
|
+
URL, and the loader shares an in-progress or loaded module across boards. A rejected load discards both
|
|
139
|
+
the cached attempt and its URL declaration: the next call can retry a corrected URL without a mismatch
|
|
140
|
+
warning. After a successful load, later boards reuse that module and a different `canvasKitWasm` logs
|
|
141
|
+
a console warning. Default Inter styles and script fallbacks load lazily as text needs them. Font and
|
|
142
|
+
wasm binaries are separate assets, excluded from the 360 kB JavaScript ceiling.
|
|
143
|
+
|
|
144
|
+
**Serve Loro's wasm even when using a MemoryDocument.** This is the safe instruction across bundlers:
|
|
145
|
+
Vite retains the editor's runtime imports through `@daasboard/doc` to `loro-crdt`, while webpack can
|
|
146
|
+
remove unused Loro code. When present, its browser entry fetches and instantiates `loro_wasm_bg.wasm`
|
|
147
|
+
synchronously while `import "@daasboard/embed"` is evaluated, before `createBoard` can read
|
|
148
|
+
`assets`; `assets` does not name Loro's wasm. Serve the matching file from the installed loro-crdt
|
|
149
|
+
package at the URL your bundler emits for `new URL("./loro_wasm_bg.wasm", import.meta.url)`, or beside the
|
|
150
|
+
unbundled browser module when that URL is left unchanged. Missing it fails the import with a wasm 404.
|
|
151
|
+
Configure the bundler to emit that binary and deploy it along with the JavaScript. Vite can resolve
|
|
152
|
+
loro-crdt's `bundler/` entry, which imports the wasm as a module: include `assetsInclude: ["**/*.wasm"]`
|
|
153
|
+
in addition to any font asset patterns your application uses.
|
|
154
|
+
|
|
155
|
+
`fonts` adds picker declarations and real faces to the built-in Inter declaration (400 and 700, upright
|
|
156
|
+
and italic). Each entry has `{ family, label?, weights, italic, faces }`; `faces` is an array of URLs or
|
|
157
|
+
`Uint8Array` values. Font tables identify each face's weight/slant. Every face is registered from bytes,
|
|
158
|
+
never resolved from the host's installed fonts. Use the same bytes on server and browser for matching
|
|
159
|
+
output. Internal fallback slice families never appear in the picker. Declared URL faces are fetched in
|
|
160
|
+
parallel. Each request has a 15-second timer and an abort controller tied to mount cancellation; timers
|
|
161
|
+
are cleared when the request completes, fails or is cancelled. This does not depend on `AbortSignal.any`
|
|
162
|
+
or `AbortSignal.timeout`. A face failure names its URL and retains the original error in `cause`; a face
|
|
163
|
+
timeout has name `TimeoutError`. Cancellation or another mount failure aborts unfinished face requests.
|
|
164
|
+
|
|
165
|
+
`lookupLink`, when supplied, is the application's asynchronous `(url) => EmbedRef` callback. The
|
|
166
|
+
application owns metadata lookup and content-addressed icon/preview assets; the board does not fetch
|
|
167
|
+
arbitrary links. `backend` optionally selects `"gpu"` (the default, with CPU fallback) or `"cpu"`.
|
|
168
|
+
|
|
169
|
+
`readOnly` defaults to false and is fixed for the mount. A read-only
|
|
170
|
+
board allows camera navigation, selection, `selectAll`, and switching between select and hand. It
|
|
171
|
+
creates no text session, suppresses editing keys and write gestures, and guards UI writes/commands and
|
|
172
|
+
its borrowed document facade. The application can still update its own adapter externally; read-only is
|
|
173
|
+
an interaction policy, not server authorization.
|
|
174
|
+
`UiHost.onChange` is intentionally inert because font declarations and read-only state are immutable.
|
|
175
|
+
|
|
176
|
+
An owned shadow tree isolates canvas, input sink and UI from host selectors. Pointer and caret
|
|
177
|
+
coordinates account for 2D affine transforms on ancestors (including scale, rotation and skew; 3D
|
|
178
|
+
perspective is outside this canvas host's coordinate contract). The backing ratio is
|
|
179
|
+
`min(4, min(devicePixelRatio || 1, 2) * max(1, sqrt(abs(transformDeterminant))))`: the base DPR is capped
|
|
180
|
+
at 2, and ancestor scale-up can increase it to a total cap of 4 device pixels per CSS pixel. Anisotropic
|
|
181
|
+
transforms use their geometric mean scale, not their maximum axis. Scale-down keeps the base ratio.
|
|
182
|
+
Scale is sampled at mount, resize and rendered frames. Keep ancestor transforms stable while the board is idle:
|
|
183
|
+
animated or newly changed transforms are reflected at the next resize or board input, not continuously
|
|
184
|
+
observed. The sink is positioned inside that tree at the caret. Canvas keys go to `UiHandle.handleKey`
|
|
185
|
+
before editor tools; keys in a text session stay in its sink. Tool shortcuts are letters; there are no
|
|
186
|
+
digit tool keys. The hand tool pans on a left drag, shows grab/grabbing cursors and returns to select
|
|
187
|
+
on Escape; a middle-button or Space drag also pans. The right button pans no more: it opens the board's
|
|
188
|
+
context menu (below). If a peer or the application ends a focused text session, the canvas receives focus and
|
|
189
|
+
contains the one-second key grace so the remaining typed keys cannot reach the page.
|
|
190
|
+
|
|
191
|
+
A plain wheel pans; a ctrl/meta+wheel zooms about the pointer. A trackpad pinch (Chromium's and Firefox's
|
|
192
|
+
ctrl+wheel updates, Safari's gesture events) zooms 1:1 with the fingers and goes on with a kinetic finish once they
|
|
193
|
+
lift, which any new input ends (a press, wheel or key that `disableBuiltins` releases too:
|
|
194
|
+
the event itself stays the host's); a mouse wheel zooms in notches, about 1.22x for a 100 px notch, on a zoomed page too.
|
|
195
|
+
A camera command (`board.camera.zoomTo`, the UI's zoom menu) stands over a pinch's finish, even one about to start.
|
|
196
|
+
The zoom stays within 0.02 to 64.
|
|
197
|
+
|
|
198
|
+
Keyboard, `beforeinput`/`input`, composition and clipboard events stop at the board's viewport,
|
|
199
|
+
except events released by `disableBuiltins` (below).
|
|
200
|
+
Pointer events, `click`, `dblclick`, `contextmenu`, `wheel` and Safari's `gesturestart`/`gesturechange`/`gestureend`
|
|
201
|
+
bubble to the page so host menus and activity listeners still see board interaction. Every bubbling event that the board handles arrives
|
|
202
|
+
`defaultPrevented`; host handlers must respect that flag before applying their own default action.
|
|
203
|
+
Ancestor capture handlers
|
|
204
|
+
run first by DOM design; the host must not cancel board input there. Events outside the board are
|
|
205
|
+
untouched.
|
|
206
|
+
|
|
207
|
+
Keys/blur listen on the canvas, as do the wheel and Safari's gesture events (a trackpad's pinch; on a touch screen,
|
|
208
|
+
while a finger is on the board, the board only prevents the page zoom they would start); drags use pointer capture, and a `ResizeObserver` watches the supplied container. With the built-in UI mounted, the viewport listens for `focusin` and `focusout` and the canvas for
|
|
209
|
+
`focus` (the text session's focus rule), and so does each host container holding a root of the UI. A resolution `MediaQueryList` change listener resizes the backing canvas and rearms itself
|
|
210
|
+
when device-pixel ratio changes, even while the frame loop is idle. Rendered frames also check the ratio
|
|
211
|
+
as a backstop; there is no DPR polling interval. An environment that changes DPR without delivering a
|
|
212
|
+
media-query notification is corrected on the next rendered frame.
|
|
213
|
+
The one document listener is `visibilitychange`: it releases reconstructible caches on hide and wakes
|
|
214
|
+
the scheduler on show, including hidden starts. Disposal removes that listener along
|
|
215
|
+
with element listeners, observers, animation frames, timers, subscriptions and native render handles.
|
|
216
|
+
The existing shared CanvasKit module/font-pool caches and UI custom-element definitions have page
|
|
217
|
+
lifetime; disposing a board releases its own references, not other boards' resources.
|
|
218
|
+
|
|
219
|
+
Hand, section and preset tools are available through `tools.setTool`, and their creation
|
|
220
|
+
styles through `tools.setCreationStyle` and `tools.creationStyle`. See [third-party notices](THIRD_PARTY_NOTICES.md)
|
|
221
|
+
for redistribution.
|
|
222
|
+
|
|
223
|
+
## Joining a room
|
|
224
|
+
|
|
225
|
+
Import `connectRoom` from `@daasboard/doc`, then give its initialized page to `createBoard`.
|
|
226
|
+
`@daasboard/embed` does not re-export the helper or open a connection itself. The host owns both
|
|
227
|
+
lifetimes and keeps the relay's exact room id for `images: { room }`; a board id, page id or tenant
|
|
228
|
+
id is not a substitute.
|
|
229
|
+
|
|
230
|
+
```ts
|
|
231
|
+
import { connectRoom } from "@daasboard/doc";
|
|
232
|
+
import { createBoard } from "@daasboard/embed";
|
|
233
|
+
|
|
234
|
+
const room = "t/acme/board-123";
|
|
235
|
+
const joining = new AbortController(); // A cancel button can call joining.abort().
|
|
236
|
+
const connection = await connectRoom({
|
|
237
|
+
url: "wss://relay.example.com",
|
|
238
|
+
room,
|
|
239
|
+
token: async (room) => getRoomTokenFromYourBackend(room),
|
|
240
|
+
presence: { user: { name: "Sam", color: "#2563eb" } },
|
|
241
|
+
page: { onFatal: (error) => reportPageFailure(error) },
|
|
242
|
+
signal: joining.signal,
|
|
243
|
+
onState: (state) => {
|
|
244
|
+
statusElement.textContent = state.status === "waiting-for-editor"
|
|
245
|
+
? "Waiting for an editor to create this board…"
|
|
246
|
+
: state.status;
|
|
247
|
+
},
|
|
248
|
+
onFailure: (error) => reportRoomError(error.code),
|
|
249
|
+
});
|
|
250
|
+
// Only the winner of the empty-room claim seeds the new page, after connectRoom resolves.
|
|
251
|
+
if (connection.created) seedPage(connection.page);
|
|
252
|
+
|
|
253
|
+
let board;
|
|
254
|
+
try {
|
|
255
|
+
board = await createBoard({
|
|
256
|
+
container,
|
|
257
|
+
document: connection.page,
|
|
258
|
+
assets,
|
|
259
|
+
readOnly: connection.role !== "write",
|
|
260
|
+
images: { store, room }, // The same room passed to connectRoom above.
|
|
261
|
+
});
|
|
262
|
+
} catch (error) {
|
|
263
|
+
connection.dispose();
|
|
264
|
+
throw error;
|
|
265
|
+
}
|
|
266
|
+
// When the host unmounts:
|
|
267
|
+
board.dispose();
|
|
268
|
+
connection.dispose();
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
`url` is the relay base URL (`http(s)` or `ws(s)`), and `room` is its opaque room id, at most 256
|
|
272
|
+
UTF-8 bytes without control characters. `token` accepts a string or a `RoomToken` provider
|
|
273
|
+
`(room) => string | Promise<string>`; use a provider in a long-lived host. The same provider serves
|
|
274
|
+
snapshot requests and the socket, and the transport refreshes before the relay-reported expiry.
|
|
275
|
+
Credentials stay out of the socket URL. Omit `token` only for an explicitly open development relay.
|
|
276
|
+
`presence` passes `PresenceOptions` through to the room's presence service.
|
|
277
|
+
`page` accepts the page's `onFatal` callback, which reports a fatal WASM error, and its `now` clock
|
|
278
|
+
for typing-merge timing (default `Date.now`). Both apply to each attempt's page. It intentionally
|
|
279
|
+
does not accept `peerId`: after a lost claim, the next attempt must use a fresh peer id rather than
|
|
280
|
+
reuse the identity that authored the refused init.
|
|
281
|
+
|
|
282
|
+
`connectRoom` stages the latest snapshot before opening the socket. The relay's EPOCH confirms
|
|
283
|
+
whether to keep it or replay the whole log. The helper waits for replay, refuses entries without the
|
|
284
|
+
page's init, and claims an empty room with the init alone. A competing winner causes one fresh join;
|
|
285
|
+
a second lost claim fails. A failed replay never becomes an empty room. During each connect attempt,
|
|
286
|
+
the snapshot fetch and the first connection/replay use `stallTimeoutMs` (default 15,000): the replay's
|
|
287
|
+
silence window counts from the last incoming relay frame, so a long replay that keeps delivering
|
|
288
|
+
does not stall. The guard ends permanently for that attempt at its first `live`, before its empty-room
|
|
289
|
+
claim or viewer wait. `signal` cancels a pending snapshot fetch, replay, claim or viewer wait; after
|
|
290
|
+
the promise resolves, use `dispose()`.
|
|
291
|
+
|
|
292
|
+
After the first `live`, an outage shows as `reconnecting`, even while a claim or viewer wait is still
|
|
293
|
+
pending. The transport keeps retrying for as long as it takes, retains edits made offline and sends
|
|
294
|
+
them after reconnecting. A claim whose ACK was lost remains pending and can settle `created` from
|
|
295
|
+
the replay, so the winning host still seeds its template. Show the connection state and keep the
|
|
296
|
+
same connection; do not call `connectRoom` again to recover from an outage. A pending connect can
|
|
297
|
+
still be cancelled through `signal`, or ended by a terminal refusal or transport failure.
|
|
298
|
+
|
|
299
|
+
An empty room with a `read` grant stays in `waiting-for-editor`, without making a claim. Show the
|
|
300
|
+
waiting state and a cancel control instead of mounting an uninitialized board. Waiting on a live
|
|
301
|
+
connection is not a stall. The promise resolves when an editor creates the page; if this client's
|
|
302
|
+
grant becomes `write` first, it may claim the still-empty room itself. With an existing page, a
|
|
303
|
+
viewer resolves normally and the host mounts with `readOnly: true`.
|
|
304
|
+
|
|
305
|
+
The result exposes `page: LoroPageDoc`, `created`, the current `role`, `status`, `stats`, `error`,
|
|
306
|
+
`presence: RoomPresence`, and the underlying `transport`. `subscribe(listener)` returns an
|
|
307
|
+
unsubscribe function and reports later state changes; `onState` supplies the same state while the
|
|
308
|
+
connect is pending as well. A state has `{ status, role, stats, error }`; stats are null before a
|
|
309
|
+
socket exists, and each notification and the result's `stats` getter return a copy. Before the first
|
|
310
|
+
grant, `role` is null for an authenticated connection; an open development relay supplies `write`.
|
|
311
|
+
Once granted, `role` holds across reconnects until a new GRANT changes it. While catching up,
|
|
312
|
+
`onState` and subscriber stats-only notifications are coalesced to one per microtask; status, role
|
|
313
|
+
and error changes publish immediately. Raw transport events retain per-event delivery.
|
|
314
|
+
`events` passes through `TransportEvents`, including
|
|
315
|
+
`onGrant`, `onStatus`, `onStats`, `onError`, `onLogReset` and `onBootstrap`. `onSnapshotRetry`,
|
|
316
|
+
`onSnapshot` and `onClaimConflict` expose the bootstrap's retry, staging and competing-creator
|
|
317
|
+
outcomes for host logs. Read and update presence through `connection.presence`; `createBoard` does
|
|
318
|
+
not accept a presence service.
|
|
319
|
+
Host notification callbacks and subscribers are guarded: a thrown callback error is reported through
|
|
320
|
+
`console.error` without interrupting frame processing or the connect promise.
|
|
321
|
+
The `onFrame` notification runs after the frame is processed.
|
|
322
|
+
|
|
323
|
+
The host must follow grant changes, through `onState`, `subscribe` or `events.onGrant`. A `read`
|
|
324
|
+
grant does not update the board's interaction policy automatically. `createBoard`'s `readOnly` is
|
|
325
|
+
fixed for each mount today, so stop the old board and remount it against the same page with the new
|
|
326
|
+
policy when the role changes. The relay enforces write authorization independently of that UI.
|
|
327
|
+
`dispose()` is idempotent: it closes the socket and presence and removes subscriptions, while
|
|
328
|
+
leaving `page` usable as a local document. Disposing a board alone does not disconnect its room.
|
|
329
|
+
|
|
330
|
+
Connection failures reject with `ConnectRoomError`; inspect `error.code`, not its message. After
|
|
331
|
+
the promise resolves, only terminal failures reach `onFailure` and the state `error`: room/token
|
|
332
|
+
refusals and `transport-failed`. Outages remain `reconnecting`; `unreachable` and `replay-stalled` apply only
|
|
333
|
+
before the attempt's first `live`. Transient transport messages still go to `events.onError` without
|
|
334
|
+
making them terminal failures. Invalid relay URLs reject up front with `TypeError`, and a nonpositive
|
|
335
|
+
or nonfinite `stallTimeoutMs` rejects with `RangeError`.
|
|
336
|
+
|
|
337
|
+
| `code` | Meaning and host response |
|
|
338
|
+
|---|---|
|
|
339
|
+
| `unreachable` | Before the connect attempt's first `live`, no relay frames arrived within the stall window. Check connectivity, then offer retry. |
|
|
340
|
+
| `replay-stalled` | The attempt's first replay stopped delivering frames. Check the relay and storage, then offer retry; the helper never treats a stalled replay as an empty room. |
|
|
341
|
+
| `partial-log` | Entries arrived without the page's init. Repair or recover the room's log; never seed another page into it. |
|
|
342
|
+
| `claim-conflict` | Both permitted empty-room claims lost. Retry the join after the competing creators settle. |
|
|
343
|
+
| `token-provider-failed` | The host's token provider kept failing through the initial guard. Check the host token backend; this is not an unreachable relay. |
|
|
344
|
+
| `token-refused` | The relay refused the token (4401), or a static token failed the local ASCII/4,096-byte check. Obtain a valid room token; a local refusal has no close code. |
|
|
345
|
+
| `forbidden` | The relay denied this token access to the room (4403). Check room and key scope or the user's access. |
|
|
346
|
+
| `token-expired` | A static token expired without a provider to renew it (4408). Reconnect with a fresh token or provider. |
|
|
347
|
+
| `invalid-room` | The relay rejected the room id (4400). Fix the id before retrying. |
|
|
348
|
+
| `aborted` | The caller cancelled the pending connect. Return to the host's cancelled state. |
|
|
349
|
+
| `transport-failed` | The transport cannot safely continue, for example a corrupt replay entry. Report the failure and inspect the relay/log; do not initialize a page. |
|
|
350
|
+
|
|
351
|
+
## Clipboard and host event ownership
|
|
352
|
+
|
|
353
|
+
Outside a text session, the editor handles native `copy`, `cut` and `paste` events on its canvas and
|
|
354
|
+
on the UI's roots. It adds no document or window listener. Mod+C/X/V keep the browser's default
|
|
355
|
+
keyboard action, which dispatches the clipboard event; the board writes the data synchronously during
|
|
356
|
+
that event. Canvas keys first go through the UI root's `handleKey`, so a UI shortcut rebound to the same
|
|
357
|
+
chord takes precedence. With `ui: false`, native clipboard events still work. During a text session the
|
|
358
|
+
existing rich text clipboard (`application/x-daas-text+json`, HTML, then text) keeps precedence. Native
|
|
359
|
+
text fields in the UI keep their own browser clipboard.
|
|
360
|
+
`board.clipboard` is the object/external-text API: its methods decline while a text session owns the
|
|
361
|
+
clipboard. Text-session copy, cut and paste continue through that session's existing native-event handler.
|
|
362
|
+
|
|
363
|
+
Copy uses duplicate's copy set: selected outer objects, their descendants and connectors between copied
|
|
364
|
+
objects. `application/x-daas-objects+json` preserves objects, text marks and image references by hash;
|
|
365
|
+
`text/html` exports rich text and `text/plain` exports the text in draw order. A cut writes these formats
|
|
366
|
+
before deleting the copy set in one undo step. A read-only board copies and does not cut or paste.
|
|
367
|
+
|
|
368
|
+
The HTML carries the objects too, because the async Clipboard API's read returns only the plain text
|
|
369
|
+
and the HTML: an empty `<span data-daas-objects="…">` ahead of the rich text holds the private format's
|
|
370
|
+
string in base64, as Figma carries its own. A paste with the private format uses it; one without it, such
|
|
371
|
+
as the context menu's Paste here or another browser's paste of the copy, uses the carrier, validated as the
|
|
372
|
+
private format is. Only an element's own attribute is a carrier: the board reads a copy's where the copy puts it,
|
|
373
|
+
first in the HTML, and parses other HTML that names one, inertly, to find it, so text or a comment that reads like
|
|
374
|
+
one pastes as the text it is. A carrier that holds nothing readable pastes nothing rather than the HTML's text, and
|
|
375
|
+
so does the empty one a copy writes when its objects do not fit the input bound below a second time. The carrier's
|
|
376
|
+
own markup, 34 bytes, comes on top of that bound, so every copy within it is written, with its carrier. The
|
|
377
|
+
carrier, an empty span, adds no text and
|
|
378
|
+
changes no paragraph's alignment, list or indent where the HTML pastes as text, into a text session or another
|
|
379
|
+
app, and it wins over a system image file beside it, as the private format does (the image rules below).
|
|
380
|
+
Selection PNG is not included. Binary clipboard writing requires the asynchronous Clipboard API;
|
|
381
|
+
no selection rendering or encoding blocks the synchronous clipboard event.
|
|
382
|
+
|
|
383
|
+
Object paste remaps ids and internal references in one transaction, attaches connectors whose targets
|
|
384
|
+
were copied, leaves other endpoints free at their stored points, and selects the pasted outer objects.
|
|
385
|
+
A keyboard paste keeps the copied world coordinates. If the copied bounds do not intersect the current
|
|
386
|
+
viewport, it centers the paste in the viewport, following Figma's off-screen rule. `pasteAt` always centers
|
|
387
|
+
on the supplied world point. Each outer object's parent is decided at its own box's center after the
|
|
388
|
+
paste offset. For a paste in place, an object keeps its source's parent when the source is still on this
|
|
389
|
+
board and that parent is the top level, or a frame/section containing the copied center. Otherwise,
|
|
390
|
+
including every `pasteAt` and off-screen relocation, it uses the front-most frame/section under its own
|
|
391
|
+
center. That hit test excludes the source objects and their current descendants, so pasting a frame in
|
|
392
|
+
place creates siblings rather than nesting copies inside the source. Frames and sections can nest when
|
|
393
|
+
pasted elsewhere. Locked containers take no paste: if the chosen container is locked itself or has a
|
|
394
|
+
locked ancestor, paste climbs to the nearest frame/section above the outermost locked container, or to
|
|
395
|
+
the top level. The copies are drawn above the locked container and remain movable. It does not continue
|
|
396
|
+
the hit test into an unrelated frame behind the locked one. This rule also applies to in-place source
|
|
397
|
+
parents, off-screen relocation, and direct `controller.paste` calls with `parent` or `parents` options.
|
|
398
|
+
Creation and drop use their own parenting rules. Connectors always
|
|
399
|
+
stay at the top level. Adapters without `carriesDescendants: true` retain their flat parenting behavior.
|
|
400
|
+
Internal parent links in a copied subtree are preserved by remapping.
|
|
401
|
+
|
|
402
|
+
External HTML uses the text session's HTML parser, in an inert parsed document; it is never inserted into
|
|
403
|
+
the live page. External HTML or plain text creates one `text` object with `defaultStyle("text")`, hence no
|
|
404
|
+
fill or stroke, centered at the viewport center or explicit point. It wraps at 400 world units and grows
|
|
405
|
+
in height using the board's text layout engine, including padding. Text marks survive HTML import.
|
|
406
|
+
|
|
407
|
+
The clipboard API accepts the event's `clipboardData` or explicit formats and returns `{ ids, pending }`.
|
|
408
|
+
`ids` contains the IDs committed synchronously. `pending` is `null` when nothing waits, or a promise for
|
|
409
|
+
the deferred paste's committed IDs. It resolves to `[]` on cancellation, invalidation, or a dropped paste,
|
|
410
|
+
and never rejects. A host has accepted a paste when `ids.length > 0 || pending !== null`. The API does not
|
|
411
|
+
request ambient browser clipboard permissions. A host menu can obtain data through its own authorized
|
|
412
|
+
clipboard read and pass it to `pasteAt`. The built-in context menu does that for its Paste here, and so
|
|
413
|
+
asks for the browser's clipboard read in the host's page (below).
|
|
414
|
+
|
|
415
|
+
```ts
|
|
416
|
+
// A host-owned native event: the listener belongs on the host's own element.
|
|
417
|
+
container.addEventListener("paste", (event) => {
|
|
418
|
+
if (event.defaultPrevented || !event.clipboardData) return;
|
|
419
|
+
const { ids, pending } = board.clipboard.pasteAt({ x: 600, y: 400 }, event.clipboardData);
|
|
420
|
+
if (ids.length > 0 || pending !== null) {
|
|
421
|
+
event.preventDefault();
|
|
422
|
+
}
|
|
423
|
+
});
|
|
424
|
+
const formats = board.clipboard.copy(); // { objects, html, text }, or null for an empty selection
|
|
425
|
+
if (formats) board.clipboard.paste(formats);
|
|
426
|
+
// copy(event.clipboardData) and cut(event.clipboardData) also write all formats during a native event.
|
|
427
|
+
```
|
|
428
|
+
|
|
429
|
+
The private format is untrusted, including data copied by another board version. Input is capped at
|
|
430
|
+
2 MiB of UTF-8 across the formats before parsing, at most 10,000 objects, and at most 256 parent levels.
|
|
431
|
+
The carrier's 34 bytes of markup come on top beside the private format, which leaves the HTML unparsed, and
|
|
432
|
+
once a carrier is read; what a carrier holds counts as the private format does.
|
|
433
|
+
The versioned object envelope and every object's
|
|
434
|
+
schema fields are checked; invalid objects and duplicate ids are dropped, as are cyclic/deep subtrees
|
|
435
|
+
and children of rejected parents. Copy encodes an external parent as a root and an external connector
|
|
436
|
+
target as a free endpoint at its stored point. An incoming private object with a dangling parent or
|
|
437
|
+
attached target is rejected. Page normalization derives draw order and geometry. Unknown kinds are
|
|
438
|
+
dropped; invalid JSON pastes nothing. A present but invalid private payload does not fall back to HTML or text. No parse or
|
|
439
|
+
clipboard data error escapes the API. Image bytes are not included or fetched by this API.
|
|
440
|
+
|
|
441
|
+
`disableBuiltins` is immutable for a mount. It disables event handling, not API access: the matching event
|
|
442
|
+
is neither prevented nor stopped, and `board.controller.commands`, `board.tools`, `board.camera` and
|
|
443
|
+
`board.clipboard` remain callable (with read-only and disposal guards). Names are:
|
|
444
|
+
|
|
445
|
+
| Name | Released built-in handling |
|
|
446
|
+
| --- | --- |
|
|
447
|
+
| `clipboard` | Copy, cut and paste keys/events, including text sessions and clipboard `beforeinput` |
|
|
448
|
+
| `copy`, `cut`, `paste` | One clipboard operation |
|
|
449
|
+
| `shortcuts` | All keyboard shortcuts |
|
|
450
|
+
| `shortcut:<chord>` | One literal chord, for example `shortcut:Mod+Z`, `shortcut:Alt+ArrowLeft` or `shortcut:Escape` |
|
|
451
|
+
| `command:<name>` | A named command's keys: `undo`, `redo`, `delete`, `duplicate`, `selectAll`, `bringToFront`, `bringForward`, `sendBackward`, `sendToBack`, `lock`, `locationAndSize`, `zoomIn`, `zoomOut`, `zoomReset`, `zoomFit`, `zoomSelection`; editor `cancel` and `nudge`; text `bold`, `italic`, `underline`, `strike` |
|
|
452
|
+
| `tool:<name>` | A built-in tool's keys and canvas gestures, a finger's and a pen's included, using the names accepted by `board.tools.setTool` |
|
|
453
|
+
| `pan`, `zoom` | Camera gesture keys and pointer/wheel navigation; zoom also releases a trackpad pinch (its ctrl+wheel and Safari's gesture events) and the UI's zoom shortcuts. On a touch screen, `pan` releases a finger's pan and fling and the pan of two fingers, and `zoom` their zoom ("Tablets", below) |
|
|
454
|
+
| `textEditing` | Enter/F2, double-click and double-tap text-session entry |
|
|
455
|
+
| `textInput` | Text-session keys, input and composition events |
|
|
456
|
+
| `contextMenu` | The right button's press and the canvas's `contextmenu` event, the Menu key and Shift+F10, and a long press: no menu opens and the browser's own shows |
|
|
457
|
+
|
|
458
|
+
Chord syntax is the same as `ui.shortcuts`: modifiers joined with `+`; `Mod` is Cmd on Apple platforms
|
|
459
|
+
and Ctrl elsewhere. Disabling a native clipboard chord also releases its resulting clipboard event;
|
|
460
|
+
`shortcuts` releases all three. Native default actions remain the host's responsibility after an event is
|
|
461
|
+
released. UI fields retain normal native text editing and control navigation.
|
|
462
|
+
|
|
463
|
+
```ts
|
|
464
|
+
const board = await createBoard({
|
|
465
|
+
container, document: page, assets,
|
|
466
|
+
disableBuiltins: ["clipboard", "command:undo", "tool:rect", "shortcut:Escape"],
|
|
467
|
+
ui: { shortcuts: { rect: "Alt+R", duplicate: null } },
|
|
468
|
+
});
|
|
469
|
+
```
|
|
470
|
+
|
|
471
|
+
`ui.shortcuts` only rebinds or removes the UI's own tool and command bindings; it does not remove the
|
|
472
|
+
editor's fallback Delete, undo, nudge or z-order keys. `disableBuiltins` takes priority over both, follows
|
|
473
|
+
later `board.ui.configure({ shortcuts: ... })` changes for named tool/command bindings, and works with
|
|
474
|
+
`ui: false`. Use `command:delete` to release both the UI's rebound delete key and the editor's
|
|
475
|
+
Delete/Backspace fallback. Calling the same operation through the API still works.
|
|
476
|
+
|
|
477
|
+
## Tablets
|
|
478
|
+
|
|
479
|
+
The board works with a finger and a pen on a touch screen. A mouse and a trackpad keep the desktop handling, on a
|
|
480
|
+
tablet too.
|
|
481
|
+
|
|
482
|
+
The tablet target is iPadOS Safari, tested on an iPad (9th generation). Android tablets are untested and unsupported
|
|
483
|
+
for now: the same code runs in Android Chrome, but nothing below has been checked on an Android device.
|
|
484
|
+
|
|
485
|
+
The host has a few duties:
|
|
486
|
+
|
|
487
|
+
- Serve the page with `<meta name="viewport" content="width=device-width, initial-scale=1">`. Without it a tablet
|
|
488
|
+
lays the page out about 980 px wide and scales it, and the board with it.
|
|
489
|
+
- Don't count on `user-scalable=no`. iPadOS Safari ignores it. The board's canvas has `touch-action: none`, so a
|
|
490
|
+
gesture on the board never zooms the page. A pinch elsewhere on the page still does.
|
|
491
|
+
- Expect the board to take every touch that starts on it. A finger dragged on the board never scrolls the page, so a
|
|
492
|
+
board inside a scrolling page needs room around it.
|
|
493
|
+
- Start text editing from a tap. On iPadOS, a focus outside a user gesture opens no keyboard, so `board.focus()` from
|
|
494
|
+
a timer or a promise shows none. The board starts a double tap's text session inside the tap's own handler.
|
|
495
|
+
- Pass `memory: { images: 96 * 1024 * 1024 }` on a tablet. A tablet has less memory than a laptop, and the board does
|
|
496
|
+
not set tablet defaults yet.
|
|
497
|
+
- Skip the events the board prevented, as on a desktop.
|
|
498
|
+
|
|
499
|
+
A finger edits as a mouse does:
|
|
500
|
+
|
|
501
|
+
| Gesture | Does |
|
|
502
|
+
| --- | --- |
|
|
503
|
+
| Tap | Selects what is under the finger. On empty canvas, clears the selection. |
|
|
504
|
+
| Double tap | Edits a shape's text, as a double-click does. |
|
|
505
|
+
| Drag from empty canvas | Box-selects. |
|
|
506
|
+
| Drag from an object | Selects it unless it is selected already, then moves the selection. |
|
|
507
|
+
| Drag on a handle | Resizes or rotates. On an end marker of the one selected connector, moves that end (below). |
|
|
508
|
+
| Long press, then release | Selects what is under the finger unless it is selected already, and opens the menu there. |
|
|
509
|
+
| Long press, then drag | The drag, as without the long press. No menu opens. |
|
|
510
|
+
| Two fingers | Zoom and pan together. Lifted while moving, they fling. |
|
|
511
|
+
| Three or more fingers | Nothing. They cancel what one or two fingers started, and a finger put down again before they all lift does nothing either. |
|
|
512
|
+
|
|
513
|
+
A press waits until it means something: a tap (lifted within 10 CSS px), a drag (moved past 10 px) or a long press
|
|
514
|
+
(held still for 500 ms). So two fingers never select or move anything first. A second finger cancels a drag in
|
|
515
|
+
progress, and nothing is written; the two fingers then move the camera. While a press waits to mean something it owns
|
|
516
|
+
the canvas's keys as a mouse's press does: Escape cancels it, and the tools' keys wait until the finger lifts (the
|
|
517
|
+
built-in UI's shortcuts act first, as during a mouse's press). A press acts on what the finger touched (the object, the
|
|
518
|
+
handle, a gradient handle of that type of gradient, a connector's starting shape, an end of the selected connector), even
|
|
519
|
+
if the long press's selection or a collaborator's edit changed the board meanwhile; if that is gone, nothing happens, not even a double tap's text
|
|
520
|
+
session. Without the built-in UI's menu (`ui: false`,
|
|
521
|
+
`ui.contextMenu: false`), a long press does nothing, as a right press does. With a creation tool, a tap creates at the
|
|
522
|
+
default size and a drag draws the box. In a text session a finger places the caret and selects text as a mouse does,
|
|
523
|
+
and a tap outside ends the session.
|
|
524
|
+
|
|
525
|
+
While a connector is the one selected object, the markers on its two ends are handles, for a mouse, a pen and a finger
|
|
526
|
+
alike. Dragging one moves that end: off its shape it is free where it is released, and over a shape it attaches to that
|
|
527
|
+
shape's nearest side, as the connector tool attaches a new connector's end. The drag is one undo step, Escape or a second
|
|
528
|
+
finger cancels it with nothing written, and under a `"pan"` option it never pans. A finger grabs a marker within 22 CSS
|
|
529
|
+
px of its center, or 10 px where it lands inside the shape that end is on, so the rest of that shape stays the shape's.
|
|
530
|
+
In a larger selection, and on a locked connector, the markers are drawn hollow and take no press.
|
|
531
|
+
|
|
532
|
+
In a text session a finger drives, the board draws selection handles: a knob below the caret, and one at each end of a
|
|
533
|
+
selected range, the range's start above its line and its end below. A finger grabs a handle within 22 CSS px of its
|
|
534
|
+
knob, or 10 px inside the edited text's box, so a tap or a double tap on the text next to the caret still reaches the
|
|
535
|
+
text. Dragging an end's handle moves that end and keeps the other; dragging the caret's handle moves the caret. A double
|
|
536
|
+
tap in the text selects a word. A long press in the text selects the word under the finger and opens the menu (Cut,
|
|
537
|
+
Copy, Paste) at its release; without the menu it selects nothing, as a long press elsewhere does. A mouse's session
|
|
538
|
+
shows no handles, and a mouse press hides them until a finger presses again.
|
|
539
|
+
|
|
540
|
+
The board keeps the caret in view above a virtual keyboard (iPadOS Safari, and Android Chrome since 108, shrink the
|
|
541
|
+
visual viewport when the keyboard rises, and would scroll the page to the focused text). While a text session is open,
|
|
542
|
+
the board reads `window.visualViewport` and listens to its `resize` and `scroll`; it removes both listeners when the
|
|
543
|
+
session ends. As the keyboard changes the visible part, or the user types, the board pans its own camera by the least
|
|
544
|
+
that keeps the caret 24 CSS px inside the part of the board the user can see, and keeps its hidden input element there
|
|
545
|
+
too, so the browser finds nothing to scroll in your page. It never pans back after the user pans away, until they type.
|
|
546
|
+
A floating or split iPad keyboard doesn't shrink the visual viewport, so the board can't see it. Inside a rotated or
|
|
547
|
+
skewed ancestor the board doesn't follow the caret, and keeps its hidden input element at the caret; inside a scaled or
|
|
548
|
+
translated one it follows exactly.
|
|
549
|
+
|
|
550
|
+
A pen works as a mouse does, whatever the options say. A palm resting under it is ignored. Its secondary button opens
|
|
551
|
+
the menu, as a right press does.
|
|
552
|
+
|
|
553
|
+
The `touch` option makes a finger pan instead, for hosts whose users mostly look at boards:
|
|
554
|
+
|
|
555
|
+
```ts
|
|
556
|
+
const board = await createBoard({
|
|
557
|
+
container, document: page, assets,
|
|
558
|
+
touch: { canvasDrag: "pan", objectDrag: "pan" },
|
|
559
|
+
});
|
|
560
|
+
```
|
|
561
|
+
|
|
562
|
+
- `canvasDrag` is what a finger dragged from empty canvas does: `"select"` box-selects (the default), `"pan"` pans and
|
|
563
|
+
flings.
|
|
564
|
+
- `objectDrag` is what a finger dragged from an object that isn't selected does: `"move"` selects and moves it (the
|
|
565
|
+
default), `"pan"` pans and flings.
|
|
566
|
+
|
|
567
|
+
Under a `"pan"` option, a long press and then a drag brings back the mouse's action: from empty canvas it box-selects,
|
|
568
|
+
and from an object it picks the object up. A drag from the selection always moves it. Taps, double taps, the long
|
|
569
|
+
press's menu and two fingers work the same under every setting. Both options are fixed for the mount and apply to
|
|
570
|
+
fingers only. Any other value, another field (a typo such as `objectdrag`), or a `touch` that isn't an object throws a
|
|
571
|
+
`TypeError` naming the option before anything mounts, so a typo never quietly gives users the other grammar.
|
|
572
|
+
|
|
573
|
+
`disableBuiltins` covers touch with the same names:
|
|
574
|
+
|
|
575
|
+
- `tool:<name>` releases that tool's finger and pen gestures.
|
|
576
|
+
- `pan` releases a finger's pan and its fling (with the hand tool, or under a `"pan"` option) and the pan of two
|
|
577
|
+
fingers. `zoom` releases their zoom, and Safari's gesture events. With one of the two released, two fingers do the
|
|
578
|
+
other alone. With both, the board neither handles nor prevents two fingers: their events are the host's, and a drag
|
|
579
|
+
the first finger had started is cancelled, writing nothing.
|
|
580
|
+
- `contextMenu` releases the long press: it selects nothing and opens no menu.
|
|
581
|
+
- `textEditing` releases the double tap's text session.
|
|
582
|
+
|
|
583
|
+
Once a gesture is released to the host, its pointer events reach the host as they are, neither handled nor prevented.
|
|
584
|
+
A finger's first `pointerdown` can still arrive prevented: until the press means something, it may become a long
|
|
585
|
+
press's menu or a pinch the board takes, so the board takes the press. Only when nothing the press could become is the
|
|
586
|
+
board's (every one of those features released) does its `pointerdown` arrive unprevented. A second finger, or a regrip,
|
|
587
|
+
while a released two-finger gesture's first finger is still down stays the host's too. `board.camera.onChange`
|
|
588
|
+
reports a pinch's and a fling's camera changes as it reports the others. The board listens for pointer events only, on
|
|
589
|
+
its canvas: it adds no `touchstart` or `touchmove` listener to the page.
|
|
590
|
+
|
|
591
|
+
## The built-in UI
|
|
592
|
+
|
|
593
|
+
`ui` mounts the built-in UI (`@daasboard/ui`) over the
|
|
594
|
+
board. `true` or no value mounts the defaults: the tools toolbar at the bottom, and the selection toolbar at the top
|
|
595
|
+
while something is selected. The property pane is opt-in. An object configures it:
|
|
596
|
+
|
|
597
|
+
```ts
|
|
598
|
+
const board = await createBoard({
|
|
599
|
+
container, document: page, assets,
|
|
600
|
+
ui: {
|
|
601
|
+
theme: "auto", // "light", "dark", or tokens over the auto preset
|
|
602
|
+
toolbar: { placement: "left", tools: [{ tools: ["select", "hand"] }, "|", "rect", "ellipse", "text", "sticky"] },
|
|
603
|
+
selectionToolbar: { placement: "floating" }, // above the selection; "top" docks it
|
|
604
|
+
pane: { container: document.getElementById("properties")! }, // in the host's own layout
|
|
605
|
+
color: { gradients: true }, // in the selection toolbar too; the pane has them by default
|
|
606
|
+
prefs: viewerPrefs, // what the UI remembers per viewer; in memory by default
|
|
607
|
+
},
|
|
608
|
+
});
|
|
609
|
+
```
|
|
610
|
+
|
|
611
|
+
`false` gives the bare canvas, for the whole mount: no UI element, none of the UI's listeners, and `board.ui` is
|
|
612
|
+
null. The host builds its own UI on `board.controller`, `board.tools` and `board.camera`. A UI can't be added later:
|
|
613
|
+
`ui: false` stays a guarantee for the board's lifetime, as `readOnly` does, and a configure on a board without a UI
|
|
614
|
+
would otherwise do nothing silently.
|
|
615
|
+
|
|
616
|
+
`board.ui.configure(partial)` changes the options at run time. `partial` merges over the options in effect:
|
|
617
|
+
|
|
618
|
+
- **Objects merge field by field at every depth.** A field the partial leaves out keeps its value, so
|
|
619
|
+
`configure({ toolbar: { overflow: false } })` keeps the toolbar's placement and tools.
|
|
620
|
+
- **Lists, booleans, strings, functions and elements replace.** So do the `prefs` and recents stores.
|
|
621
|
+
`configure({ toolbar: { tools: ["select", "text"] } })` shows those two tools.
|
|
622
|
+
- **`true` keeps an object; `false` replaces it.** This holds for an option that takes a boolean or an object, such
|
|
623
|
+
as `pane` or `quickActions`. `configure({ pane: true })` keeps the pane where it is. `configure({ pane: false })`
|
|
624
|
+
takes it off and forgets its options, so a later `configure({ pane: true })` brings it back with the defaults, on
|
|
625
|
+
the board.
|
|
626
|
+
- **`container: null` puts the pane back on the board**, since a configure that leaves `container` out keeps it in
|
|
627
|
+
the host's container.
|
|
628
|
+
|
|
629
|
+
The UI supports custom tools, selection-toolbar items, pane sections and replacement controls through
|
|
630
|
+
the exported configuration types in `@daasboard/ui`.
|
|
631
|
+
|
|
632
|
+
**Surfaces in a host's container.** The pane's `container`, and a toolbar's `{ container }` placement, put that
|
|
633
|
+
surface in the host's element as another root of the UI. It is themed and configured with the board's UI, and it
|
|
634
|
+
moves or goes with a configure and with `dispose()`. While a root is in one of the host's containers, the board
|
|
635
|
+
listens there for `focusin` and `focusout` (the text session's focus rule, below). Those listeners go with the root.
|
|
636
|
+
|
|
637
|
+
**Text sessions and the UI's focus:**
|
|
638
|
+
|
|
639
|
+
- **A press on a toolbar or pane button keeps the input sink's focus.** Bold formats the selected range, and the
|
|
640
|
+
typing goes on.
|
|
641
|
+
- **The focus moving into the UI keeps the session.** This covers a popover's search or hex field and a pane field,
|
|
642
|
+
in the board or in a host's container. What is picked there formats the selected range. Enter in a toolbar or pane
|
|
643
|
+
field hands the focus back to the sink, and so does a popover as it closes.
|
|
644
|
+
- **The focus leaving the UI for anything but the sink ends the session:** a page control, the page itself, or the
|
|
645
|
+
canvas. The window losing the focus ends nothing.
|
|
646
|
+
- **The caret shows only while the sink holds the focus.**
|
|
647
|
+
|
|
648
|
+
**Recent paints** are the viewer's. The board keeps them in `ui.prefs`, under `picker.recents`: newest first,
|
|
649
|
+
each paint once, at most 16.
|
|
650
|
+
|
|
651
|
+
- **Across boards.** Boards on one prefs store share the list, and so do boards on stores over the same storage, such
|
|
652
|
+
as two `localStoragePrefs` with one prefix. A picker shows another board's paint the next time it opens. A board
|
|
653
|
+
without `ui.prefs` keeps its own list, in memory for its lifetime.
|
|
654
|
+
- **When a paint is added.** Once, when a picker session that committed it closes. A preview, a cancel or a refused
|
|
655
|
+
commit adds nothing, and the list is in no undo stack.
|
|
656
|
+
- **Another viewer.** `board.ui.configure({ prefs })` with another store switches the list. A picker open across the
|
|
657
|
+
switch gives the paint it committed before the switch to the previous viewer, and what it commits after to the new
|
|
658
|
+
one.
|
|
659
|
+
- **What's stored.** The list is read entry by entry: an entry that isn't a paint (written by hand, or by another
|
|
660
|
+
version) is left out, and nothing throws.
|
|
661
|
+
- **Another store.** `ui.color.recents.store` replaces the board's (one per board, or shared), and
|
|
662
|
+
`ui.color.recents: false` turns recent paints off. Either way the board reads and writes no recent paints in the
|
|
663
|
+
prefs.
|
|
664
|
+
- **`ui.color.recents.max`** narrows how many a picker shows. The board's store keeps 16, so a larger `max` shows 16
|
|
665
|
+
at most; a host's store can keep more.
|
|
666
|
+
|
|
667
|
+
A `<daas-paint-picker>` placed outside any board's UI has no prefs to use. It shares one module-wide list, in memory
|
|
668
|
+
for the page's lifetime, with every other such picker on the page, unless the host passes it a store.
|
|
669
|
+
|
|
670
|
+
**Gradient handles.** While the paint picker is open on one object's linear or radial gradient (a
|
|
671
|
+
fill layer in the pane, or the selection toolbar's Fill where its color options allow gradients), the board draws
|
|
672
|
+
the gradient's handles on the canvas:
|
|
673
|
+
|
|
674
|
+
- **Dragging.** Drag a linear gradient's end, or a radial gradient's center or radius. A drag previews the whole fill
|
|
675
|
+
on every move and commits once on release, one undo step. Escape cancels it, and so do a lost pointer and a tool
|
|
676
|
+
switch.
|
|
677
|
+
- **Presses.** A press on a handle keeps the picker open, and the focus where it was. Any other press closes the
|
|
678
|
+
picker, then does on the canvas what it does as drawn, read before the focus moves: on the object's corner it moves
|
|
679
|
+
the object, since the handles hide its transform handles. A pan with the middle button takes no focus,
|
|
680
|
+
and the picker in the pane or in a docked selection toolbar stays open through it. A floating selection toolbar
|
|
681
|
+
hides while the camera moves, and its picker closes with it.
|
|
682
|
+
- **No canvas gesture.** A handle drag is the picker's own gesture, so a floating selection toolbar stays through it.
|
|
683
|
+
- **Keys.** While a drag holds the pointer, keys at the canvas wait for its release, Escape excepted.
|
|
684
|
+
|
|
685
|
+
`ui.color.canvasHandles: false` turns the handles off; a read-only board shows none. While they show, the picker's
|
|
686
|
+
popover listens for presses on the board's viewport, and on its own root where that root is in a host's container,
|
|
687
|
+
until it closes. Nothing listens outside the board, so a press there on page content
|
|
688
|
+
that takes no focus leaves the picker open.
|
|
689
|
+
|
|
690
|
+
**The context menu.** A right-click on the canvas opens the board's menu. The right button pans no more; the
|
|
691
|
+
middle button, Space and the hand tool still do.
|
|
692
|
+
|
|
693
|
+
- **What it offers.** On an object or a selection: Cut, Copy, Paste here, Duplicate and Delete, each with its key. A
|
|
694
|
+
right press on an object outside the selection selects it first, as a left press would; on a selected object the
|
|
695
|
+
selection stays. On empty canvas the selection clears and the menu offers Paste here. A read-only board offers Copy
|
|
696
|
+
only. A `copy`, `cut`, `paste` or `command:<name>` that `disableBuiltins` releases hides its item.
|
|
697
|
+
- **What an item does.** What its key does. Cut and Copy put on the clipboard exactly what Mod+X and Mod+C put there:
|
|
698
|
+
the board runs the browser's own command with the focus on a hidden editable element of its own, where its clipboard
|
|
699
|
+
handler writes the formats, then gives the focus back. Duplicate is Mod+D and Delete is the Delete key: the same
|
|
700
|
+
targets, one undo step each, and the keys' locked and read-only rules.
|
|
701
|
+
- **Paste here** reads the system clipboard with `navigator.clipboard.read()` and pastes centered on the clicked point
|
|
702
|
+
through `pasteAt`, so the parent rules above apply there. Objects copied from a board come back as objects: the
|
|
703
|
+
copied HTML carries them (above). Text or HTML from another app pastes as a text object. An image on the
|
|
704
|
+
clipboard pastes as an image at the point, as Mod+V inserts one (the image rules below), and a paste that waits
|
|
705
|
+
for the image store shows in the overlay as Mod+V's does. A refused read pastes nothing, and so does one that
|
|
706
|
+
settles after the page hid, shown again or not, or after the pending inserts were cancelled (the image rules below:
|
|
707
|
+
Escape on the idle canvas, `board.images.cancel()`). What lands is selected only if the selection and the editing
|
|
708
|
+
context stayed as the pick found them, as an upload's is from its start. The item hides where the browser has no
|
|
709
|
+
`navigator.clipboard.read` (outside a secure context).
|
|
710
|
+
- **The browser may ask first.** The read runs in the host's page. Chromium asks once per origin for the
|
|
711
|
+
clipboard-read permission (an iframe needs `allow="clipboard-read"`). Firefox and Safari read what the same origin
|
|
712
|
+
copied without asking, and otherwise show a Paste item the user clicks; Safari hands another origin's HTML over
|
|
713
|
+
sanitized.
|
|
714
|
+
- **In a text session,** a right-click in the edited text offers Cut, Copy and Paste for the text's selection, as the
|
|
715
|
+
keys do there. Paste pastes at the selection the pick found: a read that settles after the text or its selection
|
|
716
|
+
changed (a key, a click, a peer's edit) pastes nothing. Anywhere else a right press ends the session as a left press
|
|
717
|
+
does, then opens the menu.
|
|
718
|
+
- **Keyboard.** The Menu key and Shift+F10 open it at the selection; its Paste then pastes as Mod+V does. The arrow
|
|
719
|
+
keys, Enter and Escape work as in the other menus. Escape and a click outside close it and write nothing. The keys
|
|
720
|
+
are the board's: a `contextmenu` event the browser fires for them (on Windows as the Menu key is released, and in a
|
|
721
|
+
text session) stops at the board when its menu shows, so a page that opens a menu of its own on that event does not
|
|
722
|
+
show it beside the board's; only a listener capturing on the way down sees it. With the menu off, or nothing in it to
|
|
723
|
+
offer, the event reaches the page prevented, as a right-click's does.
|
|
724
|
+
- **When it opens.** On the canvas's `contextmenu` event, which fires on the press on macOS and Linux and on the
|
|
725
|
+
release on Windows. The menu shows once the press is released: a popover shown during the press would close as the
|
|
726
|
+
release lands outside it (the Popover API's light dismiss). The press takes no focus, so a text session's sink keeps
|
|
727
|
+
it, and the event reaches the page `defaultPrevented`. The menu holds the focus while it shows and hands it to the
|
|
728
|
+
board as it closes, as the UI's other menus do (the sink during a text session). A selection change, a pan or a zoom,
|
|
729
|
+
or a canvas gesture closes it.
|
|
730
|
+
- **Off.** `ui.contextMenu: false` turns the menu off, and `ui: false` has none. The board then still keeps the
|
|
731
|
+
browser's own menu off the canvas, and a right press does nothing, unless `disableBuiltins: ["contextMenu"]` releases
|
|
732
|
+
the press, the event, the Menu key and Shift+F10 to the host, neither handled nor prevented, for a menu of its own.
|
|
733
|
+
|
|
734
|
+
**Read-only** hides the creation tools, the selection toolbar and the pane's write controls, whatever the options
|
|
735
|
+
say. The zoom menu and the pane's values stay.
|
|
736
|
+
|
|
737
|
+
`createBoard` does not supply document color tokens to the UI, so `ui.color.tokens` has nothing to show.
|
|
738
|
+
|
|
739
|
+
### Images
|
|
740
|
+
|
|
741
|
+
The host owns the bytes. Pass `images: { store, room }` to `createBoard`; `room` is the exact
|
|
742
|
+
transport log room and is required only for stores with `touch`. The board never opens host-page
|
|
743
|
+
storage. An original-only memory or IndexedDB store implements `put` and `get` and needs no room.
|
|
744
|
+
|
|
745
|
+
```ts
|
|
746
|
+
const originals = new Map<string, Blob>();
|
|
747
|
+
const board = await createBoard({
|
|
748
|
+
container, document, assets,
|
|
749
|
+
images: { store: {
|
|
750
|
+
async put(image) { originals.set(image.hash, image.bytes); },
|
|
751
|
+
async get(hash) { const bytes = originals.get(hash); return bytes ? { bytes } : null; },
|
|
752
|
+
} },
|
|
753
|
+
memory: { images: 128 * 1024 * 1024 },
|
|
754
|
+
onImageError(hash, rung, reason) { console.warn("Image unavailable", hash, rung, reason); },
|
|
755
|
+
});
|
|
756
|
+
```
|
|
757
|
+
|
|
758
|
+
Drop or paste image files on the board, use the toolbar's Image action, call `board.images.pick()`, or pass
|
|
759
|
+
files to `board.images.insert(files, point?)`. All successful files in a batch commit together,
|
|
760
|
+
after storage resolves. Disposal, hiding the board, `board.images.cancel()`, or Escape on the idle
|
|
761
|
+
canvas with nothing selected cancels pending inserts, a context menu Paste here still reading the
|
|
762
|
+
clipboard included; the first Escape with a selection only
|
|
763
|
+
deselects it. An Escape consumed by text editing, a tool gesture, or the UI does
|
|
764
|
+
not. A host ignoring the signal cannot revive a cancelled insert. New images fit the visible area.
|
|
765
|
+
They are selected only if the editing context stayed unchanged and idle throughout the upload;
|
|
766
|
+
otherwise the user's current selection, text session, and gesture keep their targets. Images
|
|
767
|
+
keep their aspect ratio when resized; Shift allows stretching. PNG, JPEG, GIF's first frame and
|
|
768
|
+
WebP decode locally. SVG and ICO require `store.renders` to list their MIME types and `get` must
|
|
769
|
+
return a supported raster rendition. The full SHA-256 names the original bytes; oversized inputs
|
|
770
|
+
that are scaled in a worker are hashed after scaling. `onImageScaled` reports that change.
|
|
771
|
+
JPEG orientation comes from its first Exif APP1 packet; a following XMP packet does not replace it.
|
|
772
|
+
PNG/WebP are normalized only for Exif orientations 2–8; orientation 1 retains the original bytes
|
|
773
|
+
and colour profile. Rotation preserves the source's encoding class: lossless sources use PNG,
|
|
774
|
+
lossy opaque sources use JPEG at quality 90, and lossy sources with alpha use WebP at quality 90.
|
|
775
|
+
The resulting upright bytes are hashed and stored, so their look does not depend on Exif support. Dimensions and thumbnails come from the
|
|
776
|
+
worker's decoded pixels. Only inputs over a byte, pixel, or side limit may be scaled or retried at a
|
|
777
|
+
smaller size. If normalization alone exceeds 32 MiB, insertion refuses it without resizing or a
|
|
778
|
+
scaled notice. Rendering also normalizes older externally supplied PNG/WebP references, with GPU
|
|
779
|
+
orientation draws waiting for the same idle/gesture gate as texture uploads.
|
|
780
|
+
|
|
781
|
+
The worker refuses inputs over 128 MiB or 100 megapixels before decoding, and safely refuses
|
|
782
|
+
when CSP or browser support prevents worker preprocessing. It never falls back to main-thread
|
|
783
|
+
scaling. Stored originals fit 32 MiB, 16,383 pixels per side, and their pixel-class limit. A bounded
|
|
784
|
+
ThumbHash travels with the reference. No bytes or object URLs are serialized into a document.
|
|
785
|
+
|
|
786
|
+
`ImageStore.get(hash, rung, { room, signal })` receives the room even
|
|
787
|
+
on read-only boards. URLs are fetched with CORS and credentials omitted. `put` may return canonical
|
|
788
|
+
`StoredImage` facts, including a thumb; otherwise the board uses its prepared facts. `renders`,
|
|
789
|
+
`touch`, `flush`, `pending`, `dispose`, `share`, `import`, and `refreshUrl` are optional capabilities.
|
|
790
|
+
`assetServiceStore` implements upload, signing, touch, share and import capabilities (below).
|
|
791
|
+
|
|
792
|
+
A store implementing `touch` owns each `(room, hash)` obligation until the service acknowledges
|
|
793
|
+
it, retries pending obligations independently of the board, and prevents an old acknowledgment
|
|
794
|
+
from clearing a newer obligation. `touch(room, hashes, { until, signal })` defaults to `until: "attempt"`,
|
|
795
|
+
which returns the first attempt's answers, including `pending`. With `until: "answered"` it waits
|
|
796
|
+
through background retries until every hash is `stored`, `missing`, or `denied`. An aborted signal
|
|
797
|
+
rejects that caller's wait; the store keeps its obligations and retries.
|
|
798
|
+
|
|
799
|
+
Pasted references and a link lookup's icon/preview pass a barrier before entering the document.
|
|
800
|
+
New hashes wait with `until: "answered"`; `stored` and `missing` allow the commit, and `denied`
|
|
801
|
+
omits the image while the operation's other objects still commit. Missing and denied results call
|
|
802
|
+
`onImageError`. A waiting paste has an overlay, lets editing continue, and uses the same idle-canvas
|
|
803
|
+
Escape cancellation as an upload. The live view determines which hashes can commit immediately;
|
|
804
|
+
a hash found only in trash or the undo stack still waits when pasted. Undo, redo, and duplication
|
|
805
|
+
write held values synchronously and touch afterward. An upload needs only its completed `put`.
|
|
806
|
+
A store without `touch` has no barrier. Clipboard copies carry validated thumbs and require full
|
|
807
|
+
lowercase SHA-256 hashes. A private object payload, or one the HTML carries, takes priority over a system
|
|
808
|
+
image file.
|
|
809
|
+
System image files upload only when no HTML is present or the inertly parsed HTML has no text beyond
|
|
810
|
+
whitespace. Office rich text therefore keeps the text paste path; image-only HTML still uploads.
|
|
811
|
+
Clipboard methods return `{ ids, pending }`; a deferred paste has empty `ids` and a non-null `pending`.
|
|
812
|
+
It commits later if it remains valid, preserving any intervening selection or gesture. Commit errors
|
|
813
|
+
use the browser's ordinary error reporting, and `pending` resolves with any IDs that actually committed;
|
|
814
|
+
they are never reported as an image store failure.
|
|
815
|
+
|
|
816
|
+
There is no mount registration, and the board never registers hashes inferred from its live view.
|
|
817
|
+
`board.images.flush()` delegates to `store.flush(room)`; `board.images.register(hashes, { signal })`
|
|
818
|
+
replaces `registerAll()` and delegates to `store.touch(room, hashes, { until: "answered", signal })`.
|
|
819
|
+
Both return `{ stored, missing, denied, pending }` sets; a completed `register` has no pending hashes.
|
|
820
|
+
Before publishing an imported document, the host lists all its history hashes (including trash and
|
|
821
|
+
replaced values), awaits `register(hashes)`, and publishes only if no hash was denied. Use
|
|
822
|
+
`imageHashesInHistory` from `@daasboard/doc` to extract them (below). Restoring the same room's own edits needs
|
|
823
|
+
no registration. The board's disposal never disposes the store. Keep
|
|
824
|
+
it alive while edits may publish, or transfer the obligations returned by `store.dispose()` to
|
|
825
|
+
another store. `store.pending()` exposes those obligations oldest first.
|
|
826
|
+
|
|
827
|
+
The decoded cache defaults to 256 MiB on GPU and 128 MiB on CPU, configurable via `memory.images`.
|
|
828
|
+
It counts mipmaps and thumbnails, evicts off-screen images, and degrades visible targets to fit.
|
|
829
|
+
`onImageError(hash, rung, reason)` reports every failed attempt, including read deadlines, transient
|
|
830
|
+
service errors and missing-image retries. The reason describes that attempt; a callback does not mean
|
|
831
|
+
the rung has failed permanently. A failed higher rung leaves ready lower rungs drawable.
|
|
832
|
+
Image-bearing objects have their own spatial index; neighborhood demand is planned on the renderer's idle
|
|
833
|
+
queue after the camera settles, with no per-frame demand walk on image-free boards.
|
|
834
|
+
Decode starts only outside live gestures. GPU uses browser decoding; CPU (including Node) uses
|
|
835
|
+
CanvasKit and refuses originals above 4096² pixels before allocation. GPU rungs stop at 4096;
|
|
836
|
+
CPU rungs stop at 2048. Image arrivals invalidate pictures and damage without text relayout.
|
|
837
|
+
An unresolved reference draws its validated thumb or the flat placeholder. A private clipboard copy
|
|
838
|
+
can carry short-lived shares for its image references. A paste touches the target room first and imports
|
|
839
|
+
only missing hashes with shares; it waits for those imports before committing its objects in one undo
|
|
840
|
+
step. If a share is absent, expired or refused, its SHA-256 reference remains as a placeholder and the
|
|
841
|
+
other objects still paste. A denied target omits its images. Cancellation or a board becoming read-only
|
|
842
|
+
before the wait ends prevents the paste from committing.
|
|
843
|
+
|
|
844
|
+
### The asset-service store
|
|
845
|
+
|
|
846
|
+
```ts
|
|
847
|
+
import { assetServiceStore, createBoard } from "@daasboard/embed";
|
|
848
|
+
|
|
849
|
+
const store = assetServiceStore({
|
|
850
|
+
endpoint: "https://assets.example.com", // Or https://assets.example.com/assets/v1.
|
|
851
|
+
token: async () => getAssetTokenFromYourBackend(),
|
|
852
|
+
// Optional: permit imports from these other asset deployments.
|
|
853
|
+
importOrigins: ["https://other-assets.example.com"],
|
|
854
|
+
// shareOnCopy: false, // Opt out of clipboard bearer capabilities.
|
|
855
|
+
});
|
|
856
|
+
const board = await createBoard({
|
|
857
|
+
container, document: page, assets,
|
|
858
|
+
images: { store, room: transportRoom },
|
|
859
|
+
});
|
|
860
|
+
```
|
|
861
|
+
|
|
862
|
+
Clipboard shares are written only for an HTTPS asset endpoint. On a plain-HTTP deployment,
|
|
863
|
+
images copied across tenants paste as placeholders.
|
|
864
|
+
|
|
865
|
+
Use the exact log room supplied to the document's transport. Board, page and tenant identifiers
|
|
866
|
+
are not substitutes. Keep one store per tenant, sharing it across boards as needed. The first asset
|
|
867
|
+
token pins the tenant; a later token naming another tenant rejects with
|
|
868
|
+
`AssetServiceError.code === "tenant_changed"` and keeps the first tenant's cache and obligations.
|
|
869
|
+
Create a new store when changing tenants. The server verifies tokens; the client reads only their
|
|
870
|
+
tenant and expiry for this binding and refreshes two minutes before expiry or once after an HTTP 401.
|
|
871
|
+
Concurrent refreshes share the provider call. Node imports and construction use no browser APIs.
|
|
872
|
+
|
|
873
|
+
`put` uses the board's existing SHA-256 without hashing again. It begins the upload for its room,
|
|
874
|
+
PUTs exactly to the returned `put.url` with `put.headers`, then awaits complete. A stored answer
|
|
875
|
+
deduplicates without a PUT. Service metadata supplies the returned dimensions, MIME and optional
|
|
876
|
+
thumb. Browser PUTs use XHR for byte progress; Node uses fetch and reports the start and completion.
|
|
877
|
+
Both paths support cancellation. PUT and complete have a deadline of 30 seconds plus one second
|
|
878
|
+
per 128 KiB, capped at five minutes. Copy has the separate budget below; other API requests have
|
|
879
|
+
a 30-second deadline.
|
|
880
|
+
|
|
881
|
+
`get` batches signing requests within a task, at most 256 hashes per room, and returns a signed URL
|
|
882
|
+
for the requested rung. Signatures are cached until five minutes before expiry. The first read for
|
|
883
|
+
each room is always signed with that room, even if its signatures are cached from another board.
|
|
884
|
+
Roomless reads are supported for callers such as server renderers. The bounded LRU defaults are
|
|
885
|
+
4,096 signatures and 256 rooms, configurable with `signatureCacheSize` and `roomCacheSize`;
|
|
886
|
+
eviction requires a new read. A failed read for another room preserves fresh signatures for drawing
|
|
887
|
+
in rooms already registered, but blocks sharing those hashes until their next successful sign.
|
|
888
|
+
No image bodies are cached by the store. SVG and ICO renditions need
|
|
889
|
+
a service that generates raster renditions; an originals-only service cannot draw them.
|
|
890
|
+
|
|
891
|
+
`share(hash)` is synchronous: it returns the cached signed `orig` URL and its expiry as Unix seconds,
|
|
892
|
+
or `null` if the image has no signature, fewer than five minutes remain, a refresh failed, a token
|
|
893
|
+
changed tenant, the store was disposed, or `shareOnCopy: false` was set. It never fetches or extends a
|
|
894
|
+
capability. Shares are HTTPS URLs and appear only in the private clipboard format's optional
|
|
895
|
+
`assets: { [sha256]: { url, expires } }` member. HTML and plain-text clipboard formats contain no shares.
|
|
896
|
+
A share is a bearer capability for one original and all its tiers for its remaining lifetime, normally
|
|
897
|
+
5–30 minutes. Clipboard managers, sync and native apps that read the private format can use it.
|
|
898
|
+
|
|
899
|
+
`import(hash, { url }, { room, signal })` sends `{ hash, from: url, room }` to `POST /assets/v1/copy`
|
|
900
|
+
with this store's pinned target-tenant token. A successful server copy returns its `StoredImage`
|
|
901
|
+
facts only once its original and record are present and its use for the destination room is confirmed.
|
|
902
|
+
It performs no browser PUT or staging upload. The client allows **360 seconds in total** for a copy,
|
|
903
|
+
including token acquisition, requests and retry waits. It retries `busy`, HTTP 5xx and network failures
|
|
904
|
+
after 1, 2, 4, 8, then at most 10 seconds, waiting longer when `Retry-After` requires it. Cancellation
|
|
905
|
+
or store disposal interrupts requests and retry waits. A refused source capability (`422 expired_share`
|
|
906
|
+
or a bad signature's 403), `denied`, `missing`, `hash_mismatch` and `invalid_request` are final for that
|
|
907
|
+
image; they do not refresh the target token. An actual target-token 401 permits one refresh.
|
|
908
|
+
The service bounds the transfer using the source record's byte count (30 seconds plus one second per
|
|
909
|
+
128 KiB); the client budget covers the largest copy and authorization with margin. This does not change
|
|
910
|
+
`put`/complete's existing deadline. A target already holding the hash needs only its touch.
|
|
911
|
+
|
|
912
|
+
Only the service's explicit `foreign_source` answer permits a foreign download. By default no foreign
|
|
913
|
+
origin is approved. `importOrigins` accepts HTTPS origins (an optional trailing slash, no credentials,
|
|
914
|
+
path, query or fragment). The source must itself be an HTTPS URL with no credentials or fragment,
|
|
915
|
+
exactly `/assets/v1/t/<32 lowercase hex>/<64 lowercase SHA-256>/orig`, and one canonical `e`, `k` and `s`
|
|
916
|
+
query field. Its path must name the requested hash and its signature must not be expired. The request
|
|
917
|
+
uses CORS, `credentials: "omit"` and `redirect: "error"`, with no target bearer token. Disallowed
|
|
918
|
+
origins and malformed or expired URLs are never fetched. Native download errors are reduced to a
|
|
919
|
+
code, without exposing their signed URL queries.
|
|
920
|
+
|
|
921
|
+
The foreign download has a **32 MiB body cap** (checked against Content-Length and every streamed chunk)
|
|
922
|
+
and a **30-second deadline** from request start through body consumption and SHA-256 verification.
|
|
923
|
+
A refused redirect, HTTP error, oversized or stalled response, cancellation, or SHA-256 mismatch fails
|
|
924
|
+
the import. Only verified original bytes enter `put`; the destination service inspects them and supplies
|
|
925
|
+
their dimensions and type. A denied destination is refused by the service before fallback, and again
|
|
926
|
+
by upload authorization if it becomes denied during the download. A refused share therefore retains its
|
|
927
|
+
hash placeholder after the paste's successful initial touch; it never changes the image's identity or
|
|
928
|
+
drops the paste's unrelated objects. `onImageError` reports the failure. Hosts should not log private
|
|
929
|
+
clipboard payloads or signed URL queries.
|
|
930
|
+
|
|
931
|
+
**Signed URL failures:** when a URL returns 403, the board calls the store's optional `refreshUrl`
|
|
932
|
+
once and retries the read. `assetServiceStore` implements this by re-signing the refused URL. Without
|
|
933
|
+
that capability, or when the replacement URL is also refused, the image is reported as `denied`.
|
|
934
|
+
The store also proactively refreshes signatures five minutes before expiry.
|
|
935
|
+
|
|
936
|
+
Touch obligations are owned by the store, each with its own sequence number. A failed attempt
|
|
937
|
+
returns `pending` and retries after 1, 2, 4, 8, 16, 32, then 60 seconds, with ±20% jitter and a hard
|
|
938
|
+
60-second maximum. Retries continue until answered or the host disposes the store. A 403 answers
|
|
939
|
+
`denied`; a successful response answers `stored` or `missing`. Waiting touches retain each answer
|
|
940
|
+
through background retries, so one denied hash cannot disappear while other hashes still wait.
|
|
941
|
+
`flush(room)` sends the obligations pending at that call immediately, bypassing backoff, and awaits
|
|
942
|
+
that attempt. Newer obligations are excluded; old replies never acknowledge newer touches.
|
|
943
|
+
`pending()` and `dispose()` return unique `{ room, hash }` pairs, oldest first. Disposal stops
|
|
944
|
+
retries and returns the remaining work for handoff; cancelling a waiting touch keeps its work.
|
|
945
|
+
|
|
946
|
+
The host must also honor the barrier when it writes image references itself. Before calling
|
|
947
|
+
`board.controller.create`, `set`, or writing an adapter directly with a new reference, await
|
|
948
|
+
`store.touch(room, hashes, { until: "answered" })` and refuse denied hashes, or first await a
|
|
949
|
+
successful `put` for that room. Those direct writes do not invoke the board's paste barrier.
|
|
950
|
+
|
|
951
|
+
For a full Loro import, stage the document before opening any publishing transport:
|
|
952
|
+
|
|
953
|
+
```ts
|
|
954
|
+
import { imageHashesInHistory, LoroPageDoc, WsTransport } from "@daasboard/doc";
|
|
955
|
+
|
|
956
|
+
const imported = LoroPageDoc.open(snapshotBytes);
|
|
957
|
+
const hashes = imageHashesInHistory(imported.doc);
|
|
958
|
+
const board = await createBoard({
|
|
959
|
+
container, document: imported, assets, images: { store, room },
|
|
960
|
+
});
|
|
961
|
+
const registration = await board.images.register(hashes, { signal });
|
|
962
|
+
if (registration.denied.size) throw new Error("Image history registration denied");
|
|
963
|
+
// Only now may the imported history enter the log.
|
|
964
|
+
const transport = new WsTransport(imported, relayUrl, room, {}, { token: roomToken });
|
|
965
|
+
```
|
|
966
|
+
|
|
967
|
+
`imageHashesInHistory(doc, since?)` returns sorted unique hashes from operation values, including
|
|
968
|
+
overwritten values, trash and deleted metadata. Its optional `since` is a Loro `VersionVector`;
|
|
969
|
+
it includes repeated writes after that version. It rejects shallow histories, invalid starting
|
|
970
|
+
versions and unsupported operation formats rather than publishing a partial registration set.
|
|
971
|
+
The helper may commit pending local operations, like Loro's export methods. A restored edit from
|
|
972
|
+
this same room and tenant already passed the barrier and needs no new registration.
|