@clarusjs/editor 0.0.0 → 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 (55) hide show
  1. package/README.md +8 -1
  2. package/dist/behaviours/content.d.ts +12 -0
  3. package/dist/behaviours/content.js +27 -0
  4. package/dist/behaviours/editor.d.ts +9 -0
  5. package/dist/behaviours/editor.js +8 -0
  6. package/dist/behaviours/suggestion.d.ts +50 -0
  7. package/dist/behaviours/suggestion.js +198 -0
  8. package/dist/behaviours/toolbar.d.ts +12 -0
  9. package/dist/behaviours/toolbar.js +54 -0
  10. package/dist/core/editor.d.ts +71 -0
  11. package/dist/core/editor.js +170 -0
  12. package/dist/core/extension.d.ts +44 -0
  13. package/dist/core/extension.js +3 -0
  14. package/dist/core/from-text.d.ts +11 -0
  15. package/dist/core/from-text.js +67 -0
  16. package/dist/core/length.d.ts +8 -0
  17. package/dist/core/length.js +6 -0
  18. package/dist/core/plain-text.d.ts +7 -0
  19. package/dist/core/plain-text.js +30 -0
  20. package/dist/core/registry.d.ts +18 -0
  21. package/dist/core/registry.js +50 -0
  22. package/dist/core/schema.d.ts +27 -0
  23. package/dist/core/schema.js +104 -0
  24. package/dist/emoji.d.ts +15 -0
  25. package/dist/emoji.js +8 -0
  26. package/dist/extensions/base.d.ts +5 -0
  27. package/dist/extensions/base.js +10 -0
  28. package/dist/extensions/code-block.d.ts +6 -0
  29. package/dist/extensions/code-block.js +58 -0
  30. package/dist/extensions/composer.d.ts +14 -0
  31. package/dist/extensions/composer.js +19 -0
  32. package/dist/extensions/history.d.ts +5 -0
  33. package/dist/extensions/history.js +8 -0
  34. package/dist/extensions/link.d.ts +7 -0
  35. package/dist/extensions/link.js +45 -0
  36. package/dist/extensions/markdown-shortcuts.d.ts +5 -0
  37. package/dist/extensions/markdown-shortcuts.js +23 -0
  38. package/dist/extensions/marks.d.ts +15 -0
  39. package/dist/extensions/marks.js +36 -0
  40. package/dist/extensions/mention.d.ts +6 -0
  41. package/dist/extensions/mention.js +22 -0
  42. package/dist/extensions/placeholder.d.ts +8 -0
  43. package/dist/extensions/placeholder.js +11 -0
  44. package/dist/index.d.ts +18 -0
  45. package/dist/index.js +17 -0
  46. package/dist/server.d.ts +43 -0
  47. package/dist/server.js +133 -0
  48. package/package.json +98 -4
  49. package/src/components/count.tscl +40 -0
  50. package/src/components/field.tscl +115 -0
  51. package/src/components/files.tscl +23 -0
  52. package/src/components/send.tscl +49 -0
  53. package/src/components/suggestions.tscl +66 -0
  54. package/src/components/tool.tscl +12 -0
  55. package/src/components/toolbar.tscl +34 -0
