@clarusjs/editor 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.
Files changed (56) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +9 -2
  3. package/dist/behaviours/content.d.ts +12 -0
  4. package/dist/behaviours/content.js +27 -0
  5. package/dist/behaviours/editor.d.ts +9 -0
  6. package/dist/behaviours/editor.js +8 -0
  7. package/dist/behaviours/suggestion.d.ts +50 -0
  8. package/dist/behaviours/suggestion.js +198 -0
  9. package/dist/behaviours/toolbar.d.ts +12 -0
  10. package/dist/behaviours/toolbar.js +54 -0
  11. package/dist/core/editor.d.ts +71 -0
  12. package/dist/core/editor.js +170 -0
  13. package/dist/core/extension.d.ts +44 -0
  14. package/dist/core/extension.js +3 -0
  15. package/dist/core/from-text.d.ts +11 -0
  16. package/dist/core/from-text.js +67 -0
  17. package/dist/core/length.d.ts +8 -0
  18. package/dist/core/length.js +6 -0
  19. package/dist/core/plain-text.d.ts +7 -0
  20. package/dist/core/plain-text.js +30 -0
  21. package/dist/core/registry.d.ts +18 -0
  22. package/dist/core/registry.js +50 -0
  23. package/dist/core/schema.d.ts +27 -0
  24. package/dist/core/schema.js +104 -0
  25. package/dist/emoji.d.ts +15 -0
  26. package/dist/emoji.js +8 -0
  27. package/dist/extensions/base.d.ts +5 -0
  28. package/dist/extensions/base.js +10 -0
  29. package/dist/extensions/code-block.d.ts +6 -0
  30. package/dist/extensions/code-block.js +58 -0
  31. package/dist/extensions/composer.d.ts +14 -0
  32. package/dist/extensions/composer.js +19 -0
  33. package/dist/extensions/history.d.ts +5 -0
  34. package/dist/extensions/history.js +8 -0
  35. package/dist/extensions/link.d.ts +7 -0
  36. package/dist/extensions/link.js +45 -0
  37. package/dist/extensions/markdown-shortcuts.d.ts +5 -0
  38. package/dist/extensions/markdown-shortcuts.js +23 -0
  39. package/dist/extensions/marks.d.ts +15 -0
  40. package/dist/extensions/marks.js +36 -0
  41. package/dist/extensions/mention.d.ts +6 -0
  42. package/dist/extensions/mention.js +22 -0
  43. package/dist/extensions/placeholder.d.ts +8 -0
  44. package/dist/extensions/placeholder.js +11 -0
  45. package/dist/index.d.ts +18 -0
  46. package/dist/index.js +17 -0
  47. package/dist/server.d.ts +43 -0
  48. package/dist/server.js +133 -0
  49. package/package.json +101 -3
  50. package/src/components/count.tscl +40 -0
  51. package/src/components/field.tscl +115 -0
  52. package/src/components/files.tscl +23 -0
  53. package/src/components/send.tscl +49 -0
  54. package/src/components/suggestions.tscl +66 -0
  55. package/src/components/tool.tscl +12 -0
  56. package/src/components/toolbar.tscl +34 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Felix Orinda
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,10 @@
1
- # Temporary Holding Version
1
+ # @clarusjs/editor
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A rich text editor for [clarusjs](https://clarusjs.com), on ProseMirror, in pieces you put together:
4
+
5
+ - **Parts** (headless `.tscl` islands, prefix `editor`): `<editor-field>` (a plain textarea until it's focused, then the editor), and the parts that name it with `field="id"`: `<editor-toolbar>` with `<editor-tool>`, `<editor-suggestions>` (@ mentions, / commands, : emoji), `<editor-count>`, `<editor-send>`, `<editor-files>`.
6
+ - **Behaviours** (`editor`, `toolbar`, `suggestion`, `content`) for `[use]`, to build your own.
7
+ - **The core:** `createEditor()` and plain-object extensions.
8
+ - **`@clarusjs/editor/server`:** `validate()` and `renderHTML()`, with no DOM.
9
+
10
+ Full examples to copy (a chat composer, a comment box) are on [ui.clarusjs.com](https://ui.clarusjs.com). See the [editor guide](https://clarusjs.com/guide/editor-composer).
@@ -0,0 +1,12 @@
1
+ import type { Extension } from '../core/extension.ts';
2
+ /**
3
+ * Renders `value` into `el`; returns the dispose (which empties it). A value that isn't a document renders nothing.
4
+ * @example
5
+ * <div [use]="(el) => content(el, { value: message.body, format: 'json', extensions: composerExtensions() })"></div>
6
+ * @see https://clarusjs.com/guide/editor-composer#behaviours
7
+ */
8
+ export declare function content(el: HTMLElement, options: {
9
+ value: string | object;
10
+ format: 'json' | 'html';
11
+ extensions: Extension[];
12
+ }): () => void;
@@ -0,0 +1,27 @@
1
+ import { DOMParser, DOMSerializer, Node } from 'prosemirror-model';
2
+ import { buildSchema } from '../core/schema.js';
3
+ const schemas = new WeakMap();
4
+ export function content(el, options) {
5
+ let schema = schemas.get(options.extensions);
6
+ if (!schema)
7
+ schemas.set(options.extensions, (schema = buildSchema(options.extensions)));
8
+ let doc;
9
+ try {
10
+ if (options.format === 'html') {
11
+ const body = document.implementation.createHTMLDocument('').body;
12
+ body.innerHTML = String(options.value);
13
+ doc = DOMParser.fromSchema(schema).parse(body);
14
+ }
15
+ else {
16
+ doc = Node.fromJSON(schema, typeof options.value === 'string' ? JSON.parse(options.value) : options.value);
17
+ doc.check();
18
+ if (doc.type !== schema.topNodeType)
19
+ doc = undefined;
20
+ }
21
+ }
22
+ catch {
23
+ doc = undefined;
24
+ }
25
+ el.replaceChildren(doc ? DOMSerializer.fromSchema(schema).serializeFragment(doc.content) : '');
26
+ return () => el.replaceChildren();
27
+ }
@@ -0,0 +1,9 @@
1
+ import { type EditorOptions } from '../core/editor.ts';
2
+ export { editorOf } from '../core/registry.ts';
3
+ /**
4
+ * An editor inside `el`, for `[use]`; returns the dispose.
5
+ * @example
6
+ * <div id="note" [use]="(el) => editor(el, { extensions: composerExtensions(), format: 'json' })"></div>
7
+ * @see https://clarusjs.com/guide/editor-composer#behaviours
8
+ */
9
+ export declare function editor(el: HTMLElement, options: EditorOptions): () => void;
@@ -0,0 +1,8 @@
1
+ import { createEditor } from '../core/editor.js';
2
+ import { register } from '../core/registry.js';
3
+ export { editorOf } from '../core/registry.js';
4
+ export function editor(el, options) {
5
+ const instance = createEditor({ ...options, element: el });
6
+ const unregister = register(el, instance);
7
+ return () => { unregister(); instance.destroy(); };
8
+ }
@@ -0,0 +1,50 @@
1
+ import type { Editor } from '../core/editor.ts';
2
+ import type { Emoji } from '../emoji.ts';
3
+ /**
4
+ * One suggestion: an id, the label shown, and for emoji the character.
5
+ * @see https://clarusjs.com/guide/editor-composer#suggestions
6
+ */
7
+ export type SuggestionItem = {
8
+ id: string;
9
+ label: string;
10
+ char?: string;
11
+ };
12
+ /**
13
+ * What `suggestion()` takes.
14
+ * @see https://clarusjs.com/guide/editor-composer#suggestions
15
+ */
16
+ export type SuggestionOptions = {
17
+ /** The element the `editor` behaviour runs on. */
18
+ editor: Element;
19
+ char: '@' | '/' | ':';
20
+ /** The items for what's typed after the character; `signal` aborts when a newer query replaces it. */
21
+ search(query: string, signal: AbortSignal): Promise<SuggestionItem[]> | SuggestionItem[];
22
+ /** Called with the chosen item and the range of the trigger and its query, to replace or run. */
23
+ pick(item: SuggestionItem, range: {
24
+ from: number;
25
+ to: number;
26
+ }, editor: Editor): void;
27
+ /** Characters to type after the trigger before it opens. Default 2 for ":", else 0. */
28
+ minLength?: number;
29
+ };
30
+ /**
31
+ * Suggestions on `list`, for the editor on `options.editor`; returns the dispose.
32
+ * @example
33
+ * <ul [use]="(el) => suggestion(el, { editor: field, char: '@', search: findPeople, pick: (item, range, e) => e.run('mention', item, range) })"></ul>
34
+ * @see https://clarusjs.com/guide/editor-composer#suggestions
35
+ */
36
+ export declare function suggestion(list: HTMLElement, options: SuggestionOptions): () => void;
37
+ /**
38
+ * The built-in emoji (Unicode's, with their names, groups, and GitHub's shortcodes), loaded on first call as its own
39
+ * chunk.
40
+ * @see https://clarusjs.com/guide/editor-composer#suggestions
41
+ */
42
+ export declare function loadEmoji(): Promise<Emoji[]>;
43
+ /**
44
+ * Emoji for what's typed after ":", best first: a shortcode that is it (":+1"), one that starts with it (":thumbsu"),
45
+ * a word of the name starting with it (underscores for spaces: ":thumbs_up"), then a tag (":happy").
46
+ * @example
47
+ * search: (q) => searchEmoji(q)
48
+ * @see https://clarusjs.com/guide/editor-composer#suggestions
49
+ */
50
+ export declare function searchEmoji(query: string, limit?: number): Promise<Emoji[]>;
@@ -0,0 +1,198 @@
1
+ import { position } from '@clarusjs/ui-primitives/position.js';
2
+ import { editorOf } from '../core/registry.js';
3
+ const DEBOUNCE = 200;
4
+ const HIDDEN = 'position:absolute;width:1px;height:1px;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap';
5
+ let uid = 0;
6
+ export function suggestion(list, options) {
7
+ const ed = editorOf(options.editor);
8
+ if (!ed)
9
+ throw new Error('@clarusjs/editor: suggestion() needs the element the editor behaviour runs on');
10
+ const { view } = ed;
11
+ const char = options.char;
12
+ const min = options.minLength ?? (char === ':' ? 2 : 0);
13
+ const esc = char.replace(/[/]/g, '\\$&');
14
+ const pattern = new RegExp(`(?:^|\\s)${esc}([^\\s${esc}]*)$`);
15
+ list.id ||= `cl-suggestions-${++uid}`;
16
+ list.setAttribute('role', 'listbox');
17
+ list.hidden = true;
18
+ const status = document.createElement('div');
19
+ status.setAttribute('role', 'status');
20
+ status.dataset.part = 'suggestion-status';
21
+ status.style.cssText = HIDDEN;
22
+ list.after(status);
23
+ const cache = new Map();
24
+ let range = null;
25
+ let query = null;
26
+ let items = [];
27
+ let active = 0;
28
+ let dismissed = -1;
29
+ let timer;
30
+ let controller;
31
+ let unposition;
32
+ const anchor = {
33
+ getBoundingClientRect() {
34
+ try {
35
+ const c = view.coordsAtPos(range?.from ?? view.state.selection.from);
36
+ return new DOMRect(c.left, c.top, 0, c.bottom - c.top);
37
+ }
38
+ catch {
39
+ return view.dom.getBoundingClientRect();
40
+ }
41
+ },
42
+ };
43
+ const optionId = (i) => `${list.id}-${i}`;
44
+ function render() {
45
+ list.replaceChildren(...items.map((item, i) => {
46
+ const li = document.createElement('li');
47
+ li.id = optionId(i);
48
+ li.setAttribute('role', 'option');
49
+ li.setAttribute('aria-selected', String(i === active));
50
+ li.dataset.part = 'suggestion';
51
+ li.textContent = item.char ? `${item.char} ${item.label}` : item.label;
52
+ li.addEventListener('mousedown', (e) => { e.preventDefault(); pick(i); });
53
+ return li;
54
+ }));
55
+ view.dom.setAttribute('aria-activedescendant', optionId(active));
56
+ }
57
+ function hide() {
58
+ list.hidden = true;
59
+ list.replaceChildren();
60
+ view.dom.removeAttribute('aria-controls');
61
+ view.dom.removeAttribute('aria-activedescendant');
62
+ unposition?.();
63
+ unposition = undefined;
64
+ }
65
+ function close() {
66
+ clearTimeout(timer);
67
+ controller?.abort();
68
+ controller = undefined;
69
+ range = null;
70
+ query = null;
71
+ items = [];
72
+ hide();
73
+ }
74
+ function show(next) {
75
+ items = next;
76
+ active = 0;
77
+ status.textContent = items.length ? `${items.length} result${items.length === 1 ? '' : 's'}` : 'No results';
78
+ if (!items.length)
79
+ return hide();
80
+ render();
81
+ if (list.hidden) {
82
+ list.hidden = false;
83
+ view.dom.setAttribute('aria-controls', list.id);
84
+ unposition = position(list, anchor, { side: 'bottom', align: 'start' });
85
+ }
86
+ }
87
+ function pick(i) {
88
+ const item = items[i];
89
+ const r = range;
90
+ close();
91
+ if (item && r)
92
+ options.pick(item, r, ed);
93
+ }
94
+ function match(state) {
95
+ const { $from, empty } = state.selection;
96
+ if (!empty || $from.parent.type.spec.code)
97
+ return null;
98
+ const m = pattern.exec($from.parent.textBetween(0, $from.parentOffset, undefined, (leaf) => (leaf.type.name === 'hard_break' ? '\n' : '\ufffc')));
99
+ if (!m || m[1].length < min)
100
+ return null;
101
+ return { from: $from.pos - m[1].length - 1, to: $from.pos, query: m[1] };
102
+ }
103
+ function update(state) {
104
+ const m = match(state);
105
+ if (!m)
106
+ dismissed = -1;
107
+ if (!m || m.from === dismissed)
108
+ return void (range && close());
109
+ const moved = range?.from !== m.from;
110
+ range = { from: m.from, to: m.to };
111
+ if (m.query === query) {
112
+ if (moved && !list.hidden) {
113
+ unposition?.();
114
+ unposition = position(list, anchor, { side: 'bottom', align: 'start' });
115
+ }
116
+ return;
117
+ }
118
+ query = m.query;
119
+ clearTimeout(timer);
120
+ controller?.abort();
121
+ controller = undefined;
122
+ const hit = cache.get(query);
123
+ if (hit)
124
+ return show(hit);
125
+ items = [];
126
+ hide();
127
+ const q = query;
128
+ timer = setTimeout(async () => {
129
+ const c = (controller = new AbortController());
130
+ try {
131
+ const result = await options.search(q, c.signal);
132
+ if (c !== controller)
133
+ return;
134
+ cache.set(q, result);
135
+ show(result);
136
+ }
137
+ catch (err) {
138
+ if (c.signal.aborted || c !== controller)
139
+ return;
140
+ items = [];
141
+ hide();
142
+ status.textContent = 'Search failed';
143
+ console.error('[@clarusjs/editor] search failed', err);
144
+ }
145
+ }, DEBOUNCE);
146
+ }
147
+ const remove = ed.addPlugin({
148
+ view: () => ({ update: (v) => update(v.state) }),
149
+ props: {
150
+ handleKeyDown(v, event) {
151
+ if (list.hidden || !items.length)
152
+ return false;
153
+ if (event.isComposing || event.keyCode === 229 || v.composing)
154
+ return false;
155
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
156
+ active = (active + (event.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length;
157
+ render();
158
+ return true;
159
+ }
160
+ if (event.key === 'Enter' || event.key === 'Tab') {
161
+ pick(active);
162
+ return true;
163
+ }
164
+ if (event.key === 'Escape') {
165
+ dismissed = range.from;
166
+ close();
167
+ return true;
168
+ }
169
+ return false;
170
+ },
171
+ },
172
+ });
173
+ return () => {
174
+ close();
175
+ status.remove();
176
+ remove();
177
+ };
178
+ }
179
+ let emojiList;
180
+ export function loadEmoji() {
181
+ return (emojiList ??= import('../emoji.js').then((m) => m.emoji));
182
+ }
183
+ export async function searchEmoji(query, limit = 8) {
184
+ const q = query.toLowerCase();
185
+ const words = ' ' + q.replace(/_/g, ' ');
186
+ const rank = (e) => e.aliases.includes(q) ? 0
187
+ : e.aliases.some((a) => a.startsWith(q)) ? 1
188
+ : (' ' + e.name).includes(words) ? 2
189
+ : e.tags.some((t) => t.startsWith(q)) ? 3
190
+ : 4;
191
+ const found = [];
192
+ for (const e of await loadEmoji()) {
193
+ const r = rank(e);
194
+ if (r < 4)
195
+ found.push([r, e]);
196
+ }
197
+ return found.sort((a, b) => a[0] - b[0]).slice(0, limit).map(([, e]) => e);
198
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * A toolbar for the editor on `options.editor`; returns the dispose. The `link` button asks for an address, or
3
+ * unlinks when a link is selected.
4
+ * @example
5
+ * <div aria-label="Formatting" [use]="(el) => toolbar(el, { editor: field })">
6
+ * <button type="button" data-command="bold" aria-label="Bold">B</button>
7
+ * </div>
8
+ * @see https://clarusjs.com/guide/editor-composer#behaviours
9
+ */
10
+ export declare function toolbar(el: HTMLElement, options: {
11
+ editor: Element;
12
+ }): () => void;
@@ -0,0 +1,54 @@
1
+ import { rovingFocus } from '@clarusjs/ui-primitives/roving-focus.js';
2
+ import { effect } from 'clarusjs/runtime';
3
+ import { editorOf } from '../core/registry.js';
4
+ export function toolbar(el, options) {
5
+ const ed = editorOf(options.editor);
6
+ if (!ed)
7
+ throw new Error('@clarusjs/editor: toolbar() needs the element the editor behaviour runs on');
8
+ if (!el.hasAttribute('role'))
9
+ el.setAttribute('role', 'toolbar');
10
+ const buttons = () => [...el.querySelectorAll('button[data-command]')];
11
+ const stopRoving = rovingFocus(el, { orientation: 'horizontal' });
12
+ const down = (e) => { if (e.target.closest('button[data-command]'))
13
+ e.preventDefault(); };
14
+ const click = (e) => {
15
+ const button = e.target.closest('button[data-command]');
16
+ if (!button || !el.contains(button))
17
+ return;
18
+ const command = button.dataset.command;
19
+ if (command === 'link') {
20
+ if (ed.active('link'))
21
+ ed.run('unlink');
22
+ else {
23
+ const href = prompt('Link address');
24
+ if (href)
25
+ ed.run('link', href.trim());
26
+ }
27
+ }
28
+ else
29
+ ed.run(command);
30
+ ed.focus();
31
+ };
32
+ el.addEventListener('mousedown', down);
33
+ el.addEventListener('click', click);
34
+ const stop = effect(() => {
35
+ ed.state.get();
36
+ for (const b of buttons()) {
37
+ const command = b.dataset.command;
38
+ b.setAttribute('aria-pressed', String(ed.active(command)));
39
+ b.disabled = command === 'link' ? false : !ed.can(command);
40
+ }
41
+ const all = buttons();
42
+ if (!all.some((b) => b.tabIndex === 0 && !b.disabled)) {
43
+ const first = all.find((b) => !b.disabled);
44
+ for (const b of all)
45
+ b.tabIndex = b === first ? 0 : -1;
46
+ }
47
+ });
48
+ return () => {
49
+ stop();
50
+ stopRoving();
51
+ el.removeEventListener('mousedown', down);
52
+ el.removeEventListener('click', click);
53
+ };
54
+ }
@@ -0,0 +1,71 @@
1
+ import { type ReadSignal, type Signal } from 'clarusjs/runtime';
2
+ import { type Schema } from 'prosemirror-model';
3
+ import { EditorState, type PluginSpec } from 'prosemirror-state';
4
+ import { EditorView } from 'prosemirror-view';
5
+ import type { Extension } from './extension.ts';
6
+ /**
7
+ * What `createEditor()` takes.
8
+ * @see https://clarusjs.com/guide/editor-composer#the-core
9
+ */
10
+ export type EditorOptions = {
11
+ extensions: Extension[];
12
+ /** How the value is given and emitted: ProseMirror JSON, or HTML. */
13
+ format: 'json' | 'html';
14
+ value?: string | object;
15
+ /** Start from plain text instead (a textarea's, with its caret): blank lines make paragraphs. */
16
+ text?: {
17
+ value: string;
18
+ caret?: number;
19
+ };
20
+ /** With value: where the cursor starts, as an offset into the value's plain text (a textarea's caret). */
21
+ caret?: number;
22
+ editable?: boolean;
23
+ /** The editable's accessible name. */
24
+ label?: string;
25
+ /** Called with the value when the user sends (Enter, or Mod-Enter); the editor then clears, unless it returns false. */
26
+ onSend?(value: string | object): boolean | void;
27
+ /** Enter sends and Shift+Enter is a new line (the default), or Enter is a new line and Mod-Enter sends. */
28
+ enterSends?: boolean;
29
+ maxLength?: number;
30
+ /** Called with files pasted or dropped in; they don't go into the document. */
31
+ onFiles?(files: File[]): void;
32
+ };
33
+ /**
34
+ * A running editor.
35
+ * @see https://clarusjs.com/guide/editor-composer#the-core
36
+ */
37
+ export type Editor = {
38
+ /** The value in the chosen format; setting it replaces the document. */
39
+ value: Signal<string | object>;
40
+ /** The length in graphemes, a mention counting as its label. */
41
+ length: ReadSignal<number>;
42
+ /** The limit (maxLength), if any, and whether the length is past it. */
43
+ maxLength: number | undefined;
44
+ over: ReadSignal<boolean>;
45
+ /** The ProseMirror state, after every change (the selection's too): for toolbars. */
46
+ state: ReadSignal<EditorState>;
47
+ /** Runs a command by name (`bold`, `link`, `undo`…), with its arguments: false when it can't run. */
48
+ run(name: string, ...args: unknown[]): boolean;
49
+ can(name: string, ...args: unknown[]): boolean;
50
+ /** Whether a mark or block is active at the selection, by command name (`bold`) or mark or node name (`strong`). */
51
+ active(name: string): boolean;
52
+ /** Adds a ProseMirror plugin, before the editor's own (its keys come first); returns how to remove it. */
53
+ addPlugin(spec: PluginSpec<any>): () => void;
54
+ focus(): void;
55
+ clear(): void;
56
+ /** Sends unless empty or over the limit: calls `onSend`, clears (unless it returned false), and returns true. */
57
+ send(): boolean;
58
+ destroy(): void;
59
+ view: EditorView;
60
+ schema: Schema;
61
+ };
62
+ /**
63
+ * Creates an editor inside `element`.
64
+ * @example
65
+ * const editor = createEditor({ element, extensions: composerExtensions(), format: 'json', onSend: post })
66
+ * effect(() => console.log(editor.length.get()))
67
+ * @see https://clarusjs.com/guide/editor-composer#the-core
68
+ */
69
+ export declare function createEditor(options: EditorOptions & {
70
+ element: HTMLElement;
71
+ }): Editor;
@@ -0,0 +1,170 @@
1
+ import { derived, effect, state } from 'clarusjs/runtime';
2
+ import { baseKeymap, chainCommands, newlineInCode } from 'prosemirror-commands';
3
+ import { inputRules } from 'prosemirror-inputrules';
4
+ import { keymap } from 'prosemirror-keymap';
5
+ import { DOMParser, DOMSerializer, Node } from 'prosemirror-model';
6
+ import { EditorState, Plugin, Selection, TextSelection } from 'prosemirror-state';
7
+ import { EditorView } from 'prosemirror-view';
8
+ import { docLength } from './length.js';
9
+ import { fromText, posAtOffset } from './from-text.js';
10
+ import { buildSchema } from './schema.js';
11
+ const safari = () => typeof navigator !== 'undefined' && /Apple Computer/.test(navigator.vendor);
12
+ const same = (a, b) => a === b || (typeof a === 'object' && typeof b === 'object' && a !== null && b !== null && JSON.stringify(a) === JSON.stringify(b));
13
+ const ALIASES = { bold: 'strong', italic: 'em', codeBlock: 'code_block' };
14
+ export function createEditor(options) {
15
+ const { extensions, format, enterSends = true, maxLength } = options;
16
+ const editable = options.editable !== false;
17
+ const schema = buildSchema(extensions);
18
+ const commands = Object.assign(Object.create(null), ...extensions.map((e) => e.commands?.(schema) ?? {}));
19
+ const parse = (value) => {
20
+ if (value === undefined || value === '')
21
+ return schema.topNodeType.createAndFill();
22
+ if (format === 'json')
23
+ return Node.fromJSON(schema, typeof value === 'string' ? JSON.parse(value) : value);
24
+ const body = document.implementation.createHTMLDocument('').body;
25
+ body.innerHTML = String(value);
26
+ return DOMParser.fromSchema(schema).parse(body);
27
+ };
28
+ const serialize = (doc) => {
29
+ if (format === 'json')
30
+ return doc.toJSON();
31
+ const div = document.createElement('div');
32
+ div.append(DOMSerializer.fromSchema(schema).serializeFragment(doc.content));
33
+ return div.innerHTML;
34
+ };
35
+ const isBlank = (doc) => doc.textBetween(0, doc.content.size, '\n', (n) => n.type.spec.leafText?.(n) ?? '').trim() === '';
36
+ const hardBreak = (s, dispatch) => {
37
+ if (!schema.nodes.hard_break)
38
+ return false;
39
+ dispatch?.(s.tr.replaceSelectionWith(schema.nodes.hard_break.create()).scrollIntoView());
40
+ return true;
41
+ };
42
+ const newLine = chainCommands(newlineInCode, hardBreak);
43
+ let compositionEnd = 0;
44
+ const enter = new Plugin({
45
+ props: {
46
+ handleDOMEvents: { compositionend: () => { compositionEnd = Date.now(); return false; } },
47
+ handleKeyDown(view, event) {
48
+ if (event.key !== 'Enter')
49
+ return false;
50
+ if (event.isComposing || event.keyCode === 229 || view.composing)
51
+ return false;
52
+ if (safari() && Date.now() - compositionEnd < 500) {
53
+ compositionEnd = 0;
54
+ return true;
55
+ }
56
+ if (event.shiftKey)
57
+ return newLine(view.state, view.dispatch);
58
+ if (event.ctrlKey || event.metaKey) {
59
+ send();
60
+ return true;
61
+ }
62
+ if (!enterSends || view.state.selection.$from.parent.type.spec.code)
63
+ return baseKeymap.Enter(view.state, view.dispatch, view);
64
+ send();
65
+ return true;
66
+ },
67
+ },
68
+ });
69
+ const { Enter: _enter, 'Mod-Enter': _modEnter, ...baseKeys } = baseKeymap;
70
+ const rules = extensions.flatMap((e) => e.inputRules?.(schema) ?? []);
71
+ const plugins = [
72
+ enter,
73
+ ...(rules.length ? [inputRules({ rules })] : []),
74
+ ...extensions.map((e) => keymap(e.keys?.(schema) ?? {})),
75
+ keymap(baseKeys),
76
+ ...extensions.flatMap((e) => e.plugins?.(schema) ?? []),
77
+ ];
78
+ const start = options.text ? fromText(schema, options.text.value, options.text.caret) : (() => {
79
+ const doc = parse(options.value);
80
+ return { doc, pos: options.caret === undefined ? undefined : posAtOffset(doc, options.caret) };
81
+ })();
82
+ const initial = EditorState.create({
83
+ schema, plugins, doc: start.doc,
84
+ selection: start.pos === undefined ? (options.text ? Selection.atEnd(start.doc) : undefined) : TextSelection.create(start.doc, start.pos),
85
+ });
86
+ let lastEmitted = serialize(initial.doc);
87
+ const value = state(lastEmitted);
88
+ const length = state(docLength(initial.doc));
89
+ const current = state(initial);
90
+ const files = (list) => {
91
+ const all = Array.from(list ?? []);
92
+ if (!all.length || !options.onFiles)
93
+ return false;
94
+ options.onFiles(all);
95
+ return true;
96
+ };
97
+ const view = new EditorView(options.element, {
98
+ state: initial,
99
+ editable: () => editable,
100
+ attributes: { role: 'textbox', 'aria-multiline': 'true', ...(options.label ? { 'aria-label': options.label } : {}), ...(editable ? {} : { 'aria-readonly': 'true' }) },
101
+ handlePaste: (_view, event) => files(event.clipboardData?.files),
102
+ handleDrop: (_view, event) => files(event.dataTransfer?.files),
103
+ dispatchTransaction(tr) {
104
+ const before = view.state.doc;
105
+ view.updateState(view.state.apply(tr));
106
+ if (view.state.doc !== before) {
107
+ lastEmitted = serialize(view.state.doc);
108
+ length.set(docLength(view.state.doc));
109
+ value.set(lastEmitted);
110
+ }
111
+ current.set(view.state);
112
+ },
113
+ });
114
+ const replace = (doc, history = true) => {
115
+ const tr = view.state.tr.replaceWith(0, view.state.doc.content.size, doc.content);
116
+ if (!history)
117
+ tr.setMeta('addToHistory', false);
118
+ view.dispatch(tr);
119
+ };
120
+ const stop = effect(() => {
121
+ const v = value.get();
122
+ if (!same(v, lastEmitted))
123
+ replace(parse(v), false);
124
+ });
125
+ const clear = () => replace(schema.topNodeType.createAndFill());
126
+ const send = () => {
127
+ const doc = view.state.doc;
128
+ if (isBlank(doc) || (maxLength !== undefined && docLength(doc) > maxLength))
129
+ return false;
130
+ if (options.onSend?.(value.get()) === false)
131
+ return false;
132
+ clear();
133
+ return true;
134
+ };
135
+ const command = (name, args) => commands[name]?.(...args);
136
+ return {
137
+ value,
138
+ length,
139
+ maxLength,
140
+ over: derived(() => maxLength !== undefined && length.get() > maxLength),
141
+ state: current,
142
+ view,
143
+ schema,
144
+ run: (name, ...args) => command(name, args)?.(view.state, view.dispatch, view) ?? false,
145
+ can: (name, ...args) => command(name, args)?.(view.state) ?? false,
146
+ active(name) {
147
+ const n = ALIASES[name] ?? name;
148
+ const { $from, from, to, empty } = view.state.selection;
149
+ const mark = schema.marks[n];
150
+ if (mark)
151
+ return empty ? !!mark.isInSet(view.state.storedMarks ?? $from.marks()) : view.state.doc.rangeHasMark(from, to, mark);
152
+ return schema.nodes[n] ? $from.parent.type === schema.nodes[n] : false;
153
+ },
154
+ addPlugin(spec) {
155
+ const plugin = new Plugin(spec);
156
+ view.updateState(view.state.reconfigure({ plugins: [plugin, ...view.state.plugins] }));
157
+ current.set(view.state);
158
+ return () => {
159
+ if (view.isDestroyed)
160
+ return;
161
+ view.updateState(view.state.reconfigure({ plugins: view.state.plugins.filter((p) => p !== plugin) }));
162
+ current.set(view.state);
163
+ };
164
+ },
165
+ focus: () => view.focus(),
166
+ clear,
167
+ send,
168
+ destroy() { stop(); view.destroy(); },
169
+ };
170
+ }