noteloom 0.3.3 → 0.5.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.
Files changed (104) hide show
  1. package/README.md +173 -808
  2. package/bin/noteloom.mjs +139 -0
  3. package/dist/canvas.cjs +2 -0
  4. package/dist/canvas.cjs.map +1 -0
  5. package/dist/canvas.d.ts +2 -0
  6. package/dist/canvas.js +5 -0
  7. package/dist/canvas.js.map +1 -0
  8. package/dist/collab.cjs +2 -0
  9. package/dist/collab.cjs.map +1 -0
  10. package/dist/collab.d.ts +19 -0
  11. package/dist/collab.js +379 -0
  12. package/dist/collab.js.map +1 -0
  13. package/dist/comments.cjs +2 -0
  14. package/dist/comments.cjs.map +1 -0
  15. package/dist/comments.d.ts +17 -0
  16. package/dist/comments.js +19 -0
  17. package/dist/comments.js.map +1 -0
  18. package/dist/index.cjs +2 -0
  19. package/dist/index.cjs.map +1 -0
  20. package/dist/index.d.ts +374 -34
  21. package/dist/index.js +3983 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/persistence.cjs +2 -0
  24. package/dist/persistence.cjs.map +1 -0
  25. package/dist/persistence.d.ts +11 -0
  26. package/dist/persistence.js +12 -0
  27. package/dist/persistence.js.map +1 -0
  28. package/dist/shared/CommentAvatar-TKqsM8vG.js +53 -0
  29. package/dist/shared/CommentAvatar-TKqsM8vG.js.map +1 -0
  30. package/dist/shared/CommentAvatar-V457IgoQ.cjs +2 -0
  31. package/dist/shared/CommentAvatar-V457IgoQ.cjs.map +1 -0
  32. package/dist/shared/CommentThreadCard-CwKd6fp3.js +213 -0
  33. package/dist/shared/CommentThreadCard-CwKd6fp3.js.map +1 -0
  34. package/dist/shared/CommentThreadCard-YziIa8My.cjs +2 -0
  35. package/dist/shared/CommentThreadCard-YziIa8My.cjs.map +1 -0
  36. package/dist/shared/CommentsPanel-DezejDdE.cjs +2 -0
  37. package/dist/shared/CommentsPanel-DezejDdE.cjs.map +1 -0
  38. package/dist/shared/CommentsPanel-dx7IaoqS.js +76 -0
  39. package/dist/shared/CommentsPanel-dx7IaoqS.js.map +1 -0
  40. package/dist/shared/VersionHistory-DhYb8C2e.js +1120 -0
  41. package/dist/shared/VersionHistory-DhYb8C2e.js.map +1 -0
  42. package/dist/shared/VersionHistory-DuSxis_7.cjs +12 -0
  43. package/dist/shared/VersionHistory-DuSxis_7.cjs.map +1 -0
  44. package/dist/shared/VoiceListeningIndicator-BXByLZwO.cjs +2 -0
  45. package/dist/shared/VoiceListeningIndicator-BXByLZwO.cjs.map +1 -0
  46. package/dist/shared/VoiceListeningIndicator-bv285FSY.js +338 -0
  47. package/dist/shared/VoiceListeningIndicator-bv285FSY.js.map +1 -0
  48. package/dist/shared/fieldRegistry-BoYyW3GH.cjs +2 -0
  49. package/dist/shared/fieldRegistry-BoYyW3GH.cjs.map +1 -0
  50. package/dist/shared/fieldRegistry-PjJWXFoB.js +223 -0
  51. package/dist/shared/fieldRegistry-PjJWXFoB.js.map +1 -0
  52. package/dist/shared/icons-BCseh2pt.cjs +3531 -0
  53. package/dist/shared/icons-BCseh2pt.cjs.map +1 -0
  54. package/dist/shared/icons-D5Ctow8R.js +4279 -0
  55. package/dist/shared/icons-D5Ctow8R.js.map +1 -0
  56. package/dist/shared/index-CbIBsFmI.cjs +2 -0
  57. package/dist/shared/index-CbIBsFmI.cjs.map +1 -0
  58. package/dist/shared/index-D_8hJpI7.js +2145 -0
  59. package/dist/shared/index-D_8hJpI7.js.map +1 -0
  60. package/dist/shared/indexedDbPersistence-BKlGPFTP.js +112 -0
  61. package/dist/shared/indexedDbPersistence-BKlGPFTP.js.map +1 -0
  62. package/dist/shared/indexedDbPersistence-BWJ1h5Vp.cjs +2 -0
  63. package/dist/shared/indexedDbPersistence-BWJ1h5Vp.cjs.map +1 -0
  64. package/dist/shared/leafBlockFactory-CaLWUcfa.cjs +2 -0
  65. package/dist/shared/leafBlockFactory-CaLWUcfa.cjs.map +1 -0
  66. package/dist/shared/leafBlockFactory-DSa1XCox.js +335 -0
  67. package/dist/shared/leafBlockFactory-DSa1XCox.js.map +1 -0
  68. package/dist/shared/serialize-BqKU9EZy.js +86 -0
  69. package/dist/shared/serialize-BqKU9EZy.js.map +1 -0
  70. package/dist/shared/serialize-CqwX55uK.cjs +3 -0
  71. package/dist/shared/serialize-CqwX55uK.cjs.map +1 -0
  72. package/dist/shared/starter-kit-DyX1U84W.cjs +27 -0
  73. package/dist/shared/starter-kit-DyX1U84W.cjs.map +1 -0
  74. package/dist/shared/starter-kit-mfeNxqFn.js +4980 -0
  75. package/dist/shared/starter-kit-mfeNxqFn.js.map +1 -0
  76. package/dist/shared/usePopoverEdgeClamp-CPRWQtZV.cjs +2 -0
  77. package/dist/shared/usePopoverEdgeClamp-CPRWQtZV.cjs.map +1 -0
  78. package/dist/shared/usePopoverEdgeClamp-D_hB5t60.js +109 -0
  79. package/dist/shared/usePopoverEdgeClamp-D_hB5t60.js.map +1 -0
  80. package/dist/shared/useServiceWorkerUpdate-BduabXv6.js +94 -0
  81. package/dist/shared/useServiceWorkerUpdate-BduabXv6.js.map +1 -0
  82. package/dist/shared/useServiceWorkerUpdate-DQboGesi.cjs +2 -0
  83. package/dist/shared/useServiceWorkerUpdate-DQboGesi.cjs.map +1 -0
  84. package/dist/starter-kit.cjs +2 -0
  85. package/dist/starter-kit.cjs.map +1 -0
  86. package/dist/starter-kit.d.ts +9 -0
  87. package/dist/starter-kit.js +10 -0
  88. package/dist/starter-kit.js.map +1 -0
  89. package/dist/style.css +3529 -3283
  90. package/dist/versions.cjs +2 -0
  91. package/dist/versions.cjs.map +1 -0
  92. package/dist/versions.d.ts +11 -0
  93. package/dist/versions.js +13 -0
  94. package/dist/versions.js.map +1 -0
  95. package/dist/voice.cjs +2 -0
  96. package/dist/voice.cjs.map +1 -0
  97. package/dist/voice.d.ts +7 -0
  98. package/dist/voice.js +8 -0
  99. package/dist/voice.js.map +1 -0
  100. package/package.json +159 -92
  101. package/dist/noteloom.cjs +0 -3292
  102. package/dist/noteloom.cjs.map +0 -1
  103. package/dist/noteloom.es.js +0 -15047
  104. package/dist/noteloom.es.js.map +0 -1