@@ -0,0 +1,44 @@
1
+ import type { InputRule } from 'prosemirror-inputrules';
2
+ import type { DOMOutputSpec, MarkSpec as PMMarkSpec, Mark, Node, NodeSpec as PMNodeSpec, Schema } from 'prosemirror-model';
3
+ import type { Command, Plugin } from 'prosemirror-state';
4
+ /**
5
+ * A node type: ProseMirror's NodeSpec, with `render` (a DOM-free description of its HTML, used in the browser and to
6
+ * render on the server) in place of `toDOM`. Text nodes have none: they are their text.
7
+ * @see https://clarusjs.com/guide/editor-composer#extensions
8
+ */
9
+ export type NodeSpec = PMNodeSpec & {
10
+ render?: (node: Node) => DOMOutputSpec;
11
+ };
12
+ /**
13
+ * A mark type: ProseMirror's MarkSpec, with `render` in place of `toDOM`.
14
+ * @see https://clarusjs.com/guide/editor-composer#extensions
15
+ */
16
+ export type MarkSpec = PMMarkSpec & {
17
+ render: (mark: Mark, inline: boolean) => DOMOutputSpec;
18
+ };
19
+ /**
20
+ * An editor extension: the nodes and marks it adds to the schema, its commands (by name), keys, input rules and
21
+ * ProseMirror plugins, and the extensions it needs or can't be used with.
22
+ * @example
23
+ * const highlight = defineExtension({ name: 'highlight', marks: { highlight: { render: () => ['mark', 0] } } })
24
+ * @see https://clarusjs.com/guide/editor-composer#extensions
25
+ */
26
+ export type Extension = {
27
+ name: string;
28
+ nodes?: Record<string, NodeSpec>;
29
+ marks?: Record<string, MarkSpec>;
30
+ /** Commands by name: each takes arguments and returns a ProseMirror command, built for the editor's schema. */
31
+ commands?: (schema: Schema) => Record<string, (...args: any[]) => Command>;
32
+ keys?: (schema: Schema) => Record<string, Command>;
33
+ inputRules?: (schema: Schema) => InputRule[];
34
+ plugins?: (schema: Schema) => Plugin[];
35
+ requires?: string[];
36
+ conflicts?: string[];
37
+ };
38
+ /**
39
+ * An extension, typed. Plain data in, the same object out.
40
+ * @example
41
+ * const bold = defineExtension({ name: 'bold', marks: { strong: { render: () => ['strong', 0] } } })
42
+ * @see https://clarusjs.com/guide/editor-composer#extensions
43
+ */
44
+ export declare function defineExtension(extension: Extension): Extension;
@@ -0,0 +1,3 @@
1
+ export function defineExtension(extension) {
2
+ return extension;
3
+ }
@@ -0,0 +1,11 @@
1
+ import type { Node, Schema } from 'prosemirror-model';
2
+ /** A document from plain text (blank lines apart: paragraphs; a line break: a hard break), and where `caret` falls. */
3
+ export declare function fromText(schema: Schema, text: string, caret?: number): {
4
+ doc: Node;
5
+ pos?: number;
6
+ };
7
+ /**
8
+ * The position in `doc` for an offset into its plain text, counted as plainText() counts it (blocks apart by a blank
9
+ * line, a hard break one character, a mention its "@label"): where a textarea's caret goes in the rich document.
10
+ */
11
+ export declare function posAtOffset(doc: Node, offset: number): number;
@@ -0,0 +1,67 @@
1
+ export function fromText(schema, text, caret) {
2
+ if (text.includes('\r')) {
3
+ if (caret !== undefined)
4
+ caret -= (text.slice(0, caret).match(/\r\n/g) ?? []).length;
5
+ text = text.replace(/\r\n?/g, '\n');
6
+ }
7
+ const blocks = [[]];
8
+ let buf = '';
9
+ let pos = 1;
10
+ let at;
11
+ const flush = () => { if (buf)
12
+ blocks[blocks.length - 1].push(schema.text(buf)); buf = ''; };
13
+ for (let i = 0; i < text.length;) {
14
+ if (i === caret)
15
+ at = pos;
16
+ if (text.startsWith('\n\n', i)) {
17
+ if (caret === i + 1)
18
+ at = pos;
19
+ flush();
20
+ blocks.push([]);
21
+ pos += 2;
22
+ i += 2;
23
+ }
24
+ else if (text[i] === '\n') {
25
+ flush();
26
+ blocks[blocks.length - 1].push(schema.nodes.hard_break.create());
27
+ pos += 1;
28
+ i += 1;
29
+ }
30
+ else {
31
+ buf += text[i];
32
+ pos += 1;
33
+ i += 1;
34
+ }
35
+ }
36
+ if (caret !== undefined && caret >= text.length)
37
+ at = pos;
38
+ flush();
39
+ return { doc: schema.node('doc', null, blocks.map((b) => schema.node('paragraph', null, b))), pos: at };
40
+ }
41
+ export function posAtOffset(doc, offset) {
42
+ let left = Math.max(0, offset);
43
+ let blockStart = 0;
44
+ let end = 1;
45
+ for (let i = 0; i < doc.childCount; i++) {
46
+ const block = doc.child(i);
47
+ if (i > 0) {
48
+ if (left < 2)
49
+ return end;
50
+ left -= 2;
51
+ }
52
+ let p = blockStart + 1;
53
+ for (let j = 0; j < block.childCount; j++) {
54
+ const child = block.child(j);
55
+ const len = child.isText ? child.text.length : child.type.name === 'hard_break' ? 1 : (child.type.spec.leafText?.(child) ?? '').length;
56
+ if (left <= len)
57
+ return child.isText ? p + left : left === 0 ? p : p + child.nodeSize;
58
+ left -= len;
59
+ p += child.nodeSize;
60
+ }
61
+ end = p;
62
+ if (left === 0)
63
+ return end;
64
+ blockStart += block.nodeSize;
65
+ }
66
+ return end;
67
+ }
@@ -0,0 +1,8 @@
1
+ import type { Node } from 'prosemirror-model';
2
+ /**
3
+ * The length of a document, in graphemes.
4
+ * @example
5
+ * length(editor.state.doc) // 3 for "👨‍👩‍👧ab"
6
+ * @see https://clarusjs.com/guide/editor-composer#limits
7
+ */
8
+ export declare function docLength(doc: Node): number;
@@ -0,0 +1,6 @@
1
+ const segmenter = typeof Intl !== 'undefined' && 'Segmenter' in Intl ? new Intl.Segmenter(undefined, { granularity: 'grapheme' }) : undefined;
2
+ const graphemes = (text) => (segmenter ? [...segmenter.segment(text)].length : [...text].length);
3
+ const leafText = (leaf) => (leaf.type.name === 'mention' ? String(leaf.attrs.label ?? '') : leaf.type.name === 'hard_break' ? '\n' : '');
4
+ export function docLength(doc) {
5
+ return graphemes(doc.textBetween(0, doc.content.size, '\n', leafText));
6
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * The plain text of a value in `format`.
3
+ * @example
4
+ * plainText('<p>Hi</p><p>there</p>', 'html') // 'Hi\n\nthere'
5
+ * @see https://clarusjs.com/guide/editor-composer#loading
6
+ */
7
+ export declare function plainText(value: unknown, format: 'json' | 'html'): string;
@@ -0,0 +1,30 @@
1
+ const inline = (node) => node.type === 'text' ? node.text ?? ''
2
+ : node.type === 'hard_break' ? '\n'
3
+ : node.type === 'mention' ? `@${node.attrs?.label ?? ''}`
4
+ : (node.content ?? []).map(inline).join('');
5
+ const ENTITIES = { lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' };
6
+ const char = (n) => (n > 0x10ffff || (n >= 0xd800 && n <= 0xdfff) || n === 0 ? '\uFFFD' : String.fromCodePoint(n));
7
+ const decode = (s) => s.replace(/&(#x[\da-f]+|#\d+|[a-z]+);/gi, (m, e) => e[0] === '#' ? char(e[1] === 'x' || e[1] === 'X' ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10))
8
+ : e.toLowerCase() === 'amp' ? '&' : ENTITIES[e.toLowerCase()] ?? m);
9
+ export function plainText(value, format) {
10
+ if (value == null || value === '')
11
+ return '';
12
+ if (format === 'json') {
13
+ try {
14
+ const doc = (typeof value === 'string' ? JSON.parse(value) : value);
15
+ return Array.isArray(doc.content) ? doc.content.map(inline).join('\n\n') : '';
16
+ }
17
+ catch {
18
+ return '';
19
+ }
20
+ }
21
+ const text = String(value)
22
+ .replace(/(<\/(?:p|pre|h[1-6]|li|blockquote|div)>)\s+/gi, '$1')
23
+ .replace(/<br\s*\/?>/gi, '\n')
24
+ .replace(/<\/(p|pre|h[1-6]|li|blockquote|div)>/gi, '\u0000')
25
+ .replace(/<[^>]*>/g, '');
26
+ const blocks = decode(text).split('\u0000');
27
+ if (blocks.length > 1 && blocks[blocks.length - 1] === '')
28
+ blocks.pop();
29
+ return blocks.join('\n\n');
30
+ }
@@ -0,0 +1,18 @@
1
+ import type { Editor } from './editor.ts';
2
+ type Wire = (editor: Editor, el: Element) => (() => void) | void;
3
+ /** Records the editor on `el` and wires the parts waiting for its id; returns how to unrecord it (unwiring them). */
4
+ export declare function register(el: Element, editor: Editor): () => void;
5
+ /**
6
+ * The editor running on `el`, if any.
7
+ * @see https://clarusjs.com/guide/editor-composer#behaviours
8
+ */
9
+ export declare function editorOf(el: Element): Editor | undefined;
10
+ /**
11
+ * Wires `wire` to the editor of the field with this id: now if it exists, else when it does. What `wire` returns is
12
+ * called when that editor goes (and `wire` runs again if one comes back). Returns how to stop.
13
+ * @example
14
+ * onEditor('msg', (editor) => effect(() => (count = editor.length.get())))
15
+ * @see https://clarusjs.com/guide/editor-composer#parts
16
+ */
17
+ export declare function onEditor(id: string, wire: Wire): () => void;
18
+ export {};
@@ -0,0 +1,50 @@
1
+ const instances = new WeakMap();
2
+ const ids = new WeakMap();
3
+ const newest = new Map();
4
+ const waiting = new Map();
5
+ const unwire = (w) => {
6
+ w.undo?.();
7
+ w.undo = undefined;
8
+ w.el = undefined;
9
+ };
10
+ export function register(el, editor) {
11
+ const id = el.id;
12
+ instances.set(el, editor);
13
+ ids.set(el, id);
14
+ newest.set(id, el);
15
+ for (const w of waiting.get(id) ?? []) {
16
+ unwire(w);
17
+ w.el = el;
18
+ w.undo = w.wire(editor, el);
19
+ }
20
+ return () => {
21
+ instances.delete(el);
22
+ ids.delete(el);
23
+ if (newest.get(id) === el)
24
+ newest.delete(id);
25
+ for (const w of waiting.get(id) ?? [])
26
+ if (w.el === el)
27
+ unwire(w);
28
+ };
29
+ }
30
+ export function editorOf(el) {
31
+ return instances.get(el);
32
+ }
33
+ export function onEditor(id, wire) {
34
+ const w = { wire };
35
+ let set = waiting.get(id);
36
+ if (!set)
37
+ waiting.set(id, (set = new Set()));
38
+ set.add(w);
39
+ const el = newest.get(id);
40
+ const editor = el && instances.get(el);
41
+ if (el && editor && el.isConnected) {
42
+ w.el = el;
43
+ w.undo = wire(editor, el);
44
+ }
45
+ return () => {
46
+ if (set.delete(w) && !set.size && waiting.get(id) === set)
47
+ waiting.delete(id);
48
+ unwire(w);
49
+ };
50
+ }
@@ -0,0 +1,27 @@
1
+ import { Schema, type DOMOutputSpec } from 'prosemirror-model';
2
+ import type { Extension } from './extension.ts';
3
+ export { defineExtension, type Extension, type MarkSpec, type NodeSpec } from './extension.ts';
4
+ export declare const TAG_NAME: RegExp;
5
+ export declare const ATTR_NAME: RegExp;
6
+ /** A tag or attribute name without its namespace URI (what HTML writes). */
7
+ export declare const localName: (name: string) => string;
8
+ /**
9
+ * The attribute whose value (or something inside it) a render spec uses as part of the spec itself: a document could
10
+ * then write elements and attributes of its choosing. Undefined when none does.
11
+ */
12
+ export declare function attrInSpec(spec: unknown, attrs: Record<string, unknown> | undefined): string | undefined;
13
+ /**
14
+ * A render spec made safe: a part that came from the node's own attributes renders nothing, unsafe tags render
15
+ * nothing, attributes that run script are dropped, and every attribute goes through clarusjs's attribute check
16
+ * (URLs refused as templates refuse them), in the browser as on the server.
17
+ */
18
+ export declare function safeSpec(spec: DOMOutputSpec, attrs?: Record<string, unknown>): DOMOutputSpec;
19
+ /**
20
+ * The ProseMirror schema for `extensions`: their nodes (in order; the first is the top node unless one is `doc`) and
21
+ * marks, each `render` used as `toDOM`. A missing `requires`, a `conflicts` pair, or a node or mark two extensions
22
+ * both define is an error naming them.
23
+ * @example
24
+ * const schema = buildSchema(composerExtensions())
25
+ * @see https://clarusjs.com/guide/editor-composer#extensions
26
+ */
27
+ export declare function buildSchema(extensions: Extension[]): Schema;
@@ -0,0 +1,104 @@
1
+ import { attrValue } from 'clarusjs/runtime';
2
+ import { Schema } from 'prosemirror-model';
3
+ export { defineExtension } from './extension.js';
4
+ const fail = (message) => { throw new Error(`@clarusjs/editor: ${message}`); };
5
+ const UNSAFE_TAGS = new Set(['script', 'style', 'iframe', 'frame', 'frameset', 'object', 'embed', 'link', 'meta', 'base', 'template', 'noscript']);
6
+ const UNSAFE_ATTR = /^(on|srcdoc$|formaction$)/i;
7
+ export const TAG_NAME = /^(?:[a-zA-Z][a-zA-Z0-9+.-]*:\S+ )?[a-zA-Z][a-zA-Z0-9-]*$/;
8
+ export const ATTR_NAME = /^(?:[a-zA-Z][a-zA-Z0-9+.-]*:\S+ )?[a-zA-Z_:][a-zA-Z0-9_:.-]*$/;
9
+ export const localName = (name) => name.slice(name.lastIndexOf(' ') + 1);
10
+ const hasHole = (s) => s === 0 || (Array.isArray(s) && s.some(hasHole));
11
+ function attrObjects(attrs) {
12
+ const found = new Map();
13
+ const walk = (v, key) => {
14
+ if (!v || typeof v !== 'object' || found.has(v))
15
+ return;
16
+ found.set(v, key);
17
+ for (const x of Object.values(v))
18
+ walk(x, key);
19
+ };
20
+ for (const [key, v] of Object.entries(attrs ?? {}))
21
+ walk(v, key);
22
+ return found;
23
+ }
24
+ export function attrInSpec(spec, attrs) {
25
+ const from = attrObjects(attrs);
26
+ if (!from.size)
27
+ return undefined;
28
+ const walk = (s) => {
29
+ if (!s || typeof s !== 'object')
30
+ return undefined;
31
+ if (from.has(s))
32
+ return from.get(s);
33
+ return Array.isArray(s) ? s.reduce((hit, c) => hit ?? walk(c), undefined) : undefined;
34
+ };
35
+ return walk(spec);
36
+ }
37
+ export function safeSpec(spec, attrs) {
38
+ const from = attrObjects(attrs);
39
+ const clean = (s) => {
40
+ if (typeof s === 'string')
41
+ return s;
42
+ if (s && typeof s === 'object' && from.has(s))
43
+ return '';
44
+ const refused = () => (hasHole(s) ? ['span', 0] : ['span']);
45
+ if (!Array.isArray(s))
46
+ return s;
47
+ const [tag, ...rest] = s;
48
+ if (typeof tag !== 'string' || !TAG_NAME.test(tag) || UNSAFE_TAGS.has(localName(tag).toLowerCase()))
49
+ return refused();
50
+ const out = [tag];
51
+ rest.forEach((child, i) => {
52
+ if (i === 0 && child && typeof child === 'object' && !Array.isArray(child) && !from.has(child)) {
53
+ const kept = {};
54
+ for (const [name, value] of Object.entries(child)) {
55
+ if (!ATTR_NAME.test(name) || UNSAFE_ATTR.test(localName(name)) || (value && typeof value === 'object'))
56
+ continue;
57
+ const v = attrValue(localName(name), value, localName(tag));
58
+ if (v !== null)
59
+ kept[name] = v === true ? '' : v;
60
+ }
61
+ out.push(kept);
62
+ }
63
+ else if (i === 0 && child && typeof child === 'object' && !Array.isArray(child))
64
+ out.push({});
65
+ else
66
+ out.push(child === 0 ? 0 : clean(child));
67
+ });
68
+ return out;
69
+ };
70
+ return clean(spec);
71
+ }
72
+ export function buildSchema(extensions) {
73
+ const names = new Set(extensions.map((e) => e.name));
74
+ for (const e of extensions) {
75
+ for (const r of e.requires ?? [])
76
+ if (!names.has(r))
77
+ fail(`"${e.name}" requires "${r}"`);
78
+ for (const c of e.conflicts ?? [])
79
+ if (names.has(c))
80
+ fail(`"${e.name}" conflicts with "${c}"`);
81
+ }
82
+ const nodes = {};
83
+ const marks = {};
84
+ const nodeOwner = new Map();
85
+ const markOwner = new Map();
86
+ for (const e of extensions) {
87
+ for (const [name, spec] of Object.entries(e.nodes ?? {})) {
88
+ if (nodeOwner.has(name))
89
+ fail(`"${e.name}" and "${nodeOwner.get(name)}" both define the node "${name}"`);
90
+ nodeOwner.set(name, e.name);
91
+ const { render, ...rest } = spec;
92
+ nodes[name] = render ? { ...rest, render, toDOM: (node) => safeSpec(render(node), node.attrs) } : rest;
93
+ }
94
+ for (const [name, spec] of Object.entries(e.marks ?? {})) {
95
+ if (markOwner.has(name))
96
+ fail(`"${e.name}" and "${markOwner.get(name)}" both define the mark "${name}"`);
97
+ markOwner.set(name, e.name);
98
+ const { render, ...rest } = spec;
99
+ marks[name] = { ...rest, render, toDOM: (mark, inline) => safeSpec(render(mark, inline), mark.attrs) };
100
+ }
101
+ }
102
+ const ordered = Object.fromEntries(Object.entries(nodes).sort(([a], [b]) => (a === 'doc' ? -1 : b === 'doc' ? 1 : 0)));
103
+ return new Schema({ nodes: ordered, marks, topNode: nodes.doc ? 'doc' : Object.keys(nodes)[0] });
104
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * One emoji: the character, its Unicode name, group and subgroup, its shortcodes and tags (gemoji), and the label a
3
+ * list shows (its first shortcode, or its name when it has none).
4
+ */
5
+ export type Emoji = {
6
+ id: string;
7
+ label: string;
8
+ char: string;
9
+ name: string;
10
+ group: string;
11
+ subgroup: string;
12
+ aliases: string[];
13
+ tags: string[];
14
+ };
15
+ export declare const emoji: Emoji[];