@clarusjs/editor 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.
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
@@ -0,0 +1,45 @@
1
+ import { attrValue, UNSAFE_URL } from 'clarusjs/runtime';
2
+ import { defineExtension } from '../core/extension.js';
3
+ const safe = (href) => typeof href === 'string' && href.trim() !== '' && attrValue('href', href, 'a') !== UNSAFE_URL;
4
+ export const link = defineExtension({
5
+ name: 'link',
6
+ marks: {
7
+ link: {
8
+ attrs: { href: {} },
9
+ inclusive: false,
10
+ parseDOM: [{ tag: 'a[href]', getAttrs: (el) => { const href = el.getAttribute('href'); return safe(href) ? { href } : false; } }],
11
+ render: (mark) => ['a', { href: attrValue('href', mark.attrs.href, 'a'), rel: 'noopener noreferrer nofollow' }, 0],
12
+ },
13
+ },
14
+ commands: (schema) => ({
15
+ link: (href) => (state, dispatch) => {
16
+ const { from, to, empty } = state.selection;
17
+ if (empty || !safe(href))
18
+ return false;
19
+ dispatch?.(state.tr.addMark(from, to, schema.marks.link.create({ href })));
20
+ return true;
21
+ },
22
+ unlink: () => (state, dispatch) => {
23
+ let { from, to } = state.selection;
24
+ const type = schema.marks.link;
25
+ if (from === to) {
26
+ const { parent, parentOffset } = state.selection.$from;
27
+ const start = from - parentOffset;
28
+ let pos = start;
29
+ let run;
30
+ parent.forEach((child) => {
31
+ const end = pos + child.nodeSize;
32
+ if (type.isInSet(child.marks))
33
+ run = run && run[1] === pos ? [run[0], end] : !run || run[1] < from ? [pos, end] : run;
34
+ pos = end;
35
+ });
36
+ if (run && run[0] <= from && from <= run[1])
37
+ [from, to] = run;
38
+ }
39
+ if (!state.doc.rangeHasMark(from, to, type))
40
+ return false;
41
+ dispatch?.(state.tr.removeMark(from, to, type));
42
+ return true;
43
+ },
44
+ }),
45
+ });
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Markdown shortcuts while typing.
3
+ * @see https://clarusjs.com/guide/editor-composer#extensions
4
+ */
5
+ export declare const markdownShortcuts: import("../index.ts").Extension;
@@ -0,0 +1,23 @@
1
+ import { InputRule, textblockTypeInputRule } from 'prosemirror-inputrules';
2
+ import { defineExtension } from '../core/extension.js';
3
+ const markRule = (pattern, type) => new InputRule(pattern, (state, match, start, end) => {
4
+ let leaf = false;
5
+ state.doc.nodesBetween(start, end, (node) => { if (node.isInline && !node.isText)
6
+ leaf = true; });
7
+ if (leaf)
8
+ return null;
9
+ const open = match[0].indexOf(match[1]);
10
+ const from = start + open;
11
+ const to = from + match[1].length;
12
+ return state.tr.delete(to, end).addMark(from, to, type.create()).delete(start, from).removeStoredMark(type);
13
+ }, { inCodeMark: false });
14
+ export const markdownShortcuts = defineExtension({
15
+ name: 'markdownShortcuts',
16
+ inputRules: (schema) => [
17
+ schema.marks.strong && markRule(/\*\*([^*\s](?:[^*]*[^*\s])?)\*\*$/, schema.marks.strong),
18
+ schema.marks.em && markRule(/(?<![*\w])\*([^*\s](?:[^*]*[^*\s])?)\*$/, schema.marks.em),
19
+ schema.marks.em && markRule(/(?<![_\w])_([^_\s](?:[^_]*[^_\s])?)_$/, schema.marks.em),
20
+ schema.marks.code && markRule(/`([^`]+)`$/, schema.marks.code),
21
+ schema.nodes.code_block && textblockTypeInputRule(/^```$/, schema.nodes.code_block),
22
+ ].filter((r) => !!r),
23
+ });
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Bold (`strong`): Mod-b, the command `bold`.
3
+ * @see https://clarusjs.com/guide/editor-composer#extensions
4
+ */
5
+ export declare const bold: import("../index.ts").Extension;
6
+ /**
7
+ * Italic (`em`): Mod-i, the command `italic`.
8
+ * @see https://clarusjs.com/guide/editor-composer#extensions
9
+ */
10
+ export declare const italic: import("../index.ts").Extension;
11
+ /**
12
+ * Inline code (`code`): Mod-e, the command `code`.
13
+ * @see https://clarusjs.com/guide/editor-composer#extensions
14
+ */
15
+ export declare const code: import("../index.ts").Extension;
@@ -0,0 +1,36 @@
1
+ import { toggleMark } from 'prosemirror-commands';
2
+ import { defineExtension } from '../core/extension.js';
3
+ const styleOf = (el, property) => new RegExp(`(?:^|;)\\s*${property}\\s*:\\s*([^;]+)`, 'i').exec(el.getAttribute('style') ?? '')?.[1]?.trim().toLowerCase();
4
+ export const bold = defineExtension({
5
+ name: 'bold',
6
+ marks: {
7
+ strong: {
8
+ parseDOM: [
9
+ { tag: 'strong' },
10
+ { tag: 'b', getAttrs: (el) => !/^(normal|400)$/.test(styleOf(el, 'font-weight') ?? '') && null },
11
+ { style: 'font-weight=400', clearMark: (m) => m.type.name === 'strong' },
12
+ { style: 'font-weight', getAttrs: (v) => /^(bold(er)?|[5-9]\d{2,})$/.test(v) && null },
13
+ ],
14
+ render: () => ['strong', 0],
15
+ },
16
+ },
17
+ commands: (schema) => ({ bold: () => toggleMark(schema.marks.strong) }),
18
+ keys: (schema) => ({ 'Mod-b': toggleMark(schema.marks.strong) }),
19
+ });
20
+ export const italic = defineExtension({
21
+ name: 'italic',
22
+ marks: {
23
+ em: {
24
+ parseDOM: [{ tag: 'em' }, { tag: 'i' }, { style: 'font-style=italic' }, { style: 'font-style=normal', clearMark: (m) => m.type.name === 'em' }],
25
+ render: () => ['em', 0],
26
+ },
27
+ },
28
+ commands: (schema) => ({ italic: () => toggleMark(schema.marks.em) }),
29
+ keys: (schema) => ({ 'Mod-i': toggleMark(schema.marks.em) }),
30
+ });
31
+ export const code = defineExtension({
32
+ name: 'code',
33
+ marks: { code: { code: true, parseDOM: [{ tag: 'code' }], render: () => ['code', 0] } },
34
+ commands: (schema) => ({ code: () => toggleMark(schema.marks.code) }),
35
+ keys: (schema) => ({ 'Mod-e': toggleMark(schema.marks.code) }),
36
+ });
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Mentions: the node `mention` with the attributes `id` and `label`, and the command `mention(attrs, range?)` that
3
+ * inserts one (a suggestion's pick: `editor.run('mention', item, range)`).
4
+ * @see https://clarusjs.com/guide/editor-composer#mentions
5
+ */
6
+ export declare const mention: import("../index.ts").Extension;
@@ -0,0 +1,22 @@
1
+ import { defineExtension } from '../core/extension.js';
2
+ export const mention = defineExtension({
3
+ name: 'mention',
4
+ requires: ['base'],
5
+ nodes: {
6
+ mention: {
7
+ attrs: { id: {}, label: {} },
8
+ inline: true, group: 'inline', atom: true, selectable: false,
9
+ parseDOM: [{ tag: 'span[data-mention]', getAttrs: (el) => ({ id: el.getAttribute('data-mention'), label: (el.textContent ?? '').replace(/^@/, '') }) }],
10
+ leafText: (node) => `@${node.attrs.label}`,
11
+ render: (node) => ['span', { 'data-mention': node.attrs.id }, `@${node.attrs.label}`],
12
+ },
13
+ },
14
+ commands: (schema) => ({
15
+ mention: (attrs, range) => (state, dispatch) => {
16
+ const { from, to } = range ?? state.selection;
17
+ const node = schema.nodes.mention.create({ id: attrs.id, label: attrs.label });
18
+ dispatch?.(state.tr.replaceWith(from, to, [node, schema.text(' ')]).scrollIntoView());
19
+ return true;
20
+ },
21
+ }),
22
+ });
@@ -0,0 +1,8 @@
1
+ import { type Extension } from '../core/extension.ts';
2
+ /**
3
+ * A placeholder shown while the editor is empty.
4
+ * @example
5
+ * createEditor({ extensions: [...composerExtensions(), placeholder('Reply…')] })
6
+ * @see https://clarusjs.com/guide/editor-composer#extensions
7
+ */
8
+ export declare function placeholder(text: string): Extension;
@@ -0,0 +1,11 @@
1
+ import { Plugin } from 'prosemirror-state';
2
+ import { defineExtension } from '../core/extension.js';
3
+ const isEmpty = (doc) => doc.childCount === 1 && doc.firstChild.isTextblock && doc.firstChild.content.size === 0;
4
+ export function placeholder(text) {
5
+ return defineExtension({
6
+ name: 'placeholder',
7
+ plugins: () => [new Plugin({
8
+ props: { attributes: (state) => ({ 'aria-placeholder': text, 'data-placeholder': text, ...(isEmpty(state.doc) ? { 'data-empty': '' } : {}) }) },
9
+ })],
10
+ });
11
+ }
@@ -0,0 +1,18 @@
1
+ export { createEditor, type Editor, type EditorOptions } from './core/editor.ts';
2
+ export { buildSchema, defineExtension, type Extension, type MarkSpec, type NodeSpec } from './core/schema.ts';
3
+ export { editor, editorOf } from './behaviours/editor.ts';
4
+ export { onEditor } from './core/registry.ts';
5
+ export type { Emoji } from './emoji.ts';
6
+ export { toolbar } from './behaviours/toolbar.ts';
7
+ export { content } from './behaviours/content.ts';
8
+ export { plainText } from './core/plain-text.ts';
9
+ export { loadEmoji, searchEmoji, suggestion, type SuggestionItem, type SuggestionOptions } from './behaviours/suggestion.ts';
10
+ export { base } from './extensions/base.ts';
11
+ export { bold, code, italic } from './extensions/marks.ts';
12
+ export { link } from './extensions/link.ts';
13
+ export { codeBlock } from './extensions/code-block.ts';
14
+ export { mention } from './extensions/mention.ts';
15
+ export { markdownShortcuts } from './extensions/markdown-shortcuts.ts';
16
+ export { history } from './extensions/history.ts';
17
+ export { placeholder } from './extensions/placeholder.ts';
18
+ export { composerExtensions } from './extensions/composer.ts';
package/dist/index.js ADDED
@@ -0,0 +1,17 @@
1
+ export { createEditor } from './core/editor.js';
2
+ export { buildSchema, defineExtension } from './core/schema.js';
3
+ export { editor, editorOf } from './behaviours/editor.js';
4
+ export { onEditor } from './core/registry.js';
5
+ export { toolbar } from './behaviours/toolbar.js';
6
+ export { content } from './behaviours/content.js';
7
+ export { plainText } from './core/plain-text.js';
8
+ export { loadEmoji, searchEmoji, suggestion } from './behaviours/suggestion.js';
9
+ export { base } from './extensions/base.js';
10
+ export { bold, code, italic } from './extensions/marks.js';
11
+ export { link } from './extensions/link.js';
12
+ export { codeBlock } from './extensions/code-block.js';
13
+ export { mention } from './extensions/mention.js';
14
+ export { markdownShortcuts } from './extensions/markdown-shortcuts.js';
15
+ export { history } from './extensions/history.js';
16
+ export { placeholder } from './extensions/placeholder.js';
17
+ export { composerExtensions } from './extensions/composer.js';
@@ -0,0 +1,43 @@
1
+ import type { Extension } from './core/extension.ts';
2
+ /**
3
+ * How a value is stored: ProseMirror JSON (an object, or its string) or HTML; or plain text, as a textarea posts it
4
+ * before the editor loads (a field's <name>-format says which).
5
+ * @see https://clarusjs.com/guide/editor-composer#format
6
+ */
7
+ export type Format = 'json' | 'html' | 'text';
8
+ /**
9
+ * Checks a submitted value against the extensions' schema: its nodes and marks, their nesting, every URL, and the
10
+ * length when `maxLength` is set (in graphemes, as the browser counts). On success, `doc` is the checked document as
11
+ * ProseMirror JSON: store that, or render it.
12
+ * @example
13
+ * const result = validate(form.get('message'), composerExtensions(), { maxLength: 2000 })
14
+ * if (!result.ok) return new Response(result.error, { status: 422 })
15
+ * @see https://clarusjs.com/guide/editor-composer#on-the-server
16
+ */
17
+ export declare function validate(value: string | object, extensions: Extension[], options?: {
18
+ format?: Format;
19
+ maxLength?: number;
20
+ }): {
21
+ ok: true;
22
+ doc: object;
23
+ } | {
24
+ ok: false;
25
+ error: string;
26
+ };
27
+ /**
28
+ * A document's length in graphemes, a mention counting as its label: the count a `maxLength` limits.
29
+ * @example
30
+ * length(json) // 3 for "👨‍👩‍👧ab"
31
+ * @see https://clarusjs.com/guide/editor-composer#limits
32
+ */
33
+ export declare function length(value: object, extensions?: Extension[]): number;
34
+ /**
35
+ * The HTML of a value, rendered with the extensions' `render` specs: text and attributes escaped, URLs checked. Use it
36
+ * to show stored content on a page that ships no editor at all.
37
+ * @example
38
+ * const html = renderHTML(message.body, composerExtensions())
39
+ * @see https://clarusjs.com/guide/editor-composer#on-the-server
40
+ */
41
+ export declare function renderHTML(value: string | object, extensions: Extension[], options?: {
42
+ format?: Format;
43
+ }): string;
package/dist/server.js ADDED
@@ -0,0 +1,133 @@
1
+ import { parseHTML } from 'linkedom';
2
+ import { DOMParser, Node } from 'prosemirror-model';
3
+ import { attrValue, UNSAFE_URL } from 'clarusjs/runtime';
4
+ import { docLength } from './core/length.js';
5
+ import { fromText } from './core/from-text.js';
6
+ import { ATTR_NAME, TAG_NAME, attrInSpec, buildSchema, localName } from './core/schema.js';
7
+ import { base } from './extensions/base.js';
8
+ const BASE = [base];
9
+ const schemas = new WeakMap();
10
+ const schemaOf = (extensions) => {
11
+ let s = schemas.get(extensions);
12
+ if (!s)
13
+ schemas.set(extensions, (s = buildSchema(extensions)));
14
+ return s;
15
+ };
16
+ function parse(value, schema, format) {
17
+ if (format === 'text')
18
+ return fromText(schema, String(value)).doc;
19
+ if (format === 'html') {
20
+ const { document } = parseHTML(`<!doctype html><html><body>${String(value)}</body></html>`);
21
+ return DOMParser.fromSchema(schema).parse(document.body);
22
+ }
23
+ const json = typeof value === 'string' ? JSON.parse(value) : value;
24
+ const doc = Node.fromJSON(schema, json);
25
+ doc.check();
26
+ return doc;
27
+ }
28
+ function renderProblem(doc) {
29
+ let found;
30
+ const walk = (spec) => {
31
+ if (found || !Array.isArray(spec))
32
+ return;
33
+ const [tag, ...rest] = spec;
34
+ if (typeof tag !== 'string' || !TAG_NAME.test(tag))
35
+ return void (found = `invalid tag: ${tag}`);
36
+ const attrs = rest[0] && typeof rest[0] === 'object' && !Array.isArray(rest[0]) ? rest[0] : undefined;
37
+ for (const [name, value] of Object.entries(attrs ?? {})) {
38
+ if (!ATTR_NAME.test(name))
39
+ return void (found = `invalid attribute: ${name}`);
40
+ if (value != null && typeof value === 'object')
41
+ return void (found = `invalid attribute: ${name}`);
42
+ if (typeof value === 'string' && attrValue(localName(name), value, localName(tag)) === UNSAFE_URL)
43
+ return void (found = `unsafe URL: ${value}`);
44
+ }
45
+ for (const child of rest.slice(attrs ? 1 : 0))
46
+ walk(child);
47
+ };
48
+ doc.descendants((node) => {
49
+ const raw = node.type.spec.render;
50
+ const used = raw && attrInSpec(raw(node), node.attrs);
51
+ if (used)
52
+ return void (found = `invalid attribute: ${used}`);
53
+ for (const mark of node.marks) {
54
+ const m = mark.type.spec.render;
55
+ const usedByMark = m && attrInSpec(m(mark, true), mark.attrs);
56
+ if (usedByMark)
57
+ return void (found = `invalid attribute: ${usedByMark}`);
58
+ }
59
+ if (!node.isText && (raw || node.type.spec.toDOM))
60
+ walk(raw ? raw(node) : node.type.spec.toDOM(node));
61
+ for (const mark of node.marks)
62
+ walk((mark.type.spec.render ?? mark.type.spec.toDOM)(mark, true));
63
+ return !found;
64
+ });
65
+ return found;
66
+ }
67
+ export function validate(value, extensions, options = {}) {
68
+ let doc;
69
+ const schema = schemaOf(extensions);
70
+ try {
71
+ doc = parse(value, schema, options.format ?? 'json');
72
+ if (doc.type !== schema.topNodeType)
73
+ return { ok: false, error: `not a document: ${doc.type.name}` };
74
+ const problem = renderProblem(doc);
75
+ if (problem)
76
+ return { ok: false, error: problem };
77
+ if (options.maxLength !== undefined) {
78
+ const n = docLength(doc);
79
+ if (n > options.maxLength)
80
+ return { ok: false, error: `too long: ${n} of ${options.maxLength}` };
81
+ }
82
+ }
83
+ catch (err) {
84
+ return { ok: false, error: err.message };
85
+ }
86
+ return { ok: true, doc: doc.toJSON() };
87
+ }
88
+ export function length(value, extensions = BASE) {
89
+ return docLength(Node.fromJSON(schemaOf(extensions), value));
90
+ }
91
+ const VOID = new Set(['br', 'hr', 'img', 'input', 'wbr']);
92
+ const escapeText = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
93
+ const escapeAttr = (s) => escapeText(s).replace(/"/g, '&quot;');
94
+ function specHTML(spec, inner) {
95
+ if (!Array.isArray(spec))
96
+ return '';
97
+ const [full, ...rest] = spec;
98
+ if (typeof full !== 'string' || !TAG_NAME.test(full))
99
+ return '';
100
+ const tag = localName(full);
101
+ let attrs = '';
102
+ let i = 0;
103
+ if (rest[0] && typeof rest[0] === 'object' && !Array.isArray(rest[0])) {
104
+ for (const [name, value] of Object.entries(rest[0])) {
105
+ if (!ATTR_NAME.test(name))
106
+ continue;
107
+ const local = localName(name);
108
+ const v = attrValue(local, value, tag);
109
+ if (v === null)
110
+ continue;
111
+ attrs += v === true ? ` ${local}` : ` ${local}="${escapeAttr(v)}"`;
112
+ }
113
+ i = 1;
114
+ }
115
+ if (VOID.has(tag))
116
+ return `<${tag}${attrs}>`;
117
+ let body = '';
118
+ for (const child of rest.slice(i))
119
+ body += child === 0 ? inner() : typeof child === 'string' ? escapeText(child) : specHTML(child, inner);
120
+ return `<${tag}${attrs}>${body}</${tag}>`;
121
+ }
122
+ function nodeHTML(node) {
123
+ const inner = () => { let s = ''; node.forEach((child) => { s += nodeHTML(child); }); return s; };
124
+ const toDOM = node.type.spec.toDOM;
125
+ const html = node.isText ? escapeText(node.text) : toDOM ? specHTML(toDOM(node), inner) : inner();
126
+ return node.isInline ? node.marks.reduceRight((h, mark) => specHTML(mark.type.spec.toDOM(mark, true), () => h), html) : html;
127
+ }
128
+ export function renderHTML(value, extensions, options = {}) {
129
+ const doc = parse(value, schemaOf(extensions), options.format ?? 'json');
130
+ let html = '';
131
+ doc.forEach((child) => { html += nodeHTML(child); });
132
+ return html;
133
+ }
package/package.json CHANGED
@@ -1,6 +1,104 @@
1
1
  {
2
2
  "name": "@clarusjs/editor",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "A rich-text editor for clarusjs: a composer to drop in, behaviours to build your own, and a server side that validates and renders without a DOM.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/forinda/clarusjs.git",
10
+ "directory": "packages/editor"
11
+ },
12
+ "homepage": "https://clarusjs.com/guide/editor-composer",
13
+ "keywords": [
14
+ "clarusjs",
15
+ "editor",
16
+ "rich-text",
17
+ "prosemirror",
18
+ "composer"
19
+ ],
20
+ "engines": {
21
+ "node": "^22.12.0 || ^24.0.0 || >=26.0.0"
22
+ },
23
+ "exports": {
24
+ ".": {
25
+ "types": "./dist/index.d.ts",
26
+ "default": "./dist/index.js"
27
+ },
28
+ "./server": {
29
+ "types": "./dist/server.d.ts",
30
+ "default": "./dist/server.js"
31
+ },
32
+ "./components/*": "./src/components/*",
33
+ "./plain-text": {
34
+ "types": "./dist/core/plain-text.d.ts",
35
+ "default": "./dist/core/plain-text.js"
36
+ },
37
+ "./registry": {
38
+ "types": "./dist/core/registry.d.ts",
39
+ "default": "./dist/core/registry.js"
40
+ },
41
+ "./toolbar": {
42
+ "types": "./dist/behaviours/toolbar.d.ts",
43
+ "default": "./dist/behaviours/toolbar.js"
44
+ },
45
+ "./suggestion": {
46
+ "types": "./dist/behaviours/suggestion.d.ts",
47
+ "default": "./dist/behaviours/suggestion.js"
48
+ },
49
+ "./content": {
50
+ "types": "./dist/behaviours/content.d.ts",
51
+ "default": "./dist/behaviours/content.js"
52
+ },
53
+ "./editor": {
54
+ "types": "./dist/behaviours/editor.d.ts",
55
+ "default": "./dist/behaviours/editor.js"
56
+ },
57
+ "./extensions": {
58
+ "types": "./dist/extensions/composer.d.ts",
59
+ "default": "./dist/extensions/composer.js"
60
+ }
61
+ },
62
+ "clarusjs": {
63
+ "components": "./src/components",
64
+ "prefix": "editor"
65
+ },
66
+ "files": [
67
+ "dist",
68
+ "src/components",
69
+ "LICENSE",
70
+ "README.md"
71
+ ],
72
+ "publishConfig": {
73
+ "access": "public"
74
+ },
75
+ "peerDependencies": {
76
+ "clarusjs": "^0.19.0"
77
+ },
78
+ "dependencies": {
79
+ "@clarusjs/ui-primitives": "^0.3.2",
80
+ "linkedom": "^0.18.15",
81
+ "prosemirror-commands": "^1.7.2",
82
+ "prosemirror-history": "^1.5.2",
83
+ "prosemirror-inputrules": "^1.7.0",
84
+ "prosemirror-keymap": "^1.2.3",
85
+ "prosemirror-model": "^1.25.13",
86
+ "prosemirror-state": "^1.4.4",
87
+ "prosemirror-transform": "^1.12.7",
88
+ "prosemirror-view": "^1.44.0"
89
+ },
90
+ "devDependencies": {
91
+ "@types/node": "^26.6.6",
92
+ "clarusjs": "^0.19.0",
93
+ "happy-dom": "^21.0.4",
94
+ "typescript": "^7.0.2",
95
+ "vite": "^8.3.8",
96
+ "vitest": "^5.1.1"
97
+ },
98
+ "sideEffects": false,
99
+ "scripts": {
100
+ "build": "node ../../scripts/build-package.mjs",
101
+ "test": "vitest run",
102
+ "typecheck": "tsc --noEmit"
103
+ }
6
104
  }
@@ -0,0 +1,40 @@
1
+ {{--
2
+ Editor count (@clarusjs/editor): the length of the field named by [field] and its limit ([maxLength] on the field),
3
+ as "120/2000"; data-over once past it. Graphemes, as people count: an emoji is one, a mention its label.
4
+
5
+ <editor-count [field]="'msg'" />
6
+
7
+ Headless: data-part="count", data-over.
8
+ --}}
9
+ @input field: string
10
+
11
+ <script>
12
+ import { effect, untrack } from 'clarusjs/runtime'
13
+ import { onEditor } from '@clarusjs/editor/registry'
14
+ let count = state(0)
15
+ let max = state(0)
16
+ let over = state(false)
17
+ // follows the field [field] names, again whenever a parent changes it
18
+ function wire() {
19
+ let off
20
+ const stop = effect(() => {
21
+ const id = field
22
+ off?.()
23
+ off = untrack(() =>
24
+ onEditor(id, (editor) => {
25
+ max = editor.maxLength ?? 0
26
+ return effect(() => {
27
+ count = editor.length.get()
28
+ over = editor.over.get()
29
+ })
30
+ }),
31
+ )
32
+ })
33
+ return () => {
34
+ stop()
35
+ off?.()
36
+ }
37
+ }
38
+ </script>
39
+
40
+ <span data-part="count" [data-over]="over ? '' : false" [use]="wire">{{ max ? count + '/' + max : count }}</span>
@@ -0,0 +1,115 @@
1
+ {{--
2
+ Editor field (@clarusjs/editor): a plain <textarea> from the server (typing, and posting a form through [name], work
3
+ with no JavaScript), then the editor, with the text and caret, once its code loads (attach="interaction": on first
4
+ focus). Its id (required, unique on the page) is how the other parts name it: field="that id".
5
+
6
+ <editor-field attach="interaction" [id]="'msg'" [label]="'Message'" [maxLength]="2000" [(value)]="draft"
7
+ (send)="post($event.value)" (files)="upload($event.files)" />
8
+
9
+ Enter sends ((send), then it clears; $info.cancel() keeps the text), Shift+Enter is a new line; [enterSends]="false"
10
+ makes Enter a new line and Ctrl/⌘+Enter send. Files pasted or dropped go to (files). With [name] in a form it posts
11
+ the value under that name, and <name>-format: 'text' (posted with no JavaScript), 'json' or 'html'. Pass that to
12
+ validate() from @clarusjs/editor/server.
13
+ Headless: data-part="editor" (the textarea, then the editor's box, whose editable is [role='textbox']).
14
+ --}}
15
+ @input id: string
16
+ @input label: string = 'Message'
17
+ @input placeholder: string = ''
18
+ @input format: 'json' | 'html' = 'json'
19
+ @input name: string = ''
20
+ @input maxLength: number = 0
21
+ @input enterSends: boolean = true
22
+ @input codeBlocks: boolean = true
23
+ @input mentions: boolean = true
24
+ @input rows: number = 3
25
+ @model value: any = ''
26
+ @event send: { value: any }
27
+ @event files: { files: File[] }
28
+
29
+ <script>
30
+ import { effect } from 'clarusjs/runtime'
31
+ import { editor, editorOf } from '@clarusjs/editor/editor'
32
+ import { composerExtensions } from '@clarusjs/editor/extensions'
33
+ import { plainText } from '@clarusjs/editor/plain-text'
34
+ // The editor replaces the textarea once attached (a microtask later, so the loader's replay finds the textarea).
35
+ let ready = state(false)
36
+ const initial = plainText(value, format)
37
+ let draft = { text: initial, caret: undefined, focused: false }
38
+ let hidden
39
+ // the format the running editor serializes (fixed when it mounts): what the form says it posts
40
+ let posted = state(format)
41
+ const key = (v) => (typeof v === 'string' ? v : JSON.stringify(v))
42
+
43
+ function takeOver(textarea) {
44
+ queueMicrotask(() => {
45
+ draft = { text: textarea.value, caret: textarea.selectionStart, focused: document.activeElement === textarea }
46
+ ready = true
47
+ })
48
+ }
49
+ // (send), then, unless cancelled and with [name] in a form, the form posts it (as it would with no JavaScript).
50
+ function sent(v) {
51
+ // a form that isn't valid yet (another field required): it says so, and nothing is sent or cleared
52
+ if (name && hidden?.form && !hidden.form.reportValidity()) return false
53
+ if (!emit('send', { value: v })) return false
54
+ if (name && hidden?.form) {
55
+ hidden.value = typeof v === 'string' ? v : JSON.stringify(v)
56
+ hidden.form.requestSubmit()
57
+ }
58
+ }
59
+ function mount(el) {
60
+ posted = format
61
+ const stop = editor(el, {
62
+ extensions: composerExtensions({ codeBlocks, mentions, placeholder }),
63
+ format,
64
+ label,
65
+ enterSends,
66
+ maxLength: maxLength || undefined,
67
+ // untouched: the rich value, the caret where it was; typed in: what was typed
68
+ ...(draft.text === initial ? { value, caret: draft.caret } : { text: { value: draft.text, caret: draft.caret } }),
69
+ onSend: sent,
70
+ onFiles: (files) => emit('files', { files }),
71
+ })
72
+ const ed = editorOf(el)
73
+ const write = effect(() => {
74
+ value = ed.value.get()
75
+ })
76
+ // A new value from the parent ([(value)]) replaces the document. Only a change: the write above reaches value
77
+ // through the parent, so until it does value is the old one, which must not undo what was typed.
78
+ let seen = value
79
+ const read = effect(() => {
80
+ const v = value
81
+ if (v === seen) return
82
+ seen = v
83
+ // a parent passes back a copy of what was written: the same document is no change (or the two would loop)
84
+ if (key(v) !== key(ed.value.get())) ed.value.set(v)
85
+ })
86
+ if (draft.focused) ed.focus()
87
+ return () => {
88
+ read()
89
+ write()
90
+ stop()
91
+ }
92
+ }
93
+ </script>
94
+
95
+ @if (ready) {
96
+ <div [id]="id" data-part="editor" [use]="mount"></div>
97
+ @if (name) {
98
+ <input type="hidden" [name]="name" [value]="typeof value === 'string' ? value : JSON.stringify(value)" [use]="(el) => { hidden = el }" />
99
+ <input type="hidden" [name]="name + '-format'" [value]="posted" />
100
+ }
101
+ } @else {
102
+ <textarea
103
+ [id]="id"
104
+ data-part="editor"
105
+ [name]="name || false"
106
+ [placeholder]="placeholder || false"
107
+ [aria-label]="label"
108
+ [rows]="rows"
109
+ [value]="initial"
110
+ [use]="takeOver"
111
+ ></textarea>
112
+ @if (name) {
113
+ <input type="hidden" [name]="name + '-format'" value="text" />
114
+ }
115
+ }