@axium/rich-text 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.
@@ -0,0 +1,237 @@
1
+ import { Node } from '@tiptap/core';
2
+ import { Fragment, Slice, type Node as ProseMirrorNode } from '@tiptap/pm/model';
3
+ import { Plugin, PluginKey } from '@tiptap/pm/state';
4
+ import { Suggestion, type SuggestionProps } from '@tiptap/suggestion';
5
+ import { mount, unmount, type Snippet } from 'svelte';
6
+ import type * as z from 'zod';
7
+ import NodeView from './NodeView.svelte';
8
+ import SuggestionList from './SuggestionList.svelte';
9
+
10
+ export interface CustomNodeProps<Data> {
11
+ data: Data;
12
+ selected: boolean;
13
+ editable: boolean;
14
+ }
15
+
16
+ export interface SuggestionItem<Data> {
17
+ text: string;
18
+ /** Icon name */
19
+ i?: string;
20
+ data: Data;
21
+ }
22
+
23
+ export interface CustomNodeSuggestions<Data> {
24
+ /** Typing this character opens the suggestion list. */
25
+ char: string;
26
+ items(query: string, signal: AbortSignal): SuggestionItem<Data>[] | Promise<SuggestionItem<Data>[]>;
27
+ }
28
+
29
+ /** The element a node is copied as, so other apps keep something meaningful, like a link. */
30
+ export interface CustomNodeHTML {
31
+ tag?: string;
32
+ attributes?: Record<string, string>;
33
+ }
34
+
35
+ export interface CustomNodeOptions<Data> {
36
+ /** The node's type in the document JSON. */
37
+ name: string;
38
+ /** Validates data parsed from pasted HTML. */
39
+ schema: z.ZodType<Data>;
40
+ render: Snippet<[CustomNodeProps<Data>]>;
41
+ /** Plain text for the clipboard and plain-text output. */
42
+ text(data: Data): string;
43
+ html?(data: Data): CustomNodeHTML;
44
+ suggest?: CustomNodeSuggestions<Data>;
45
+ /** Transforms pasted copies of the node, or drops them by returning `null`. */
46
+ paste?(data: Data): Data | null;
47
+ }
48
+
49
+ export interface CustomNode<Data> extends CustomNodeOptions<Data> {
50
+ extension: Node;
51
+ }
52
+
53
+ /**
54
+ * Define an atomic inline node whose `data` is stored in the document unchanged, as `{ type: name, attrs: { data } }`.
55
+ */
56
+ export function defineNode<Data>(options: CustomNodeOptions<Data>): CustomNode<Data> {
57
+ const { name, schema } = options;
58
+
59
+ function parseData(element: HTMLElement): { data: Data } | false {
60
+ try {
61
+ const result = schema.safeParse(JSON.parse(element.getAttribute('data-attributes') ?? 'null'));
62
+ return result.success ? { data: result.data } : false;
63
+ } catch {
64
+ return false;
65
+ }
66
+ }
67
+
68
+ function transformPasted(fragment: Fragment): Fragment {
69
+ const children: ProseMirrorNode[] = [];
70
+ fragment.forEach(child => {
71
+ if (child.type.name != name) {
72
+ children.push(child.isLeaf ? child : child.copy(transformPasted(child.content)));
73
+ return;
74
+ }
75
+ const data = options.paste!(child.attrs.data);
76
+ if (data !== null) children.push(child.type.create({ data }));
77
+ });
78
+ return Fragment.fromArray(children);
79
+ }
80
+
81
+ const extension = Node.create({
82
+ name,
83
+ group: 'inline',
84
+ inline: true,
85
+ atom: true,
86
+ selectable: true,
87
+ draggable: true,
88
+
89
+ addAttributes() {
90
+ return { data: { default: null, rendered: false } };
91
+ },
92
+
93
+ parseHTML() {
94
+ return [{ tag: `[data-type="${name}"]`, priority: 100, getAttrs: parseData }];
95
+ },
96
+
97
+ renderHTML({ node }) {
98
+ const { tag = 'span', attributes = {} } = options.html?.(node.attrs.data) ?? {};
99
+ return [
100
+ tag,
101
+ { ...attributes, 'data-type': name, 'data-attributes': JSON.stringify(node.attrs.data) },
102
+ options.text(node.attrs.data),
103
+ ];
104
+ },
105
+
106
+ renderText({ node }) {
107
+ return options.text(node.attrs.data);
108
+ },
109
+
110
+ addNodeView() {
111
+ return ({ node, editor }) => {
112
+ const dom = document.createElement('span');
113
+ dom.className = 'rich-text-node';
114
+ dom.dataset.type = name;
115
+ dom.contentEditable = 'false';
116
+
117
+ const props = $state<CustomNodeProps<Data>>({
118
+ data: node.attrs.data,
119
+ selected: false,
120
+ editable: editor.isEditable,
121
+ });
122
+
123
+ const view = mount(NodeView<Data>, { target: dom, props: { render: options.render, props } });
124
+
125
+ function syncEditable() {
126
+ props.editable = editor.isEditable;
127
+ }
128
+ editor.on('update', syncEditable);
129
+
130
+ return {
131
+ dom,
132
+ update(updated) {
133
+ if (updated.type !== node.type) return false;
134
+ props.data = updated.attrs.data;
135
+ return true;
136
+ },
137
+ selectNode() {
138
+ props.selected = true;
139
+ dom.classList.add('ProseMirror-selectednode');
140
+ },
141
+ deselectNode() {
142
+ props.selected = false;
143
+ dom.classList.remove('ProseMirror-selectednode');
144
+ },
145
+ ignoreMutation: () => true,
146
+ destroy() {
147
+ editor.off('update', syncEditable);
148
+ unmount(view);
149
+ },
150
+ };
151
+ };
152
+ },
153
+
154
+ addProseMirrorPlugins() {
155
+ const plugins: Plugin[] = [];
156
+
157
+ if (options.paste) {
158
+ plugins.push(
159
+ new Plugin({
160
+ key: new PluginKey(`${name}-paste`),
161
+ props: {
162
+ transformPasted: slice => new Slice(transformPasted(slice.content), slice.openStart, slice.openEnd),
163
+ },
164
+ })
165
+ );
166
+ }
167
+
168
+ if (options.suggest) {
169
+ const { char, items } = options.suggest;
170
+ plugins.push(
171
+ Suggestion<SuggestionItem<Data>, SuggestionItem<Data>>({
172
+ editor: this.editor,
173
+ pluginKey: new PluginKey(`${name}-suggestion`),
174
+ char,
175
+ items: ({ query, signal }) => items(query, signal),
176
+ command({ editor, range, props: item }) {
177
+ editor
178
+ .chain()
179
+ .focus()
180
+ .insertContentAt(range, [
181
+ { type: name, attrs: { data: item.data } },
182
+ { type: 'text', text: ' ' },
183
+ ])
184
+ .run();
185
+ },
186
+ floatingUi: { strategy: 'fixed' },
187
+ render: renderSuggestions<Data>,
188
+ })
189
+ );
190
+ }
191
+
192
+ return plugins;
193
+ },
194
+ });
195
+
196
+ return { ...options, extension };
197
+ }
198
+
199
+ function renderSuggestions<Data>() {
200
+ const element = document.createElement('div');
201
+ element.popover = 'manual';
202
+ element.className = 'rich-text-suggestions';
203
+
204
+ const suggestions = $state<{ items: SuggestionItem<Data>[]; loading: boolean; select(item: SuggestionItem<Data>): void }>({
205
+ items: [],
206
+ loading: false,
207
+ select() {},
208
+ });
209
+
210
+ let list: { keydown(event: KeyboardEvent): boolean } | undefined;
211
+ let removePositioning: (() => void) | undefined;
212
+
213
+ function sync(props: SuggestionProps<SuggestionItem<Data>, SuggestionItem<Data>>) {
214
+ suggestions.items = props.items;
215
+ suggestions.loading = props.loading;
216
+ suggestions.select = props.command;
217
+ }
218
+
219
+ return {
220
+ onStart(props: SuggestionProps<SuggestionItem<Data>, SuggestionItem<Data>>) {
221
+ sync(props);
222
+ list = mount(SuggestionList<Data>, { target: element, props: { suggestions } });
223
+ removePositioning = props.mount(element);
224
+ element.showPopover();
225
+ },
226
+ onUpdate: sync,
227
+ onKeyDown({ event }: { event: KeyboardEvent }) {
228
+ return list?.keydown(event) ?? false;
229
+ },
230
+ onExit() {
231
+ removePositioning?.();
232
+ if (list) unmount(list);
233
+ list = undefined;
234
+ element.remove();
235
+ },
236
+ };
237
+ }
@@ -0,0 +1,22 @@
1
+ import { toPlainText, type RichTextDocument } from '@axium/rich-text';
2
+ import { getHTMLFromFragment, getSchema } from '@tiptap/core';
3
+ import { Node } from '@tiptap/pm/model';
4
+ import { createExtensions, type RichTextPreset } from './extensions.js';
5
+ import type { CustomNode } from './nodes.svelte.js';
6
+
7
+ export interface SerializeOptions {
8
+ preset?: RichTextPreset;
9
+ nodes?: CustomNode<any>[];
10
+ }
11
+
12
+ /** Custom nodes are written as the element from their `html` option. */
13
+ export function toHTML(content: RichTextDocument, options: SerializeOptions = {}): string {
14
+ const schema = getSchema(createExtensions(options.preset ?? 'document', options.nodes));
15
+ return getHTMLFromFragment(Node.fromJSON(schema, content).content, schema);
16
+ }
17
+
18
+ export function toText(content: RichTextDocument, nodes: CustomNode<any>[] = []): string {
19
+ return toPlainText(content, {
20
+ nodes: Object.fromEntries(nodes.map(node => [node.name, child => node.text(child.attrs?.data)])),
21
+ });
22
+ }
@@ -0,0 +1,78 @@
1
+ import { text } from '@axium/client';
2
+ import { Icon } from '@axium/client/components';
3
+ import { TaskItem as BaseTaskItem } from '@tiptap/extension-list';
4
+ import { mount, unmount } from 'svelte';
5
+
6
+ /** A task item whose checkbox uses Axium's checkbox markup. */
7
+ export const TaskItem = BaseTaskItem.extend({
8
+ addNodeView() {
9
+ return ({ node, getPos, editor }) => {
10
+ let current = node;
11
+
12
+ const item = document.createElement('li');
13
+ item.dataset.type = 'taskItem';
14
+
15
+ const control = document.createElement('div');
16
+ control.className = 'task-checkbox';
17
+ control.contentEditable = 'false';
18
+
19
+ const input = document.createElement('input');
20
+ input.type = 'checkbox';
21
+ input.id = `task-${crypto.randomUUID()}`;
22
+ input.setAttribute('aria-label', text('RichText.task_done'));
23
+
24
+ const label = document.createElement('label');
25
+ label.className = 'checkbox';
26
+ label.htmlFor = input.id;
27
+ label.addEventListener('mousedown', event => event.preventDefault());
28
+
29
+ const icon = mount(Icon, { target: label, props: { i: 'check' } });
30
+
31
+ const content = document.createElement('div');
32
+ control.append(input, label);
33
+ item.append(control, content);
34
+
35
+ function sync() {
36
+ item.dataset.checked = String(current.attrs.checked);
37
+ input.checked = current.attrs.checked;
38
+ input.disabled = !editor.isEditable;
39
+ }
40
+
41
+ input.addEventListener('change', () => {
42
+ const position = getPos();
43
+ if (!editor.isEditable || typeof position != 'number') {
44
+ input.checked = current.attrs.checked;
45
+ return;
46
+ }
47
+
48
+ editor
49
+ .chain()
50
+ .focus(undefined, { scrollIntoView: false })
51
+ .command(({ tr }) => {
52
+ tr.setNodeMarkup(position, undefined, { ...current.attrs, checked: input.checked });
53
+ return true;
54
+ })
55
+ .run();
56
+ });
57
+
58
+ editor.on('update', sync);
59
+ sync();
60
+
61
+ return {
62
+ dom: item,
63
+ contentDOM: content,
64
+ update(updated) {
65
+ if (updated.type !== current.type) return false;
66
+ current = updated;
67
+ sync();
68
+ return true;
69
+ },
70
+ ignoreMutation: mutation => mutation.type != 'selection' && !content.contains(mutation.target),
71
+ destroy() {
72
+ editor.off('update', sync);
73
+ unmount(icon);
74
+ },
75
+ };
76
+ };
77
+ },
78
+ });
@@ -0,0 +1,12 @@
1
+ {
2
+ "extends": ["../tsconfig.json"],
3
+ "compilerOptions": {
4
+ "rootDir": "..",
5
+ "noEmit": true,
6
+ "module": "preserve",
7
+ "moduleResolution": "Bundler",
8
+ "lib": ["ESNext", "DOM", "DOM.Iterable"]
9
+ },
10
+ "include": ["./**/*", "../src/.*.ts", "../locales/*.json"],
11
+ "references": [{ "path": ".." }]
12
+ }
@@ -0,0 +1,16 @@
1
+ {
2
+ "RichText": {
3
+ "bold": "Bold",
4
+ "italic": "Italic",
5
+ "underline": "Underline",
6
+ "strike": "Strikethrough",
7
+ "code": "Code",
8
+ "link": "Link",
9
+ "link_placeholder": "Paste or type a link",
10
+ "link_apply": "Apply",
11
+ "unlink": "Remove link",
12
+ "task_done": "Done",
13
+ "suggestions_loading": "Loading…",
14
+ "suggestions_empty": "No results"
15
+ }
16
+ }
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
- "name": "@axium/rich-text",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@axium/rich-text",
3
+ "version": "0.1.0",
4
+ "author": "James Prevett <axium@jamespre.dev>",
5
+ "description": "Rich text editing for Axium",
6
+ "funding": {
7
+ "type": "individual",
8
+ "url": "https://github.com/sponsors/james-pre"
9
+ },
10
+ "license": "LGPL-3.0-or-later",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/james-pre/axium.git"
14
+ },
15
+ "homepage": "https://github.com/james-pre/axium#readme",
16
+ "bugs": {
17
+ "url": "https://github.com/james-pre/axium/issues"
18
+ },
19
+ "type": "module",
20
+ "main": "dist/index.js",
21
+ "types": "dist/index.d.ts",
22
+ "exports": {
23
+ ".": "./dist/index.js",
24
+ "./*": "./dist/*.js",
25
+ "./components": "./lib/index.js",
26
+ "./components/*": "./lib/*.svelte"
27
+ },
28
+ "files": [
29
+ "dist",
30
+ "lib",
31
+ "locales"
32
+ ],
33
+ "scripts": {
34
+ "build": "tsc"
35
+ },
36
+ "peerDependencies": {
37
+ "@axium/client": ">=0.44.0",
38
+ "@james-pre/locales": "^1.0.0",
39
+ "svelte": "^5.36.0",
40
+ "zod": "^4.0.5"
41
+ },
42
+ "dependencies": {
43
+ "@tiptap/core": "^3.35.0",
44
+ "@tiptap/extension-bubble-menu": "^3.35.0",
45
+ "@tiptap/extension-list": "^3.35.0",
46
+ "@tiptap/extension-table": "^3.35.0",
47
+ "@tiptap/pm": "^3.35.0",
48
+ "@tiptap/starter-kit": "^3.35.0",
49
+ "@tiptap/suggestion": "^3.35.0"
50
+ }
51
+ }