package/README.md CHANGED
@@ -2,43 +2,20 @@
2
2
 
3
3
  [![version](https://img.shields.io/npm/v/noteloom.svg?label=version&color=3178c6)](https://www.npmjs.com/package/noteloom)
4
4
  [![downloads](https://img.shields.io/npm/dm/noteloom.svg?label=downloads&color=44cc11)](https://www.npmjs.com/package/noteloom)
5
- [![license](https://img.shields.io/npm/l/noteloom.svg?label=license&color=44cc11)](https://github.com/vishwakarmanikhil/noteloom/blob/master/LICENSE)
5
+ [![license](https://img.shields.io/npm/l/noteloom.svg?label=license&color=44cc11)](LICENSE)
6
6
  [![Sponsor](https://img.shields.io/badge/Sponsor-%E2%9D%A4-333?logo=githubsponsors&logoColor=white)](https://github.com/sponsors/vishwakarmanikhil)
7
7
 
8
- **[Live site & docs →](https://noteloom.qusere.in)** · **[Play with the demo →](https://noteloom.qusere.in/playground/)**
8
+ **A React block editor with zero runtime dependencies.** Nestable blocks, inline
9
+ widgets mid-sentence, slash commands, tables, undo/redo, clipboard — all built on
10
+ a small normalized store. The only things it needs from your app are `react` and
11
+ `react-dom`.
9
12
 
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
13
+ **[Docs & demo →](https://noteloom.qusere.in)** · **[Playground →](https://noteloom.qusere.in/playground/)** · **[Full guide](docs/guide.md)**
35
14
 
36
15
  ```bash
37
16
  npm install noteloom react react-dom
38
17
  ```
39
18
 
40
- ## 2. Create an editor
41
-
42
19
  ```jsx
43
20
  import { useEditor, NoteloomEditor } from 'noteloom';
44
21
 
@@ -48,826 +25,214 @@ function Editor() {
48
25
  }
49
26
  ```
50
27
 
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)
28
+ That's the whole thing a working editor with every built-in block/inline type,
29
+ slash + `@` + emoji menus, the formatting toolbar, keyboard shortcuts, clipboard,
30
+ find & replace, and the default theme, all wired up. No CSS import needed.
31
+
32
+ Pass a starting document (`useEditor({ doc })` — the [simple JSON format](#document-format)
33
+ or the internal shape, auto-detected), or `history: false` to drop undo/redo.
34
+
35
+ ## Highlights
36
+
37
+ - **Inline widgets are first-class** — a `select` dropdown, date picker, or
38
+ `@mention` chip sits _in the middle of a sentence_, not on its own line.
39
+ - **Fine-grained rendering** every block subscribes only to its own data;
40
+ editing one paragraph in a 500-block doc repaints just that block.
41
+ - **13 built-in block types** — paragraph, heading, list (bulleted/numbered/to-do/toggle),
42
+ table, multi-column layout, divider, callout, blockquote, code, toggle heading,
43
+ button, embed, canvas — plus atomic inline types (`select`, `date`, `checkbox`, …).
44
+ - **Typed extension API** — `defineBlock` / `defineInline` / `defineExtension`
45
+ with a stable `ctx` facade; `npx noteloom new block <name>` to scaffold one.
46
+ - **One canonical document format** — self-contained JSON with a published
47
+ [schema](docs/document.schema.json); `editor.toJSON()`.
48
+ - **Opt-in heavy features** — collaboration, persistence, comments, version
49
+ history, voice typing each have their own import so they leave your bundle if
50
+ unused.
51
+ - **Retheme-able**, RTL-aware, keyboard-operable, mobile/touch-first.
52
+
53
+ ## Composing the block set
54
+
55
+ `useEditor()` registers every built-in type. Pass `extensions` to control the
56
+ set drop what you don't need, add the freehand-drawing `canvas` block from its
57
+ own (heavier) entry point, and register your own via `defineBlock`:
58
+
59
+ ```jsx
60
+ import { useEditor, NoteloomEditor, starterKit, defineBlock } from 'noteloom';
61
+ import { canvasBlockType } from 'noteloom/canvas';
62
+ import { RatingBlock } from './RatingBlock.jsx'; // a React component, receives { id }
63
+
64
+ // A whole custom block type no text, no children, value lives in props.
65
+ // examples/02-custom-block/ is the runnable version of this.
66
+ const rating = defineBlock({
67
+ name: 'rating',
68
+ component: RatingBlock,
69
+ contentModel: 'void', // 'blocks' | 'runs' | 'void'
70
+ defaultProps: { stars: 0 },
71
+ toHTML: (block) => `<div data-stars="${block.props.stars}"></div>`,
72
+ slashCommand: {
73
+ label: 'Rating',
74
+ keywords: ['stars'],
75
+ run: (store, { blockId }) => {
76
+ /* erase "/rating", insert a { type: 'rating' } block after blockId */
158
77
  },
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
- ],
78
+ },
183
79
  });
184
80
 
185
81
  function Editor() {
186
82
  const editor = useEditor({
187
- registerInlineTypes: (inlineRegistry) => {
188
- registerBuiltInInlineTypes(inlineRegistry);
189
- inlineRegistry.register('status', statusFieldType);
190
- },
83
+ extensions: [
84
+ ...starterKit({ exclude: ['canvas'] }), // every built-in except canvas…
85
+ canvasBlockType, // …then canvas back, explicitly, from noteloom/canvas
86
+ rating, // …plus your own
87
+ ],
191
88
  });
192
89
  return <NoteloomEditor editor={editor} />;
193
90
  }
194
91
  ```
195
92
 
196
- `examples/03-custom-field-type/` is a complete runnable version of this pattern.
197
-
198
- Inserting one from "/" or "@" opens its picker immediately, focused and ready to search — no second click needed to actually pick something right after inserting it. Picking a value then moves focus straight on to the next block, so filling in a form-like document ("Diagnosis: [pick]", then the next line, then the next...) is a smooth insert → pick → keep-typing flow. Reopening an *existing* chip elsewhere to change its value later doesn't also jump away — this only applies right after a fresh insertion.
199
-
200
- `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):
201
-
202
- ```js
203
- createSelectFieldType({
204
- type: 'assignee',
205
- label: 'Assignee',
206
- placeholder: 'Assign to…',
207
- variant: 'tag',
208
- triggers: ['slash', 'at'], // reachable via "/assignee" AND by typing "@" directly
209
- options: async (query) => {
210
- const res = await fetch(`/api/users?search=${encodeURIComponent(query)}`);
211
- const users = await res.json();
212
- return users.map((u) => ({ value: u.id, label: u.name }));
213
- },
214
- });
215
- ```
216
-
217
- A few things worth knowing about the dynamic path:
218
-
219
- - 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.
220
- - 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.
221
- - `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.
222
- - A **static** array works just as well when it comes from a JSON file — `import options from './options.json'` (or fetch it once at setup) is already a plain array by the time it reaches `options`, no special handling needed. A hybrid of both ("show a local list, search an API once the user types") is just a function that returns the static list for an empty query and calls your API otherwise — the same debounce applies regardless of what the function does inside.
223
- - The option list itself is **virtualized** — only the rows currently scrolled into view are ever mounted, so a list of thousands of options (static or a big resolved page) scrolls smoothly, same as a list of ten.
224
-
225
- ### Letting end users create their own field types, in-editor
226
-
227
- 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`):
228
-
229
- ```jsx
230
- import { NoteloomEditor, FieldTypeEditorModal, useFieldTypeEditor } from 'noteloom';
231
-
232
- function NewFieldTypeButton() {
233
- const { openCreate } = useFieldTypeEditor();
234
- return <button onClick={openCreate}>+ New field type</button>;
235
- }
236
-
237
- <NoteloomEditor editor={editor}>
238
- <NewFieldTypeButton />
239
- <FieldTypeEditorModal />
240
- </NoteloomEditor>;
241
- ```
242
-
243
- 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.
244
-
245
- Once at least one is created this way, a table column set to "Select" type gets a **"Copy options from…"** dropdown in its own menu (alongside its usual "+ New field type" button) — pick one to seed the column's option list from it in one shot, instead of typing the same options out again by hand. It's a one-time copy, not a live link: renaming/adding/removing options on the column afterward never touches the source field type.
246
-
247
- ## Exporting the document (JSON / HTML / plain text)
248
-
249
- ```js
250
- import { exportDocumentJSON, exportDocumentHTML, exportDocumentText } from 'noteloom';
251
-
252
- exportDocumentJSON(store); // a JSON *string* — JSON.parse() it to get { version, rootId, blocks, runs }, usable as useEditor({ doc })
253
- exportDocumentHTML(store, registry, inlineRegistry);
254
- exportDocumentText(store, registry, inlineRegistry);
255
- ```
256
-
257
- Or mount the ready-made button + modal instead of wiring your own UI:
258
-
259
- ```jsx
260
- import { DocumentExportButton } from 'noteloom';
261
-
262
- <DocumentExportButton label="View source" />
263
- ```
264
-
265
- 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.
266
-
267
- ### A simpler JSON shape for storage/API/CRUD use
268
-
269
- `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.
270
-
271
- 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:
272
-
273
- ```js
274
- import { exportDocumentSimpleJSON, importDocumentSimpleJSON } from 'noteloom';
275
-
276
- const json = exportDocumentSimpleJSON(store, registry, inlineRegistry);
277
- // {
278
- // "version": 1,
279
- // "blocks": [
280
- // { "id": "p1", "type": "paragraph", "data": { "text": "Hello <strong>world</strong>" } },
281
- // { "id": "h1", "type": "heading", "data": { "text": "Key features", "level": 3 } },
282
- // {
283
- // "id": "li1", "type": "listItem",
284
- // "data": { "text": "Nested item", "ordered": false, "checked": null },
285
- // "children": [ /* nested listItem blocks, same shape */ ]
286
- // },
287
- // {
288
- // "id": "t1", "type": "table",
289
- // "data": { "columns": [{ "id": "c1", "label": "Name" }], "rows": [["Cell text"]] }
290
- // }
291
- // ]
292
- // }
293
-
294
- // ...later, or on a different machine/process:
295
- const doc = importDocumentSimpleJSON(json, registry, inlineRegistry); // -> { rootId, blocks, runs }
296
- const editor2 = useEditor({ doc }); // or `new EditorStore(doc)` directly outside React
297
- ```
298
-
299
- 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).
93
+ `starterKit()` on its own is the full default set (`useEditor()` with no
94
+ `extensions` is identical). `defineExtension` also carries **behavior** —
95
+ `keymap`, `onBeforeInput`, `onPaste`, `setup(ctx)` and `smartQuotes()` /
96
+ `autoPairBrackets()` are ready-made ones. Full walkthrough:
97
+ [guide extension API](docs/guide.md#defineblock--extensions--the-newer-way).
300
98
 
301
- 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.
99
+ ## Import map
302
100
 
303
- 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.
101
+ The basic editor is one import. Heavy optional features have their own entry so
102
+ a bundle that doesn't use them drops the code:
304
103
 
305
- ## Templates
306
-
307
- 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.
308
-
309
- **Block templates reusable snippets, insertable via "/":**
310
-
311
- ```js
312
- import { EditorStore, captureBlockTemplate, registerBlockTemplates, registerBuiltInBlocks } from 'noteloom';
313
-
314
- // Build once (a throwaway store is fine — only its content is captured):
315
- const draftStore = new EditorStore({
316
- rootId: 'root',
317
- blocks: [
318
- { id: 'root', type: 'page', parentId: null, contentIds: ['h1', 'li1'], props: {} },
319
- { id: 'h1', type: 'heading', parentId: 'root', contentIds: ['r1'], props: { level: 2 } },
320
- { id: 'li1', type: 'listItem', parentId: 'root', contentIds: [], props: { ordered: true, titleRunIds: ['r2'] } },
321
- ],
322
- runs: [
323
- { id: 'r1', type: 'text', value: 'Meeting agenda', marks: {} },
324
- { id: 'r2', type: 'text', value: 'Review previous action items', marks: {} },
325
- ],
326
- });
327
- const agendaSnippet = captureBlockTemplate(draftStore, ['h1', 'li1']);
328
-
329
- const editor = useEditor({
330
- registerBlocks: (registry) => {
331
- registerBuiltInBlocks(registry);
332
- registerBlockTemplates(registry, [{ id: 'agenda', label: 'Meeting agenda', keywords: ['agenda'], roots: agendaSnippet.roots }]);
333
- },
334
- });
335
- ```
336
-
337
- 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 "/".
338
-
339
- **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)`.
340
-
341
- **Saving/browsing a library of templates** (either kind), persisted so it survives reload:
342
-
343
- ```jsx
344
- import { useEditor, NoteloomEditor, useTemplates, TemplatePicker, saveTemplate, exportDocumentJSON } from 'noteloom';
345
-
346
- function NewDocumentScreen({ onPick }) {
347
- const { templates, isLoaded } = useTemplates({ scope: 'document' }); // or 'block', or omit for both
348
- if (!isLoaded) return <p>Loading…</p>;
349
- return <TemplatePicker templates={templates} onSelect={(template) => onPick(template.doc)} />;
350
- }
351
-
352
- // Saving the current document as a reusable template:
353
- async function saveCurrentAsTemplate(store, name) {
354
- await saveTemplate({
355
- id: crypto.randomUUID(),
356
- scope: 'document',
357
- name,
358
- doc: JSON.parse(exportDocumentJSON(store)), // exportDocumentJSON returns a JSON *string* — parse it first
359
- });
360
- }
361
- ```
362
-
363
- `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.
364
-
365
- **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))`:
366
-
367
- ```jsx
368
- async function handleImport(event) {
369
- const template = JSON.parse(await event.target.files[0].text());
370
- await saveTemplate(template);
371
- }
372
- ```
104
+ | Import | What's in it |
105
+ | ---------------------- | ------------------------------------------------------------------------------------ |
106
+ | `noteloom` | the editor, every built-in type, menus, clipboard, export, templates, find & replace |
107
+ | `noteloom/theme` | the default stylesheet (also `noteloom/style.css`) |
108
+ | `noteloom/starter-kit` | `starterKit()`, `defineBlock`, `defineInline`, `registerExtensions` |
109
+ | `noteloom/collab` | real-time collaboration (a custom CRDT over WebRTC) |
110
+ | `noteloom/persistence` | IndexedDB auto-save + PWA service-worker hook |
111
+ | `noteloom/comments` | comment threads + the built-in comment UI |
112
+ | `noteloom/versions` | automatic version history + `<VersionHistory>` |
113
+ | `noteloom/voice` | voice typing |
114
+ | `noteloom/canvas` | the freehand-drawing block |
373
115
 
374
- (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.)
116
+ Every name in a feature entry is still exported from `noteloom` too (deprecated;
117
+ see [`docs/migration.md`](docs/migration.md)).
375
118
 
376
- ## Comments
377
-
378
- 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:
379
-
380
- ### The built-in UI (zero comment-authoring code of your own)
381
-
382
- Pass `commentAuthorId` — the current user's id — to `<NoteloomEditor>` and the whole experience just works, Notion/Google Docs-style:
383
-
384
- ```jsx
385
- <NoteloomEditor editor={editor} commentAuthorId={currentUser.id} showCommentsPanel />
386
- ```
387
-
388
- - 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.
389
- - 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.
390
- - `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.
391
-
392
- 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.
393
-
394
- 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.
395
-
396
- ### Full control (bring your own UI)
397
-
398
- 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):
399
-
400
- ```jsx
401
- import { addComment, replyToComment, resolveComment, deleteComment, useComments, resolveMultiRunSelection } from 'noteloom';
402
-
403
- <NoteloomEditor
404
- editor={editor}
405
- onComment={(range) => {
406
- const text = window.prompt('Comment text?');
407
- if (text) addComment(editor.store, range, { authorId: currentUser.id, text });
408
- }}
409
- />;
410
-
411
- // Outside the floating toolbar entirely, resolve the selection yourself:
412
- function AddCommentButton({ store }) {
413
- function handleClick() {
414
- const range = resolveMultiRunSelection(); // { blockId, startRunId, startOffset, endRunId, endOffset }
415
- if (!range) return; // no non-collapsed selection
416
- addComment(store, range, { authorId: currentUser.id, text: 'Can we tighten this up?' });
417
- }
418
- return <button onClick={handleClick}>Add comment</button>;
419
- }
420
-
421
- // A hand-rolled list, using useComments() directly instead of CommentsPanel/CommentThreadCard:
422
- function CommentsSidebar({ store }) {
423
- const comments = useComments();
424
- return (
425
- <ul>
426
- {comments.map((thread) => (
427
- <li key={thread.id}>
428
- {thread.messages.map((m) => <p key={m.id}>{m.authorId}: {m.text}</p>)}
429
- <button onClick={() => replyToComment(store, thread.id, { authorId: currentUser.id, text: '...' })}>Reply</button>
430
- <button onClick={() => resolveComment(store, thread.id, !thread.resolved)}>{thread.resolved ? 'Reopen' : 'Resolve'}</button>
431
- <button onClick={() => deleteComment(store, thread.id)}>Delete</button>
432
- </li>
433
- ))}
434
- </ul>
435
- );
436
- }
437
- ```
438
-
439
- `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.
440
-
441
- 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.
442
-
443
- **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.
444
-
445
- `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`.
446
-
447
- ## Version history
448
-
449
- Google Docs-style — there's no "type a label and save" step. Point-in-time document snapshots (stored in IndexedDB, a third object store alongside `usePersistedDocument`'s `documents` and Templates' `templates`) are captured automatically after each burst of edits settles down, each one attributed to whoever made the changes. `examples/07-version-history/` is a complete runnable app.
450
-
451
- ```jsx
452
- import { useEditor, NoteloomEditor, VersionHistory } from 'noteloom';
453
-
454
- const editor = useEditor({ currentUserId: currentUser.id }); // stamps every edit's author, see below
455
-
456
- <NoteloomEditor editor={editor}>
457
- <VersionHistory docId={docId} />
458
- </NoteloomEditor>;
459
- ```
460
-
461
- That's the whole integration. `<VersionHistory>` is self-contained: it renders the "Version history" button, and for as long as it's mounted it also quietly captures snapshots in the background — no separate wiring needed. Clicking the button opens a drawer (matching the built-in Comments UI's own design language) listing every version grouped by day, each showing an avatar, author, relative time, and a lightweight summary ("3 blocks changed"); clicking one opens it on a **Changes** tab — a word-level diff against the version right before it, insertions highlighted green, deletions struck through in red, Google Docs "show changes"-style — with a **Preview** tab alongside for a plain read-only render, and a "Restore this version" button.
462
-
463
- **Attribution** — `currentUserId` (passed to `useEditor()`, or `history.setDefaultActorId(id)`/`new History(store, { defaultActorId })` for the granular API) is stamped as every edit's `actorId` automatically; `VersionHistory`/`createAutoVersionHistory` read it straight off the history log, no separate identity plumbing required. Omit it and versions still get created, just with `authorId: null` (shown as "Unknown").
464
-
465
- **Tuning the capture window** — `<VersionHistory docId idleMs={5 * 60 * 1000} maxVersions={200} />`: `idleMs` (default 5 minutes) is how long edits need to pause before a version is closed and saved (a smaller value in the example app, so you don't have to actually wait); `maxVersions` prunes the oldest versions beyond that count. For the granular API, or to save an explicit snapshot right before some risky action, use `createAutoVersionHistory({ store, docId, idleMs?, maxVersions? })` directly — it returns `{ stop, flush }`; `flush()` closes and saves the current window immediately instead of waiting for the idle gap (e.g. right before navigating away).
466
-
467
- Restoring needs no new function — it's the exact same `applyDocumentTemplate(store, doc)` Templates already uses to wholesale-replace a live editor's content, which is what the drawer's own Restore button calls. `saveDocumentVersion`/`loadDocumentVersion`/`deleteDocumentVersion`/`listDocumentVersions` are the raw storage operations everything above is built on, for anywhere the built-in UI doesn't fit; `useDocumentVersions(docId)` is the reactive hook if you want to build your own list instead of `<VersionHistory>`; `diffDocumentsHTML(prevDoc, nextDoc)` is the diffing function behind the Changes tab (pass `null` as `prevDoc` to mark everything as newly added), for building a custom diff view instead.
468
-
469
- ## Right-to-left / multi-language text
470
-
471
- 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:
472
-
473
- ```js
474
- import { operations } from 'noteloom';
475
-
476
- // Document-wide default:
477
- store.applyOperation(operations.updateBlockProps(store.getRootId(), { dir: 'rtl' }));
478
- // Or just one block:
479
- store.applyOperation(operations.updateBlockProps(blockId, { dir: 'rtl' }));
480
- ```
481
-
482
- 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.
483
-
484
- 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.
485
-
486
- ## Printing & PDF
487
-
488
- `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.
489
-
490
- 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:
491
-
492
- ```js
493
- window.print(); // Ctrl+P / Cmd+P works too — "Save as PDF" in the print dialog is your PDF export
494
- ```
495
-
496
- 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.
497
-
498
- ## Voice typing
499
-
500
- `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:
501
-
502
- ```jsx
503
- import { useVoiceTyping } from 'noteloom';
504
-
505
- function MicButton() {
506
- const voice = useVoiceTyping();
507
- if (!voice.isSupported) return null; // e.g. Firefox — no bundled fallback, degrades to nothing
508
- return (
509
- <button onClick={() => (voice.isListening ? voice.stop() : voice.start())}>
510
- {voice.isListening ? 'Stop dictation' : 'Start dictation'}
511
- </button>
512
- );
513
- }
514
- ```
515
-
516
- 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.
517
-
518
- ## Mobile / touch support
519
-
520
- 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):
521
-
522
- ```jsx
523
- import { MobileActionBar } from 'noteloom';
524
-
525
- // next to your other trigger hooks/components, same containerRef:
526
- <MobileActionBar containerRef={containerRef} />
527
- ```
528
-
529
- `examples/basic` has this fully wired up (run `npm run dev`, then resize to a narrow viewport or open it on a phone).
530
-
531
- It renders nothing on a mouse/trackpad, and nothing until focus is actually inside the editor. Its contents swap based on context:
532
-
533
- - **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.
534
- - **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).
535
- - **Collapsed caret, table cell** → insert row/column.
536
- - **Collapsed caret, code block** → language picker.
537
- - **Collapsed caret, callout** → color picker.
538
- - **Collapsed caret, everywhere else** → "+" (opens `MobileBlockPickerSheet`, a tap-friendly bottom sheet listing every insertable block, same commands "/" already offers), Undo/Redo, dismiss-keyboard.
539
-
540
- 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).
541
-
542
- **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.
543
-
544
- **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.
545
-
546
- ## Accessibility
547
-
548
- - 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.
549
- - `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."
550
- - 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.
551
- - 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.
552
- - Table header cells have `scope="col"`, and the column-resize/embed-resize sliders both expose `aria-valuemin/valuemax/valuenow`.
119
+ ---
553
120
 
554
- ## Offline persistence
121
+ > [!TIP]
122
+ >
123
+ > **🛰️ Offline, serverless group editing**
124
+ >
125
+ > `noteloom/collab` is a **custom block-tree CRDT over WebRTC** — peers connect
126
+ > directly, so a group can co-edit one document over a LAN or an offline hotspot
127
+ > with **nothing in the cloud**. Bring any channel to exchange connection setup:
128
+ > a `BroadcastChannel` (same-machine tabs), a tiny WebSocket relay on the LAN
129
+ > (`tools/lan-relay-server/`), or Firebase / Supabase realtime.
130
+ >
131
+ > ```jsx
132
+ > import { CollabSession } from 'noteloom/collab';
133
+ >
134
+ > const session = new CollabSession({ history: editor.store, signaling });
135
+ > session.connect(remotePeerId, { initiator: true });
136
+ > // every edit now syncs to connected peers; incoming edits merge live
137
+ > ```
138
+ >
139
+ > Pair it with `noteloom/persistence` and the doc survives every peer
140
+ > disconnecting. _Experimental_ —
141
+ > [guide → live collaboration](docs/guide.md#live-collaboration-experimental).
555
142
 
556
- 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:
143
+ ---
557
144
 
558
- ```jsx
559
- import { useEditor, NoteloomEditor, usePersistedDocument } from 'noteloom';
145
+ ## Styling
560
146
 
561
- function App() {
562
- const editor = useEditor({ doc: myStarterDoc });
563
- const { isLoaded } = usePersistedDocument({ store: editor.store, docId: 'my-document-id' });
147
+ No CSS import needed — the default theme injects on mount. Retheme via CSS
148
+ custom properties on `:root`:
564
149
 
565
- if (!isLoaded) return <p>Loading…</p>;
566
- return <NoteloomEditor editor={editor} />;
150
+ ```css
151
+ :root {
152
+ --noteloom-accent: #16a34a;
153
+ --noteloom-radius-md: 4px;
154
+ --noteloom-font: 'Inter', sans-serif;
567
155
  }
568
156
  ```
569
157
 
570
- 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.
571
-
572
- Everything already auto-saves, but `usePersistedDocument` also wires up the keyboard shortcut every user reaches for anyway: **Ctrl+S (Windows/Linux) or Cmd+S (Mac)** forces an immediate save (skipping the rest of the debounce window) and blocks the browser's own "Save Page" dialog from popping up instead — pass `{ saveShortcut: false }` to opt out, and `onSave` (fires after every save, shortcut-triggered or manual) to show your own "Saved" feedback. The hook also returns `save()` directly, for a manual Save button:
573
-
574
- ```jsx
575
- const { isLoaded, save } = usePersistedDocument({
576
- store: editor.store,
577
- docId: 'my-document-id',
578
- onSave: () => showSavedToast(),
579
- });
580
- ```
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 }` — `flush()` returns a Promise that resolves once the write actually lands (or immediately if there was nothing pending).
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
- ## File & image uploads
158
+ Or `theme="none"` to style every `.be-*` class yourself. Dark mode follows
159
+ `prefers-color-scheme` (or `data-theme="dark"`). Details: [guide → styling](docs/guide.md#styling--zero-setup-required).
610
160
 
611
- The image/video/audio/file block (`embed`, reachable via "/image", "/video", etc.) ships with zero configuration needed: a picked or dropped file is read straight into a `data:` URL and stored directly in the document. That keeps everything fully self-contained works offline, round-trips through copy/paste and undo/redo like any other block — at the cost of bloating the document for large media, since this package has no backend of its own to hand a file to instead.
161
+ > A future major will stop auto-injecting the themeadd `import 'noteloom/theme'`
162
+ > now to keep it, or `theme="none"` if you already style the editor.
612
163
 
613
- For real upload-to-a-server behavior — local disk, AWS S3, or any other cloud storage — pass `uploadFile` to `<NoteloomEditor>` (or `<EditorProvider>` for the granular API):
164
+ ## Document format
614
165
 
615
166
  ```jsx
616
- <NoteloomEditor
617
- editor={editor}
618
- uploadFile={async (file, { kind }) => {
619
- const body = new FormData();
620
- body.append('file', file);
621
- const res = await fetch('/api/upload', { method: 'POST', body });
622
- const { url } = await res.json();
623
- return { src: url }; // { name?, mimeType? } also accepted, defaulting to the file's own
624
- }}
625
- />
626
- ```
627
-
628
- A few things worth knowing:
629
-
630
- - **AWS S3** (or any presigned-URL-style object storage) is the same shape, just two requests instead of one — ask your own backend for a presigned PUT URL, then `PUT` the file straight to it:
631
- ```js
632
- uploadFile: async (file) => {
633
- const { uploadUrl, publicUrl } = await fetch('/api/s3-presign', {
634
- method: 'POST',
635
- headers: { 'Content-Type': 'application/json' },
636
- body: JSON.stringify({ filename: file.name, contentType: file.type }),
637
- }).then((r) => r.json());
638
- await fetch(uploadUrl, { method: 'PUT', body: file, headers: { 'Content-Type': file.type } });
639
- return { src: publicUrl };
640
- }
641
- ```
642
- Any other cloud storage (Cloudinary, Supabase Storage, R2, GCS, ...) is one of these two shapes — a single API call back with a hosted URL, or a signed-URL handshake — since this package only ever needs the final `{ src }`, not how it got there.
643
- - **Small/medium/large file handling** is entirely `uploadFile`'s own business, off `file.size` (bytes) — this package deliberately hardcodes no byte thresholds of its own, since what counts as "large" varies wildly by app:
644
- ```js
645
- uploadFile: async (file) => {
646
- if (file.size < 200 * 1024) return { src: await inlineAsDataUrl(file) }; // small: keep it simple
647
- if (file.size < 25 * 1024 * 1024) return uploadToYourServer(file); // medium
648
- return uploadToS3Multipart(file); // large: chunked/multipart
649
- }
650
- ```
651
- - While `uploadFile` is resolving, the block shows an "Uploading…" state; if it rejects, a dismissible error message is shown instead and nothing is written to the document — the file input stays available to try again.
652
- - `maxFileSize` (bytes) only applies to the **built-in, zero-config `data:` URL fallback** — an oversized file is rejected with a clear error instead of silently bloating the document. It has no effect once `uploadFile` is configured, since the host's own function (or backend) is what decides what it can handle.
653
- - `useFileUpload()` exposes the same `{ uploadFile, maxFileSize }` to your own components, for building custom upload UI outside the `embed` block that still honors the same configuration.
654
-
655
- ## Live collaboration (experimental)
656
-
657
- 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.
658
-
659
- ```jsx
660
- import { useEditor, NoteloomEditor, CollabSession } from 'noteloom';
661
- import { useEffect } from 'react';
662
-
663
- function App() {
664
- const editor = useEditor({ doc: myDoc });
665
-
666
- useEffect(() => {
667
- // `signaling` is any object shaped like SignalingChannel (src/sync/signaling.js):
668
- // { localPeerId, send(toPeerId, message), onMessage(cb) }
669
- const session = new CollabSession({ history: editor.store, signaling });
670
- session.connect(remotePeerId, { initiator: true }); // `initiator: true` on exactly one side of each pair
671
- return () => session.destroy();
672
- }, []);
673
-
674
- return <NoteloomEditor editor={editor} />;
675
- }
676
- ```
677
-
678
- 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.
679
-
680
- ### Signaling options
681
-
682
- `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:
683
-
684
- - **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.
685
- - **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:
686
-
687
- ```js
688
- import { createWebSocketSignaling, CollabSession } from 'noteloom';
689
-
690
- const signaling = createWebSocketSignaling({
691
- url: 'ws://192.168.1.5:8080', // a relay running on your LAN -- or any host, if you want internet-wide instead
692
- roomId: 'my-document-id', // anyone using the same roomId ends up in the same room
693
- peerId: crypto.randomUUID(),
694
- });
695
- const session = new CollabSession({ history: editor.store, signaling });
696
-
697
- signaling.onPeerDiscovered((remotePeerId) => {
698
- const initiator = signaling.localPeerId > remotePeerId; // deterministic tie-break
699
- session.connect(remotePeerId, { initiator });
700
- });
701
- ```
702
-
703
- 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.
704
-
705
- ### Presence / awareness (live cursors, who's online)
706
-
707
- `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"):
708
-
709
- ```js
710
- import { usePresence } from 'noteloom';
711
-
712
- // broadcast your own position (throttled automatically, ~100ms by default)
713
- session.setLocalPresence({ runId: caret.runId, offset: caret.offset, name: 'Alex' });
714
-
715
- // react to everyone else's, reactively
716
- function PeerCursors({ session }) {
717
- const presence = usePresence(session); // Map<peerId, data>, re-renders on change
718
- return [...presence.entries()].map(([peerId, data]) => /* render however you like */);
719
- }
167
+ const doc = editor.toJSON(); // { version: 1, blocks: [{ id, type, data, children? }] }
168
+ const restored = useEditor({ doc }); // loads it back — internal shape works too
720
169
  ```
721
170
 
722
- 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.
171
+ Schema: [`docs/document.schema.json`](docs/document.schema.json). The normalized
172
+ engine graph is available via `editor.toJSON({ format: 'internal' })` when you
173
+ need it. HTML / Markdown / Word / plain-text export and a drop-in `View source`
174
+ button: [guide → exporting](docs/guide.md#exporting-the-document-json--html--markdown--word--pdf--plain-text).
723
175
 
724
- **How conflicts resolve:**
725
- - Concurrent inserts (even at the same position) — both survive, converging to the same order on every peer.
726
- - Concurrent delete vs. edit of the same block — the delete wins.
727
- - Concurrent type-conversion of the same block ("Turn into") — one type wins deterministically (the same one, on every peer), not two duplicate blocks.
728
- - 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.
176
+ ## Features (all in the [full guide](docs/guide.md))
729
177
 
730
- ### Tombstone garbage collection
178
+ | Feature | |
179
+ | ----------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- |
180
+ | [Custom dropdown / mention field types](docs/guide.md#custom-dropdown--mention-field-types-static-or-dynamicapi-backed) | static or API-backed, no component to write |
181
+ | [Templates](docs/guide.md#templates) | reusable documents + insertable block snippets |
182
+ | [Comments](docs/guide.md#comments) | thread on a range; built-in UI or bring your own |
183
+ | [Version history](docs/guide.md#version-history) | Google Docs-style automatic snapshots + diff |
184
+ | [Offline persistence + PWA](docs/guide.md#offline-persistence) | IndexedDB auto-save, offline app shell |
185
+ | [Live collaboration](docs/guide.md#live-collaboration-experimental) | multi-peer over WebRTC, bring-your-own signaling _(experimental)_ |
186
+ | [Voice typing](docs/guide.md#voice-typing) | dictation + spoken commands via the browser's Speech API |
187
+ | [Mobile / touch](docs/guide.md#mobile--touch-support) | bottom action bar, tap-friendly sheets |
188
+ | [Find & replace](docs/guide.md#find--replace) | `Ctrl/Cmd+F`, match case / whole word |
189
+ | [File & image uploads](docs/guide.md#file--image-uploads) | `data:` URL by default, or wire `uploadFile` to S3/etc. |
190
+ | [RTL / multi-language](docs/guide.md#right-to-left--multi-language-text) | automatic per-block direction |
191
+ | [Accessibility](docs/guide.md#accessibility) | keyboard-operable menus, live-region announcements |
192
+ | [The granular API](docs/guide.md#advanced-the-granular-api) | build the editor surface by hand |
731
193
 
732
- 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:
194
+ ## Requirements
733
195
 
734
- ```js
735
- import { useEditor, createPeriodicTombstoneGC } from 'noteloom';
196
+ React 18.2+ or 19, and a modern browser (`contentEditable` + `beforeinput`;
197
+ IndexedDB for `noteloom/persistence`; WebRTC for `noteloom/collab`;
198
+ `SpeechRecognition` for `noteloom/voice`). SSR-safe — renders nothing on the
199
+ server and hydrates on mount.
736
200
 
737
- const editor = useEditor({ doc: myDoc });
738
- const gc = createPeriodicTombstoneGC({ store: editor.store, intervalMs: 60 * 60 * 1000, maxAgeMs: 24 * 60 * 60 * 1000 }); // hourly sweep, 24h retention (both defaults, shown explicitly)
201
+ ## Status
739
202
 
740
- // later, when the store is no longer in use:
741
- gc.stop();
742
- ```
743
-
744
- 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).
745
-
746
- **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.
747
-
748
- ### Reconnecting reliably
749
-
750
- `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:
751
-
752
- - **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.
753
- - **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).
754
-
755
- **Known limitations — read before relying on this in production:**
756
- - **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.
757
- - **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.
758
- - **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.
759
- - **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.
760
- - 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.
761
- - 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.
762
-
763
- ---
203
+ Pre-1.0 (`0.4.x`). Changes are **additive only** until a deliberate major —
204
+ existing code keeps working, deprecations get a full minor-version notice, and
205
+ the frozen list in [`docs/stability.md`](docs/stability.md) says exactly what
206
+ semver covers. `noteloom/collab` is **experimental**.
764
207
 
765
- # Advanced: the granular API
208
+ ## Contributing
766
209
 
767
- 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.
210
+ Issues and PRs welcomeit's a small, opinionated project.
768
211
 
769
- ## Building the editor by hand
770
-
771
- ```jsx
772
- import {
773
- EditorStore,
774
- History,
775
- EditorProvider,
776
- BlockChildren,
777
- createBlockRegistry,
778
- registerBuiltInBlocks,
779
- createInlineRegistry,
780
- registerBuiltInInlineTypes,
781
- useClipboardHandlers,
782
- useSlashMenuTrigger,
783
- useEditorKeyboardShortcuts,
784
- SlashMenu,
785
- } from 'noteloom';
786
- import { useMemo, useRef } from 'react';
787
-
788
- function Editor() {
789
- const containerRef = useRef(null);
790
- const { store, registry, inlineRegistry } = useMemo(() => {
791
- const registry = createBlockRegistry();
792
- registerBuiltInBlocks(registry);
793
- const inlineRegistry = createInlineRegistry();
794
- registerBuiltInInlineTypes(inlineRegistry);
795
- const store = new History(
796
- new EditorStore({
797
- rootId: 'root',
798
- blocks: [
799
- { id: 'root', type: 'page', parentId: null, contentIds: ['p1'], props: {} },
800
- { id: 'p1', type: 'paragraph', parentId: 'root', contentIds: ['r1'], props: {} },
801
- ],
802
- runs: [{ id: 'r1', type: 'text', value: 'Hello — try typing "/" for commands.', marks: {} }],
803
- }),
804
- );
805
- return { store, registry, inlineRegistry };
806
- }, []);
807
-
808
- const { onCopy, onCut, onPaste } = useClipboardHandlers();
809
- const slashMenu = useSlashMenuTrigger(containerRef);
810
- useEditorKeyboardShortcuts(containerRef);
811
-
812
- return (
813
- <EditorProvider store={store} registry={registry} inlineRegistry={inlineRegistry} history={store}>
814
- <div ref={containerRef} onCopy={onCopy} onCut={onCut} onPaste={onPaste}>
815
- <BlockChildren parentId="root" />
816
- <SlashMenu
817
- isOpen={slashMenu.isOpen}
818
- rect={slashMenu.rect}
819
- commands={slashMenu.commands}
820
- runId={slashMenu.runId}
821
- onSelect={slashMenu.selectCommand}
822
- onClose={slashMenu.close}
823
- />
824
- </div>
825
- </EditorProvider>
826
- );
827
- }
828
- ```
829
-
830
- 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.
831
-
832
- ## Registering a brand-new block/inline type, from scratch
833
-
834
- 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:
835
-
836
- ```js
837
- registry.register('myBlock', {
838
- component: MyBlockComponent, // receives only { id }
839
- isLeaf: true, // true if contentIds holds run ids, false if it holds child block ids
840
- toHTML(block, ctx) { /* ... */ },
841
- fromHTML(domNode, ctx) { /* ... or return null if this node isn't yours */ },
842
- toPlainText(block, ctx) { /* ... */ },
843
- slashCommand: { label: 'My Block', keywords: ['my'], run(store, ctx) { /* ... */ } },
844
- });
212
+ ```bash
213
+ git clone https://github.com/vishwakarmanikhil/noteloom.git
214
+ cd noteloom && npm install
215
+ npm test # vitest (no build step needed)
216
+ npm run dev:quickstart # or dev:custom-block / dev:collab / dev:lan-collab / …
845
217
  ```
846
218
 
847
- `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.
848
-
849
- ---
850
-
851
- # Development
219
+ Before a PR:
852
220
 
853
- ```bash
854
- npm install
855
- npm run dev:quickstart # examples/01-quickstart useEditor()/<NoteloomEditor>
856
- npm run dev # examples/basic — the same editor built from the granular API
857
- npm test # vitest (jsdom + @testing-library/react)
858
- npm run typecheck # tsc --noEmit against src/index.d.ts
859
- npm run build # library build (dist/, ESM + CJS + index.d.ts)
860
- ```
221
+ - **`npm test`** and **`npm run lint`** (CI runs the suite on Node 18/20/22;
222
+ errors block, warnings don't).
223
+ - **Add/update tests**`test/` mirrors `src/`. Touching rendering or export
224
+ output? Refresh the golden snapshots (`npx playwright test golden-document
225
+ --update-snapshots`) in the same commit.
226
+ - **Public API change?** Update the entry file, its `.d.ts`, and the frozen list
227
+ in `test/publicApi.test.js` the diff is the review signal.
228
+ - **`npm run changeset`** for anything user-facing — it becomes the release note.
229
+ - **Keep the zero-runtime-dependency rule** — nothing in `src/` may add a runtime
230
+ `dependency`.
861
231
 
862
- See `examples/README.md` for the rest of the runnable examples, and `CONTRIBUTING.md` for the full contributor guide.
232
+ Full detail code layout, the framework-free-core boundary, sync-layer testing
233
+ advice — in [`CONTRIBUTING.md`](CONTRIBUTING.md). Example apps and what each
234
+ teaches: [`examples/README.md`](examples/README.md).
863
235
 
864
- ## Known limitations
236
+ ## License
865
237
 
866
- - 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.
867
- - `<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.
868
- - 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.
869
- - `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.
870
- - 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.
871
- - 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.
872
- - 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.
873
- - 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.
238
+ MIT