yurich 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +387 -2
- package/dist/index.cjs +2 -0
- package/dist/index.d.cts +183 -0
- package/dist/index.d.ts +183 -0
- package/dist/index.mjs +863 -0
- package/package.json +73 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 lee yujoo
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,388 @@
|
|
|
1
|
-
#
|
|
1
|
+
# yurich
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://github.com/YUJOO-LEE/yurich)
|
|
4
|
+
[](https://www.npmjs.com/package/yurich)
|
|
5
|
+
|
|
6
|
+
A headless rich text editor for React built on native `contentEditable` + Selection API.
|
|
7
|
+
|
|
8
|
+
## Why yurich?
|
|
9
|
+
|
|
10
|
+
- **Zero dependencies** — Only React as a peer dependency. No ProseMirror, no Slate, no heavy document model.
|
|
11
|
+
- **Native contentEditable** — Uses the browser's built-in editing with the Selection API directly. Does **not** use `document.execCommand`.
|
|
12
|
+
- **HTML-native model** — The DOM *is* the document. No separate document model to sync.
|
|
13
|
+
- **Schema from extensions** — The extensions you enable define which tags exist. Everything else is removed on paste, on load, and in the output.
|
|
14
|
+
- **Headless** — No default styles or UI. Full control over your toolbar and layout.
|
|
15
|
+
- **Accessible** — ARIA roles and keyboard shortcuts built in.
|
|
16
|
+
- **IME/Composition support** — The document is left alone while a CJK or other IME composition is in progress.
|
|
17
|
+
|
|
18
|
+
## Installation
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
npm install yurich
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
React 18+ is a peer dependency:
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
npm install react react-dom
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Quick Start
|
|
31
|
+
|
|
32
|
+
```tsx
|
|
33
|
+
import {
|
|
34
|
+
useEditor,
|
|
35
|
+
EditorProvider,
|
|
36
|
+
EditorContent,
|
|
37
|
+
Bold,
|
|
38
|
+
Italic,
|
|
39
|
+
Underline,
|
|
40
|
+
useEditorContext,
|
|
41
|
+
useIsActive,
|
|
42
|
+
} from 'yurich';
|
|
43
|
+
|
|
44
|
+
function ToolbarButton({ command, label, children }: {
|
|
45
|
+
command: string;
|
|
46
|
+
label: string;
|
|
47
|
+
children: React.ReactNode;
|
|
48
|
+
}) {
|
|
49
|
+
const editor = useEditorContext();
|
|
50
|
+
const active = useIsActive(editor, command);
|
|
51
|
+
return (
|
|
52
|
+
<button
|
|
53
|
+
aria-pressed={active}
|
|
54
|
+
aria-label={label}
|
|
55
|
+
onMouseDown={e => e.preventDefault()}
|
|
56
|
+
onClick={() => editor.execute(command)}
|
|
57
|
+
>
|
|
58
|
+
{children}
|
|
59
|
+
</button>
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function MyEditor() {
|
|
64
|
+
const editor = useEditor({
|
|
65
|
+
extensions: [Bold, Italic, Underline],
|
|
66
|
+
initialValue: '<p>Hello World!</p>',
|
|
67
|
+
onChange: (html) => console.log(html),
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
return (
|
|
71
|
+
<EditorProvider editor={editor}>
|
|
72
|
+
<div role="toolbar" aria-label="Formatting">
|
|
73
|
+
<ToolbarButton command="toggleBold" label="Bold">B</ToolbarButton>
|
|
74
|
+
<ToolbarButton command="toggleItalic" label="Italic">I</ToolbarButton>
|
|
75
|
+
<ToolbarButton command="toggleUnderline" label="Underline">U</ToolbarButton>
|
|
76
|
+
</div>
|
|
77
|
+
<EditorContent className="my-editor" ariaLabel="Rich text editor" />
|
|
78
|
+
</EditorProvider>
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
`onMouseDown={e => e.preventDefault()}` keeps the selection in the editor when a toolbar button is clicked.
|
|
84
|
+
|
|
85
|
+
## Extensions
|
|
86
|
+
|
|
87
|
+
| Extension | Commands | Keyboard Shortcut |
|
|
88
|
+
|---|---|---|
|
|
89
|
+
| `Bold` | `toggleBold` | `Mod+B` |
|
|
90
|
+
| `Italic` | `toggleItalic` | `Mod+I` |
|
|
91
|
+
| `Underline` | `toggleUnderline` | `Mod+U` |
|
|
92
|
+
| `Strikethrough` | `toggleStrikethrough` | `Mod+Shift+S` |
|
|
93
|
+
| `Code` | `toggleCode` | — |
|
|
94
|
+
| `Link` | `setLink`, `removeLink` | — |
|
|
95
|
+
| `Heading` | `setHeading`, `removeHeading` | — |
|
|
96
|
+
| `OrderedList` | `toggleOrderedList` | — |
|
|
97
|
+
| `UnorderedList` | `toggleUnorderedList` | — |
|
|
98
|
+
| `Blockquote` | `toggleBlockquote` | — |
|
|
99
|
+
| `CodeBlock` | `toggleCodeBlock` | — |
|
|
100
|
+
| `TextAlign` | `alignLeft`, `alignCenter`, `alignRight`, `alignJustify` | — |
|
|
101
|
+
|
|
102
|
+
> `Mod` is `Cmd` on macOS and `Ctrl` on Windows/Linux.
|
|
103
|
+
|
|
104
|
+
An editor keeps only what its extensions declare. With `extensions: [Bold]`, pasted italic text loses the italic and a pasted heading becomes a paragraph.
|
|
105
|
+
|
|
106
|
+
### Command values
|
|
107
|
+
|
|
108
|
+
```ts
|
|
109
|
+
// Heading level 1-6. Other values are ignored.
|
|
110
|
+
editor.execute('setHeading', 2);
|
|
111
|
+
|
|
112
|
+
// Only http:, https: and mailto: addresses are accepted.
|
|
113
|
+
// With a selection the text becomes the link; with only a caret the address is inserted as the link text.
|
|
114
|
+
editor.execute('setLink', { href: 'https://example.com' });
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
### How commands behave
|
|
118
|
+
|
|
119
|
+
- A mark command (`toggleBold`, …) needs a selection. With only a caret it does nothing.
|
|
120
|
+
- A mark is active only when all of the selected text has it. Toggling a partly bold selection makes all of it bold.
|
|
121
|
+
- Removing a mark from part of a marked run keeps the mark on the rest.
|
|
122
|
+
- Block commands apply to every selected block. A selection that ends at the very start of a block does not include that block.
|
|
123
|
+
- List commands apply to the selected items only. Turning one item of a list off, or into another list type, splits the list around it.
|
|
124
|
+
- A heading, blockquote or code block applied inside a list takes the item out of the list.
|
|
125
|
+
|
|
126
|
+
## API Reference
|
|
127
|
+
|
|
128
|
+
### `useEditor(options)`
|
|
129
|
+
|
|
130
|
+
Creates an editor instance that lives as long as the component.
|
|
131
|
+
|
|
132
|
+
| Option | Type | Default | Description |
|
|
133
|
+
|---|---|---|---|
|
|
134
|
+
| `extensions` | `Extension[]` | — | Extensions to enable (required) |
|
|
135
|
+
| `initialValue` | `string` | `undefined` | Initial HTML content. Read once; replace the content later with `setHTML`. |
|
|
136
|
+
| `onChange` | `(html: string) => void` | `undefined` | Called when the content changes (HTML) |
|
|
137
|
+
| `onChangeJSON` | `(json: DocumentJSON) => void` | `undefined` | Called when the content changes (JSON) |
|
|
138
|
+
| `sanitize` | `boolean` | `true` | Sanitize the output of `getHTML()` and `onChange`. Read once. |
|
|
139
|
+
| `historyLimit` | `number` | `100` | Max undo steps. Read once. |
|
|
140
|
+
|
|
141
|
+
`onChange` and `onChangeJSON` are called at most once per animation frame, and only when the content actually changed.
|
|
142
|
+
|
|
143
|
+
### `EditorInstance`
|
|
144
|
+
|
|
145
|
+
| Member | Signature | Description |
|
|
146
|
+
|---|---|---|
|
|
147
|
+
| `execute` | `(command: string, value?: unknown) => void` | Run a command by name |
|
|
148
|
+
| `isActive` | `(name: string, value?: unknown) => boolean` | Whether a command or extension is active at the selection, e.g. `isActive('setHeading', 2)` |
|
|
149
|
+
| `getHTML` | `() => string` | The content as sanitized HTML |
|
|
150
|
+
| `getJSON` | `() => DocumentJSON` | The content as JSON |
|
|
151
|
+
| `setHTML` | `(html: string, options?: { history?: boolean }) => void` | Replace the whole content. See below. |
|
|
152
|
+
| `history.undo` / `history.redo` | `() => void` | Undo / redo |
|
|
153
|
+
| `history.canUndo` / `history.canRedo` | `() => boolean` | Whether undo / redo is available |
|
|
154
|
+
| `subscribe` | `(listener: () => void) => () => void` | Call `listener` whenever content, selection, or history changes. Returns an unsubscribe function. |
|
|
155
|
+
| `el` | `HTMLElement \| null` | The editable element. `null` until `EditorContent` first mounts. |
|
|
156
|
+
|
|
157
|
+
The instance itself never changes, so reading `editor.isActive(...)` or `editor.history.canUndo()` during render does not re-render the component. Read them through the hooks below.
|
|
158
|
+
|
|
159
|
+
The methods for writing extensions are listed under [Custom Extensions](#custom-extensions).
|
|
160
|
+
|
|
161
|
+
### Replacing the content
|
|
162
|
+
|
|
163
|
+
`setHTML` replaces the whole document, for content that arrives after the editor is created or for switching to another document.
|
|
164
|
+
|
|
165
|
+
```ts
|
|
166
|
+
editor.setHTML(post.html); // one undo step: undo brings back the previous content
|
|
167
|
+
editor.setHTML(post.html, { history: false }); // clears the undo history: loading a document, switching documents
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
The HTML goes through the sanitizer and the document rules, and `onChange` is called. Before `EditorContent` first mounts, `setHTML` sets the initial content.
|
|
171
|
+
|
|
172
|
+
### `useIsActive`, `useCanUndo`, `useCanRedo`
|
|
173
|
+
|
|
174
|
+
Each hook subscribes the component to one value and re-renders it only when that value changes. Moving the caret re-renders the buttons whose state flipped and nothing else.
|
|
175
|
+
|
|
176
|
+
```tsx
|
|
177
|
+
const isBold = useIsActive(editor, 'toggleBold');
|
|
178
|
+
const isH2 = useIsActive(editor, 'setHeading', 2);
|
|
179
|
+
const canUndo = useCanUndo(editor);
|
|
180
|
+
const canRedo = useCanRedo(editor);
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
`editor` comes from `useEditor` or `useEditorContext`, so the hooks work inside and outside an `EditorProvider`.
|
|
184
|
+
|
|
185
|
+
### `useEditorState(editor, selector)`
|
|
186
|
+
|
|
187
|
+
The hook the three above are built on, for state they do not cover.
|
|
188
|
+
|
|
189
|
+
```tsx
|
|
190
|
+
const isEmpty = useEditorState(editor, e => (e.el?.textContent ?? '') === '');
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
Return a primitive from the selector. An object is a new value on every change and re-renders every time.
|
|
194
|
+
|
|
195
|
+
### `EditorProvider` and `useEditorContext`
|
|
196
|
+
|
|
197
|
+
`EditorProvider` gives the editor to the components below it. `useEditorContext` reads it.
|
|
198
|
+
|
|
199
|
+
```tsx
|
|
200
|
+
<EditorProvider editor={editor}>
|
|
201
|
+
{/* Toolbar, EditorContent, etc. */}
|
|
202
|
+
</EditorProvider>
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
### `EditorContent`
|
|
206
|
+
|
|
207
|
+
Shows the editable area. Must be inside an `EditorProvider`.
|
|
208
|
+
|
|
209
|
+
| Prop | Type | Description |
|
|
210
|
+
|---|---|---|
|
|
211
|
+
| `className` | `string` | CSS class for the editable element |
|
|
212
|
+
| `ariaLabel` | `string` | Accessible label |
|
|
213
|
+
| `ariaDescribedBy` | `string` | ID of a describing element |
|
|
214
|
+
|
|
215
|
+
The editable element belongs to the editor instance, not to `EditorContent`. Unmounting `EditorContent` and mounting it again keeps the content and the undo history, and `getHTML()`, `getJSON()` and undo keep working in between.
|
|
216
|
+
|
|
217
|
+
Dropping content into the editor is disabled, because it would bypass the sanitizer.
|
|
218
|
+
|
|
219
|
+
### Serializers
|
|
220
|
+
|
|
221
|
+
Convert any element with the rules of a set of extensions:
|
|
222
|
+
|
|
223
|
+
```ts
|
|
224
|
+
import { toHTML, toJSON, Bold, Link } from 'yurich';
|
|
225
|
+
|
|
226
|
+
const html = toHTML(element, [Bold, Link]);
|
|
227
|
+
const json = toJSON(element, [Bold, Link]);
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
## Output Formats
|
|
231
|
+
|
|
232
|
+
### HTML
|
|
233
|
+
|
|
234
|
+
```ts
|
|
235
|
+
editor.getHTML();
|
|
236
|
+
// '<p>Hello <strong>World</strong></p>'
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
### JSON
|
|
240
|
+
|
|
241
|
+
```ts
|
|
242
|
+
editor.getJSON();
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
```json
|
|
246
|
+
{
|
|
247
|
+
"type": "doc",
|
|
248
|
+
"content": [
|
|
249
|
+
{
|
|
250
|
+
"type": "paragraph",
|
|
251
|
+
"content": [
|
|
252
|
+
{ "type": "text", "text": "Hello " },
|
|
253
|
+
{ "type": "text", "text": "World", "marks": [{ "type": "bold" }] }
|
|
254
|
+
]
|
|
255
|
+
}
|
|
256
|
+
]
|
|
257
|
+
}
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
**Node types:** `paragraph`, `heading` (`attrs.level`), `blockquote`, `codeBlock`, `orderedList`, `unorderedList`, `listItem`, `text`. A block with a text alignment carries `attrs.textAlign`.
|
|
261
|
+
|
|
262
|
+
**Mark types:** `bold`, `italic`, `underline`, `strikethrough`, `code`, `link` (`attrs.href`, plus `attrs.target` and `attrs.rel` when the link opens in a new tab), and the types of custom marks.
|
|
263
|
+
|
|
264
|
+
A line break inside a block is a text node `"\n"`.
|
|
265
|
+
|
|
266
|
+
`getJSON()` reuses the nodes of blocks that did not change between calls. Treat the result as immutable.
|
|
267
|
+
|
|
268
|
+
## Custom Extensions
|
|
269
|
+
|
|
270
|
+
A toggled inline format or block type is one call:
|
|
271
|
+
|
|
272
|
+
```ts
|
|
273
|
+
import { mark, block } from 'yurich';
|
|
274
|
+
|
|
275
|
+
// <mark>, command `toggleHighlight`, JSON mark type `highlight`
|
|
276
|
+
const Highlight = mark({ name: 'highlight', tag: 'mark', shortcut: 'Mod+Shift+H' });
|
|
277
|
+
|
|
278
|
+
// <aside>, command `toggleCallout`, JSON node type `callout`
|
|
279
|
+
const Callout = block({ name: 'callout', tag: 'aside' });
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
The command is `toggle` + the capitalized name. A tag declared this way is part of the editor's schema: it survives paste, `initialValue`, undo and `getHTML()`, and appears in `getJSON()`.
|
|
283
|
+
|
|
284
|
+
For anything else, write the extension object:
|
|
285
|
+
|
|
286
|
+
```ts
|
|
287
|
+
import type { Extension } from 'yurich';
|
|
288
|
+
|
|
289
|
+
const Mention: Extension = {
|
|
290
|
+
name: 'mention',
|
|
291
|
+
marks: [{
|
|
292
|
+
tag: 'cite',
|
|
293
|
+
type: 'mention',
|
|
294
|
+
attrs: { 'data-id': value => (value && /^\d+$/.test(value) ? value : null) },
|
|
295
|
+
}],
|
|
296
|
+
commands: {
|
|
297
|
+
setMention: (editor, value) => editor.setMark('cite', { 'data-id': String(value) }),
|
|
298
|
+
removeMention: editor => editor.removeMark('cite'),
|
|
299
|
+
},
|
|
300
|
+
isActive: editor => editor.isMarkActive('cite'),
|
|
301
|
+
};
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
**`Extension`**
|
|
305
|
+
|
|
306
|
+
| Field | Type | Description |
|
|
307
|
+
|---|---|---|
|
|
308
|
+
| `name` | `string` | Unique name |
|
|
309
|
+
| `marks` | `MarkSpec[]` | Inline tags: `tag`, JSON `type`, optional `aliases` (tags rewritten to `tag`) and `attrs` |
|
|
310
|
+
| `blocks` | `BlockSpec[]` | Block tags: `tag`, JSON `type`, optional `aliases` and fixed JSON `attrs` |
|
|
311
|
+
| `blockStyles` | `Record<string, readonly string[]>` | CSS properties allowed on blocks and the values each may take |
|
|
312
|
+
| `commands` | `Record<string, CommandFn>` | Command name → `(editor, value) => void` |
|
|
313
|
+
| `keyboardShortcuts` | `Record<string, string>` | Key combo → command name |
|
|
314
|
+
| `isActive` | `(editor, command?, value?) => boolean` | Whether the extension is active at the selection |
|
|
315
|
+
|
|
316
|
+
Tags are lowercase. An attribute is kept only when the mark declares a rule for it: the rule receives the current value (or `null`) and the element, and returns the value to write or `null` to leave the attribute out.
|
|
317
|
+
|
|
318
|
+
**Editor methods for commands**
|
|
319
|
+
|
|
320
|
+
| Method | Description |
|
|
321
|
+
|---|---|
|
|
322
|
+
| `toggleMark(tag)` | Add the mark to the selection, or remove it when all of the selection has it |
|
|
323
|
+
| `setMark(tag, attrs?, text?)` | Add the mark with attributes. With only a caret, `text` is inserted and marked. |
|
|
324
|
+
| `removeMark(tag)` | Remove the mark from the selection. With only a caret, remove the whole mark around it. |
|
|
325
|
+
| `isMarkActive(tag)` | Whether all of the selected text has the mark |
|
|
326
|
+
| `setBlock(tag)` / `toggleBlock(tag)` | Change the selected blocks to `tag` / toggle between `tag` and paragraph |
|
|
327
|
+
| `isBlockActive(tag)` | Whether every selected block is a `tag` |
|
|
328
|
+
| `toggleList(tag)` / `isListActive(tag)` | `'ol'` or `'ul'` |
|
|
329
|
+
| `setBlockStyle(property, value)` / `getBlockStyle(property)` | A style declared in `blockStyles` |
|
|
330
|
+
| `change(edit)` | Run your own DOM edit on `editor.el`. The document is normalized, recorded in history and reported afterwards. |
|
|
331
|
+
|
|
332
|
+
All of them act on the selection inside this editor and do nothing when the selection is elsewhere.
|
|
333
|
+
|
|
334
|
+
## Internals
|
|
335
|
+
|
|
336
|
+
### Document rules
|
|
337
|
+
|
|
338
|
+
After every change — typing, paste, a command, or your own edit of `editor.el` — the changed blocks are brought back to these rules:
|
|
339
|
+
|
|
340
|
+
- The editable element holds only blocks. Loose text is wrapped in `<p>`, and `<div>` lines become `<p>`.
|
|
341
|
+
- Every tag is in the schema and written in its canonical form (`<b>` → `<strong>`, `<i>` → `<em>`, `<del>` → `<s>`). Other tags are unwrapped.
|
|
342
|
+
- A mark is never nested in itself, never empty, and never split into identical neighbours.
|
|
343
|
+
- A list holds only items, is never empty, and is joined with an identical list next to it.
|
|
344
|
+
|
|
345
|
+
### History
|
|
346
|
+
|
|
347
|
+
Typing is grouped: keystrokes less than 300ms apart are one undo step. A command or a paste is always a step of its own. Undo and redo restore the selection along with the content.
|
|
348
|
+
|
|
349
|
+
Restored content goes through the sanitizer.
|
|
350
|
+
|
|
351
|
+
## Security
|
|
352
|
+
|
|
353
|
+
HTML enters the document in four places — `initialValue`, `setHTML`, paste, and undo/redo — and all of them go through the sanitizer. `getHTML()` and `onChange` sanitize again on the way out.
|
|
354
|
+
|
|
355
|
+
The sanitizer rebuilds the content from the schema instead of removing what looks dangerous:
|
|
356
|
+
|
|
357
|
+
- Only the tags of the enabled extensions come out, plus `<p>` and `<br>`.
|
|
358
|
+
- Only declared attributes come out: `href`, `target` and `rel` on links, and `text-align` on blocks with `TextAlign`. No `on*` handlers, `class`, `id` or other styles.
|
|
359
|
+
- Link addresses must start with `http://`, `https://` or `mailto:`. `target` may only be `_blank`, and then `rel="noopener noreferrer"` is set.
|
|
360
|
+
- `<script>`, `<style>`, `<iframe>`, `<svg>`, `<math>`, `<noscript>`, `<title>`, `<audio>`, `<video>` and similar tags are removed together with their content, even when an extension declares them.
|
|
361
|
+
- Other unknown tags are removed but their text is kept. An unknown tag that starts a line in HTML (`<td>`, `<section>`, …) becomes a paragraph.
|
|
362
|
+
- Plain text is pasted as text nodes and never parsed as HTML.
|
|
363
|
+
|
|
364
|
+
`sanitize: false` makes `getHTML()` and `onChange` return the DOM as it is. Sanitize on the server if you use it.
|
|
365
|
+
|
|
366
|
+
## Browser Support
|
|
367
|
+
|
|
368
|
+
| Browser | Version |
|
|
369
|
+
|---|---|
|
|
370
|
+
| Chrome | 85+ |
|
|
371
|
+
| Firefox | 79+ |
|
|
372
|
+
| Safari | 14+ |
|
|
373
|
+
| Edge | 85+ |
|
|
374
|
+
|
|
375
|
+
## Development
|
|
376
|
+
|
|
377
|
+
```bash
|
|
378
|
+
yarn dev # demo
|
|
379
|
+
yarn lint
|
|
380
|
+
yarn typecheck
|
|
381
|
+
yarn test # Playwright: Chromium, WebKit, Firefox, and iPhone / Pixel emulation
|
|
382
|
+
```
|
|
383
|
+
|
|
384
|
+
The first test run needs the browsers: `yarn playwright install`.
|
|
385
|
+
|
|
386
|
+
## License
|
|
387
|
+
|
|
388
|
+
MIT
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const E=require("react"),pe=require("react/jsx-runtime"),qe={tag:"p",type:"paragraph",aliases:["div"]},P=e=>{const t=new Map,n=new Map,s=new Map,o=(r,l)=>{for(const i of[l.tag,...l.aliases??[]])r.set(i,l)};o(n,qe);for(const r of e){r.marks?.forEach(l=>o(t,l)),r.blocks?.forEach(l=>o(n,l));for(const[l,i]of Object.entries(r.blockStyles??{}))s.set(l,new Set(i))}return{marks:t,blocks:n,blockStyles:s,blockSelector:Array.from(n.keys()).join(",")}},j=(e,t)=>e instanceof HTMLElement&&t.blocks.has(e.localName),Ue=300,Fe=e=>{let t=[],n=[],s={blocks:[],before:null,after:null},o=null,r=null;const l=()=>{r!==null&&(clearTimeout(r),r=null),o&&(t.push(s),t.length>e&&t.shift(),s=o,o=null,n=[])};return{reset(i){t=[],n=[],o=null,s={blocks:i,before:null,after:null}},record(i,u){if(!u){l(),o=i,l();return}o=o?{...i,before:o.before}:i,r!==null&&clearTimeout(r),r=setTimeout(l,Ue)},undo(){l();const i=t.pop();if(!i)return null;const u=s;return n.push(u),s=i,{blocks:i.blocks,selection:u.before}},redo(){l();const i=n.pop();return i?(t.push(s),s=i,{blocks:i.blocks,selection:i.after}):null},canUndo:()=>t.length>0||o!==null,canRedo:()=>n.length>0&&o===null,cancelTimer(){r!==null&&(clearTimeout(r),r=null)}}},I=(e,t)=>{const n=e.ownerDocument.createElement(t);for(const s of Array.from(e.attributes))n.setAttribute(s.name,s.value);return n.append(...e.childNodes),e.replaceWith(n),n},w=e=>{e.replaceWith(...e.childNodes)},M=e=>e instanceof HTMLElement&&(e.localName==="ul"||e.localName==="ol"),ze=(e,t)=>e.attributes.length===t.attributes.length&&Array.from(e.attributes).every(n=>t.getAttribute(n.name)===n.value),Y=e=>{const t=window.getSelection(),n=t?.anchorNode??null,s=t?.focusNode??null,o=t?.anchorOffset??0,r=t?.focusOffset??0;e(),!(!t||!n||!s)&&(n.nodeType!==Node.TEXT_NODE||s.nodeType!==Node.TEXT_NODE||!n.isConnected||!s.isConnected||t.anchorNode===n&&t.anchorOffset===o&&t.focusNode===s&&t.focusOffset===r||t.setBaseAndExtent(n,Math.min(o,n.length),s,Math.min(r,s.length)))},ge=(e,t)=>{const n=Array.from(e.childNodes),s=n.some(i=>j(i,t)),o=[];let r=[];const l=()=>{if(r.length===0)return;if(r.some(u=>u.nodeType===Node.ELEMENT_NODE||u.textContent?.trim())||!s){const u=(e.ownerDocument??document).createElement("p");e.insertBefore(u,r[0]),u.append(...r),o.push(u)}else r.forEach(u=>e.removeChild(u));r=[]};for(const i of n)j(i,t)?l():i.nodeType===Node.ELEMENT_NODE||i.nodeType===Node.TEXT_NODE?r.push(i):e.removeChild(i);return l(),o},ye=e=>{let t=e.nextSibling;for(;t instanceof Element&&t.localName===e.localName;)e.append(...t.childNodes),t.remove(),t=e.nextSibling},Ke=e=>{for(const t of Array.from(e.childNodes)){if(t instanceof Element&&t.localName==="li")continue;if(t.nodeType===Node.TEXT_NODE&&!t.textContent?.trim()){t.remove();continue}const n=e.ownerDocument.createElement("li");t.replaceWith(n),n.append(t)}if(e.children.length===0){e.remove();return}ye(e)},We=(e,t,n)=>{let s=t;for(const o of[t,...t.querySelectorAll("*")]){if(!e.contains(o))continue;const r=o.localName;if(r==="br")continue;const l=n.marks.get(r)??n.blocks.get(r);if(!l){w(o);continue}const i=l.tag===r?o:I(o,l.tag);if(o===s&&(s=i),n.marks.has(r)){const u=i.parentElement?.closest(l.tag);i.childNodes.length===0?i.remove():u&&u!==e&&e.contains(u)&&w(i)}}s.normalize();for(const o of Array.from(s.querySelectorAll("*"))){if(!n.marks.has(o.localName)||!e.contains(o))continue;let r=o.nextSibling;for(;r instanceof Element&&r.localName===o.localName&&ze(o,r);)o.append(...r.childNodes),r.remove(),r=o.nextSibling}s.normalize();for(const o of[s,...s.querySelectorAll("ul, ol")])M(o)&&e.contains(o)&&Ke(o)},ie=(e,t,n)=>{Y(()=>{const s=new Set(ge(e,t));for(const o of n)o instanceof Element&&o.parentNode===e&&s.add(o);for(const o of s)o.parentNode===e&&We(e,o,t);for(const o of Array.from(e.children))M(o)&&o.parentNode===e&&ye(o)})},Xe=new Set(["script","style","title","iframe","noscript","noembed","noframes","plaintext","xmp","svg","math","audio","video"]),ae=["address","article","aside","blockquote","dd","details","div","dl","dt","fieldset","figcaption","figure","footer","h1","h2","h3","h4","h5","h6","header","hr","li","main","nav","ol","p","pre","section","summary","table","tbody","td","tfoot","th","thead","tr","ul"].join(","),Ne=e=>{const t=document.createRange();return t.selectNodeContents(e),Array.from(t.cloneContents().childNodes)},ke=(e,t)=>{const n=[];for(const s of(e??"").split(";")){const o=s.indexOf(":");if(o===-1)continue;const r=s.slice(0,o).trim().toLowerCase(),l=s.slice(o+1).trim().toLowerCase();t.blockStyles.get(r)?.has(l)&&n.push(`${r}: ${l}`)}return n.join("; ")};let J=null;const _=(e,t,n)=>{for(const s of e){const o=$e(s,n);o&&t.appendChild(o)}},$e=(e,t)=>{const n=J,s=m=>{const g=n.createDocumentFragment();return _(m,g,t),g};if(e instanceof HTMLFormElement)return s(Ne(e));if(e.nodeType===Node.TEXT_NODE)return n.createTextNode(e.textContent??"");if(!(e instanceof Element))return null;const o=e.localName;if(Xe.has(o))return null;if(o==="br")return n.createElement("br");const r=t.marks.get(o);if(r){const m=n.createElement(r.tag);for(const[g,S]of Object.entries(r.attrs??{})){const h=S(e.getAttribute(g),e);h!==null&&m.setAttribute(g,h)}return _(e.childNodes,m,t),m}const l=e.matches(ae),i=e.querySelector(ae)!==null,u=t.blocks.get(o);if((u?.tag==="p"||!u&&l)&&i)return s(e.childNodes);if(u||l){const m=n.createElement(u?.tag??"p"),g=ke(e.getAttribute("style"),t);return g&&m.setAttribute("style",g),_(e.childNodes,m,t),u||m.childNodes.length>0?m:null}return s(e.childNodes)},Q=(e,t)=>{J??=document.implementation.createHTMLDocument("");const n=J.createElement("div");return _(e,n,t),n.innerHTML},H=(e,t)=>{if(!e)return"";const n=new DOMParser().parseFromString(e,"text/html");return Q(n.body.childNodes,t)},Je=e=>e.replace(/-([a-z])/g,(t,n)=>n.toUpperCase()),be=(e,t,n,s=!1)=>{const o=h=>{const y={type:"text",text:h};return t.length>0&&(y.marks=[...t]),[y]},r=(h,y)=>Array.from(h).flatMap(p=>be(p,y,n));if(e instanceof HTMLFormElement)return r(Ne(e),t);if(e.nodeType===Node.TEXT_NODE){const h=e.textContent??"";return(s?h.trim():h)?o(h):[]}if(!(e instanceof Element))return[];const l=e.localName;if(l==="br")return s?[]:o(`
|
|
2
|
+
`);const i=n.marks.get(l);if(i){const h={type:i.type},y={};for(const[p,v]of Object.entries(i.attrs??{})){const A=v(e.getAttribute(p),e);A!==null&&(y[p]=A)}return Object.keys(y).length>0&&(h.attrs=y),r(e.childNodes,[...t,h])}const u=n.blocks.get(l);if(!u)return r(e.childNodes,t);const m={type:u.type},g={...u.attrs};for(const h of ke(e.getAttribute("style"),n).split("; ")){const[y,p]=h.split(": ");p&&(g[Je(y)]=p)}Object.keys(g).length>0&&(m.attrs=g);const S=r(e.childNodes,t);return S.length>0&&(m.content=S),[m]},Ee=(e,t)=>be(e,[],t,!0),Ve=(e,t)=>Q(e.childNodes,P(t)),Ge=(e,t)=>{const n=P(t);return{type:"doc",content:Array.from(e.childNodes).flatMap(s=>Ee(s,n))}},k=e=>{const t=window.getSelection();if(!t||t.rangeCount===0)return null;const n=t.getRangeAt(0);return e.contains(n.commonAncestorContainer)?n:null},Se=e=>{const t=window.getSelection();t&&(t.removeAllRanges(),t.addRange(e))},ve=(e,t)=>{const n=document.createRange();n.setStart(e,0),n.setEnd(t,t.length),Se(n)},Z=e=>{let t=e;for(;t.lastChild;)t=t.lastChild;const n=document.createRange();t.nodeType===Node.TEXT_NODE?n.setStart(t,t.length):t===e?n.setStart(e,0):n.setStartAfter(t),n.collapse(!0),Se(n)},Ye=e=>{let t=e;for(;t.lastChild;)t=t.lastChild;const n=window.getSelection();t.nodeType===Node.TEXT_NODE?n?.collapse(t,t.length):t===e?n?.collapse(e,0):n?.collapse(t.parentNode,Array.prototype.indexOf.call(t.parentNode.childNodes,t))},ue=(e,t,n)=>{if(t===e)return n<e.childNodes.length?[n,0]:[Math.max(n-1,0),1/0];let s=t;for(;s.parentNode!==e;)s=s.parentNode;const o=document.createRange();return o.setStart(s,0),o.setEnd(t,n),[Array.prototype.indexOf.call(e.childNodes,s),o.toString().length]},de=(e,[t,n])=>{const s=e.childNodes[Math.min(t,e.childNodes.length-1)];if(!s)return[e,0];const o=document.createTreeWalker(s,NodeFilter.SHOW_TEXT);let r=n,l=null;for(let i=o.nextNode();i;i=o.nextNode()){if(r<=i.length)return[i,r];r-=i.length,l=i}return l?[l,l.length]:[s,0]},W=e=>{const t=window.getSelection();return!t?.anchorNode||!t.focusNode||!e.contains(t.anchorNode)||!e.contains(t.focusNode)?null:{anchor:ue(e,t.anchorNode,t.anchorOffset),focus:ue(e,t.focusNode,t.focusOffset)}},Qe=(e,t)=>{const n=window.getSelection();if(!(!n||!e.isConnected)){if(!t){Z(e);return}n.setBaseAndExtent(...de(e,t.anchor),...de(e,t.focus))}},x=(e,t,n)=>{for(let s=e;s&&s!==n;s=s.parentNode)if(s instanceof HTMLElement&&(s.localName===t.tag||t.aliases?.includes(s.localName)))return s;return null},ee=(e,t)=>{const n=t.commonAncestorContainer,s=n.nodeType===Node.TEXT_NODE?n.parentNode:n,o=document.createTreeWalker(s,NodeFilter.SHOW_TEXT),r=[];for(let l=o.nextNode();l;l=o.nextNode()){if(!t.intersectsNode(l)||l.parentNode===e||M(l.parentNode))continue;const i=l===t.startContainer?t.startOffset:0,u=l===t.endContainer?t.endOffset:l.length;i<u&&r.push({node:l,start:i,end:u})}return r},Ae=e=>e.map(({node:t,start:n,end:s})=>(s<t.length&&t.splitText(s),n>0?t.splitText(n):t)),fe=(e,t)=>{for(const[n,s]of Object.entries(t??{}))e.setAttribute(n,s)},Te=(e,t,n)=>{if(t.collapsed)return x(t.startContainer,n,e)!==null;const s=ee(e,t);return s.length>0&&s.every(o=>x(o.node,n,e))},xe=(e,t,n,s,o)=>{if(t.collapsed){if(!o)return;t.insertNode(document.createTextNode(o))}const r=Ae(ee(e,t));if(r.length!==0){for(const l of r){const i=x(l,n,e);if(i){fe(i,s);continue}const u=document.createElement(n.tag);fe(u,s),l.replaceWith(u),u.append(l)}ve(r[0],r[r.length-1])}},Ze=(e,t)=>{const n=document.createRange();n.setStart(e,0),n.setEndBefore(t);const s=document.createRange();s.setStartAfter(t),s.setEnd(e,e.childNodes.length);for(const[o,r]of[[n,"before"],[s,"after"]]){const l=o.extractContents();if(!l.textContent&&!l.querySelector("br"))continue;const i=e.cloneNode(!1);i.append(l),e[r](i)}w(e)},Ce=(e,t,n)=>{if(t.collapsed){const o=x(t.startContainer,n,e);o&&Y(()=>w(o));return}const s=Ae(ee(e,t));if(s.length!==0){for(const o of s)for(let r=x(o,n,e);r;r=x(o,n,e))Ze(r,o);ve(s[0],s[s.length-1])}},et=(e,t,n)=>{t.collapsed||(Te(e,t,n)?Ce(e,t,n):xe(e,t,n))},Le=(e,t)=>j(e,t)&&!M(e),he=(e,t,n)=>{for(let s=e;s&&s!==t;s=s.parentNode)if(Le(s,n))return s;return null},tt=(e,t)=>{const n=document.createRange();return n.selectNodeContents(t),e.compareBoundaryPoints(Range.START_TO_START,n)>0&&n.setStart(e.startContainer,e.startOffset),e.compareBoundaryPoints(Range.END_TO_END,n)<0&&n.setEnd(e.endContainer,e.endOffset),n.toString()!==""},C=(e,t,n)=>{const s=(i,u)=>i.childNodes[u]??i.lastChild??i,o=he(s(t.startContainer,t.startOffset),e,n),r=he(s(t.endContainer,t.endOffset),e,n);if(!o)return[];if(!r||o===r)return[o];const l=Array.from(e.querySelectorAll(n.blockSelector)).filter(i=>Le(i,n)&&!i.querySelector(n.blockSelector)&&t.intersectsNode(i));return l.length>1&&!tt(t,l[l.length-1])&&l.pop(),l},te=e=>{if(!k(e))return null;if(e.childNodes.length===0){const t=document.createElement("p");t.append(document.createElement("br")),e.append(t),window.getSelection()?.collapse(t,0)}return k(e)},we=(e,t)=>{let n=null;Y(()=>{n=t()});const s=k(e);n&&(!s||s.startContainer===e)&&Ye(n)},V=(e,t)=>{const n=e.parentElement;if(!M(n))return I(e,t);const s=n.cloneNode(!1);for(;e.nextSibling;)s.append(e.nextSibling);return n.after(e),s.childNodes.length>0&&e.after(s),n.childNodes.length===0&&n.remove(),I(e,t)},nt=(e,t,n)=>{const s=t.blocks.get(n);if(!s||s.tag!==n||n==="li"||n==="ul"||n==="ol")return;const o=te(e);if(!o)return;const r=C(e,o,t);we(e,()=>{let l=null;for(const i of r)i.localName===n?l=i:l=i.localName==="li"?V(i,n):I(i,n);return l})},ot=(e,t,n)=>{const s=k(e);if(!s)return!1;const o=C(e,s,t);return o.length>0&&o.every(r=>r.localName===n)},st=(e,t,n,s)=>{if(!t.blockStyles.get(n)?.has(s))return;const o=te(e);if(o)for(const r of C(e,o,t))r.style.setProperty(n,s)},rt=(e,t,n)=>{const s=k(e);if(!s)return null;const[o]=C(e,s,t);return o?.style.getPropertyValue(n)||null},G=(e,t)=>e.localName==="li"&&e.parentElement?.localName===t,ct=(e,t,n)=>{const s=k(e);if(!s)return!1;const o=C(e,s,t);return o.length>0&&o.every(r=>G(r,n))},lt=(e,t)=>{const n=document.createElement(t),s=document.createElement("li"),o=e.getAttribute("style");return o&&s.setAttribute("style",o),s.append(...e.childNodes),n.append(s),e.replaceWith(n),s},it=(e,t,n)=>{if(!t.blocks.has(n))return;const s=te(e);if(!s)return;const o=C(e,s,t),r=o.every(l=>G(l,n));we(e,()=>{let l=null;for(const i of o)r?l=V(i,"p"):G(i,n)?l=i:l=lt(i.localName==="li"?V(i,"p"):i,n);return l})},ne=(e,t)=>{e.deleteContents();const n=t.lastChild;if(e.insertNode(t),!n)return;const s=n.nextSibling;s?.nodeName==="BR"&&!s.nextSibling&&s.remove(),Z(n)},at=(e,t,n,s)=>{t.deleteContents();let o=t.startContainer;for(;o&&o!==e&&o.parentNode!==e;)o=o.parentNode;if(!o||o===e||!j(o,s)){ne(t,n);return}ge(n,s);const r=n.lastChild;if(!r)return;const l=document.createRange();l.selectNodeContents(o),l.setStart(t.startContainer,t.startOffset);const i=o.cloneNode(!1);i.append(l.extractContents()),o.after(n,i);for(const u of[o,i])u.textContent?.trim()||u.remove();Z(r)},ut=(e,t,n,s)=>{const o=document.createElement("template");o.innerHTML=n;const r=o.content,l=r.childNodes.length===1?r.firstChild:null;l instanceof HTMLElement&&l.localName==="p"&&!l.querySelector(s.blockSelector)&&w(l),r.querySelector(s.blockSelector)?at(e,t,r,s):ne(t,r)},dt=(e,t,n)=>{const s=document.createDocumentFragment(),o=t.startContainer,r=(o instanceof Element?o:o.parentElement)?.closest("pre");r&&e.contains(r)?s.append(n):n.split(/\r\n?|\n/).forEach((l,i)=>{i>0&&s.append(document.createElement("br")),l&&s.append(l)}),ne(t,s)},ft=typeof navigator<"u"&&/Mac|iPhone|iPad|iPod/.test(navigator.userAgent),ht=new Set(["Control","Shift","Alt","Meta"]),mt=e=>{const t=[];return(ft?e.metaKey:e.ctrlKey)&&t.push("Mod"),e.shiftKey&&t.push("Shift"),e.altKey&&t.push("Alt"),ht.has(e.key)||t.push(e.key.length===1?e.key.toUpperCase():e.key),t.join("+")},pt=(e,t)=>{for(const n of e){const s=n.keyboardShortcuts?.[t];if(s)return s}return null},gt=(e,t)=>e.length===t.length&&e.every((n,s)=>n===t[s]),yt=e=>{let t=e,n=P(t.extensions);const s=Fe(t.historyLimit??100);let o=null,r=null,l=!1,i=0,u=0,m=null;const g=new Set;let S=new WeakMap;const h=new Set;let y=!1,p=[],v=null;const A=()=>{u++,g.forEach(c=>c())},U=()=>{m===null&&(m=requestAnimationFrame(()=>{m=null,t.onChange?.(N.getHTML()),t.onChangeJSON?.(N.getJSON())}))},F=c=>{let a=S.get(c);return a||(a={},S.set(c,a)),a},O=c=>{if(o)for(const a of c){if(y=!0,a.target===o){a.addedNodes.forEach(f=>h.add(f));continue}let d=a.target;for(;d&&d.parentNode!==o;)d=d.parentNode;d&&(h.add(d),S.delete(d))}},z=c=>Array.from(c.children,a=>F(a).raw??=a.outerHTML),b=(c=!1)=>{if(!o||!r||(O(r.takeRecords()),!y||l))return;ie(o,n,h),O(r.takeRecords()),h.clear(),y=!1;const a=z(o);gt(a,p)||(s.record({blocks:a,before:v,after:W(o)},c),p=a,U()),v=W(o)??v,A()},se=c=>{if(!c||!o||!r)return;const{blocks:a}=c;let d=0;for(;d<p.length&&d<a.length&&p[d]===a[d];)d++;let f=p.length,T=a.length;for(;f>d&&T>d&&p[f-1]===a[T-1];)f--,T--;const R=Array.from(o.children),le=document.createElement("template");le.innerHTML=H(a.slice(d,T).join(""),n),R.slice(d,f).forEach(Ie=>Ie.remove()),o.insertBefore(le.content,R[f]??null),O(r.takeRecords()),h.clear(),y=!1,p=z(o),Qe(o,c.selection),v=c.selection,A(),U()},re=(()=>{let c=!1;return()=>{const a=!!o&&k(o)!==null;o&&a&&(v=W(o)),(a||c)&&A(),c=a}})(),De=c=>{if(c.isComposing)return;const a=c.metaKey||c.ctrlKey,d=c.key.toLowerCase();if(a&&(d==="z"||d==="y")){c.preventDefault(),d==="z"&&!c.shiftKey?N.history.undo():N.history.redo();return}const f=pt(t.extensions,mt(c));f&&(c.preventDefault(),N.execute(f))},_e=c=>{c.preventDefault();const a=c.clipboardData?.getData("text/html"),d=c.clipboardData?.getData("text/plain");N.change(()=>{const f=o&&k(o);!o||!f||(a?ut(o,f,H(a,n),n):d&&dt(o,f,d))})},ce=(c,a)=>{c.innerHTML=H(a,n),ie(c,n,Array.from(c.childNodes)),p=z(c),s.reset(p),v=null},Pe=()=>{const c=document.createElement("div");return c.contentEditable="true",c.setAttribute("role","textbox"),c.setAttribute("aria-multiline","true"),c.tabIndex=0,ce(c,t.initialValue??""),c.addEventListener("keydown",De),c.addEventListener("paste",_e),c.addEventListener("drop",a=>a.preventDefault()),c.addEventListener("compositionstart",()=>{l=!0}),c.addEventListener("compositionend",()=>{l=!1,b(!0)}),r=new MutationObserver(a=>{O(a),b(!0)}),r.observe(c,{childList:!0,subtree:!0,characterData:!0,attributes:!0}),c},B=c=>{const a=n.marks.get(c);return a&&a.tag===c?a:null},K=c=>{N.change(()=>{const a=o&&k(o);o&&a&&c(o,a)})},je=(c,a)=>{const d=o&&k(o);return o&&d?a(o,d):c},N={get el(){return o},get extensions(){return t.extensions},get revision(){return u},history:{undo:()=>{b(),se(s.undo())},redo:()=>{b(),se(s.redo())},canUndo:()=>s.canUndo(),canRedo:()=>s.canRedo()},mount(c){o??=Pe(),c.append(o),document.addEventListener("selectionchange",re)},unmount(){o?.remove(),document.removeEventListener("selectionchange",re)},destroy(){s.cancelTimer(),m!==null&&(cancelAnimationFrame(m),m=null)},setOptions(c){const a=c.extensions!==void 0&&(c.extensions.length!==t.extensions.length||c.extensions.some((d,f)=>d!==t.extensions[f]));t={...t,...c},a&&(n=P(t.extensions),S=new WeakMap)},subscribe(c){return g.add(c),()=>{g.delete(c)}},execute(c,a){for(const d of t.extensions){const f=d.commands?.[c];if(f){N.change(()=>f(N,a));return}}throw new Error(`Command not found: ${c}`)},isActive(c,a){return!o||!k(o)?!1:(t.extensions.find(f=>f.commands?.[c]&&f.isActive)??t.extensions.find(f=>f.name===c&&f.isActive))?.isActive?.(N,c,a)??!1},getHTML(){return o?(b(),t.sanitize===!1?o.innerHTML:Array.from(o.children,c=>F(c).html??=Q([c],n)).join("")):""},getJSON(){return o?(b(),{type:"doc",content:Array.from(o.children).flatMap(c=>F(c).json??=Ee(c,n))}):{type:"doc",content:[]}},setHTML(c,{history:a=!0}={}){if(!o||!r){t={...t,initialValue:c};return}if(b(),a){o.innerHTML=H(c,n),b();return}ce(o,c),r.takeRecords(),h.clear(),y=!1,A(),U()},change(c){if(!(!o||l)){if(i>0){c();return}b(),i++;try{c()}finally{i--}b()}},toggleMark(c){const a=B(c);a&&K((d,f)=>et(d,f,a))},setMark(c,a,d){const f=B(c);f&&K((T,R)=>xe(T,R,f,a,d))},removeMark(c){const a=B(c);a&&K((d,f)=>Ce(d,f,a))},isMarkActive(c){const a=B(c);return a?je(!1,(d,f)=>Te(d,f,a)):!1},setBlock(c){N.change(()=>o&&nt(o,n,c))},toggleBlock(c){N.setBlock(N.isBlockActive(c)?"p":c)},isBlockActive(c){return o?ot(o,n,c):!1},toggleList(c){N.change(()=>o&&it(o,n,c))},isListActive(c){return o?ct(o,n,c):!1},setBlockStyle(c,a){N.change(()=>o&&st(o,n,c,a))},getBlockStyle(c){return o?rt(o,n,c):null}};return N},Nt=e=>{const[t]=E.useState(()=>yt(e)),{extensions:n,onChange:s,onChangeJSON:o}=e;return E.useEffect(()=>{t.setOptions({extensions:n,onChange:s,onChangeJSON:o})}),E.useEffect(()=>()=>t.destroy(),[t]),t},Me=E.createContext(null),Oe=()=>{const e=E.useContext(Me);if(!e)throw new Error("useEditorContext must be used within an EditorProvider");return e},kt=({editor:e,children:t})=>pe.jsx(Me.Provider,{value:e,children:t}),X=(e,t,n)=>{n===void 0?e.removeAttribute(t):e.setAttribute(t,n)},Be=({className:e,ariaLabel:t,ariaDescribedBy:n})=>{const s=Oe(),o=E.useRef(null);return E.useEffect(()=>{if(o.current)return s.mount(o.current),()=>s.unmount()},[s]),E.useEffect(()=>{const r=s.el;r&&(X(r,"class",e),X(r,"aria-label",t),X(r,"aria-describedby",n))},[s,e,t,n]),pe.jsx("div",{ref:o,style:{display:"contents"}})};Be.displayName="EditorContent";const q=(e,t)=>{const n=E.useRef(null),s=()=>{const o=n.current;if(o&&o.revision===e.revision&&o.selector===t)return o.value;const r=t(e);return n.current={revision:e.revision,selector:t,value:r},r};return E.useSyncExternalStore(e.subscribe,s,s)},bt=(e,t,n)=>q(e,s=>s.isActive(t,n)),Et=e=>q(e,t=>t.history.canUndo()),St=e=>q(e,t=>t.history.canRedo()),Re=e=>`toggle${e[0].toUpperCase()}${e.slice(1)}`,L=e=>{const{name:t,tag:n,aliases:s,shortcut:o}=e,r=Re(t);return{name:t,marks:[{tag:n,type:t,aliases:s}],commands:{[r]:l=>l.toggleMark(n)},keyboardShortcuts:o?{[o]:r}:void 0,isActive:l=>l.isMarkActive(n)}},oe=e=>{const{name:t,tag:n,shortcut:s}=e,o=Re(t);return{name:t,blocks:[{tag:n,type:t}],commands:{[o]:r=>r.toggleBlock(n)},keyboardShortcuts:s?{[s]:o}:void 0,isActive:r=>r.isBlockActive(n)}},vt=L({name:"bold",tag:"strong",aliases:["b"],shortcut:"Mod+B"}),At=L({name:"italic",tag:"em",aliases:["i"],shortcut:"Mod+I"}),Tt=L({name:"underline",tag:"u",shortcut:"Mod+U"}),xt=L({name:"strikethrough",tag:"s",aliases:["del"],shortcut:"Mod+Shift+S"}),Ct=L({name:"code",tag:"code"}),Lt=oe({name:"blockquote",tag:"blockquote"}),wt=oe({name:"codeBlock",tag:"pre"}),D=[1,2,3,4,5,6],Mt={name:"heading",blocks:D.map(e=>({tag:`h${e}`,type:"heading",attrs:{level:e}})),commands:{setHeading:(e,t)=>{D.includes(t)&&e.setBlock(`h${t}`)},removeHeading:e=>e.setBlock("p")},isActive:(e,t,n)=>{if(t==="setHeading")return D.includes(n)&&e.isBlockActive(`h${n}`);const s=D.some(o=>e.isBlockActive(`h${o}`));return t==="removeHeading"?!s:s}},He=(e,t)=>{const n=`toggle${e[0].toUpperCase()}${e.slice(1)}`;return{name:e,blocks:[{tag:t,type:e},{tag:"li",type:"listItem"}],commands:{[n]:s=>s.toggleList(t)},isActive:s=>s.isListActive(t)}},Ot=He("orderedList","ol"),Bt=He("unorderedList","ul"),$={alignLeft:"left",alignCenter:"center",alignRight:"right",alignJustify:"justify"},Rt={name:"textAlign",blockStyles:{"text-align":Object.values($)},commands:Object.fromEntries(Object.entries($).map(([e,t])=>[e,n=>n.setBlockStyle("text-align",t)])),isActive:(e,t)=>t!==void 0&&(e.getBlockStyle("text-align")??"left")===$[t]},me=e=>/^(https?:\/\/|mailto:)/i.test(e),Ht={name:"link",marks:[{tag:"a",type:"link",attrs:{href:e=>e&&me(e)?e:null,target:e=>e==="_blank"?e:null,rel:(e,t)=>t.getAttribute("target")==="_blank"?"noopener noreferrer":null}}],commands:{setLink:(e,t)=>{const n=t?.href;n&&me(n)&&e.setMark("a",{href:n},n)},removeLink:e=>e.removeMark("a")},isActive:e=>e.isMarkActive("a")};exports.Blockquote=Lt;exports.Bold=vt;exports.Code=Ct;exports.CodeBlock=wt;exports.EditorContent=Be;exports.EditorProvider=kt;exports.Heading=Mt;exports.Italic=At;exports.Link=Ht;exports.OrderedList=Ot;exports.Strikethrough=xt;exports.TextAlign=Rt;exports.Underline=Tt;exports.UnorderedList=Bt;exports.block=oe;exports.mark=L;exports.toHTML=Ve;exports.toJSON=Ge;exports.useCanRedo=St;exports.useCanUndo=Et;exports.useEditor=Nt;exports.useEditorContext=Oe;exports.useEditorState=q;exports.useIsActive=bt;
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { JSX } from 'react/jsx-runtime';
|
|
2
|
+
import { ReactNode } from 'react';
|
|
3
|
+
|
|
4
|
+
export declare type AttributeRule = (value: string | null, el: Element) => string | null;
|
|
5
|
+
|
|
6
|
+
/** A block type toggled against the paragraph, e.g. `block({ name: 'blockquote', tag: 'blockquote' })` */
|
|
7
|
+
export declare const block: (options: {
|
|
8
|
+
name: string;
|
|
9
|
+
tag: string;
|
|
10
|
+
shortcut?: string;
|
|
11
|
+
}) => Extension;
|
|
12
|
+
|
|
13
|
+
export declare const Blockquote: Extension;
|
|
14
|
+
|
|
15
|
+
export declare type BlockSpec = {
|
|
16
|
+
tag: string;
|
|
17
|
+
/** Node type in JSON */
|
|
18
|
+
type: string;
|
|
19
|
+
aliases?: string[];
|
|
20
|
+
/** Fixed attributes added to the JSON node */
|
|
21
|
+
attrs?: Record<string, unknown>;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export declare const Bold: Extension;
|
|
25
|
+
|
|
26
|
+
export declare const Code: Extension;
|
|
27
|
+
|
|
28
|
+
export declare const CodeBlock: Extension;
|
|
29
|
+
|
|
30
|
+
export declare type CommandFn = (editor: EditorInstance, value?: unknown) => void;
|
|
31
|
+
|
|
32
|
+
export declare type DocumentJSON = {
|
|
33
|
+
type: 'doc';
|
|
34
|
+
content: NodeJSON[];
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
/** A place for the editor's own element. The element and its content outlive this component. */
|
|
38
|
+
export declare const EditorContent: {
|
|
39
|
+
({ className, ariaLabel, ariaDescribedBy }: EditorContentProps): JSX.Element;
|
|
40
|
+
displayName: string;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
export declare type EditorContentProps = {
|
|
44
|
+
className?: string;
|
|
45
|
+
ariaLabel?: string;
|
|
46
|
+
ariaDescribedBy?: string;
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
export declare type EditorHistory = {
|
|
50
|
+
undo: () => void;
|
|
51
|
+
redo: () => void;
|
|
52
|
+
canUndo: () => boolean;
|
|
53
|
+
canRedo: () => boolean;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
export declare type EditorInstance = {
|
|
57
|
+
/** The editable element. Null until the editor is first mounted. */
|
|
58
|
+
readonly el: HTMLElement | null;
|
|
59
|
+
readonly extensions: Extension[];
|
|
60
|
+
/** Increases whenever content, selection, or history changes */
|
|
61
|
+
readonly revision: number;
|
|
62
|
+
readonly history: EditorHistory;
|
|
63
|
+
mount: (host: HTMLElement) => void;
|
|
64
|
+
unmount: () => void;
|
|
65
|
+
destroy: () => void;
|
|
66
|
+
setOptions: (options: Partial<EditorOptions>) => void;
|
|
67
|
+
subscribe: (listener: () => void) => () => void;
|
|
68
|
+
execute: (command: string, value?: unknown) => void;
|
|
69
|
+
isActive: (commandOrName: string, value?: unknown) => boolean;
|
|
70
|
+
getHTML: () => string;
|
|
71
|
+
getJSON: () => DocumentJSON;
|
|
72
|
+
/** Replaces the whole document. `history: false` clears the undo history instead of adding a step. */
|
|
73
|
+
setHTML: (html: string, options?: {
|
|
74
|
+
history?: boolean;
|
|
75
|
+
}) => void;
|
|
76
|
+
/** Runs a DOM edit, then normalizes the document, records history and reports the change */
|
|
77
|
+
change: (edit: () => void) => void;
|
|
78
|
+
toggleMark: (tag: string) => void;
|
|
79
|
+
/** With only a caret, `text` is inserted and becomes the marked content */
|
|
80
|
+
setMark: (tag: string, attrs?: Record<string, string>, text?: string) => void;
|
|
81
|
+
removeMark: (tag: string) => void;
|
|
82
|
+
isMarkActive: (tag: string) => boolean;
|
|
83
|
+
setBlock: (tag: string) => void;
|
|
84
|
+
toggleBlock: (tag: string) => void;
|
|
85
|
+
isBlockActive: (tag: string) => boolean;
|
|
86
|
+
toggleList: (tag: 'ol' | 'ul') => void;
|
|
87
|
+
isListActive: (tag: 'ol' | 'ul') => boolean;
|
|
88
|
+
setBlockStyle: (property: string, value: string) => void;
|
|
89
|
+
getBlockStyle: (property: string) => string | null;
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
export declare type EditorOptions = {
|
|
93
|
+
extensions: Extension[];
|
|
94
|
+
initialValue?: string;
|
|
95
|
+
onChange?: (html: string) => void;
|
|
96
|
+
onChangeJSON?: (json: DocumentJSON) => void;
|
|
97
|
+
sanitize?: boolean;
|
|
98
|
+
historyLimit?: number;
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
export declare const EditorProvider: ({ editor, children }: EditorProviderProps) => JSX.Element;
|
|
102
|
+
|
|
103
|
+
declare type EditorProviderProps = {
|
|
104
|
+
editor: EditorInstance;
|
|
105
|
+
children: ReactNode;
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
export declare type Extension = {
|
|
109
|
+
name: string;
|
|
110
|
+
marks?: MarkSpec[];
|
|
111
|
+
blocks?: BlockSpec[];
|
|
112
|
+
/** CSS properties allowed on blocks, with the values each may take */
|
|
113
|
+
blockStyles?: Record<string, readonly string[]>;
|
|
114
|
+
commands?: Record<string, CommandFn>;
|
|
115
|
+
keyboardShortcuts?: Record<string, string>;
|
|
116
|
+
isActive?: (editor: EditorInstance, command?: string, value?: unknown) => boolean;
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
export declare const Heading: Extension;
|
|
120
|
+
|
|
121
|
+
export declare const Italic: Extension;
|
|
122
|
+
|
|
123
|
+
export declare const Link: Extension;
|
|
124
|
+
|
|
125
|
+
/** An inline format toggled over the selection, e.g. `mark({ name: 'highlight', tag: 'mark' })` gives `toggleHighlight` */
|
|
126
|
+
export declare const mark: (options: {
|
|
127
|
+
name: string;
|
|
128
|
+
tag: string;
|
|
129
|
+
aliases?: string[];
|
|
130
|
+
shortcut?: string;
|
|
131
|
+
}) => Extension;
|
|
132
|
+
|
|
133
|
+
export declare type MarkJSON = {
|
|
134
|
+
type: string;
|
|
135
|
+
attrs?: Record<string, unknown>;
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
export declare type MarkSpec = {
|
|
139
|
+
/** Lowercase tag the mark is written as */
|
|
140
|
+
tag: string;
|
|
141
|
+
/** Mark type in JSON */
|
|
142
|
+
type: string;
|
|
143
|
+
/** Other tags read as this mark and rewritten to `tag` */
|
|
144
|
+
aliases?: string[];
|
|
145
|
+
/** Attributes to keep. A rule returns the value to write, or null to leave the attribute out. */
|
|
146
|
+
attrs?: Record<string, AttributeRule>;
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
export declare type NodeJSON = {
|
|
150
|
+
type: string;
|
|
151
|
+
attrs?: Record<string, unknown>;
|
|
152
|
+
content?: NodeJSON[];
|
|
153
|
+
marks?: MarkJSON[];
|
|
154
|
+
text?: string;
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
export declare const OrderedList: Extension;
|
|
158
|
+
|
|
159
|
+
export declare const Strikethrough: Extension;
|
|
160
|
+
|
|
161
|
+
export declare const TextAlign: Extension;
|
|
162
|
+
|
|
163
|
+
export declare const toHTML: (el: HTMLElement, extensions: Extension[]) => string;
|
|
164
|
+
|
|
165
|
+
export declare const toJSON: (el: HTMLElement, extensions: Extension[]) => DocumentJSON;
|
|
166
|
+
|
|
167
|
+
export declare const Underline: Extension;
|
|
168
|
+
|
|
169
|
+
export declare const UnorderedList: Extension;
|
|
170
|
+
|
|
171
|
+
export declare const useCanRedo: (editor: EditorInstance) => boolean;
|
|
172
|
+
|
|
173
|
+
export declare const useCanUndo: (editor: EditorInstance) => boolean;
|
|
174
|
+
|
|
175
|
+
export declare const useEditor: (options: EditorOptions) => EditorInstance;
|
|
176
|
+
|
|
177
|
+
export declare const useEditorContext: () => EditorInstance;
|
|
178
|
+
|
|
179
|
+
export declare const useEditorState: <T>(editor: EditorInstance, selector: (editor: EditorInstance) => T) => T;
|
|
180
|
+
|
|
181
|
+
export declare const useIsActive: (editor: EditorInstance, commandOrName: string, value?: unknown) => boolean;
|
|
182
|
+
|
|
183
|
+
export { }
|