noteloom 0.1.7 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +827 -438
- package/dist/index.d.ts +849 -0
- package/dist/noteloom.cjs +418 -12
- package/dist/noteloom.cjs.map +1 -1
- package/dist/noteloom.es.js +8636 -6289
- package/dist/noteloom.es.js.map +1 -1
- package/dist/style.css +410 -4
- package/package.json +31 -6
package/README.md
CHANGED
|
@@ -1,438 +1,827 @@
|
|
|
1
|
-
# noteloom
|
|
2
|
-
|
|
3
|
-
[](https://www.npmjs.com/package/noteloom)
|
|
4
|
-
[](https://www.npmjs.com/package/noteloom)
|
|
5
|
-
[](https://github.com/vishwakarmanikhil/noteloom/blob/master/LICENSE)
|
|
6
|
-
[](https://github.com/sponsors/vishwakarmanikhil)
|
|
7
|
-
|
|
8
|
-
**[Live site & docs →](https://noteloom.qusere.in)** · **[Play with the demo →](https://noteloom.qusere.in/playground/)**
|
|
9
|
-
|
|
10
|
-
A React-first, block-based rich text editor with **zero runtime dependencies** — the only things it expects from your app are `react` and `react-dom`. Everything else (undo/redo, clipboard, slash commands, tables, inline widgets) is built from scratch on top of a small normalized document store.
|
|
11
|
-
|
|
12
|
-
## ✨ Highlights
|
|
13
|
-
|
|
14
|
-
- **
|
|
15
|
-
- **Inline widgets mid-sentence** — select dropdowns, dates, checkboxes, and `@mentions`, spliced directly into running text, not forced onto their own line.
|
|
16
|
-
- **A real default theme**, injected automatically, fully retheme-able via CSS custom properties, or opt out entirely and bring your own.
|
|
17
|
-
- **Mobile/touch-first UI** — a bottom action bar, tap-friendly block picker, and touch-aware popovers, not just a desktop UI that technically renders on a phone.
|
|
18
|
-
- **Voice typing** — continuous dictation plus spoken structural commands ("heading one", "bulleted list", "undo") via the browser's own Speech API, no SDK bundled.
|
|
19
|
-
- **RTL & accessibility built in** — automatic per-block text direction, keyboard-operable menus, live-region announcements, and more.
|
|
20
|
-
- **Two JSON export shapes** — the normalized engine format, or a simpler self-contained shape for storage/API/CRUD use — plus HTML and plain-text export, all with a drop-in "View source" button.
|
|
21
|
-
- **Zero runtime dependencies**, a flat/normalized document model that diffs and stores cleanly, and fine-grained React re-rendering (editing one paragraph in a 500-block doc repaints just that block).
|
|
22
|
-
|
|
23
|
-
## Why this exists
|
|
24
|
-
|
|
25
|
-
Most rich-text editors either bring their own large dependency tree, or force every "special" piece of content (a dropdown, a date, a mention) onto its own line. This one is built around two ideas:
|
|
26
|
-
|
|
27
|
-
- **Inline heterogeneous content is a first-class citizen.** A `select` dropdown, a date picker, or an `@mention` chip can sit in the middle of a sentence, mixed with regular text, in one paragraph — not forced onto a block of its own.
|
|
28
|
-
- **Fine-grained React re-rendering, no virtual-DOM-for-content-editable fights.** Every block subscribes only to its own data via `useSyncExternalStore`; editing one paragraph in a 500-block document doesn't re-render anything else (see `test/performance/largeDocument.test.jsx` for the regression guard on this).
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
```
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
}
|
|
111
|
-
```
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
**
|
|
116
|
-
|
|
117
|
-
```jsx
|
|
118
|
-
<
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
```
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
```jsx
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
<
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
//
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
const
|
|
290
|
-
|
|
291
|
-
```
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
`
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
)
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
});
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
1
|
+
# noteloom
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/noteloom)
|
|
4
|
+
[](https://www.npmjs.com/package/noteloom)
|
|
5
|
+
[](https://github.com/vishwakarmanikhil/noteloom/blob/master/LICENSE)
|
|
6
|
+
[](https://github.com/sponsors/vishwakarmanikhil)
|
|
7
|
+
|
|
8
|
+
**[Live site & docs →](https://noteloom.qusere.in)** · **[Play with the demo →](https://noteloom.qusere.in/playground/)**
|
|
9
|
+
|
|
10
|
+
A React-first, block-based rich text editor with **zero runtime dependencies** — the only things it expects from your app are `react` and `react-dom`. Everything else (undo/redo, clipboard, slash commands, tables, inline widgets) is built from scratch on top of a small normalized document store.
|
|
11
|
+
|
|
12
|
+
## ✨ Highlights
|
|
13
|
+
|
|
14
|
+
- **11 built-in block types** — paragraph, heading, list (bulleted/numbered/to-do/toggle), table, multi-column layout, divider, callout, blockquote, code, toggle heading, button, and embed.
|
|
15
|
+
- **Inline widgets mid-sentence** — select dropdowns, dates, checkboxes, and `@mentions`, spliced directly into running text, not forced onto their own line.
|
|
16
|
+
- **A real default theme**, injected automatically, fully retheme-able via CSS custom properties, or opt out entirely and bring your own.
|
|
17
|
+
- **Mobile/touch-first UI** — a bottom action bar, tap-friendly block picker, and touch-aware popovers, not just a desktop UI that technically renders on a phone.
|
|
18
|
+
- **Voice typing** — continuous dictation plus spoken structural commands ("heading one", "bulleted list", "undo") via the browser's own Speech API, no SDK bundled.
|
|
19
|
+
- **RTL & accessibility built in** — automatic per-block text direction, keyboard-operable menus, live-region announcements, and more.
|
|
20
|
+
- **Two JSON export shapes** — the normalized engine format, or a simpler self-contained shape for storage/API/CRUD use — plus HTML and plain-text export, all with a drop-in "View source" button.
|
|
21
|
+
- **Zero runtime dependencies**, a flat/normalized document model that diffs and stores cleanly, and fine-grained React re-rendering (editing one paragraph in a 500-block doc repaints just that block).
|
|
22
|
+
|
|
23
|
+
## Why this exists
|
|
24
|
+
|
|
25
|
+
Most rich-text editors either bring their own large dependency tree, or force every "special" piece of content (a dropdown, a date, a mention) onto its own line. This one is built around two ideas:
|
|
26
|
+
|
|
27
|
+
- **Inline heterogeneous content is a first-class citizen.** A `select` dropdown, a date picker, or an `@mention` chip can sit in the middle of a sentence, mixed with regular text, in one paragraph — not forced onto a block of its own.
|
|
28
|
+
- **Fine-grained React re-rendering, no virtual-DOM-for-content-editable fights.** Every block subscribes only to its own data via `useSyncExternalStore`; editing one paragraph in a 500-block document doesn't re-render anything else (see `test/performance/largeDocument.test.jsx` for the regression guard on this).
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
# Getting started
|
|
33
|
+
|
|
34
|
+
## 1. Install
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
npm install noteloom react react-dom
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## 2. Create an editor
|
|
41
|
+
|
|
42
|
+
```jsx
|
|
43
|
+
import { useEditor, NoteloomEditor } from 'noteloom';
|
|
44
|
+
|
|
45
|
+
function Editor() {
|
|
46
|
+
const editor = useEditor();
|
|
47
|
+
return <NoteloomEditor editor={editor} />;
|
|
48
|
+
}
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
That's the whole thing. `useEditor()` creates a fully wired store (undo/redo included) and both registries pre-populated with every built-in block and inline type; `<NoteloomEditor>` renders it with clipboard, slash/emoji/@-mention menus, the floating format toolbar, keyboard shortcuts, and block-range drag already hooked up. No CSS to import either — see [Styling](#styling--zero-setup-required) below.
|
|
52
|
+
|
|
53
|
+
## 3. (Optional) pass a starting document, or turn off undo/redo
|
|
54
|
+
|
|
55
|
+
```jsx
|
|
56
|
+
const editor = useEditor({
|
|
57
|
+
doc: myDocumentJSON, // defaults to one empty paragraph
|
|
58
|
+
history: true, // default; false gives a plain EditorStore with no undo/redo
|
|
59
|
+
});
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## 4. Try it / learn by example
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
npm run dev:quickstart # the exact 3 lines above, runnable
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Then work through the rest of `examples/` in order — each one adds exactly one new idea on top of the last (a custom block, a custom dropdown field, theming, ...). See **[`examples/README.md`](examples/README.md)** for the full list and what each one teaches.
|
|
69
|
+
|
|
70
|
+
Everything past this point is a reference guide, in two parts:
|
|
71
|
+
|
|
72
|
+
- **[Basic guide](#basic-guide)** — every built-in feature (styling, custom field types, export, collaboration, offline, ...), all built on `useEditor()`/`<NoteloomEditor>` from step 2 above.
|
|
73
|
+
- **[Advanced: the granular API](#advanced-the-granular-api)** — for when you need more control than that gives you (a custom toolbar, a hand-picked subset of blocks, writing a whole new block component). `useEditor()` still hands you the raw pieces (`{ store, registry, inlineRegistry }`) to drop into this API — the two are never an either/or choice.
|
|
74
|
+
|
|
75
|
+
---
|
|
76
|
+
|
|
77
|
+
# Basic guide
|
|
78
|
+
|
|
79
|
+
Every example below uses `editor`/`store`/`registry`/`inlineRegistry` from `useEditor()` (`const { store, registry, inlineRegistry } = editor;`) unless it says otherwise.
|
|
80
|
+
|
|
81
|
+
## Built-in block types
|
|
82
|
+
|
|
83
|
+
`paragraph`, `heading` (h1–h3), `listItem` (bulleted, numbered, to-do, and toggle — with Tab/Shift+Tab nesting and standard Enter conventions), `table` (with row/column insert/delete), `layout` (multi-column), `divider`, `callout`, `blockquote`, `code`, `toggleHeading`, `button`, and `embed` (image/video/audio/file).
|
|
84
|
+
|
|
85
|
+
## Built-in inline types
|
|
86
|
+
|
|
87
|
+
Atomic, non-text content that can be spliced into running text via the slash menu at any cursor position — `select` (with in-editor add/remove-option UI), `date` (native `<input type="date">`), `checkbox`.
|
|
88
|
+
|
|
89
|
+
There's no separate hardcoded `mention` type — an `@name` chip is just an ordinary use of `createSelectFieldType` (see [Custom dropdown / mention field types](#custom-dropdown--mention-field-types-static-or-dynamicapi-backed) below), with `triggers: ['slash', 'at']` so it also shows up under a second, dedicated "@" trigger (`useAtMenuTrigger`), alongside "/".
|
|
90
|
+
|
|
91
|
+
## Styling — zero setup required
|
|
92
|
+
|
|
93
|
+
You don't need to import any CSS. The moment `<NoteloomEditor>` mounts, it injects a single `<style>` tag with a minimal, clean default theme — no `import 'noteloom/style.css'` line, no build-tool CSS configuration, nothing to wire up. It's idempotent (mounting more than one editor on a page only injects it once) and client-only (a no-op under SSR; hydrate as normal and it injects on mount).
|
|
94
|
+
|
|
95
|
+
**Retheme it** by overriding the CSS custom properties it reads from — defined on `:root` (not scoped to a wrapper element, since portaled pieces like the slash menu and Select's popover aren't DOM descendants of the editor itself):
|
|
96
|
+
|
|
97
|
+
```css
|
|
98
|
+
:root {
|
|
99
|
+
--noteloom-accent: #16a34a; /* swap the indigo accent for green */
|
|
100
|
+
--noteloom-radius-md: 4px; /* sharper corners */
|
|
101
|
+
--noteloom-font: 'Inter', sans-serif;
|
|
102
|
+
}
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
Dark mode follows `prefers-color-scheme` automatically; to control it explicitly instead (e.g. a manual light/dark toggle), set `data-theme="dark"` or `data-theme="light"` on any ancestor (typically `<html>`) — see the full variable list in `src/style.css`. (`examples/04-styling/` is a complete runnable version of everything in this section.)
|
|
106
|
+
|
|
107
|
+
**Scope overrides to one editor instance**, or add your own class for full custom CSS, via `className`/`style` — passing either wraps the editor surface in one `<div className="be-root ...">`:
|
|
108
|
+
|
|
109
|
+
```jsx
|
|
110
|
+
<NoteloomEditor editor={editor} className="my-editor" style={{ '--noteloom-accent': '#16a34a' }} />
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
No wrapper `<div>` is added unless you pass one of these props, so existing usage is unaffected either way.
|
|
114
|
+
|
|
115
|
+
**Opt out entirely** with `theme="none"` — nothing gets injected, and you take full responsibility for styling every `.be-*` class yourself (or import `noteloom/style.css` manually if you just want control over *when* it loads, e.g. before your own overrides in a specific `<link>` order):
|
|
116
|
+
|
|
117
|
+
```jsx
|
|
118
|
+
<NoteloomEditor editor={editor} theme="none" />
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
`examples/basic/src/style.css` shows the extra page-level chrome (fonts, page width, the demo's own toolbar buttons) a host app typically adds around the editor — none of that is part of the default theme itself.
|
|
122
|
+
|
|
123
|
+
**Customize individual blocks**, not just the root, via `getBlockClassName`:
|
|
124
|
+
|
|
125
|
+
```jsx
|
|
126
|
+
<NoteloomEditor editor={editor} getBlockClassName={(block) => (block.type === 'callout' ? 'my-callout' : undefined)} />
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
Whatever string you return is appended onto that block's own root element's class list (`be-paragraph my-callout`, alongside the fixed base class) — `block` is the real block object (`type`, `id`, `props`), so you can target a type, a specific id, or a prop value (e.g. every red callout) as precisely as you like.
|
|
130
|
+
|
|
131
|
+
## Picking only the blocks/inline types you want
|
|
132
|
+
|
|
133
|
+
`useEditor()` registers every built-in block/inline type by default — the fastest way to a fully-featured editor. If you'd rather ship only what you actually use, every built-in block/inline type is also exported individually, and `registerBlocks`/`registerInlineTypes` register just the ones you name, via `useEditor()`'s own `registerBlocks`/`registerInlineTypes` options:
|
|
134
|
+
|
|
135
|
+
```jsx
|
|
136
|
+
import { useEditor, NoteloomEditor, registerBlocks, paragraphBlockType, headingBlockType, TABLE_BLOCKS } from 'noteloom';
|
|
137
|
+
|
|
138
|
+
function Editor() {
|
|
139
|
+
const editor = useEditor({
|
|
140
|
+
registerBlocks: (registry) => registerBlocks(registry, { paragraph: paragraphBlockType, heading: headingBlockType, ...TABLE_BLOCKS }),
|
|
141
|
+
});
|
|
142
|
+
return <NoteloomEditor editor={editor} />;
|
|
143
|
+
}
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
`registerBuiltInBlocks(registry)` (what `useEditor()` calls by default) is itself just `registerBlocks(registry, { paragraph: paragraphBlockType, ... })` with every type included — so mixing "give me everything" and "just these few" across different parts of your app is never an either/or choice. `layout`/`table` each need their own group of related types registered together — see `LAYOUT_BLOCKS`/`TABLE_BLOCKS`. `TABLE_SELECT_INLINE_TYPES` (inline side) is only needed if you use a table's "select" column type.
|
|
147
|
+
|
|
148
|
+
To keep every built-in type **and** add your own on top, call `registerBuiltInBlocks` yourself inside the callback:
|
|
149
|
+
|
|
150
|
+
```jsx
|
|
151
|
+
import { useEditor, NoteloomEditor, registerBuiltInBlocks } from 'noteloom';
|
|
152
|
+
|
|
153
|
+
function Editor() {
|
|
154
|
+
const editor = useEditor({
|
|
155
|
+
registerBlocks: (registry) => {
|
|
156
|
+
registerBuiltInBlocks(registry); // keep everything built-in...
|
|
157
|
+
registry.register('myCustomType', myBlockTypeEntry); // ...plus your own (see "Advanced" below)
|
|
158
|
+
},
|
|
159
|
+
});
|
|
160
|
+
return <NoteloomEditor editor={editor} />;
|
|
161
|
+
}
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
`examples/02-custom-block/` is a complete runnable version of this pattern.
|
|
165
|
+
|
|
166
|
+
## Custom dropdown / mention field types (static, or dynamic/API-backed)
|
|
167
|
+
|
|
168
|
+
`createSelectFieldType(config)` builds a full, ready-to-register inline type from a plain config object — this is how you add your own named dropdown ("Assignee", "Status", "Priority", ...) **without writing a component**:
|
|
169
|
+
|
|
170
|
+
```jsx
|
|
171
|
+
import { useEditor, NoteloomEditor, registerBuiltInInlineTypes, createSelectFieldType } from 'noteloom';
|
|
172
|
+
|
|
173
|
+
const statusFieldType = createSelectFieldType({
|
|
174
|
+
type: 'status', // must match the key you register it under
|
|
175
|
+
label: 'Status', // shown in the "/" menu and as the search box's aria-label
|
|
176
|
+
placeholder: 'Set status…',
|
|
177
|
+
variant: 'tag', // 'tag' = colored pill; 'default' = plain bordered dropdown
|
|
178
|
+
options: [
|
|
179
|
+
{ value: 'todo', label: 'To do', color: { bg: '#e9e9e7', text: '#37352f' } },
|
|
180
|
+
{ value: 'doing', label: 'In progress', color: { bg: '#fdecc8', text: '#a06400' } },
|
|
181
|
+
{ value: 'done', label: 'Done', color: { bg: '#dbeddb', text: '#2f7a2f' } },
|
|
182
|
+
],
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
function Editor() {
|
|
186
|
+
const editor = useEditor({
|
|
187
|
+
registerInlineTypes: (inlineRegistry) => {
|
|
188
|
+
registerBuiltInInlineTypes(inlineRegistry);
|
|
189
|
+
inlineRegistry.register('status', statusFieldType);
|
|
190
|
+
},
|
|
191
|
+
});
|
|
192
|
+
return <NoteloomEditor editor={editor} />;
|
|
193
|
+
}
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
`examples/03-custom-field-type/` is a complete runnable version of this pattern.
|
|
197
|
+
|
|
198
|
+
`options` can also be a **function** instead of a plain array — `(query) => Option[] | Promise<Option[]>` — for a real database/API-backed search (React Select's `loadOptions`, essentially):
|
|
199
|
+
|
|
200
|
+
```js
|
|
201
|
+
createSelectFieldType({
|
|
202
|
+
type: 'assignee',
|
|
203
|
+
label: 'Assignee',
|
|
204
|
+
placeholder: 'Assign to…',
|
|
205
|
+
variant: 'tag',
|
|
206
|
+
triggers: ['slash', 'at'], // reachable via "/assignee" AND by typing "@" directly
|
|
207
|
+
options: async (query) => {
|
|
208
|
+
const res = await fetch(`/api/users?search=${encodeURIComponent(query)}`);
|
|
209
|
+
const users = await res.json();
|
|
210
|
+
return users.map((u) => ({ value: u.id, label: u.name }));
|
|
211
|
+
},
|
|
212
|
+
});
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
A few things worth knowing about the dynamic path:
|
|
216
|
+
|
|
217
|
+
- Your function is called **fresh on every keystroke**, debounced ~250ms — there's no built-in caching layer, so if you want caching, memoize inside your own function.
|
|
218
|
+
- Only the **resolved pick** — `{ value, label }` (plus `color` for the tag variant) — is ever written onto the document. The live options list itself is never persisted, so a chip never embeds a stale snapshot of your database; re-opening it always calls your function again.
|
|
219
|
+
- `triggers` (default `['slash']`) decides whether the type shows up under `/`, `@` (via `useAtMenuTrigger`), or both. A field that doesn't read naturally after "@" (e.g. "Priority") should usually stay slash-only.
|
|
220
|
+
|
|
221
|
+
### Letting end users create their own field types, in-editor
|
|
222
|
+
|
|
223
|
+
The above is for types **you** define in code. If you also want a non-technical end user to be able to create new (always static — there's no way to author a fetch function through a UI) select types from inside the editor itself, mount `FieldTypeEditorModal` once and wire a button to it, anywhere inside `<NoteloomEditor>` (as `children`, or in your own chrome around it via `useFieldTypeEditor`):
|
|
224
|
+
|
|
225
|
+
```jsx
|
|
226
|
+
import { NoteloomEditor, FieldTypeEditorModal, useFieldTypeEditor } from 'noteloom';
|
|
227
|
+
|
|
228
|
+
function NewFieldTypeButton() {
|
|
229
|
+
const { openCreate } = useFieldTypeEditor();
|
|
230
|
+
return <button onClick={openCreate}>+ New field type</button>;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
<NoteloomEditor editor={editor}>
|
|
234
|
+
<NewFieldTypeButton />
|
|
235
|
+
<FieldTypeEditorModal />
|
|
236
|
+
</NoteloomEditor>;
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
User-created types are persisted in the document's own `fieldTypes` collection (so they survive reload) and are automatically rehydrated back into your inline registry by `FieldTypeEditorModal` itself — you don't need to call anything extra. Each chip's popover also gets a "Manage options…" entry that reopens this same modal, pre-filled, for renaming/editing/deleting the type it belongs to.
|
|
240
|
+
|
|
241
|
+
## Exporting the document (JSON / HTML / plain text)
|
|
242
|
+
|
|
243
|
+
```js
|
|
244
|
+
import { exportDocumentJSON, exportDocumentHTML, exportDocumentText } from 'noteloom';
|
|
245
|
+
|
|
246
|
+
exportDocumentJSON(store); // a JSON *string* — JSON.parse() it to get { version, rootId, blocks, runs }, usable as useEditor({ doc })
|
|
247
|
+
exportDocumentHTML(store, registry, inlineRegistry);
|
|
248
|
+
exportDocumentText(store, registry, inlineRegistry);
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
Or mount the ready-made button + modal instead of wiring your own UI:
|
|
252
|
+
|
|
253
|
+
```jsx
|
|
254
|
+
import { DocumentExportButton } from 'noteloom';
|
|
255
|
+
|
|
256
|
+
<DocumentExportButton label="View source" />
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
It opens a modal with JSON/Simple JSON/HTML/Text tabs (reading live from the store every time it opens) and a Copy button — useful for debugging, or as a starting point for a real "export" feature.
|
|
260
|
+
|
|
261
|
+
### A simpler JSON shape for storage/API/CRUD use
|
|
262
|
+
|
|
263
|
+
`exportDocumentJSON()` above returns the *internal engine format* — the same normalized, id-referenced graph `EditorStore` operates on (blocks reference other blocks by id; text lives in a separate `runs` collection, not embedded inline). That shape is what makes per-run reactivity, O(1) structural edits, and real nesting (toggle lists, tables, inline atomic chips) work — it's not going to look like a simple flat document, on purpose.
|
|
264
|
+
|
|
265
|
+
If you just want something simpler to store, send over an API, or hand-edit — self-contained blocks in an array, `children` for nesting, no id-references to resolve — use the second, optional export/import pair instead:
|
|
266
|
+
|
|
267
|
+
```js
|
|
268
|
+
import { exportDocumentSimpleJSON, importDocumentSimpleJSON } from 'noteloom';
|
|
269
|
+
|
|
270
|
+
const json = exportDocumentSimpleJSON(store, registry, inlineRegistry);
|
|
271
|
+
// {
|
|
272
|
+
// "version": 1,
|
|
273
|
+
// "blocks": [
|
|
274
|
+
// { "id": "p1", "type": "paragraph", "data": { "text": "Hello <strong>world</strong>" } },
|
|
275
|
+
// { "id": "h1", "type": "heading", "data": { "text": "Key features", "level": 3 } },
|
|
276
|
+
// {
|
|
277
|
+
// "id": "li1", "type": "listItem",
|
|
278
|
+
// "data": { "text": "Nested item", "ordered": false, "checked": null },
|
|
279
|
+
// "children": [ /* nested listItem blocks, same shape */ ]
|
|
280
|
+
// },
|
|
281
|
+
// {
|
|
282
|
+
// "id": "t1", "type": "table",
|
|
283
|
+
// "data": { "columns": [{ "id": "c1", "label": "Name" }], "rows": [["Cell text"]] }
|
|
284
|
+
// }
|
|
285
|
+
// ]
|
|
286
|
+
// }
|
|
287
|
+
|
|
288
|
+
// ...later, or on a different machine/process:
|
|
289
|
+
const doc = importDocumentSimpleJSON(json, registry, inlineRegistry); // -> { rootId, blocks, runs }
|
|
290
|
+
const editor2 = useEditor({ doc }); // or `new EditorStore(doc)` directly outside React
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
Rich text (`data.text`) is an HTML string — the exact same per-run serialization every block type's own clipboard-copy `toHTML` already produces, so marks (bold/italic/underline/strike/code/sub/superscript/color/highlight/link) and atomic inline chips (checkbox/date/select/mention) round-trip through it the same way copy/paste already does. `table` is flattened specially (`data.columns` + `data.rows`, a 2D array) rather than exposing the internal table/row/cell block chain — the single biggest simplification versus the internal shape. Block/run ids are preserved on both export and import (useful for referencing/updating a specific block from an external system).
|
|
294
|
+
|
|
295
|
+
One existing, by-design limitation carried over from clipboard paste: an atomic inline type's *core* value round-trips (a checkbox's checked state + label, a date's ISO value, a select's chosen value + label) but its full `options` list does not — only the currently-selected option survives, the same as pasting one of these chips into another instance of the editor today.
|
|
296
|
+
|
|
297
|
+
This is purely an additive, alternate *interchange* format — the internal engine format above is unaffected either way, and this is not a replacement for it.
|
|
298
|
+
|
|
299
|
+
## Templates
|
|
300
|
+
|
|
301
|
+
Two kinds — a **document template** seeds a whole new editor (`useEditor({ doc })`), a **block template** is a saved snippet insertable anywhere via "/". Both are developer-definable in code and end-user-creatable/persisted (IndexedDB, alongside `usePersistedDocument`'s own storage but a separate object store — a template isn't tied to any one document). `examples/05-templates/` is a complete runnable app combining every piece below.
|
|
302
|
+
|
|
303
|
+
**Block templates — reusable snippets, insertable via "/":**
|
|
304
|
+
|
|
305
|
+
```js
|
|
306
|
+
import { EditorStore, captureBlockTemplate, registerBlockTemplates, registerBuiltInBlocks } from 'noteloom';
|
|
307
|
+
|
|
308
|
+
// Build once (a throwaway store is fine — only its content is captured):
|
|
309
|
+
const draftStore = new EditorStore({
|
|
310
|
+
rootId: 'root',
|
|
311
|
+
blocks: [
|
|
312
|
+
{ id: 'root', type: 'page', parentId: null, contentIds: ['h1', 'li1'], props: {} },
|
|
313
|
+
{ id: 'h1', type: 'heading', parentId: 'root', contentIds: ['r1'], props: { level: 2 } },
|
|
314
|
+
{ id: 'li1', type: 'listItem', parentId: 'root', contentIds: [], props: { ordered: true, titleRunIds: ['r2'] } },
|
|
315
|
+
],
|
|
316
|
+
runs: [
|
|
317
|
+
{ id: 'r1', type: 'text', value: 'Meeting agenda', marks: {} },
|
|
318
|
+
{ id: 'r2', type: 'text', value: 'Review previous action items', marks: {} },
|
|
319
|
+
],
|
|
320
|
+
});
|
|
321
|
+
const agendaSnippet = captureBlockTemplate(draftStore, ['h1', 'li1']);
|
|
322
|
+
|
|
323
|
+
const editor = useEditor({
|
|
324
|
+
registerBlocks: (registry) => {
|
|
325
|
+
registerBuiltInBlocks(registry);
|
|
326
|
+
registerBlockTemplates(registry, [{ id: 'agenda', label: 'Meeting agenda', keywords: ['agenda'], roots: agendaSnippet.roots }]);
|
|
327
|
+
},
|
|
328
|
+
});
|
|
329
|
+
```
|
|
330
|
+
|
|
331
|
+
Typing "/agenda" now shows "Meeting agenda" in the slash menu, same as any built-in block — no changes needed to `SlashMenu`/`useSlashMenuTrigger`, since `registerBlockTemplates` registers under the hood exactly the way a real block type does (just one that's never actually rendered — only its *captured content*, which already has real block types, gets inserted). `insertBlockTemplate(store, template, { parentId, index })` does the same insertion directly, if you want a button instead of/alongside "/".
|
|
332
|
+
|
|
333
|
+
**Document templates — starter documents:** no new primitives needed — a document template *is* a `DocumentJSON`, so `useEditor({ doc: someTemplate.doc })` already covers "start a new editor from it." To apply one to an **already-mounted** editor instead, use `applyDocumentTemplate(store, doc)`.
|
|
334
|
+
|
|
335
|
+
**Saving/browsing a library of templates** (either kind), persisted so it survives reload:
|
|
336
|
+
|
|
337
|
+
```jsx
|
|
338
|
+
import { useEditor, NoteloomEditor, useTemplates, TemplatePicker, saveTemplate, exportDocumentJSON } from 'noteloom';
|
|
339
|
+
|
|
340
|
+
function NewDocumentScreen({ onPick }) {
|
|
341
|
+
const { templates, isLoaded } = useTemplates({ scope: 'document' }); // or 'block', or omit for both
|
|
342
|
+
if (!isLoaded) return <p>Loading…</p>;
|
|
343
|
+
return <TemplatePicker templates={templates} onSelect={(template) => onPick(template.doc)} />;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// Saving the current document as a reusable template:
|
|
347
|
+
async function saveCurrentAsTemplate(store, name) {
|
|
348
|
+
await saveTemplate({
|
|
349
|
+
id: crypto.randomUUID(),
|
|
350
|
+
scope: 'document',
|
|
351
|
+
name,
|
|
352
|
+
doc: JSON.parse(exportDocumentJSON(store)), // exportDocumentJSON returns a JSON *string* — parse it first
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
```
|
|
356
|
+
|
|
357
|
+
`TemplatePicker` is deliberately just a plain list (name + description + a "Use" button) — wrap it in the exported `Modal` component yourself, or render it inline, whichever fits; what `onSelect` actually does (apply it, insert it, just read `.doc`) is up to you, since that differs by scope. `saveTemplate`/`loadTemplate`/`deleteTemplate`/`listTemplates` are the raw storage operations `useTemplates` is built on, for anywhere the hook's all-in-one behavior doesn't fit.
|
|
358
|
+
|
|
359
|
+
**Importing a template from a file** — since a stored template is already plain JSON, this needs no new format or function, just `saveTemplate(JSON.parse(fileText))`:
|
|
360
|
+
|
|
361
|
+
```jsx
|
|
362
|
+
async function handleImport(event) {
|
|
363
|
+
const template = JSON.parse(await event.target.files[0].text());
|
|
364
|
+
await saveTemplate(template);
|
|
365
|
+
}
|
|
366
|
+
```
|
|
367
|
+
|
|
368
|
+
(Exporting one for sharing is the mirror image — `JSON.stringify(template)`, downloaded as a `.json` file — ordinary front-end code, not something this package needs to provide.)
|
|
369
|
+
|
|
370
|
+
## Comments
|
|
371
|
+
|
|
372
|
+
Select a range, leave a comment on it; click or hover the highlighted text later to view/reply/resolve/delete it — `examples/06-comments/` is a complete runnable app. Two ways to wire it up:
|
|
373
|
+
|
|
374
|
+
### The built-in UI (zero comment-authoring code of your own)
|
|
375
|
+
|
|
376
|
+
Pass `commentAuthorId` — the current user's id — to `<NoteloomEditor>` and the whole experience just works, Notion/Google Docs-style:
|
|
377
|
+
|
|
378
|
+
```jsx
|
|
379
|
+
<NoteloomEditor editor={editor} commentAuthorId={currentUser.id} showCommentsPanel />
|
|
380
|
+
```
|
|
381
|
+
|
|
382
|
+
- The floating format toolbar's Comment button opens a small inline composer (a textarea, matching the rest of the toolbar's minimal chrome) and creates the comment on submit.
|
|
383
|
+
- Clicking (or hovering) any highlighted comment opens a popover right there with the thread's messages and Reply/Resolve/Delete — mirroring how the existing link hover card works, just triggered by click too, not hover alone.
|
|
384
|
+
- `showCommentsPanel` (optional) adds a right-side panel listing every thread in the document, unresolved first — the "extra feature" for apps that want a persistent overview alongside the inline popovers, not instead of them. It's `position: fixed` by default (see `.be-comments-panel` in style.css) so it needs no layout changes on your end; override that rule for a different placement.
|
|
385
|
+
|
|
386
|
+
Every reply/new-comment composed through any of these built-in surfaces is attributed to `commentAuthorId`. Omit it and the toolbar's Comment button disappears, the click/hover popover on existing comments still works (viewing/resolving/deleting need no identity) but hides its Reply composer, and `showCommentsPanel` still lists threads read-only in the same way.
|
|
387
|
+
|
|
388
|
+
For the granular API, render the pieces yourself anywhere under an `<EditorProvider commentAuthorId={currentUser.id}>`: `<FloatingToolbar commentAuthorId={...} .../>` for the toolbar button, `<CommentsPanel authorId={...} />` for the sidebar — the click/hover popover (`CommentPopover`) is mounted automatically inside every block's editable content, same as the link hover card, so there's nothing extra to render for it.
|
|
389
|
+
|
|
390
|
+
### Full control (bring your own UI)
|
|
391
|
+
|
|
392
|
+
Pass `onComment` instead of `commentAuthorId` — it's called with the selected range and you decide what happens next (open your own modal, pick the author yourself):
|
|
393
|
+
|
|
394
|
+
```jsx
|
|
395
|
+
import { addComment, replyToComment, resolveComment, deleteComment, useComments, resolveMultiRunSelection } from 'noteloom';
|
|
396
|
+
|
|
397
|
+
<NoteloomEditor
|
|
398
|
+
editor={editor}
|
|
399
|
+
onComment={(range) => {
|
|
400
|
+
const text = window.prompt('Comment text?');
|
|
401
|
+
if (text) addComment(editor.store, range, { authorId: currentUser.id, text });
|
|
402
|
+
}}
|
|
403
|
+
/>;
|
|
404
|
+
|
|
405
|
+
// Outside the floating toolbar entirely, resolve the selection yourself:
|
|
406
|
+
function AddCommentButton({ store }) {
|
|
407
|
+
function handleClick() {
|
|
408
|
+
const range = resolveMultiRunSelection(); // { blockId, startRunId, startOffset, endRunId, endOffset }
|
|
409
|
+
if (!range) return; // no non-collapsed selection
|
|
410
|
+
addComment(store, range, { authorId: currentUser.id, text: 'Can we tighten this up?' });
|
|
411
|
+
}
|
|
412
|
+
return <button onClick={handleClick}>Add comment</button>;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
// A hand-rolled list, using useComments() directly instead of CommentsPanel/CommentThreadCard:
|
|
416
|
+
function CommentsSidebar({ store }) {
|
|
417
|
+
const comments = useComments();
|
|
418
|
+
return (
|
|
419
|
+
<ul>
|
|
420
|
+
{comments.map((thread) => (
|
|
421
|
+
<li key={thread.id}>
|
|
422
|
+
{thread.messages.map((m) => <p key={m.id}>{m.authorId}: {m.text}</p>)}
|
|
423
|
+
<button onClick={() => replyToComment(store, thread.id, { authorId: currentUser.id, text: '...' })}>Reply</button>
|
|
424
|
+
<button onClick={() => resolveComment(store, thread.id, !thread.resolved)}>{thread.resolved ? 'Reopen' : 'Resolve'}</button>
|
|
425
|
+
<button onClick={() => deleteComment(store, thread.id)}>Delete</button>
|
|
426
|
+
</li>
|
|
427
|
+
))}
|
|
428
|
+
</ul>
|
|
429
|
+
);
|
|
430
|
+
}
|
|
431
|
+
```
|
|
432
|
+
|
|
433
|
+
`onComment` (given to `<NoteloomEditor>` or `<FloatingToolbar>` directly) always takes priority over `commentAuthorId`'s built-in composer, so the two can't fight over the same button. The Comment button only appears for a same-block selection either way — `addCommentMarkOverRange` doesn't support a cross-block range yet, the same single-block scope every mark-toggle command already has for its own splitting logic.
|
|
434
|
+
|
|
435
|
+
A comment thread is `{ id, blockId, anchorRunIds, resolved, messages: [{ id, authorId, text, createdAt }] }`. `CommentThreadCard`/`CommentComposer` (the pieces `CommentPopover`/`CommentsPanel` are built from) are exported too, for reusing the built-in look while customizing the surrounding layout.
|
|
436
|
+
|
|
437
|
+
**Scope, stated plainly:** a thread's own metadata (text, author, replies, resolved flag) is fully collaboration-aware — it broadcasts live to connected peers and undoes/redoes normally. The *highlighted range* it's anchored to is local-only in collaboration for v1: a newly-joining peer sees it correctly (full document snapshots always include it), but an already-connected peer won't see someone else's brand-new highlight appear live until their next resync. This isn't a new gap introduced by comments — every other range-based formatting operation (bold, italic, highlight, ...) already has this exact scope today, since none of them have a CRDT-safe wire representation yet.
|
|
438
|
+
|
|
439
|
+
`thread.anchorRunIds` is a creation-time hint only, meant for jumping to roughly where a comment was made — it is **not** re-validated after a later formatting edit splits or re-mints run ids in that range. To reliably find where a comment's highlight actually lives right now, look at which runs' `marks.commentIds` include it (exactly what `deleteComment` itself does internally via `removeCommentMarkEverywhere`), not `anchorRunIds`.
|
|
440
|
+
|
|
441
|
+
## Version history
|
|
442
|
+
|
|
443
|
+
Point-in-time document snapshots, stored in IndexedDB (a third object store, alongside `usePersistedDocument`'s `documents` and Templates' `templates`) — periodic, manual, or both. `examples/07-version-history/` is a complete runnable app with a version list and one-click restore.
|
|
444
|
+
|
|
445
|
+
```jsx
|
|
446
|
+
import { createPeriodicVersionSnapshotter, useDocumentVersions, saveDocumentVersion, applyDocumentTemplate, exportDocumentJSON } from 'noteloom';
|
|
447
|
+
|
|
448
|
+
// Automatic: snapshot every few minutes, keep the most recent 50.
|
|
449
|
+
useEffect(() => {
|
|
450
|
+
const snapshotter = createPeriodicVersionSnapshotter({ store: editor.store, docId, intervalMs: 5 * 60 * 1000 });
|
|
451
|
+
return () => snapshotter.stop();
|
|
452
|
+
}, [editor.store, docId]);
|
|
453
|
+
|
|
454
|
+
// Manual: "save a version now" button.
|
|
455
|
+
async function saveNow(label) {
|
|
456
|
+
const doc = JSON.parse(exportDocumentJSON(editor.store)); // exportDocumentJSON returns a JSON *string* — parse it first
|
|
457
|
+
await saveDocumentVersion({ id: crypto.randomUUID(), docId, timestamp: Date.now(), label, doc });
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
// A version list:
|
|
461
|
+
function VersionList({ docId }) {
|
|
462
|
+
const { versions, isLoaded } = useDocumentVersions(docId); // newest first
|
|
463
|
+
if (!isLoaded) return <p>Loading…</p>;
|
|
464
|
+
return (
|
|
465
|
+
<ul>
|
|
466
|
+
{versions.map((v) => (
|
|
467
|
+
<li key={v.id}>
|
|
468
|
+
{v.label ?? '(untitled)'} — {new Date(v.timestamp).toLocaleString()}
|
|
469
|
+
<button onClick={() => applyDocumentTemplate(editor.store, v.doc)}>Restore</button>
|
|
470
|
+
</li>
|
|
471
|
+
))}
|
|
472
|
+
</ul>
|
|
473
|
+
);
|
|
474
|
+
}
|
|
475
|
+
```
|
|
476
|
+
|
|
477
|
+
Restoring needs no new function — it's the exact same `applyDocumentTemplate(store, doc)` Templates already uses to wholesale-replace a live editor's content. `saveDocumentVersion`/`loadDocumentVersion`/`deleteDocumentVersion`/`listDocumentVersions` are the raw storage operations `useDocumentVersions` is built on. `createPeriodicVersionSnapshotter({ store, docId, intervalMs?, label?, maxVersions? })` prunes the oldest version past `maxVersions` (default 50) after each snapshot, so a long-running document doesn't grow the store unbounded.
|
|
478
|
+
|
|
479
|
+
## Right-to-left / multi-language text
|
|
480
|
+
|
|
481
|
+
Every block defaults to `dir="auto"` — the browser's own Unicode bidi algorithm detects direction per block from its first strong character, so a document mixing LTR and RTL blocks (an English heading over an Arabic paragraph, say) just works with zero configuration. For the cases `auto` can't infer on its own (most commonly an empty block, which has no text yet to detect a direction from), set an explicit override:
|
|
482
|
+
|
|
483
|
+
```js
|
|
484
|
+
import { operations } from 'noteloom';
|
|
485
|
+
|
|
486
|
+
// Document-wide default:
|
|
487
|
+
store.applyOperation(operations.updateBlockProps(store.getRootId(), { dir: 'rtl' }));
|
|
488
|
+
// Or just one block:
|
|
489
|
+
store.applyOperation(operations.updateBlockProps(blockId, { dir: 'rtl' }));
|
|
490
|
+
```
|
|
491
|
+
|
|
492
|
+
A block's own `dir` wins over the document's; the block gutter menu also has a "Switch to right-to-left"/"left-to-right" item that sets this per-block. Code blocks are always `dir="ltr"` regardless of the surrounding document's default — code syntax (brackets, operators) is structurally LTR no matter what language a comment or string literal happens to be written in.
|
|
493
|
+
|
|
494
|
+
This pass covers the reading/typing/gutter-position direction itself; a full logical-properties (`margin-inline-start` etc.) audit of every pixel value in `style.css` is deliberately out of scope for now — the highest-impact pieces (list/checkbox marker position, blockquote border side, block gutter position) already flip correctly.
|
|
495
|
+
|
|
496
|
+
## Printing & PDF
|
|
497
|
+
|
|
498
|
+
`style.css` includes a built-in `@media print` stylesheet: every piece of editing chrome (the block gutter, all portaled menus, the floating toolbar, resize handles, the mobile action bar, etc.) is hidden automatically, and a block hidden via "Hide in preview" stays hidden in the printout too, regardless of whether the app happens to be toggled into preview mode at the moment you print — printing always behaves like preview mode.
|
|
499
|
+
|
|
500
|
+
There's no bundled PDF-generation library (that would need a real dependency like jsPDF/pdfmake, conflicting with staying zero-runtime-dependency) — the browser's own print-to-PDF is the intended path:
|
|
501
|
+
|
|
502
|
+
```js
|
|
503
|
+
window.print(); // Ctrl+P / Cmd+P works too — "Save as PDF" in the print dialog is your PDF export
|
|
504
|
+
```
|
|
505
|
+
|
|
506
|
+
This only cleans up the *editor's* own chrome. A host app's own outer UI (nav bar, sidebar, its own toolbar) needs its own `@media print` rules the same way — see `examples/basic/src/style.css` for a worked example, since that chrome lives entirely outside this package.
|
|
507
|
+
|
|
508
|
+
## Voice typing
|
|
509
|
+
|
|
510
|
+
`useVoiceTyping()` wraps the browser's native Web Speech API (`SpeechRecognition`) for continuous dictation mixed with spoken structural commands — say "heading one", "new paragraph", "bulleted list", "quote", "undo", etc. while dictating, and the current block converts (or a new one is inserted) instead of those words being typed as text:
|
|
511
|
+
|
|
512
|
+
```jsx
|
|
513
|
+
import { useVoiceTyping } from 'noteloom';
|
|
514
|
+
|
|
515
|
+
function MicButton() {
|
|
516
|
+
const voice = useVoiceTyping();
|
|
517
|
+
if (!voice.isSupported) return null; // e.g. Firefox — no bundled fallback, degrades to nothing
|
|
518
|
+
return (
|
|
519
|
+
<button onClick={() => (voice.isListening ? voice.stop() : voice.start())}>
|
|
520
|
+
{voice.isListening ? 'Stop dictation' : 'Start dictation'}
|
|
521
|
+
</button>
|
|
522
|
+
);
|
|
523
|
+
}
|
|
524
|
+
```
|
|
525
|
+
|
|
526
|
+
No speech-to-text SDK is bundled (same zero-runtime-dependency reasoning as PDF export above) — this is built entirely on the browser's own `SpeechRecognition`/`webkitSpeechRecognition`, so `isSupported` is `false` wherever that API doesn't exist. A command is only recognized when an entire *finalized* spoken utterance (a natural pause before/after, as reported by the Speech API itself) matches a known phrase exactly — see `src/voice/voiceCommands.js` for the full table — so a command word merely mentioned mid-sentence while dictating prose is never misread as a command.
|
|
527
|
+
|
|
528
|
+
## Mobile / touch support
|
|
529
|
+
|
|
530
|
+
Typing "/"/"@" still works on a phone keyboard, but it's not a reliable or discoverable primary path there (autocorrect, awkward key access, nothing to discover it by) — so on a coarse (touch) pointer, `MobileActionBar` takes over as the touch-first equivalent, pinned above the on-screen keyboard. It needs direct access to the same DOM element your editor surface renders into (to track focus/selection inside it), which `<NoteloomEditor>` doesn't expose — so this one piece needs the [granular API](#advanced-the-granular-api):
|
|
531
|
+
|
|
532
|
+
```jsx
|
|
533
|
+
import { MobileActionBar } from 'noteloom';
|
|
534
|
+
|
|
535
|
+
// next to your other trigger hooks/components, same containerRef:
|
|
536
|
+
<MobileActionBar containerRef={containerRef} />
|
|
537
|
+
```
|
|
538
|
+
|
|
539
|
+
`examples/basic` has this fully wired up (run `npm run dev`, then resize to a narrow viewport or open it on a phone).
|
|
540
|
+
|
|
541
|
+
It renders nothing on a mouse/trackpad, and nothing until focus is actually inside the editor. Its contents swap based on context:
|
|
542
|
+
|
|
543
|
+
- **Block options** (shown whenever the caret/selection is inside any block) → Duplicate/Move up/Move down/Hide-Show/Delete, in `MobileBlockOptionsSheet` — the mobile home for the desktop per-block gutter's own grip-handle menu. The gutter itself is hidden entirely on touch input (no hover state exists to reveal it by, and its desktop position sits in a page margin that doesn't exist on a narrow viewport), so both of its actions ("+" and the options menu) live in this bar instead of the gutter on touch.
|
|
544
|
+
- **Text selected** → formatting actions (bold/italic/underline/link) — the desktop `FloatingToolbar` bubble also disables itself on touch, so this is the single formatting surface either way (both share the same `useTextFormattingActions` hook, not two copies).
|
|
545
|
+
- **Collapsed caret, table cell** → insert row/column.
|
|
546
|
+
- **Collapsed caret, code block** → language picker.
|
|
547
|
+
- **Collapsed caret, callout** → color picker.
|
|
548
|
+
- **Collapsed caret, everywhere else** → "+" (opens `MobileBlockPickerSheet`, a tap-friendly bottom sheet listing every insertable block, same commands "/" already offers), Undo/Redo, dismiss-keyboard.
|
|
549
|
+
|
|
550
|
+
Trigger-menu and `Select` popovers reposition above the caret instead of below it when there isn't room before the keyboard, via `useVirtualKeyboardInset()` (also exported, in case you're positioning your own UI against the keyboard).
|
|
551
|
+
|
|
552
|
+
**Touch detection deliberately isn't a static `matchMedia('(pointer: coarse)')` check** (see `useCoarsePointer`, also exported) — a touchscreen laptop reports its trackpad as the "primary" pointer even though the touchscreen sitting right there can be used at any moment, so a pure media-query check would never show touch UI on that class of device. Instead, the media query only supplies the *initial* guess (correct pre-interaction, SSR-safe); every real `pointerdown` afterward overrides it with that event's own `pointerType`, so a 2-in-1 laptop correctly shows desktop UI while the trackpad is in use and mobile UI the instant the screen is tapped, live, no reload needed. The same signal is mirrored onto `<html class="be-touch-input">` so plain CSS (the gutter-hiding rule above) reacts to it too, not just `MobileActionBar` itself.
|
|
553
|
+
|
|
554
|
+
**Not included**: a touch equivalent for dragging in the block gutter to select a range of blocks — most block editors keep that gesture desktop/mouse-only too.
|
|
555
|
+
|
|
556
|
+
## Accessibility
|
|
557
|
+
|
|
558
|
+
- Every portaled popover that's a genuine standalone action menu (the block gutter's Duplicate/Move/Hide/Delete menu, the block-range action menu, a table column's options menu) is keyboard-operable: opening one moves real focus onto its first item, ArrowUp/ArrowDown move between items (wrapping), Home/End jump to the first/last, and Escape closes it and returns focus to whatever opened it — not just a name-only `role="menu"` that only responds to mouse clicks.
|
|
559
|
+
- `Modal` moves focus into the dialog (its first focusable element) on open and restores it to whatever had focus before on close — not a full focus trap (this package stays zero-dependency, and its dialogs are short, single-purpose forms, not deep navigable UI), just "focus doesn't go missing."
|
|
560
|
+
- Structural actions that don't otherwise move focus anywhere describable (duplicate/move/hide/delete a block, or a whole selected range) announce what happened via a shared, visually-hidden `aria-live="polite"` region — screen-reader users get "Block deleted"/"3 blocks moved up" instead of silence.
|
|
561
|
+
- Embed images have a real, separately-authored `alt` text field (a toolbar button opens a small dialog to set it) — `alt` is never silently filled in from the uploaded file's raw filename or a pasted URL string, since neither is meaningful alt text.
|
|
562
|
+
- Table header cells have `scope="col"`, and the column-resize/embed-resize sliders both expose `aria-valuemin/valuemax/valuenow`.
|
|
563
|
+
|
|
564
|
+
## Offline persistence
|
|
565
|
+
|
|
566
|
+
For a fully offline editor — no server, no internet required — documents can auto-save to IndexedDB (native browser API, no added dependency) and reload themselves on the next visit:
|
|
567
|
+
|
|
568
|
+
```jsx
|
|
569
|
+
import { useEditor, NoteloomEditor, usePersistedDocument } from 'noteloom';
|
|
570
|
+
|
|
571
|
+
function App() {
|
|
572
|
+
const editor = useEditor({ doc: myStarterDoc });
|
|
573
|
+
const { isLoaded } = usePersistedDocument({ store: editor.store, docId: 'my-document-id' });
|
|
574
|
+
|
|
575
|
+
if (!isLoaded) return <p>Loading…</p>;
|
|
576
|
+
return <NoteloomEditor editor={editor} />;
|
|
577
|
+
}
|
|
578
|
+
```
|
|
579
|
+
|
|
580
|
+
On mount, this loads whatever was last saved under `docId` (if anything) and replaces the store's content with it; every edit after that — typing, structural changes, even changes arriving from a collaborating peer via `CollabSession` — is auto-saved back, debounced (default 500ms of quiet) so a full-document write doesn't fire on every keystroke. Different `docId`s are stored independently, so one browser can hold many separate documents (e.g. keyed by page/route). A runnable example is in `examples/offline-persist/` — run `npm run dev:offline-persist`, type something, then reload the page or close and reopen the tab.
|
|
581
|
+
|
|
582
|
+
Lower-level pieces, if `usePersistedDocument`'s all-in-one behavior doesn't fit (a non-React host app, custom load/save timing, etc.):
|
|
583
|
+
- `savePersistedDocument(docId, doc)` / `loadPersistedDocument(docId)` / `deletePersistedDocument(docId)` / `listPersistedDocumentIds()` — the raw IndexedDB operations `usePersistedDocument` is built on.
|
|
584
|
+
- `createAutoPersistence({ store, docId, debounceMs, onError })` — just the debounced auto-save half, if you want to handle the initial load yourself. Returns `{ stop, flush }`.
|
|
585
|
+
|
|
586
|
+
This is standalone — works with a solo, non-collaborating store just as well as one wired to `CollabSession` (a collaborated-on document also gets saved locally, so it survives even after every peer disconnects). Note this only makes the *editing* work offline; if the app itself is loaded from a dev server or web host, opening it for the very first time (or after clearing cache) still needs that host to be reachable once — that's the separate concern the next section covers.
|
|
587
|
+
|
|
588
|
+
### Offline app shell (PWA)
|
|
589
|
+
|
|
590
|
+
`usePersistedDocument` makes the *document* offline-capable; it doesn't make the *app itself* loadable with no network — that needs a service worker precaching the HTML/JS/CSS, which is a build-level concern (the exact list of files to cache is whatever your bundler outputs), not something a runtime library can inject. This package doesn't ship a service worker implementation for that reason — instead:
|
|
591
|
+
|
|
592
|
+
- Use a standard Vite PWA setup — [`vite-plugin-pwa`](https://vite-pwa-org.netlify.app/) is the common choice, and requires no noteloom-specific configuration; a working example is in `examples/offline-persist/vite.config.js`.
|
|
593
|
+
- `useServiceWorkerUpdate()` (exported from the package) is the one genuinely reusable piece: it watches for a newly-installed service worker sitting in the "waiting" state (the standard signal a fresh build is ready) and gives you a way to activate it —
|
|
594
|
+
|
|
595
|
+
```js
|
|
596
|
+
import { useServiceWorkerUpdate } from 'noteloom';
|
|
597
|
+
|
|
598
|
+
function UpdateBanner() {
|
|
599
|
+
const { updateAvailable, applyUpdate } = useServiceWorkerUpdate();
|
|
600
|
+
if (!updateAvailable) return null;
|
|
601
|
+
return <button onClick={applyUpdate}>Update available — reload</button>;
|
|
602
|
+
}
|
|
603
|
+
```
|
|
604
|
+
|
|
605
|
+
Works with any service worker registration, however it got there — it only observes, it doesn't register one itself.
|
|
606
|
+
|
|
607
|
+
Run `npm run dev:offline-persist`, then `npx vite build --config examples/offline-persist/vite.config.js && npx vite preview --config examples/offline-persist/vite.config.js` to try the built (not dev-mode) version — service workers only activate on a real build. Load it once online, then disconnect entirely and reload: the app shell still loads, and editing/persistence both keep working, since IndexedDB has no network dependency of its own.
|
|
608
|
+
|
|
609
|
+
## Live collaboration (experimental)
|
|
610
|
+
|
|
611
|
+
Real-time multi-peer editing, built as a custom **block-tree CRDT** — not a generic text-CRDT library bolted on — so it stays true to the zero-runtime-dependency design. Peers connect directly over WebRTC; you bring your own signaling (a WebSocket relay, Firebase/Supabase realtime, or anything else that can pass small JSON messages between two peers) to bootstrap the connection.
|
|
612
|
+
|
|
613
|
+
```jsx
|
|
614
|
+
import { useEditor, NoteloomEditor, CollabSession } from 'noteloom';
|
|
615
|
+
import { useEffect } from 'react';
|
|
616
|
+
|
|
617
|
+
function App() {
|
|
618
|
+
const editor = useEditor({ doc: myDoc });
|
|
619
|
+
|
|
620
|
+
useEffect(() => {
|
|
621
|
+
// `signaling` is any object shaped like SignalingChannel (src/sync/signaling.js):
|
|
622
|
+
// { localPeerId, send(toPeerId, message), onMessage(cb) }
|
|
623
|
+
const session = new CollabSession({ history: editor.store, signaling });
|
|
624
|
+
session.connect(remotePeerId, { initiator: true }); // `initiator: true` on exactly one side of each pair
|
|
625
|
+
return () => session.destroy();
|
|
626
|
+
}, []);
|
|
627
|
+
|
|
628
|
+
return <NoteloomEditor editor={editor} />;
|
|
629
|
+
}
|
|
630
|
+
```
|
|
631
|
+
|
|
632
|
+
From then on, every edit made via `editor.store` (typing, inserting/moving/deleting blocks, "Turn into" type conversions) is automatically broadcast to connected peers, and incoming changes merge in live.
|
|
633
|
+
|
|
634
|
+
### Signaling options
|
|
635
|
+
|
|
636
|
+
`CollabSession` only needs *something* that can pass small JSON messages between two peers to bootstrap their WebRTC connection — it never needs to touch the internet itself. Two ready-to-use signaling backends:
|
|
637
|
+
|
|
638
|
+
- **Same-browser demo, zero server** — `examples/collab/` uses the native `BroadcastChannel` API so every tab open on the same machine can find and sync with each other. Run `npm run dev:collab` and open the URL in two tabs. Good for trying the feature out; only works within one browser.
|
|
639
|
+
- **Real multi-device collaboration — same WiFi/LAN, no internet required, or over the open internet if you point it at a public host** — `createWebSocketSignaling()` (exported from the package) connects to a small relay server that only ever sees connection-setup messages, never document content:
|
|
640
|
+
|
|
641
|
+
```js
|
|
642
|
+
import { createWebSocketSignaling, CollabSession } from 'noteloom';
|
|
643
|
+
|
|
644
|
+
const signaling = createWebSocketSignaling({
|
|
645
|
+
url: 'ws://192.168.1.5:8080', // a relay running on your LAN -- or any host, if you want internet-wide instead
|
|
646
|
+
roomId: 'my-document-id', // anyone using the same roomId ends up in the same room
|
|
647
|
+
peerId: crypto.randomUUID(),
|
|
648
|
+
});
|
|
649
|
+
const session = new CollabSession({ history: editor.store, signaling });
|
|
650
|
+
|
|
651
|
+
signaling.onPeerDiscovered((remotePeerId) => {
|
|
652
|
+
const initiator = signaling.localPeerId > remotePeerId; // deterministic tie-break
|
|
653
|
+
session.connect(remotePeerId, { initiator });
|
|
654
|
+
});
|
|
655
|
+
```
|
|
656
|
+
|
|
657
|
+
A minimal reference relay server (Node, `ws`-based, ~80 lines, **not** part of the npm package) lives in `tools/lan-relay-server/` — see its README for how to run it and the wire protocol. A full runnable example wiring it up is in `examples/lan-collab/` — run `npm run dev:lan-collab` (after starting the relay), open the URL in two tabs, and it works with zero internet connectivity as long as both tabs can reach the relay.
|
|
658
|
+
|
|
659
|
+
### Presence / awareness (live cursors, who's online)
|
|
660
|
+
|
|
661
|
+
`CollabSession` also carries ephemeral "here's where I am" data alongside the document sync — entirely separate from the document CRDT (never persisted, never merge-conflicted, just "whatever the last message said"):
|
|
662
|
+
|
|
663
|
+
```js
|
|
664
|
+
import { usePresence } from 'noteloom';
|
|
665
|
+
|
|
666
|
+
// broadcast your own position (throttled automatically, ~100ms by default)
|
|
667
|
+
session.setLocalPresence({ runId: caret.runId, offset: caret.offset, name: 'Alex' });
|
|
668
|
+
|
|
669
|
+
// react to everyone else's, reactively
|
|
670
|
+
function PeerCursors({ session }) {
|
|
671
|
+
const presence = usePresence(session); // Map<peerId, data>, re-renders on change
|
|
672
|
+
return [...presence.entries()].map(([peerId, data]) => /* render however you like */);
|
|
673
|
+
}
|
|
674
|
+
```
|
|
675
|
+
|
|
676
|
+
What presence *contains* is entirely up to you — a cursor position, a display name, a color, a "currently viewing" flag — `CollabSession` only relays the data, it never inspects or interprets it. A peer's entry disappears from `usePresence`'s map the instant they disconnect, and a newly-joining peer receives everyone's already-set presence immediately rather than waiting for their next move. `examples/collab/` renders this as live colored carets with peer-id labels, resolving `{runId, offset}` to an on-screen position the same way the editor's own selection code does (via the `[data-run-id]` DOM convention) — see `PeerCursors` in its `App.jsx` for the full (host-app-level, not package-level) rendering logic.
|
|
677
|
+
|
|
678
|
+
**How conflicts resolve:**
|
|
679
|
+
- Concurrent inserts (even at the same position) — both survive, converging to the same order on every peer.
|
|
680
|
+
- Concurrent delete vs. edit of the same block — the delete wins.
|
|
681
|
+
- Concurrent type-conversion of the same block ("Turn into") — one type wins deterministically (the same one, on every peer), not two duplicate blocks.
|
|
682
|
+
- Concurrent edits to a run's text — merge at the *character* level (a real per-run CRDT, the same ordered-list mechanism blocks already use, just one level down): two peers editing different parts of the same run both survive, and two peers inserting at the exact same position both survive too, interleaved deterministically (identically on every peer) rather than one silently overwriting the other.
|
|
683
|
+
|
|
684
|
+
### Tombstone garbage collection
|
|
685
|
+
|
|
686
|
+
Deleted blocks/runs are kept as "tombstones" rather than actually removed — necessary so a concurrent operation that references a since-deleted item (an insert anchored to it, say) can still resolve correctly no matter when it arrives. Left alone, this grows without bound over a long enough session. To actually reclaim that memory:
|
|
687
|
+
|
|
688
|
+
```js
|
|
689
|
+
import { useEditor, createPeriodicTombstoneGC } from 'noteloom';
|
|
690
|
+
|
|
691
|
+
const editor = useEditor({ doc: myDoc });
|
|
692
|
+
const gc = createPeriodicTombstoneGC({ store: editor.store, intervalMs: 60 * 60 * 1000, maxAgeMs: 24 * 60 * 60 * 1000 }); // hourly sweep, 24h retention (both defaults, shown explicitly)
|
|
693
|
+
|
|
694
|
+
// later, when the store is no longer in use:
|
|
695
|
+
gc.stop();
|
|
696
|
+
```
|
|
697
|
+
|
|
698
|
+
Or call `store.pruneTombstones({ maxAgeMs })` yourself on whatever schedule you want — `createPeriodicTombstoneGC` is just a thin timer wrapper around it. `store.getTombstoneCount()` tells you how many are currently being retained, if you want to observe growth before deciding on a policy. Both work identically whether `store` is a plain `EditorStore` or a `History` wrapping one, and pruning is never itself an undo step (it doesn't change the visible document — the pruned content was already invisible).
|
|
699
|
+
|
|
700
|
+
**Why a time-based threshold is safe here specifically:** this only works because of how `CollabSession` reconnects — a peer rejoining after any absence gets a full document *snapshot* (`syncResponse`), never a replay of the ops it missed. That means a peer offline longer than the GC threshold never needs an old tombstone to resolve a stale reference; it just adopts the current state directly. The only residual risk is a single *already-connected* peer somehow stalling for exactly as long as the threshold and then delivering a queued message afterward — implausible for a live, reliable, ordered WebRTC data channel (which disconnects long before that under any real interruption), but not impossible, which is why this is opt-in rather than automatic.
|
|
701
|
+
|
|
702
|
+
### Reconnecting reliably
|
|
703
|
+
|
|
704
|
+
`CollabSession`/`createWebSocketSignaling` deliberately don't retry anything themselves (see the class doc comment) — a dropped connection is a transport-layer concern left to the host app, on purpose, so this stays a small library rather than growing an opinionated retry/backoff policy no two apps would agree on. `examples/lan-collab/` is a complete, runnable reference for the two pieces most apps end up needing on top:
|
|
705
|
+
|
|
706
|
+
- **A watchdog that actually reconnects.** `createWebSocketSignaling` exposes no `close`/`error` event for the relay connection dying silently (a sleeping laptop, a WiFi drop, the relay restarting) — so periodically checking "do I currently have zero live peers, and has it been a while since I last tried" and, if so, tearing down and recreating the whole signaling + session is the only reliable way to notice and recover. Also worth reacting to the browser's own `online` event immediately, rather than waiting for the next timer tick.
|
|
707
|
+
- **Actually catching up, not just resuming.** A reconnecting peer that keeps its existing (non-empty) store — the right default, so a solo editing session isn't wiped by a network blip — never re-triggers `CollabSession`'s adopt-a-snapshot path, since that only fires when a store is genuinely empty (see "A peer joining with their own existing document" below). Left alone, this peer silently misses everything the room changed while it was away. The fix: on a genuine *reconnect* (never the very first connection) where nothing was typed locally in the gap, reset the store back to that same empty shape first — the same field-level reset `usePersistedDocument` uses internally — so the ordinary adopt-on-empty flow does the catching-up. If local edits *were* made while disconnected, keep them as-is; there's no safe way to both preserve them and adopt someone else's snapshot without a real merge (see the next limitation).
|
|
708
|
+
|
|
709
|
+
**Known limitations — read before relying on this in production:**
|
|
710
|
+
- **Undo is local-only, and only ever touches your own edits.** Undo/redo of a text edit works by tombstoning/restoring the exact character ids *you* inserted/deleted (not by replaying an old whole-string snapshot), so undoing your own past edit to a run can never remove a peer's concurrent edit to that same run, no matter how they're interleaved. One narrower case remains open: concurrent *formatting* (bold/italic, which splits a run into new runs with new ids) racing a concurrent *edit* of the exact same run is a run-list-level (not character-level) concern this doesn't cover.
|
|
711
|
+
- **Deleted content isn't garbage-collected automatically, but can be — opt-in.** Tombstones are kept by default (needed so a late-arriving concurrent operation can still resolve correctly), which means unbounded memory growth over a long enough session unless you do something about it. `store.pruneTombstones({ maxAgeMs })` (default 24h) removes tombstones older than that safely — see "Tombstone garbage collection" above. Nothing calls this automatically; wire up `createPeriodicTombstoneGC` (or call it yourself) if you want it handled for you.
|
|
712
|
+
- **A peer joining with their own existing (different) document does not merge with yours.** `CollabSession` only adopts a peer's document wholesale when your own side is still empty — the common "open a shared link and get the document" flow. Reconciling two independently-created, already-diverged documents on first contact is a fundamentally harder problem (no shared id space) and isn't attempted. This is also why the reconnect pattern above only ever resets a store that has no unsynced local edits of its own.
|
|
713
|
+
- **Reconnecting after a dropped connection re-syncs the full document**, not just what was missed — simple and correct, at the cost of O(document size) traffic per reconnect. See "Reconnecting reliably" above for making the reconnect itself actually happen.
|
|
714
|
+
- Only structural block changes and field edits (props, type, run text) are collaboration-aware. A few coarse "resync" operations (`setBlockContentIds`, `replaceRunSpan`, `setBlockRuns` — used for DOM-reconciliation escape hatches like paste-into-contentEditable or IME composition) remain local-only for now.
|
|
715
|
+
- Large single messages (e.g. an embedded video/file's `data:` URL, or a full-document `syncResponse` for a big document) are transparently fragmented, flow-controlled against the data channel's own backpressure, and reassembled under the hood — you don't need to do anything for this, but very large embeds mean more individual send calls and somewhat higher latency to fully arrive.
|
|
716
|
+
|
|
717
|
+
---
|
|
718
|
+
|
|
719
|
+
# Advanced: the granular API
|
|
720
|
+
|
|
721
|
+
Everything above is `useEditor()`/`<NoteloomEditor>` — a convenience layer over the pieces below, nothing hidden behind them. This section is for when you need more control than that gives you: a custom toolbar, mobile chrome mounted separately, or a hand-rolled surface element.
|
|
722
|
+
|
|
723
|
+
## Building the editor by hand
|
|
724
|
+
|
|
725
|
+
```jsx
|
|
726
|
+
import {
|
|
727
|
+
EditorStore,
|
|
728
|
+
History,
|
|
729
|
+
EditorProvider,
|
|
730
|
+
BlockChildren,
|
|
731
|
+
createBlockRegistry,
|
|
732
|
+
registerBuiltInBlocks,
|
|
733
|
+
createInlineRegistry,
|
|
734
|
+
registerBuiltInInlineTypes,
|
|
735
|
+
useClipboardHandlers,
|
|
736
|
+
useSlashMenuTrigger,
|
|
737
|
+
useEditorKeyboardShortcuts,
|
|
738
|
+
SlashMenu,
|
|
739
|
+
} from 'noteloom';
|
|
740
|
+
import { useMemo, useRef } from 'react';
|
|
741
|
+
|
|
742
|
+
function Editor() {
|
|
743
|
+
const containerRef = useRef(null);
|
|
744
|
+
const { store, registry, inlineRegistry } = useMemo(() => {
|
|
745
|
+
const registry = createBlockRegistry();
|
|
746
|
+
registerBuiltInBlocks(registry);
|
|
747
|
+
const inlineRegistry = createInlineRegistry();
|
|
748
|
+
registerBuiltInInlineTypes(inlineRegistry);
|
|
749
|
+
const store = new History(
|
|
750
|
+
new EditorStore({
|
|
751
|
+
rootId: 'root',
|
|
752
|
+
blocks: [
|
|
753
|
+
{ id: 'root', type: 'page', parentId: null, contentIds: ['p1'], props: {} },
|
|
754
|
+
{ id: 'p1', type: 'paragraph', parentId: 'root', contentIds: ['r1'], props: {} },
|
|
755
|
+
],
|
|
756
|
+
runs: [{ id: 'r1', type: 'text', value: 'Hello — try typing "/" for commands.', marks: {} }],
|
|
757
|
+
}),
|
|
758
|
+
);
|
|
759
|
+
return { store, registry, inlineRegistry };
|
|
760
|
+
}, []);
|
|
761
|
+
|
|
762
|
+
const { onCopy, onCut, onPaste } = useClipboardHandlers();
|
|
763
|
+
const slashMenu = useSlashMenuTrigger(containerRef);
|
|
764
|
+
useEditorKeyboardShortcuts(containerRef);
|
|
765
|
+
|
|
766
|
+
return (
|
|
767
|
+
<EditorProvider store={store} registry={registry} inlineRegistry={inlineRegistry} history={store}>
|
|
768
|
+
<div ref={containerRef} onCopy={onCopy} onCut={onCut} onPaste={onPaste}>
|
|
769
|
+
<BlockChildren parentId="root" />
|
|
770
|
+
<SlashMenu
|
|
771
|
+
isOpen={slashMenu.isOpen}
|
|
772
|
+
rect={slashMenu.rect}
|
|
773
|
+
commands={slashMenu.commands}
|
|
774
|
+
runId={slashMenu.runId}
|
|
775
|
+
onSelect={slashMenu.selectCommand}
|
|
776
|
+
onClose={slashMenu.close}
|
|
777
|
+
/>
|
|
778
|
+
</div>
|
|
779
|
+
</EditorProvider>
|
|
780
|
+
);
|
|
781
|
+
}
|
|
782
|
+
```
|
|
783
|
+
|
|
784
|
+
See `examples/basic` for a complete working app built this way (run `npm run dev`) — it wires up everything the Basic guide above covers individually (mobile chrome, voice typing, export, field-type management, ...) from these same granular pieces.
|
|
785
|
+
|
|
786
|
+
## Registering a brand-new block/inline type, from scratch
|
|
787
|
+
|
|
788
|
+
The [Basic guide](#basic-guide) above covers *picking* existing types and *configuring* dropdown/mention field types via `createSelectFieldType` — no component required for either. Writing an entirely new block or inline type (its own React component, HTML/plain-text serialization, its own slash command) is the one thing that's inherently advanced regardless of which path built your registry:
|
|
789
|
+
|
|
790
|
+
```js
|
|
791
|
+
registry.register('myBlock', {
|
|
792
|
+
component: MyBlockComponent, // receives only { id }
|
|
793
|
+
isLeaf: true, // true if contentIds holds run ids, false if it holds child block ids
|
|
794
|
+
toHTML(block, ctx) { /* ... */ },
|
|
795
|
+
fromHTML(domNode, ctx) { /* ... or return null if this node isn't yours */ },
|
|
796
|
+
toPlainText(block, ctx) { /* ... */ },
|
|
797
|
+
slashCommand: { label: 'My Block', keywords: ['my'], run(store, ctx) { /* ... */ } },
|
|
798
|
+
});
|
|
799
|
+
```
|
|
800
|
+
|
|
801
|
+
`registry` here is `editor.registry` from `useEditor()` (call this inside the `registerBlocks` callback shown in [Picking only the blocks/inline types you want](#picking-only-the-blocksinline-types-you-want)) or a hand-built one from above — both work identically. `examples/02-custom-block/` is a complete, runnable, non-text example (a 5-star rating widget) with comments walking through every field.
|
|
802
|
+
|
|
803
|
+
---
|
|
804
|
+
|
|
805
|
+
# Development
|
|
806
|
+
|
|
807
|
+
```bash
|
|
808
|
+
npm install
|
|
809
|
+
npm run dev:quickstart # examples/01-quickstart — useEditor()/<NoteloomEditor>
|
|
810
|
+
npm run dev # examples/basic — the same editor built from the granular API
|
|
811
|
+
npm test # vitest (jsdom + @testing-library/react)
|
|
812
|
+
npm run typecheck # tsc --noEmit against src/index.d.ts
|
|
813
|
+
npm run build # library build (dist/, ESM + CJS + index.d.ts)
|
|
814
|
+
```
|
|
815
|
+
|
|
816
|
+
See `examples/README.md` for the rest of the runnable examples, and `CONTRIBUTING.md` for the full contributor guide.
|
|
817
|
+
|
|
818
|
+
## Known limitations
|
|
819
|
+
|
|
820
|
+
- No accessibility affordance exists for grouping sibling list items under a shared `role="list"` container (each list item is an independent block, not wrapped in one) — adding `role="listitem"` without that ancestor would be worse than no role at all, so it's deliberately left out pending a bigger structural change.
|
|
821
|
+
- `<NoteloomEditor>` renders `role="document"`/`aria-label` on its own surface element; if you build the surface yourself via the granular API (no library-rendered root element there — see `examples/basic/src/App.jsx`'s `EditorSurface`), add those attributes yourself the same way.
|
|
822
|
+
- Cross-block mark toggling (bold/italic/underline over a selection spanning multiple blocks) applies as one store operation per block, not a single atomic undo step.
|
|
823
|
+
- `select`'s option-adding UI and any `createSelectFieldType`-based type's options (e.g. an "Assignee" @-mention) are meant as a starting point — a real app will want to wire its own people/options source.
|
|
824
|
+
- RTL support covers direction resolution (`dir="auto"` + per-block/document override) and the highest-impact visual pieces (list markers, blockquote border, block gutter position) — a full logical-properties rewrite of every hardcoded pixel value in `style.css` is a bigger follow-up, not yet done.
|
|
825
|
+
- Voice typing (`useVoiceTyping`) only acts on *finalized* speech results, not interim/in-progress ones, and command detection requires a spoken command to be its own complete utterance — there's no explicit "command mode" trigger (push-to-command, wake phrase) yet, just pause-based auto-detection.
|
|
826
|
+
- Automated tests run under jsdom; there is no automated real-browser test suite. If you hit an edge case jsdom can't reproduce (anything involving actual native `contentEditable` browser quirks, or the real Web Speech API), please file an issue with the exact browser/OS and steps.
|
|
827
|
+
- A comment's highlighted range is local-only in collaboration for v1 (same scope every other range-based formatting operation already has — see [Comments](#comments)); a comment thread's `anchorRunIds` is a creation-time hint only, not re-validated after later formatting edits reshape that range.
|