yurich 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +399 -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 +1167 -0
- package/package.json +80 -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,400 @@
|
|
|
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
|
+
[Overview](https://leeyujoo.com/yurich/overview/) | [Quick start](https://leeyujoo.com/yurich/#quick-start) | [Live demo](https://leeyujoo.com/yurich/#live-demo) | [API reference](https://leeyujoo.com/yurich/api/)
|
|
9
|
+
|
|
10
|
+
## Why yurich?
|
|
11
|
+
|
|
12
|
+
- **Zero runtime dependencies** — React and React DOM are peer dependencies.
|
|
13
|
+
- **Native contentEditable** — Uses the browser's built-in editing with the Selection API directly. Does **not** use `document.execCommand`.
|
|
14
|
+
- **HTML-native model** — The DOM *is* the document. No separate document model to sync.
|
|
15
|
+
- **Schema from extensions** — The extensions you enable define which tags exist. Everything else is removed on paste, on load, and in the output.
|
|
16
|
+
- **Headless** — No default styles or UI. Full control over your toolbar and layout.
|
|
17
|
+
- **Accessible** — ARIA roles and keyboard shortcuts built in.
|
|
18
|
+
- **IME/Composition support** — The document is left alone while a CJK or other IME composition is in progress.
|
|
19
|
+
|
|
20
|
+
## Installation
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
npm install yurich
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
React 18+ is a peer dependency:
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
npm install react react-dom
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Quick Start
|
|
33
|
+
|
|
34
|
+
```tsx
|
|
35
|
+
import {
|
|
36
|
+
useEditor,
|
|
37
|
+
EditorProvider,
|
|
38
|
+
EditorContent,
|
|
39
|
+
Bold,
|
|
40
|
+
Italic,
|
|
41
|
+
Underline,
|
|
42
|
+
useEditorContext,
|
|
43
|
+
useIsActive,
|
|
44
|
+
} from 'yurich';
|
|
45
|
+
|
|
46
|
+
function ToolbarButton({ command, label, children }: {
|
|
47
|
+
command: string;
|
|
48
|
+
label: string;
|
|
49
|
+
children: React.ReactNode;
|
|
50
|
+
}) {
|
|
51
|
+
const editor = useEditorContext();
|
|
52
|
+
const active = useIsActive(editor, command);
|
|
53
|
+
return (
|
|
54
|
+
<button
|
|
55
|
+
type="button"
|
|
56
|
+
aria-pressed={active}
|
|
57
|
+
aria-label={label}
|
|
58
|
+
onMouseDown={e => e.preventDefault()}
|
|
59
|
+
onClick={() => editor.execute(command)}
|
|
60
|
+
>
|
|
61
|
+
{children}
|
|
62
|
+
</button>
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function MyEditor() {
|
|
67
|
+
const editor = useEditor({
|
|
68
|
+
extensions: [Bold, Italic, Underline],
|
|
69
|
+
initialValue: '<p>Hello World!</p>',
|
|
70
|
+
onChange: (html) => console.log(html),
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
return (
|
|
74
|
+
<EditorProvider editor={editor}>
|
|
75
|
+
<div role="toolbar" aria-label="Formatting">
|
|
76
|
+
<ToolbarButton command="toggleBold" label="Bold">B</ToolbarButton>
|
|
77
|
+
<ToolbarButton command="toggleItalic" label="Italic">I</ToolbarButton>
|
|
78
|
+
<ToolbarButton command="toggleUnderline" label="Underline">U</ToolbarButton>
|
|
79
|
+
</div>
|
|
80
|
+
<EditorContent className="my-editor" ariaLabel="Rich text editor" />
|
|
81
|
+
</EditorProvider>
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
`onMouseDown={e => e.preventDefault()}` keeps the selection in the editor when a toolbar button is clicked.
|
|
87
|
+
|
|
88
|
+
## Extensions
|
|
89
|
+
|
|
90
|
+
| Extension | Commands | Keyboard Shortcut |
|
|
91
|
+
|---|---|---|
|
|
92
|
+
| `Bold` | `toggleBold` | `Mod+B` |
|
|
93
|
+
| `Italic` | `toggleItalic` | `Mod+I` |
|
|
94
|
+
| `Underline` | `toggleUnderline` | `Mod+U` |
|
|
95
|
+
| `Strikethrough` | `toggleStrikethrough` | `Mod+Shift+S` |
|
|
96
|
+
| `Code` | `toggleCode` | — |
|
|
97
|
+
| `Link` | `setLink`, `removeLink` | — |
|
|
98
|
+
| `Heading` | `setHeading`, `removeHeading` | — |
|
|
99
|
+
| `OrderedList` | `toggleOrderedList` | — |
|
|
100
|
+
| `UnorderedList` | `toggleUnorderedList` | — |
|
|
101
|
+
| `Blockquote` | `toggleBlockquote` | — |
|
|
102
|
+
| `CodeBlock` | `toggleCodeBlock` | — |
|
|
103
|
+
| `TextAlign` | `alignLeft`, `alignCenter`, `alignRight`, `alignJustify` | — |
|
|
104
|
+
|
|
105
|
+
> `Mod` is `Cmd` on macOS and `Ctrl` on Windows/Linux.
|
|
106
|
+
|
|
107
|
+
An editor keeps only what its extensions declare. With `extensions: [Bold]`, pasted italic text loses the italic and a pasted heading becomes a paragraph.
|
|
108
|
+
|
|
109
|
+
### Command values
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
// Heading level 1-6. Other values are ignored.
|
|
113
|
+
editor.execute('setHeading', 2);
|
|
114
|
+
|
|
115
|
+
// Only http:, https: and mailto: addresses are accepted.
|
|
116
|
+
// With a selection the text becomes the link; with only a caret the address is inserted as the link text.
|
|
117
|
+
editor.execute('setLink', { href: 'https://example.com' });
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
### How commands behave
|
|
121
|
+
|
|
122
|
+
- A mark command (`toggleBold`, …) needs a selection. With only a caret it does nothing.
|
|
123
|
+
- A mark is active only when all of the selected text has it. Toggling a partly bold selection makes all of it bold.
|
|
124
|
+
- Removing a mark from part of a marked run keeps the mark on the rest.
|
|
125
|
+
- Block commands apply to every selected block. A selection that ends at the very start of a block does not include that block.
|
|
126
|
+
- 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.
|
|
127
|
+
- A heading, blockquote or code block applied inside a list takes the item out of the list.
|
|
128
|
+
|
|
129
|
+
## API Reference
|
|
130
|
+
|
|
131
|
+
### `useEditor(options)`
|
|
132
|
+
|
|
133
|
+
Creates an editor instance that lives as long as the component.
|
|
134
|
+
|
|
135
|
+
| Option | Type | Default | Description |
|
|
136
|
+
|---|---|---|---|
|
|
137
|
+
| `extensions` | `Extension[]` | — | Extensions to enable (required) |
|
|
138
|
+
| `initialValue` | `string` | `undefined` | Initial HTML content. Read once; replace the content later with `setHTML`. |
|
|
139
|
+
| `onChange` | `(html: string) => void` | `undefined` | Called when the content changes (HTML) |
|
|
140
|
+
| `onChangeJSON` | `(json: DocumentJSON) => void` | `undefined` | Called when the content changes (JSON) |
|
|
141
|
+
| `sanitize` | `boolean` | `true` | Sanitize the output of `getHTML()` and `onChange`. Read once. |
|
|
142
|
+
| `historyLimit` | `number` | `100` | Max undo steps. Read once. |
|
|
143
|
+
|
|
144
|
+
`onChange` and `onChangeJSON` are called at most once per animation frame. Loading HTML with `setHTML(html, { history: false })` can call them even when the HTML is unchanged.
|
|
145
|
+
|
|
146
|
+
### `EditorInstance`
|
|
147
|
+
|
|
148
|
+
| Member | Signature | Description |
|
|
149
|
+
|---|---|---|
|
|
150
|
+
| `execute` | `(command: string, value?: unknown) => void` | Run a command by name |
|
|
151
|
+
| `isActive` | `(name: string, value?: unknown) => boolean` | Whether a command or extension is active at the selection, e.g. `isActive('setHeading', 2)` |
|
|
152
|
+
| `getHTML` | `() => string` | The content as sanitized HTML |
|
|
153
|
+
| `getJSON` | `() => DocumentJSON` | The content as JSON |
|
|
154
|
+
| `setHTML` | `(html: string, options?: { history?: boolean }) => void` | Replace the whole content. See below. |
|
|
155
|
+
| `history.undo` / `history.redo` | `() => void` | Undo / redo |
|
|
156
|
+
| `history.canUndo` / `history.canRedo` | `() => boolean` | Whether undo / redo is available |
|
|
157
|
+
| `subscribe` | `(listener: () => void) => () => void` | Call `listener` whenever content, selection, or history changes. Returns an unsubscribe function. |
|
|
158
|
+
| `el` | `HTMLElement \| null` | The editable element. `null` until `EditorContent` first mounts. |
|
|
159
|
+
|
|
160
|
+
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.
|
|
161
|
+
|
|
162
|
+
The methods for writing extensions are listed under [Custom Extensions](#custom-extensions).
|
|
163
|
+
|
|
164
|
+
### Replacing the content
|
|
165
|
+
|
|
166
|
+
`setHTML` replaces the whole document, for content that arrives after the editor is created or for switching to another document.
|
|
167
|
+
|
|
168
|
+
```ts
|
|
169
|
+
editor.setHTML(post.html); // one undo step: undo brings back the previous content
|
|
170
|
+
editor.setHTML(post.html, { history: false }); // clears the undo history: loading a document, switching documents
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
The HTML goes through the sanitizer and the document rules, and `onChange` is called. Before `EditorContent` first mounts, `setHTML` sets the initial content.
|
|
174
|
+
|
|
175
|
+
### `useIsActive`, `useCanUndo`, `useCanRedo`
|
|
176
|
+
|
|
177
|
+
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.
|
|
178
|
+
|
|
179
|
+
```tsx
|
|
180
|
+
const isBold = useIsActive(editor, 'toggleBold');
|
|
181
|
+
const isH2 = useIsActive(editor, 'setHeading', 2);
|
|
182
|
+
const canUndo = useCanUndo(editor);
|
|
183
|
+
const canRedo = useCanRedo(editor);
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
`editor` comes from `useEditor` or `useEditorContext`, so the hooks work inside and outside an `EditorProvider`.
|
|
187
|
+
|
|
188
|
+
### `useEditorState(editor, selector)`
|
|
189
|
+
|
|
190
|
+
The hook the three above are built on, for state they do not cover.
|
|
191
|
+
|
|
192
|
+
```tsx
|
|
193
|
+
const isEmpty = useEditorState(editor, e => (e.el?.textContent ?? '') === '');
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
Return a primitive from the selector. An object is a new value on every change and re-renders every time.
|
|
197
|
+
|
|
198
|
+
### `EditorProvider` and `useEditorContext`
|
|
199
|
+
|
|
200
|
+
`EditorProvider` gives the editor to the components below it. `useEditorContext` reads it.
|
|
201
|
+
|
|
202
|
+
```tsx
|
|
203
|
+
<EditorProvider editor={editor}>
|
|
204
|
+
{/* Toolbar, EditorContent, etc. */}
|
|
205
|
+
</EditorProvider>
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
### `EditorContent`
|
|
209
|
+
|
|
210
|
+
Shows the editable area. Must be inside an `EditorProvider`.
|
|
211
|
+
|
|
212
|
+
| Prop | Type | Description |
|
|
213
|
+
|---|---|---|
|
|
214
|
+
| `className` | `string` | CSS class for the editable element |
|
|
215
|
+
| `ariaLabel` | `string` | Accessible label |
|
|
216
|
+
| `ariaDescribedBy` | `string` | ID of a describing element |
|
|
217
|
+
|
|
218
|
+
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.
|
|
219
|
+
|
|
220
|
+
Dropping content into the editor is disabled, because it would bypass the sanitizer.
|
|
221
|
+
|
|
222
|
+
### Serializers
|
|
223
|
+
|
|
224
|
+
Convert any element with the rules of a set of extensions:
|
|
225
|
+
|
|
226
|
+
```ts
|
|
227
|
+
import { toHTML, toJSON, Bold, Link } from 'yurich';
|
|
228
|
+
|
|
229
|
+
const html = toHTML(element, [Bold, Link]);
|
|
230
|
+
const json = toJSON(element, [Bold, Link]);
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
## Output Formats
|
|
234
|
+
|
|
235
|
+
### HTML
|
|
236
|
+
|
|
237
|
+
```ts
|
|
238
|
+
editor.getHTML();
|
|
239
|
+
// '<p>Hello <strong>World</strong></p>'
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
### JSON
|
|
243
|
+
|
|
244
|
+
```ts
|
|
245
|
+
editor.getJSON();
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
```json
|
|
249
|
+
{
|
|
250
|
+
"type": "doc",
|
|
251
|
+
"content": [
|
|
252
|
+
{
|
|
253
|
+
"type": "paragraph",
|
|
254
|
+
"content": [
|
|
255
|
+
{ "type": "text", "text": "Hello " },
|
|
256
|
+
{ "type": "text", "text": "World", "marks": [{ "type": "bold" }] }
|
|
257
|
+
]
|
|
258
|
+
}
|
|
259
|
+
]
|
|
260
|
+
}
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
**Node types:** `paragraph`, `heading` (`attrs.level`), `blockquote`, `codeBlock`, `orderedList`, `unorderedList`, `listItem`, `text`. A block with a text alignment carries `attrs.textAlign`.
|
|
264
|
+
|
|
265
|
+
**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.
|
|
266
|
+
|
|
267
|
+
A line break inside a block is a text node `"\n"`.
|
|
268
|
+
|
|
269
|
+
`getJSON()` reuses the nodes of blocks that did not change between calls. Treat the result as immutable.
|
|
270
|
+
|
|
271
|
+
## Custom Extensions
|
|
272
|
+
|
|
273
|
+
A toggled inline format or block type is one call:
|
|
274
|
+
|
|
275
|
+
```ts
|
|
276
|
+
import { mark, block } from 'yurich';
|
|
277
|
+
|
|
278
|
+
// <mark>, command `toggleHighlight`, JSON mark type `highlight`
|
|
279
|
+
const Highlight = mark({ name: 'highlight', tag: 'mark', shortcut: 'Mod+Shift+H' });
|
|
280
|
+
|
|
281
|
+
// <aside>, command `toggleCallout`, JSON node type `callout`
|
|
282
|
+
const Callout = block({ name: 'callout', tag: 'aside' });
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
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()`.
|
|
286
|
+
|
|
287
|
+
For anything else, write the extension object:
|
|
288
|
+
|
|
289
|
+
```ts
|
|
290
|
+
import type { Extension } from 'yurich';
|
|
291
|
+
|
|
292
|
+
const Mention: Extension = {
|
|
293
|
+
name: 'mention',
|
|
294
|
+
marks: [{
|
|
295
|
+
tag: 'cite',
|
|
296
|
+
type: 'mention',
|
|
297
|
+
attrs: { 'data-id': value => (value && /^\d+$/.test(value) ? value : null) },
|
|
298
|
+
}],
|
|
299
|
+
commands: {
|
|
300
|
+
setMention: (editor, value) => editor.setMark('cite', { 'data-id': String(value) }),
|
|
301
|
+
removeMention: editor => editor.removeMark('cite'),
|
|
302
|
+
},
|
|
303
|
+
isActive: editor => editor.isMarkActive('cite'),
|
|
304
|
+
};
|
|
305
|
+
```
|
|
306
|
+
|
|
307
|
+
**`Extension`**
|
|
308
|
+
|
|
309
|
+
| Field | Type | Description |
|
|
310
|
+
|---|---|---|
|
|
311
|
+
| `name` | `string` | Unique name |
|
|
312
|
+
| `marks` | `MarkSpec[]` | Inline tags: `tag`, JSON `type`, optional `aliases` (tags rewritten to `tag`) and `attrs` |
|
|
313
|
+
| `blocks` | `BlockSpec[]` | Block tags: `tag`, JSON `type`, optional `aliases` and fixed JSON `attrs` |
|
|
314
|
+
| `blockStyles` | `Record<string, readonly string[]>` | CSS properties allowed on blocks and the values each may take |
|
|
315
|
+
| `commands` | `Record<string, CommandFn>` | Command name → `(editor, value) => void` |
|
|
316
|
+
| `keyboardShortcuts` | `Record<string, string>` | Key combo → command name |
|
|
317
|
+
| `isActive` | `(editor, command?, value?) => boolean` | Whether the extension is active at the selection |
|
|
318
|
+
|
|
319
|
+
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. For `setMark`, the rule receives an inert element with the proposed attributes and the marked text. The same attribute policy applies to custom extensions and the built-in marks.
|
|
320
|
+
|
|
321
|
+
**Editor methods for commands**
|
|
322
|
+
|
|
323
|
+
| Method | Description |
|
|
324
|
+
|---|---|
|
|
325
|
+
| `toggleMark(tag)` | Add the mark to the selection, or remove it when all of the selection has it |
|
|
326
|
+
| `setMark(tag, attrs?, text?)` | Add or update the mark after validating its attributes. With only a caret, `text` is inserted and marked. |
|
|
327
|
+
| `removeMark(tag)` | Remove the mark from the selection. With only a caret, remove the whole mark around it. |
|
|
328
|
+
| `isMarkActive(tag)` | Whether all of the selected text has the mark |
|
|
329
|
+
| `setBlock(tag)` / `toggleBlock(tag)` | Change the selected blocks to `tag` / toggle between `tag` and paragraph |
|
|
330
|
+
| `isBlockActive(tag)` | Whether every selected block is a `tag` |
|
|
331
|
+
| `toggleList(tag)` / `isListActive(tag)` | `'ol'` or `'ul'` |
|
|
332
|
+
| `setBlockStyle(property, value)` / `getBlockStyle(property)` | A style declared in `blockStyles` |
|
|
333
|
+
| `change(edit)` | Run your own DOM edit on `editor.el`. The document is normalized, recorded in history and reported afterwards. |
|
|
334
|
+
|
|
335
|
+
All of them act on the selection inside this editor and do nothing when the selection is elsewhere.
|
|
336
|
+
|
|
337
|
+
## Internals
|
|
338
|
+
|
|
339
|
+
### Document rules
|
|
340
|
+
|
|
341
|
+
After every change — typing, paste, a command, or your own edit of `editor.el` — the changed blocks are brought back to these rules:
|
|
342
|
+
|
|
343
|
+
- The editable element holds only blocks. Loose text is wrapped in `<p>`, and `<div>` lines become `<p>`.
|
|
344
|
+
- Every tag is in the schema and written in its canonical form (`<b>` → `<strong>`, `<i>` → `<em>`, `<del>` → `<s>`). Other tags are unwrapped.
|
|
345
|
+
- A mark is never nested in itself, never empty, and never split into identical neighbours.
|
|
346
|
+
- A list holds only items, is never empty, and is joined with an identical list next to it.
|
|
347
|
+
|
|
348
|
+
### History
|
|
349
|
+
|
|
350
|
+
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.
|
|
351
|
+
|
|
352
|
+
Restored content goes through the sanitizer.
|
|
353
|
+
|
|
354
|
+
## Security
|
|
355
|
+
|
|
356
|
+
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.
|
|
357
|
+
|
|
358
|
+
The sanitizer rebuilds the content from the schema instead of removing what looks dangerous:
|
|
359
|
+
|
|
360
|
+
- Only the tags of the enabled extensions come out, plus `<p>` and `<br>`.
|
|
361
|
+
- The built-in extensions allow `href`, `target` and `rel` on links and `text-align` on blocks with `TextAlign`. `target` may only be `_blank`, which sets `rel="noopener noreferrer"`.
|
|
362
|
+
- URL attributes on marks require an absolute `http://` or `https://` URL. `href` also accepts `mailto:`. Event handlers, inline HTML attributes such as `srcdoc`, custom-element upgrades using `is`, and multi-URL attributes such as `srcset` are discarded.
|
|
363
|
+
- Tags such as `<script>`, `<style>`, `<iframe>`, `<svg>`, `<math>`, `<audio>` and `<video>` are removed with their content. The schema rejects these as output tags even when they are reached through an alias. Custom element names cannot be output tags.
|
|
364
|
+
- Other unknown tags are removed but their text is kept. An unknown tag that starts a line in HTML (`<td>`, `<section>`, …) becomes a paragraph.
|
|
365
|
+
- Plain text is pasted as text nodes and never parsed as HTML.
|
|
366
|
+
|
|
367
|
+
`sanitize: false` makes `getHTML()` and `onChange` return the DOM as it is. Sanitize on the server if you use it.
|
|
368
|
+
|
|
369
|
+
## Browser Support
|
|
370
|
+
|
|
371
|
+
| Browser | Version |
|
|
372
|
+
|---|---|
|
|
373
|
+
| Chrome | 85+ |
|
|
374
|
+
| Firefox | 79+ |
|
|
375
|
+
| Safari | 14+ |
|
|
376
|
+
| Edge | 85+ |
|
|
377
|
+
|
|
378
|
+
## Development
|
|
379
|
+
|
|
380
|
+
Use Node.js 24 LTS and [pnpm 12.25.1](https://pnpm.io/installation) for local development, as in CI.
|
|
381
|
+
|
|
382
|
+
```bash
|
|
383
|
+
pnpm install
|
|
384
|
+
pnpm dev # documentation and live demo
|
|
385
|
+
pnpm build:demo # static documentation site
|
|
386
|
+
pnpm lint
|
|
387
|
+
pnpm typecheck
|
|
388
|
+
pnpm test # Playwright: Chromium, WebKit, Firefox, and iPhone / Pixel emulation
|
|
389
|
+
```
|
|
390
|
+
|
|
391
|
+
The first test run needs the browsers: `pnpm exec playwright install`.
|
|
392
|
+
|
|
393
|
+
Documentation sources are in `demo/docs/<locale>/`. The build uses the examples marked in the English Markdown across all languages. Keep the section IDs after translated headings so existing links continue to work.
|
|
394
|
+
The feature guides use localized introductions, usage steps, and notes from `feature-guides.md` alongside shared React examples in `demo/feature-guides.ts`.
|
|
395
|
+
|
|
396
|
+
The docs build emits `sitemap.xml`, localized `llms.txt` indexes, and Markdown versions of every document. These files use the package homepage for canonical URLs and the package manifest for the documented version.
|
|
397
|
+
|
|
398
|
+
## License
|
|
399
|
+
|
|
400
|
+
MIT
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("react"),t=require("react/jsx-runtime");var n=new Set([`applet`,`audio`,`base`,`embed`,`fencedframe`,`frame`,`frameset`,`iframe`,`link`,`math`,`meta`,`noembed`,`noframes`,`noscript`,`object`,`plaintext`,`portal`,`script`,`style`,`svg`,`template`,`textarea`,`title`,`video`,`xmp`]),r=new Set([`action`,`background`,`cite`,`classid`,`codebase`,`data`,`dynsrc`,`formaction`,`href`,`icon`,`itemid`,`longdesc`,`lowsrc`,`manifest`,`poster`,`profile`,`src`,`usemap`,`xlink:href`]),i=new Set([`archive`,`attributionsrc`,`imagesrcset`,`is`,`ping`,`srcdoc`,`srcset`]),a=e=>n.has(e),o=e=>/^[a-z][a-z0-9-]*$/.test(e),s=e=>o(e)&&!a(e)&&e!==`form`&&!e.includes(`-`),c=(e,t)=>{if(!/^(https?:\/\/|mailto:)/i.test(t))return!1;try{let{protocol:n}=new URL(t);return n===`http:`||n===`https:`||e===`href`&&n===`mailto:`}catch{return!1}},l=e=>/^[a-z][a-z0-9_.:-]*$/.test(e)&&!e.startsWith(`on`)&&!i.has(e),u=(e,t)=>{let n=[];for(let[i,a]of Object.entries(t.attrs??{})){let t=i.toLowerCase();if(!l(t))continue;let o=a(e.getAttribute(t),e);o!==null&&(!r.has(t)||c(t,o))&&n.push([t,o])}return n},d={tag:`p`,type:`paragraph`,aliases:[`div`]},f=e=>{let t=new Map,n=new Map,r=new Map,i=(e,t)=>{if(!s(t.tag))return;let n=t.aliases?.filter(e=>o(e)&&!a(e)&&e!==`form`),r={...t,aliases:n};for(let t of[r.tag,...n??[]])e.set(t,r)};i(n,d);for(let a of e){a.marks?.forEach(e=>i(t,e)),a.blocks?.forEach(e=>i(n,e));for(let[e,t]of Object.entries(a.blockStyles??{}))r.set(e,new Set(t))}return{marks:t,blocks:n,blockStyles:r,blockSelector:Array.from(n.keys()).join(`,`)}},p=(e,t)=>e instanceof HTMLElement&&t.blocks.has(e.localName),m=300,h=e=>{let t=[],n=[],r={blocks:[],before:null,after:null},i=null,a=null,o=()=>{a!==null&&(clearTimeout(a),a=null),i&&(t.push(r),t.length>e&&t.shift(),r=i,i=null,n=[])};return{reset(e){t=[],n=[],i=null,r={blocks:e,before:null,after:null}},record(e,t){t?(i=i?{...e,before:i.before}:e,a!==null&&clearTimeout(a),a=setTimeout(o,m)):(o(),i=e,o())},undo(){o();let e=t.pop();if(!e)return null;let i=r;return n.push(i),r=e,{blocks:e.blocks,selection:i.before}},redo(){o();let e=n.pop();return e?(t.push(r),r=e,{blocks:e.blocks,selection:e.after}):null},canUndo:()=>t.length>0||i!==null,canRedo:()=>n.length>0&&i===null,cancelTimer(){a!==null&&(clearTimeout(a),a=null)}}},g=e=>{let t=window.getSelection();if(!t||t.rangeCount===0)return null;let n=t.getRangeAt(0);return e.contains(n.commonAncestorContainer)?n:null},_=e=>{let t=window.getSelection();t&&(t.removeAllRanges(),t.addRange(e))},v=(e,t)=>{let n=document.createRange();n.setStart(e,0),n.setEnd(t,t.length),_(n)},y=e=>{let t=e;for(;t.lastChild;)t=t.lastChild;let 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),_(n)},b=e=>{let t=e;for(;t.lastChild;)t=t.lastChild;let 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))},x=(e,t,n)=>{let r=[];for(let n=t;n!==e;n=n.parentNode)r.push(Array.prototype.indexOf.call(n.parentNode.childNodes,n));return[r.reverse(),n]},S=(e,[t,n])=>{let r=e;for(let e of t){let t=r.childNodes.item(e);if(!t)return[r,r.childNodes.length];r=t}let i=r.nodeType===Node.TEXT_NODE?r.length:r.childNodes.length;return[r,Math.min(n,i)]},C=(e,t)=>{let n=e.firstChild,r=t.firstChild;for(;n&&r;){if(n.nodeName!==r.nodeName||n.nodeValue!==r.nodeValue||!C(n,r))return!1;n=n.nextSibling,r=r.nextSibling}return n===r},w=(e,t,n)=>{let[r,i]=S(e,n),a=document.createRange();a.setStart(e,0),a.setEnd(r,i);let o=a.cloneContents(),s=(o.textContent?.length??0)+o.querySelectorAll(`br`).length,c=r.nodeType===Node.TEXT_NODE?i===0:i<r.childNodes.length,l=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,{acceptNode:e=>e.nodeType===Node.TEXT_NODE||e.nodeName===`BR`?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}),u=[t,0];for(let e=l.nextNode();e;e=l.nextNode())if(e.nodeType===Node.TEXT_NODE){let t=e.length;if(s<t||s===t&&!c)return[e,s];s-=t,u=[e,t]}else{let t=e.parentNode,n=Array.prototype.indexOf.call(t.childNodes,e);if(s===0)return[t,n];if(s--,u=[t,n+1],s===0&&!c)return u}return u},T=e=>{let t=window.getSelection();if(!t?.anchorNode||!t.focusNode||!e.contains(t.anchorNode)||!e.contains(t.focusNode))return null;let n=x(e,t.anchorNode,t.anchorOffset);return{anchor:n,focus:t.isCollapsed?n:x(e,t.focusNode,t.focusOffset)}},ee=(e,t,n)=>{let r=window.getSelection();if(r&&e.isConnected){if(!t)y(e);else{if(n!==void 0){let i=e.ownerDocument.createElement(`template`);if(i.innerHTML=n,!C(i.content,e)){let n=w(i.content,e,t.anchor),a=t.focus===t.anchor?n:w(i.content,e,t.focus);r.setBaseAndExtent(...n,...a);return}}r.setBaseAndExtent(...S(e,t.anchor),...S(e,t.focus))}}},E=(e,t,n=Array.from(e.attributes,({name:e,value:t})=>[e,t]))=>{let r=e.ownerDocument.createElement(t);for(let[e,t]of n)r.setAttribute(e,t);return r.append(...e.childNodes),e.replaceWith(r),r},D=e=>{e.replaceWith(...e.childNodes)},te=(e,t)=>{let n=t;for(;n&&n!==e&&n.parentNode!==e;)n=n.parentNode;return n===e?null:n},O=e=>e instanceof HTMLElement&&(e.localName===`ul`||e.localName===`ol`),ne=(e,t)=>e.attributes.length===t.attributes.length&&Array.from(e.attributes).every(e=>t.getAttribute(e.name)===e.value),re=e=>{let t=window.getSelection(),n=t?.anchorNode??null,r=t?.focusNode??null,i=t?.anchorOffset??0,a=t?.focusOffset??0;e(),t&&n&&r&&n.nodeType===Node.TEXT_NODE&&r.nodeType===Node.TEXT_NODE&&n.isConnected&&r.isConnected&&(t.anchorNode!==n||t.anchorOffset!==i||t.focusNode!==r||t.focusOffset!==a)&&t.setBaseAndExtent(n,Math.min(i,n.length),r,Math.min(a,r.length))},k=(e,t,n)=>{for(let r=e;r&&r!==n;r=r.parentNode)if(r instanceof HTMLElement&&(r.localName===t.tag||t.aliases?.includes(r.localName)))return r;return null},A=(e,t)=>{let n=t.commonAncestorContainer,r=n.nodeType===Node.TEXT_NODE?n.parentNode:n,i=document.createTreeWalker(r,NodeFilter.SHOW_TEXT),a=[];for(let n=i.nextNode();n;n=i.nextNode()){if(!t.intersectsNode(n)||n.parentNode===e||O(n.parentNode))continue;let r=n===t.startContainer?t.startOffset:0,i=n===t.endContainer?t.endOffset:n.length;r<i&&a.push({node:n,start:r,end:i})}return a},j=e=>e.map(({node:e,start:t,end:n})=>(n<e.length&&e.splitText(n),t>0?e.splitText(t):e)),ie=(e,t,n,r)=>{let i=e.ownerDocument.createElement(`template`).content.ownerDocument.createElement(t.tag);i.textContent=r;for(let{name:t,value:n}of Array.from(e.attributes))l(t)&&i.setAttribute(t,n);for(let[e,t]of Object.entries(n))l(e.toLowerCase())&&i.setAttribute(e,t);let a=new Map(u(i,t));for(let t of e.getAttributeNames())a.has(t)||e.removeAttribute(t);for(let[t,n]of a)e.getAttribute(t)!==n&&e.setAttribute(t,n)},ae=(e,t,n)=>{if(t.collapsed)return k(t.startContainer,n,e)!==null;let r=A(e,t);return r.length>0&&r.every(t=>k(t.node,n,e))},oe=(e,t,n,r,i)=>{if(t.collapsed){if(!i)return;t.insertNode(document.createTextNode(i))}let a=j(A(e,t));if(a.length!==0){for(let t of a){let i=k(t,n,e);if(i){r&&ie(i,n,r,i.textContent??``);continue}let a=document.createElement(n.tag);r&&ie(a,n,r,t.data),t.replaceWith(a),a.append(t)}v(a[0],a[a.length-1])}},se=(e,t)=>{let n=document.createRange();n.setStart(e,0),n.setEndBefore(t);let r=document.createRange();r.setStartAfter(t),r.setEnd(e,e.childNodes.length);for(let[t,i]of[[n,`before`],[r,`after`]]){let n=t.extractContents();if(!n.textContent&&!n.querySelector(`br`))continue;let r=e.cloneNode(!1);r.append(n),e[i](r)}D(e)},ce=(e,t,n)=>{if(t.collapsed){let r=k(t.startContainer,n,e);r&&re(()=>D(r));return}let r=j(A(e,t));if(r.length!==0){for(let t of r)for(let r=k(t,n,e);r;r=k(t,n,e))se(r,t);v(r[0],r[r.length-1])}},le=(e,t,n)=>{t.collapsed||(ae(e,t,n)?ce(e,t,n):oe(e,t,n))},M=e=>e.nodeType===Node.TEXT_NODE&&/^[\t\n\f\r ]*$/.test(e.textContent??``),ue=e=>Array.from(e.childNodes).some(e=>!M(e)),de=(e,t)=>{let n=[],r=null;for(let i of e.childNodes)p(i,t)?(n.push({nodes:[i],block:i}),r=null):(r||n.push(r={nodes:[],block:null}),r.nodes.push(i));return n},fe=(e,t,n)=>{for(let r of n.blockStyles.keys()){let n=e.style.getPropertyValue(r);n&&!t.style.getPropertyValue(r)&&t.style.setProperty(r,n)}},N=e=>{e.firstChild||e.append(e.ownerDocument.createElement(`br`))},P=(e,t)=>{let n=e.ownerDocument.createElement(`p`);return n.append(...t),N(n),n},pe=e=>{let t=P(e,Array.from(e.childNodes));for(let{name:n,value:r}of e.attributes)t.setAttribute(n,r);return t},me=(e,t,n,r,i)=>{let a=t.findIndex(n);if(a<0)return null;let o=e.ownerDocument.createDocumentFragment(),s=null,c=null,l=()=>{s&&ue(s)&&o.append(s),s=null};for(let u of t.slice(a))if(n(u)){l();let e=i(u);o.append(...e),c=e.at(-1)??c}else s??=e.cloneNode(!1),s.append(...r(u));return l(),e.after(o),ue(e)||e.remove(),c},he=(e,t)=>{let n=t;for(;n.parentNode&&n.parentNode!==e;)n=n.parentNode;return n.parentNode===e?n:null},ge=(e,t,n)=>{let r=de(e,n);if(!r.some(e=>e.block)){let t=pe(e);return e.replaceWith(t),t}return me(e,r,e=>e.nodes.some(e=>t.has(e)),e=>e.nodes,t=>{let r=t.block??P(e,t.nodes);return fe(e,r,n),N(r),[r]})},_e=(e,t)=>{let n=de(e,t);if(!n.some(e=>e.block))return[pe(e)];let r=[];for(let i of n){if(!i.block&&i.nodes.every(M))continue;let n=i.block??P(e,i.nodes);fe(e,n,t),N(n),r.push(n)}return r},ve=(e,t,n)=>{let r=e.ownerDocument.createDocumentFragment(),i=null,a=null;for(let t of Array.from(e.childNodes))t instanceof HTMLElement&&n.has(t)?(N(t),r.append(t),i=t,a=null):i&&(a||(a=e.cloneNode(!1),i.append(a)),a.append(t));if(!i)return null;for(;e.nextSibling;)i.append(e.nextSibling);return t.after(r),e.firstChild||e.remove(),i},ye=(e,t,n)=>{let r=new Map,i=new Set(e),a=null;for(let e of i){let n=e.parentElement;if(!O(n)){let n=_e(e,t);e.replaceWith(...n),a=n[0];continue}let o=n.closest(`li`);for(;o&&!i.has(o);)o=o.parentElement?.closest(`li`)??null;if(o)continue;let s=r.get(n);s||r.set(n,s=new Set),s.add(e)}let o=null;for(let[e,i]of r){let r=e.parentElement;a=r?.localName===`li`?ve(e,r,i)??a:me(e,Array.from(e.children),e=>i.has(e),e=>[e],e=>{let r=e.contains(n??null),i=_e(e,t);return e.remove(),r&&(o=i.find(e=>e.contains(n??null))??i[0]),i})??a}return o??a},be=(e,t)=>{let n=e.parentElement;if(O(n)){let t=n.cloneNode(!1);for(;e.nextSibling;)t.append(e.nextSibling);n.after(e),t.firstChild&&e.after(t),n.firstChild||n.remove()}return E(e,t)},xe=(e,t)=>p(e,t)&&!O(e),F=(e,t,n)=>{for(let r=e;r&&r!==t;r=r.parentNode)if(xe(r,n))return r;return null},Se=(e,t)=>{let 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()!==``},I=(e,t)=>e.childNodes[t]??e.lastChild??e,L=(e,t,n)=>{let r=F(I(t.startContainer,t.startOffset),e,n),i=F(I(t.endContainer,t.endOffset),e,n);if(!r)return[];if(!i||r===i)return[r];let a=Array.from(e.querySelectorAll(n.blockSelector)).filter(e=>xe(e,n)&&!e.querySelector(n.blockSelector)&&t.intersectsNode(e));return a.length>1&&!Se(t,a[a.length-1])&&a.pop(),a},R=e=>{if(!g(e))return null;if(e.childNodes.length===0){let t=document.createElement(`p`);t.append(document.createElement(`br`)),e.append(t),window.getSelection()?.collapse(t,0)}return g(e)},Ce=(e,t,n)=>{let r=window.getSelection(),i=g(e);if(!r||!i)return;let a=(n,r,i=r>0&&r===n.childNodes.length)=>{let a=n.childNodes[r-Number(i)];return()=>{if(a&&e.contains(a)){let e=a.parentNode;return e!==n&&p(a,t)?[a,i?a.childNodes.length:0]:e!==n&&a.nodeName===`BR`&&e.childNodes.length===1?[e,0]:[e,Array.prototype.indexOf.call(e.childNodes,a)+Number(i)]}if(n===e||!e.contains(n))return null;let o=n.nodeType===Node.TEXT_NODE?n.length:n.childNodes.length;return[n,Math.min(r,o)]}},{startContainer:o,startOffset:s,endContainer:c,endOffset:l,collapsed:u}=i,d=!u&&r.anchorNode===c&&r.anchorOffset===l,f=a(o,s),m=u?f:a(c,l,!0),h=n();if(!h)return;let _=d?m():f(),v=u?_:d?f():m();_&&v?(r.anchorNode!==_[0]||r.anchorOffset!==_[1]||r.focusNode!==v[0]||r.focusOffset!==v[1])&&r.setBaseAndExtent(..._,...v):u&&s===0?r.collapse(h,0):(u||!e.contains(r.anchorNode)||r.anchorNode===e)&&b(h)},z=(e,t,n)=>{let r=(e instanceof Element?e:e.parentElement)?.closest(n)??null;return r!==t&&t.contains(r)?r:null},we=(e,t,n)=>{if(!t.collapsed||t.startContainer===e)return null;let{startContainer:r,startOffset:i}=t;if(i&&r.nodeType===Node.TEXT_NODE)return null;let a=r.childNodes[i],o=z(r,e,`li, blockquote`);if(!o||!p(o,n))return null;let s=a??r,c=o.localName===`blockquote`,l=he(o,s),u=c&&l&&p(l,n)?l:o;if(!a&&i!==0){let t=F(s,e,n);if(i!==1||r.firstChild?.nodeName!==`BR`||!t||t.textContent||t.querySelectorAll(`br`).length!==1)return null}for(let e=s;e!==u;e=e.parentNode){let t=e.previousSibling,r=e.parentNode===o;for(;r&&t&&M(t)&&(p(e,n)||c&&/[\n\r]/.test(t.textContent??``));)t=t.previousSibling;if(t){if(c&&r&&p(t,n))break;return null}}return c?()=>ge(o,new Set([l??o]),n):()=>ye([o],n,s)},Te=(e,t,n,r)=>{let i=new Map;for(let r of e){let e=z(r,t,`blockquote`);if(!e)continue;let a=i.get(e);a||i.set(e,a=new Set);let o=he(e,r===e&&n.collapsed?I(n.startContainer,n.startOffset):r);o&&a.add(o)}if(!n.collapsed)for(let[e,t]of i)for(let i of e.childNodes)p(i,r)||M(i)||!n.intersectsNode(i)||n.endContainer===i&&n.endOffset===0||t.add(i);let a=null;for(let[e,t]of i)a=ge(e,t,r)??a;return a},B=(e,t,n)=>e.localName===t||t===`blockquote`&&z(e,n,t)!==null,Ee=(e,t,n,r=!1)=>{let i=t.blocks.get(n);if(!i||i.tag!==n||n===`li`||n===`ul`||n===`ol`)return;let a=R(e);if(!a)return;let o=L(e,a,t),s=r&&o.every(t=>B(t,n,e)),c=s?`p`:n;Ce(e,t,()=>{if(s&&n===`blockquote`)return Te(o,e,a,t);let r=null;for(let t of o)r=B(t,c,e)?t:t.localName===`li`?be(t,c):E(t,c);return r})},De=(e,t,n)=>{let r=g(e);if(!r)return!1;let i=L(e,r,t);return i.length>0&&i.every(t=>B(t,n,e))},Oe=(e,t,n,r)=>{if(!t.blockStyles.get(n)?.has(r))return;let i=R(e);if(i)for(let a of L(e,i,t))a.style.setProperty(n,r)},ke=(e,t,n)=>{let r=g(e);if(!r)return null;let[i]=L(e,r,t);return i?.style.getPropertyValue(n)||null},V=(e,t)=>e.localName===`li`&&e.parentElement?.localName===t,Ae=(e,t,n)=>Array.from(new Set(L(e,t,n).map(t=>z(t,e,`li`)??t))),je=(e,t,n)=>{let r=g(e);if(!r)return!1;let i=Ae(e,r,t);return i.length>0&&i.every(e=>V(e,n))},Me=(e,t)=>{let n=document.createElement(t),r=document.createElement(`li`),i=e.getAttribute(`style`);return i&&r.setAttribute(`style`,i),r.append(...e.childNodes),n.append(r),e.replaceWith(n),r},Ne=(e,t,n)=>{if(!t.blocks.has(n))return;let r=R(e);if(!r)return;let i=Ae(e,r,t),a=i.every(e=>V(e,n));Ce(e,t,()=>{if(a)return ye(i,t,r.collapsed?r.startContainer:void 0);let e=null;for(let t of i)e=V(t,n)?t:Me(t.localName===`li`?be(t,`p`):t,n);return e})},Pe=`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`.split(`.`).join(`,`),Fe=e=>{let t=document.createRange();return t.selectNodeContents(e),Array.from(t.cloneContents().childNodes)},H=(e,t)=>{let n=[];for(let r of(e??``).split(`;`)){let e=r.indexOf(`:`);if(e===-1)continue;let i=r.slice(0,e).trim().toLowerCase(),a=r.slice(e+1).trim().toLowerCase();t.blockStyles.get(i)?.has(a)&&n.push(`${i}: ${a}`)}return n.join(`; `)},U=null,W=(e,t,n)=>{for(let r of e){let e=Ie(r,n);e&&t.appendChild(e)}},Ie=(e,t)=>{let n=U,r=e=>{let r=n.createDocumentFragment();return W(e,r,t),r};if(e instanceof HTMLFormElement)return r(Fe(e));if(e.nodeType===Node.TEXT_NODE)return n.createTextNode(e.textContent??``);if(!(e instanceof Element))return null;let i=e.localName;if(a(i))return null;if(i===`br`)return n.createElement(`br`);let o=t.marks.get(i);if(o){let r=n.createElement(o.tag);for(let[t,n]of u(e,o))r.setAttribute(t,n);return W(e.childNodes,r,t),r}let s=e.matches(Pe),c=e.querySelector(Pe)!==null,l=t.blocks.get(i);if((l?.tag===`p`||!l&&s)&&c)return r(e.childNodes);if(l||s){let r=n.createElement(l?.tag??`p`),i=H(e.getAttribute(`style`),t);return i&&r.setAttribute(`style`,i),W(e.childNodes,r,t),l||r.childNodes.length>0?r:null}return r(e.childNodes)},G=(e,t)=>{U??=document.implementation.createHTMLDocument(``);let n=U.createElement(`div`);return W(e,n,t),n.innerHTML},K=(e,t)=>e?G(new DOMParser().parseFromString(e,`text/html`).body.childNodes,t):``,Le=(e,t)=>{let n=Array.from(e.childNodes),r=n.some(e=>p(e,t)),i=[],a=[],o=()=>{if(a.length!==0){if(a.some(e=>e.nodeType===Node.ELEMENT_NODE||e.textContent?.trim())||!r){let t=(e.ownerDocument??document).createElement(`p`);e.insertBefore(t,a[0]),t.append(...a),i.push(t)}else a.forEach(t=>e.removeChild(t));a=[]}};for(let r of n)p(r,t)?o():r.nodeType===Node.ELEMENT_NODE||r.nodeType===Node.TEXT_NODE?a.push(r):e.removeChild(r);return o(),i},Re=e=>{let t=e.nextSibling;for(;t instanceof Element&&t.localName===e.localName;)e.append(...t.childNodes),t.remove(),t=e.nextSibling},ze=e=>{for(let 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}let n=e.ownerDocument.createElement(`li`);t.replaceWith(n),n.append(t)}e.children.length===0?e.remove():Re(e)},Be=(e,t,n)=>{let r=t;for(let i of[t,...t.querySelectorAll(`*`)]){if(!e.contains(i))continue;let t=i.localName;if(t===`br`)continue;let a=n.marks.get(t),o=a??n.blocks.get(t);if(!o){D(i);continue}let s=i;if(o.tag!==t){let e=!a&&H(i.getAttribute(`style`),n),t=a?u(i,a):[];e&&t.push([`style`,e]),s=E(i,o.tag,t)}if(i===r&&(r=s),a){let t=s.parentElement?.closest(o.tag);s.childNodes.length===0?s.remove():t&&t!==e&&e.contains(t)&&D(s)}}r.normalize();for(let t of Array.from(r.querySelectorAll(`*`))){if(!n.marks.has(t.localName)||!e.contains(t))continue;let r=t.nextSibling;for(;r instanceof Element&&r.localName===t.localName&&ne(t,r);)t.append(...r.childNodes),r.remove(),r=t.nextSibling}r.normalize();for(let t of[r,...r.querySelectorAll(`ul, ol`)])O(t)&&e.contains(t)&&ze(t)},Ve=(e,t,n)=>{re(()=>{let r=new Set(Le(e,t));for(let t of n)t instanceof Element&&t.parentNode===e&&r.add(t);for(let n of r)n.parentNode===e&&Be(e,n,t);for(let t of Array.from(e.children))O(t)&&t.parentNode===e&&Re(t)})},He=e=>e.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Ue=(e,t,n,r=!1)=>{let i=e=>{let n={type:`text`,text:e};return t.length>0&&(n.marks=[...t]),[n]},o=(e,t)=>Array.from(e).flatMap(e=>Ue(e,t,n));if(e instanceof HTMLFormElement)return o(Fe(e),t);if(e.nodeType===Node.TEXT_NODE){let t=e.textContent??``;return(r?t.trim():t)?i(t):[]}if(!(e instanceof Element))return[];let s=e.localName;if(a(s))return[];if(s===`br`)return r?[]:i(`
|
|
2
|
+
`);let c=n.marks.get(s);if(c){let n={type:c.type},r=Object.fromEntries(u(e,c));return Object.keys(r).length>0&&(n.attrs=r),o(e.childNodes,[...t,n])}let l=n.blocks.get(s);if(!l)return o(e.childNodes,t);let d={type:l.type},f={...l.attrs};for(let t of H(e.getAttribute(`style`),n).split(`; `)){let[e,n]=t.split(`: `);n&&(f[He(e)]=n)}Object.keys(f).length>0&&(d.attrs=f);let p=o(e.childNodes,t);return p.length>0&&(d.content=p),[d]},We=(e,t)=>Ue(e,[],t,!0),Ge=(e,t)=>G(e.childNodes,f(t)),Ke=(e,t)=>{let n=f(t);return{type:`doc`,content:Array.from(e.childNodes).flatMap(e=>We(e,n))}},qe=(e,t)=>{let n=new WeakMap,r=new Set,i=!1,a=e=>{let t=n.get(e);return t||(t={},n.set(e,t)),t},o=t=>{for(let a of t){if(i=!0,a.target===e){a.addedNodes.forEach(e=>r.add(e));continue}let t=te(e,a.target);t&&(r.add(t),n.delete(t))}},s=new MutationObserver(e=>{o(e),t()}),c=()=>{r.clear(),i=!1},l=(t,n)=>{e.innerHTML=K(t,n)};return{root:e,observe(){s.observe(e,{childList:!0,subtree:!0,characterData:!0,attributes:!0})},normalizeChanges(t,n){return o(s.takeRecords()),!i||n?!1:(Ve(e,t,r),o(s.takeRecords()),c(),!0)},discardChanges(){s.takeRecords(),c()},invalidateCache(){n=new WeakMap},rawBlocks(){return Array.from(e.children,e=>a(e).raw??=e.outerHTML)},getHTML(t,n){return n?Array.from(e.children,e=>a(e).html??=G([e],t)).join(``):e.innerHTML},getJSON(t){return{type:`doc`,content:Array.from(e.children).flatMap(e=>a(e).json??=We(e,t))}},replaceHTML:l,loadHTML(t,n){l(t,n),Ve(e,n,Array.from(e.childNodes))},replaceBlocks(t,n,r){let i=0;for(;i<t.length&&i<n.length&&t[i]===n[i];)i++;let a=t.length,l=n.length;for(;a>i&&l>i&&t[a-1]===n[l-1];)a--,l--;let u=Array.from(e.children),d=e.ownerDocument.createElement(`template`);d.innerHTML=K(n.slice(i,l).join(``),r),u.slice(i,a).forEach(e=>e.remove()),e.insertBefore(d.content,u[a]??null),o(s.takeRecords()),c()}}},q=(e,t)=>{e.deleteContents();let n=t.lastChild;if(e.insertNode(t),!n)return;let r=n.nextSibling;r?.nodeName===`BR`&&!r.nextSibling&&r.remove(),y(n)},Je=(e,t,n,r)=>{t.deleteContents();let i=te(e,t.startContainer);if(!i||!p(i,r)){q(t,n);return}Le(n,r);let a=n.lastChild;if(!a)return;let o=document.createRange();o.selectNodeContents(i),o.setStart(t.startContainer,t.startOffset);let s=i.cloneNode(!1);s.append(o.extractContents()),i.after(n,s);for(let e of[i,s])e.textContent?.trim()||e.remove();y(a)},Ye=(e,t,n,r)=>{let i=document.createElement(`template`);i.innerHTML=n;let a=i.content,o=a.childNodes.length===1?a.firstChild:null;o instanceof HTMLElement&&o.localName===`p`&&!o.querySelector(r.blockSelector)&&D(o),a.querySelector(r.blockSelector)?Je(e,t,a,r):q(t,a)},Xe=(e,t,n)=>{let r=document.createDocumentFragment(),i=t.startContainer,a=(i instanceof Element?i:i.parentElement)?.closest(`pre`);a&&e.contains(a)?r.append(n):n.split(/\r\n?|\n/).forEach((e,t)=>{t>0&&r.append(document.createElement(`br`)),e&&r.append(e)}),q(t,r)},Ze=typeof navigator<`u`&&/Mac|iPhone|iPad|iPod/.test(navigator.userAgent),Qe=new Set([`Control`,`Shift`,`Alt`,`Meta`]),$e=e=>{let t=[];return(Ze?e.metaKey:e.ctrlKey)&&t.push(`Mod`),e.shiftKey&&t.push(`Shift`),e.altKey&&t.push(`Alt`),Qe.has(e.key)||t.push(e.key.length===1?e.key.toUpperCase():e.key),t.join(`+`)},et=(e,t)=>{for(let n of e){let e=n.keyboardShortcuts?.[t];if(e)return e}return null},tt=(e,t,n)=>{e.addEventListener(`keydown`,e=>{if(e.isComposing)return;let n=e.metaKey||e.ctrlKey,r=e.key.toLowerCase();if(n&&(r===`z`||r===`y`)){e.preventDefault(),r===`z`&&!e.shiftKey?t.history.undo():t.history.redo();return}let i=et(t.extensions,$e(e));i&&(e.preventDefault(),t.execute(i))}),e.addEventListener(`beforeinput`,r=>{if(r.inputType!==`deleteContentBackward`||!r.cancelable||r.defaultPrevented||n.composing||r.isComposing)return;n.flushTyping();let i=g(e);if(!i)return;let a=we(e,i,n.schema);if(!a)return;let o=i.startContainer;r.preventDefault(),t.change(()=>{let e=a();e&&window.getSelection()?.collapse(e.contains(o)?o:e,0)})}),e.addEventListener(`paste`,r=>{r.preventDefault();let i=r.clipboardData?.getData(`text/html`),a=r.clipboardData?.getData(`text/plain`);t.change(()=>{let t=g(e);if(t){if(i){let r=n.schema;Ye(e,t,K(i,r),r)}else a&&Xe(e,t,a)}})}),e.addEventListener(`drop`,e=>e.preventDefault()),e.addEventListener(`compositionstart`,()=>n.setComposing(!0)),e.addEventListener(`compositionend`,()=>{n.setComposing(!1),n.flushTyping()})},nt=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),rt=e=>{let t=e,n=f(t.extensions),r=h(t.historyLimit??100),i=null,a=!1,o=0,s=0,c=null,l=new Set,u=[],d=null,p=()=>{s++,l.forEach(e=>e())},m=()=>{c===null&&(c=requestAnimationFrame(()=>{c=null,t.onChange?.(D.getHTML()),t.onChangeJSON?.(D.getJSON())}))},_=(e=!1)=>{if(!i?.normalizeChanges(n,a))return;let{root:t}=i,o=i.rawBlocks(),s=T(t);nt(o,u)||(r.record({blocks:o,before:d,after:s},e),u=o,m()),d=s??d,p()},v=e=>{if(!e||!i)return;let{root:t}=i,{blocks:r}=e;i.replaceBlocks(u,r,n),u=i.rawBlocks(),ee(t,e.selection,nt(u,r)?void 0:r.join(``)),d=T(t),p(),m()},y=(()=>{let e=!1;return()=>{let t=i?.root,n=!!t&&g(t)!==null;t&&n&&(d=T(t)),(n||e)&&p(),e=n}})(),b=(e,t)=>{e.loadHTML(t,n),u=e.rawBlocks(),r.reset(u),d=null},x=()=>{let e=document.createElement(`div`);e.contentEditable=`true`,e.setAttribute(`role`,`textbox`),e.setAttribute(`aria-multiline`,`true`),e.tabIndex=0;let r=qe(e,()=>_(!0));return b(r,t.initialValue??``),tt(e,D,{get schema(){return n},get composing(){return a},setComposing(e){a=e},flushTyping:()=>_(!0)}),r.observe(),r},S=e=>{let t=n.marks.get(e);return t&&t.tag===e?t:null},C=e=>{D.change(()=>{let t=i?.root,n=t&&g(t);t&&n&&e(t,n)})},w=(e,t)=>{let n=i?.root,r=n&&g(n);return n&&r?t(n,r):e},E=e=>{D.change(()=>{i&&e(i.root)})},D={get el(){return i?.root??null},get extensions(){return t.extensions},get revision(){return s},history:{undo:()=>{_(),v(r.undo())},redo:()=>{_(),v(r.redo())},canUndo:()=>r.canUndo(),canRedo:()=>r.canRedo()},mount(e){i??=x(),e.append(i.root),document.addEventListener(`selectionchange`,y)},unmount(){i?.root.remove(),document.removeEventListener(`selectionchange`,y)},destroy(){r.cancelTimer(),c!==null&&(cancelAnimationFrame(c),c=null)},setOptions(e){let r=e.extensions!==void 0&&(e.extensions.length!==t.extensions.length||e.extensions.some((e,n)=>e!==t.extensions[n]));t={...t,...e},r&&(n=f(t.extensions),i?.invalidateCache())},subscribe(e){return l.add(e),()=>{l.delete(e)}},execute(e,n){for(let r of t.extensions){let t=r.commands?.[e];if(t){D.change(()=>t(D,n));return}}throw Error(`Command not found: ${e}`)},isActive(e,n){return!i||!g(i.root)?!1:(t.extensions.find(t=>t.commands?.[e]&&t.isActive)??t.extensions.find(t=>t.name===e&&t.isActive))?.isActive?.(D,e,n)??!1},getHTML(){return i?(_(),i.getHTML(n,t.sanitize!==!1)):``},getJSON(){return i?(_(),i.getJSON(n)):{type:`doc`,content:[]}},setHTML(e,{history:r=!0}={}){i?(_(),r?(i.replaceHTML(e,n),_()):(b(i,e),i.discardChanges(),p(),m())):t={...t,initialValue:e}},change(e){if(i&&!a){if(o>0)e();else{_(),d=T(i.root)??d,o++;try{e()}finally{o--}_()}}},toggleMark(e){let t=S(e);t&&C((e,n)=>le(e,n,t))},setMark(e,t,n){let r=S(e);r&&C((e,i)=>oe(e,i,r,t,n))},removeMark(e){let t=S(e);t&&C((e,n)=>ce(e,n,t))},isMarkActive(e){let t=S(e);return t?w(!1,(e,n)=>ae(e,n,t)):!1},setBlock(e){E(t=>Ee(t,n,e))},toggleBlock(e){E(t=>Ee(t,n,e,!0))},isBlockActive(e){return i?De(i.root,n,e):!1},toggleList(e){E(t=>Ne(t,n,e))},isListActive(e){return i?je(i.root,n,e):!1},setBlockStyle(e,t){E(r=>Oe(r,n,e,t))},getBlockStyle(e){return i?ke(i.root,n,e):null}};return D},it=t=>{let[n]=(0,e.useState)(()=>rt(t)),{extensions:r,onChange:i,onChangeJSON:a}=t;return(0,e.useEffect)(()=>{n.setOptions({extensions:r,onChange:i,onChangeJSON:a})}),(0,e.useEffect)(()=>()=>n.destroy(),[n]),n},at=(0,e.createContext)(null),ot=()=>{let t=(0,e.useContext)(at);if(!t)throw Error(`useEditorContext must be used within an EditorProvider`);return t},st=({editor:e,children:n})=>(0,t.jsx)(at.Provider,{value:e,children:n}),J=(e,t,n)=>{n===void 0?e.removeAttribute(t):e.setAttribute(t,n)},ct=({className:n,ariaLabel:r,ariaDescribedBy:i})=>{let a=ot(),o=(0,e.useRef)(null);return(0,e.useEffect)(()=>{if(o.current)return a.mount(o.current),()=>a.unmount()},[a]),(0,e.useEffect)(()=>{let e=a.el;e&&(J(e,`class`,n),J(e,`aria-label`,r),J(e,`aria-describedby`,i))},[a,n,r,i]),(0,t.jsx)(`div`,{ref:o,style:{display:`contents`}})};ct.displayName=`EditorContent`;var Y=(t,n)=>{let r=(0,e.useRef)(null),i=()=>{let e=r.current;if(e&&e.revision===t.revision&&e.selector===n)return e.value;let i=n(t);return r.current={revision:t.revision,selector:n,value:i},i};return(0,e.useSyncExternalStore)(t.subscribe,i,i)},lt=(e,t,n)=>Y(e,e=>e.isActive(t,n)),ut=e=>Y(e,e=>e.history.canUndo()),dt=e=>Y(e,e=>e.history.canRedo()),ft=e=>`toggle${e[0].toUpperCase()}${e.slice(1)}`,X=e=>{let{name:t,tag:n,aliases:r,shortcut:i}=e,a=ft(t);return{name:t,marks:[{tag:n,type:t,aliases:r}],commands:{[a]:e=>e.toggleMark(n)},keyboardShortcuts:i?{[i]:a}:void 0,isActive:e=>e.isMarkActive(n)}},Z=e=>{let{name:t,tag:n,shortcut:r}=e,i=ft(t);return{name:t,blocks:[{tag:n,type:t}],commands:{[i]:e=>e.toggleBlock(n)},keyboardShortcuts:r?{[r]:i}:void 0,isActive:e=>e.isBlockActive(n)}},pt=X({name:`bold`,tag:`strong`,aliases:[`b`],shortcut:`Mod+B`}),mt=X({name:`italic`,tag:`em`,aliases:[`i`],shortcut:`Mod+I`}),ht=X({name:`underline`,tag:`u`,shortcut:`Mod+U`}),gt=X({name:`strikethrough`,tag:`s`,aliases:[`del`],shortcut:`Mod+Shift+S`}),_t=X({name:`code`,tag:`code`}),vt=Z({name:`blockquote`,tag:`blockquote`}),yt=Z({name:`codeBlock`,tag:`pre`}),Q=[1,2,3,4,5,6],bt={name:`heading`,blocks:Q.map(e=>({tag:`h${e}`,type:`heading`,attrs:{level:e}})),commands:{setHeading:(e,t)=>{Q.includes(t)&&e.setBlock(`h${t}`)},removeHeading:e=>e.setBlock(`p`)},isActive:(e,t,n)=>{if(t===`setHeading`)return Q.includes(n)&&e.isBlockActive(`h${n}`);let r=Q.some(t=>e.isBlockActive(`h${t}`));return t===`removeHeading`?!r:r}},xt=(e,t)=>{let n=`toggle${e[0].toUpperCase()}${e.slice(1)}`;return{name:e,blocks:[{tag:t,type:e},{tag:`li`,type:`listItem`}],commands:{[n]:e=>e.toggleList(t)},isActive:e=>e.isListActive(t)}},St=xt(`orderedList`,`ol`),Ct=xt(`unorderedList`,`ul`),$={alignLeft:`left`,alignCenter:`center`,alignRight:`right`,alignJustify:`justify`},wt={name:`textAlign`,blockStyles:{"text-align":Object.values($)},commands:Object.fromEntries(Object.entries($).map(([e,t])=>[e,e=>e.setBlockStyle(`text-align`,t)])),isActive:(e,t)=>t!==void 0&&(e.getBlockStyle(`text-align`)??`left`)===$[t]},Tt={name:`link`,marks:[{tag:`a`,type:`link`,attrs:{href:e=>e&&c(`href`,e)?e:null,target:e=>e===`_blank`?e:null,rel:(e,t)=>t.getAttribute(`target`)===`_blank`?`noopener noreferrer`:null}}],commands:{setLink:(e,t)=>{let n=t?.href;n&&c(`href`,n)&&e.setMark(`a`,{href:n},n)},removeLink:e=>e.removeMark(`a`)},isActive:e=>e.isMarkActive(`a`)};exports.Blockquote=vt,exports.Bold=pt,exports.Code=_t,exports.CodeBlock=yt,exports.EditorContent=ct,exports.EditorProvider=st,exports.Heading=bt,exports.Italic=mt,exports.Link=Tt,exports.OrderedList=St,exports.Strikethrough=gt,exports.TextAlign=wt,exports.Underline=ht,exports.UnorderedList=Ct,exports.block=Z,exports.mark=X,exports.toHTML=Ge,exports.toJSON=Ke,exports.useCanRedo=dt,exports.useCanUndo=ut,exports.useEditor=it,exports.useEditorContext=ot,exports.useEditorState=Y,exports.useIsActive=lt;
|
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
|
+
/** Validates attributes against the mark spec. With only a caret, inserts and marks `text`. */
|
|
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
|
+
/** Attribute rules for editing and serialization. Return a value to keep it or null to drop it. */
|
|
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 { }
|