@axium/rich-text 0.0.0-stage → 0.0.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.
@@ -0,0 +1,389 @@
1
+ <script lang="ts">
2
+ import { contextMenu, type ContextMenuEntry } from '@axium/client/attachments';
3
+ import { emptyDocument, type RichTextDocument } from '@axium/rich-text';
4
+ import { Editor, Extension } from '@tiptap/core';
5
+ import { BubbleMenu } from '@tiptap/extension-bubble-menu';
6
+ import type { EditorState } from '@tiptap/pm/state';
7
+ import { mount, unmount, untrack } from 'svelte';
8
+ import { formattingActions, type RichTextAction, type RichTextContext } from './actions.js';
9
+ import { createExtensions, type RichTextPreset } from './extensions.js';
10
+ import './locales.js';
11
+ import type { CustomNode } from './nodes.svelte.js';
12
+ import SelectionMenu from './SelectionMenu.svelte';
13
+
14
+ let {
15
+ content = $bindable(emptyDocument()),
16
+ preset = 'document',
17
+ nodes = [],
18
+ actions = formattingActions(),
19
+ editable = true,
20
+ delay = 1000,
21
+ onchange,
22
+ class: className,
23
+ }: {
24
+ /** Replacing the document resets the editor and discards changes not yet passed to `onchange`. */
25
+ content?: RichTextDocument;
26
+ /** Only read when the editor is created. */
27
+ preset?: RichTextPreset;
28
+ /** Only read when the editor is created. */
29
+ nodes?: CustomNode<any>[];
30
+ actions?: RichTextAction[];
31
+ editable?: boolean;
32
+ /** How long to wait after the last edit before calling `onchange`, in milliseconds. */
33
+ delay?: number;
34
+ onchange?(content: RichTextDocument): unknown;
35
+ class?: string;
36
+ } = $props();
37
+
38
+ const externalUpdate = 'axium-rich-text-external';
39
+
40
+ let editor = $state.raw<Editor>();
41
+ let editorState = $state.raw<EditorState>();
42
+ const menu = $state({ linking: false });
43
+
44
+ let emitted: RichTextDocument | undefined;
45
+ let pendingContent: RichTextDocument | undefined;
46
+ let timer: ReturnType<typeof setTimeout> | undefined;
47
+
48
+ function createContext(instance: Editor): RichTextContext {
49
+ const { from, to } = instance.state.selection;
50
+ return {
51
+ editor: instance,
52
+ text: instance.state.doc.textBetween(from, to, '\n'),
53
+ wrapSelection,
54
+ editLink() {
55
+ menu.linking = true;
56
+ instance.view.focus();
57
+ },
58
+ };
59
+ }
60
+
61
+ function visibleActions(context: RichTextContext): RichTextAction[] {
62
+ return actions.filter(action => action.visible?.(context) ?? true);
63
+ }
64
+
65
+ const context = $derived(editorState && editor && createContext(editor));
66
+ const menuActions = $derived(context ? visibleActions(context) : []);
67
+
68
+ function contextEntries(): ContextMenuEntry[] {
69
+ if (!editor || editor.state.selection.empty) return [];
70
+ const current = createContext(editor);
71
+ return visibleActions(current).map(action => ({
72
+ i: action.i,
73
+ text: action.text,
74
+ danger: action.danger,
75
+ action: () => action.run(current),
76
+ }));
77
+ }
78
+
79
+ const LinkShortcut = Extension.create({
80
+ name: 'axiumLinkShortcut',
81
+ addKeyboardShortcuts() {
82
+ return {
83
+ 'Mod-k': () => {
84
+ if (this.editor.state.selection.empty || !this.editor.isEditable) return false;
85
+ menu.linking = true;
86
+ return true;
87
+ },
88
+ };
89
+ },
90
+ });
91
+
92
+ function attachEditor(element: HTMLElement) {
93
+ return untrack(() => {
94
+ const menuElement = document.createElement('div');
95
+ menuElement.popover = 'manual';
96
+ menuElement.className = 'rich-text-menu';
97
+
98
+ const instance = new Editor({
99
+ element,
100
+ content,
101
+ editable,
102
+ extensions: [
103
+ ...createExtensions(preset, nodes),
104
+ LinkShortcut,
105
+ BubbleMenu.configure({
106
+ element: menuElement,
107
+ shouldShow: ({ editor, state }) =>
108
+ !state.selection.empty && (menu.linking || visibleActions(createContext(editor)).length > 0),
109
+ options: { strategy: 'fixed', placement: 'top', onShow: () => menuElement.showPopover() },
110
+ }),
111
+ ],
112
+ onTransaction({ editor, transaction }) {
113
+ if (!transaction.docChanged && !editorState?.selection.eq(editor.state.selection)) menu.linking = false;
114
+ editorState = editor.state;
115
+ },
116
+ onUpdate({ editor, transaction }) {
117
+ if (!transaction.docChanged) return;
118
+ content = emitted = editor.getJSON() as RichTextDocument;
119
+ if (transaction.getMeta(externalUpdate)) return;
120
+ pendingContent = content;
121
+ clearTimeout(timer);
122
+ timer = setTimeout(flush, delay);
123
+ },
124
+ });
125
+
126
+ emitted = content;
127
+ editor = instance;
128
+ editorState = instance.state;
129
+
130
+ const selectionMenu = mount(SelectionMenu, {
131
+ target: menuElement,
132
+ props: {
133
+ get context() {
134
+ return context;
135
+ },
136
+ get actions() {
137
+ return menuActions;
138
+ },
139
+ menu,
140
+ },
141
+ });
142
+
143
+ return () => {
144
+ flush();
145
+ unmount(selectionMenu);
146
+ instance.destroy();
147
+ menuElement.remove();
148
+ editor = undefined;
149
+ };
150
+ });
151
+ }
152
+
153
+ $effect(() => {
154
+ const next = content;
155
+ if (!editor || next === emitted) return;
156
+ emitted = next;
157
+ pendingContent = undefined;
158
+ clearTimeout(timer);
159
+ untrack(() => editor!.commands.setContent(next, { emitUpdate: false }));
160
+ });
161
+
162
+ $effect(() => {
163
+ editor?.setEditable(editable);
164
+ });
165
+
166
+ /** Call `onchange` now with any changes still waiting for the delay. */
167
+ export function flush(): void {
168
+ clearTimeout(timer);
169
+ timer = undefined;
170
+ if (!pendingContent) return;
171
+ const changed = pendingContent;
172
+ pendingContent = undefined;
173
+ onchange?.(changed);
174
+ }
175
+
176
+ /**
177
+ * Change the data of every `node` in the document without moving the cursor or adding to undo history.
178
+ * Nodes are visited in document order, and `index` counts only nodes of this type.
179
+ * Returning `undefined` from `update` leaves that node unchanged.
180
+ * This updates `content` but does not call `onchange`.
181
+ */
182
+ export function updateNodes<Data>(node: CustomNode<Data>, update: (data: Data, index: number) => Data | undefined): void {
183
+ if (!editor) return;
184
+ const { tr, doc } = editor.state;
185
+ let index = 0;
186
+ doc.descendants((child, position) => {
187
+ if (child.type.name != node.name) return;
188
+ const data = update(child.attrs.data, index++);
189
+ if (data !== undefined) tr.setNodeMarkup(position, undefined, { data });
190
+ });
191
+ if (!tr.docChanged) return;
192
+ editor.view.dispatch(tr.setMeta('addToHistory', false).setMeta(externalUpdate, true));
193
+ }
194
+
195
+ /** Replace the selection with a `node` built from the selected text. */
196
+ export function wrapSelection<Data>(node: CustomNode<Data>, build: (text: string) => Data): boolean {
197
+ if (!editor || editor.state.selection.empty) return false;
198
+ const { from, to } = editor.state.selection;
199
+ const data = build(editor.state.doc.textBetween(from, to, '\n'));
200
+ return editor.chain().focus().insertContentAt({ from, to }, { type: node.name, attrs: { data } }).run();
201
+ }
202
+
203
+ export function getEditor(): Editor | undefined {
204
+ return editor;
205
+ }
206
+ </script>
207
+
208
+ <div class={['rich-text', className]} {@attach attachEditor} {@attach contextMenu(contextEntries)}></div>
209
+
210
+ <style>
211
+ .rich-text :global {
212
+ .ProseMirror {
213
+ outline: none;
214
+ min-height: 100%;
215
+ line-height: 1.5;
216
+ }
217
+
218
+ p,
219
+ ul,
220
+ ol,
221
+ blockquote,
222
+ pre,
223
+ table {
224
+ margin: 0 0 0.75em;
225
+ }
226
+
227
+ h1,
228
+ h2,
229
+ h3,
230
+ h4,
231
+ h5,
232
+ h6 {
233
+ margin: 1em 0 0.5em;
234
+ line-height: 1.25;
235
+ }
236
+
237
+ a {
238
+ color: var(--fg-accent);
239
+ text-decoration: underline;
240
+ }
241
+
242
+ blockquote {
243
+ border-left: var(--border-accent);
244
+ border-left-width: 3px;
245
+ padding-left: 1em;
246
+ }
247
+
248
+ code {
249
+ font-family: monospace;
250
+ background-color: var(--bg-alt);
251
+ border-radius: 0.25em;
252
+ padding: 0.1em 0.3em;
253
+ }
254
+
255
+ pre {
256
+ background-color: var(--bg-alt);
257
+ border-radius: 0.5em;
258
+ padding: 0.75em 1em;
259
+ overflow-x: auto;
260
+
261
+ code {
262
+ background: none;
263
+ padding: 0;
264
+ }
265
+ }
266
+
267
+ hr {
268
+ border: none;
269
+ border-top: var(--border-accent);
270
+ margin: 1.5em 0;
271
+ }
272
+
273
+ ul[data-type='taskList'] {
274
+ list-style: none;
275
+ padding-left: 0;
276
+
277
+ ul[data-type='taskList'] {
278
+ padding-left: 1.75em;
279
+ }
280
+ }
281
+
282
+ li[data-type='taskItem'] {
283
+ display: flex;
284
+ align-items: flex-start;
285
+ gap: 0.5em;
286
+
287
+ > div:last-child {
288
+ flex: 1;
289
+ }
290
+
291
+ &[data-checked='true'] > div:last-child {
292
+ opacity: 0.6;
293
+ text-decoration: line-through;
294
+ }
295
+
296
+ &[data-checked='false'] label.checkbox .Icon {
297
+ visibility: hidden;
298
+ }
299
+ }
300
+
301
+ .task-checkbox {
302
+ display: flex;
303
+ align-items: center;
304
+ height: 1.5em;
305
+ user-select: none;
306
+ }
307
+
308
+ table {
309
+ border-collapse: collapse;
310
+ width: 100%;
311
+ }
312
+
313
+ th,
314
+ td {
315
+ border: var(--border-accent);
316
+ padding: 0.25em 0.5em;
317
+ vertical-align: top;
318
+ text-align: left;
319
+
320
+ > p {
321
+ margin: 0;
322
+ }
323
+ }
324
+
325
+ th {
326
+ background-color: var(--bg-alt);
327
+ }
328
+
329
+ .selectedCell {
330
+ background-color: var(--bg-accent);
331
+ }
332
+
333
+ .rich-text-node {
334
+ border-radius: 0.25em;
335
+ }
336
+
337
+ .ProseMirror-selectednode {
338
+ outline: 2px solid var(--fg-accent);
339
+ }
340
+ }
341
+
342
+ @media print {
343
+ :global(.rich-text-menu, .rich-text-suggestions) {
344
+ display: none;
345
+ }
346
+
347
+ .rich-text :global {
348
+ color: #000;
349
+
350
+ a {
351
+ color: inherit;
352
+ }
353
+
354
+ code,
355
+ pre,
356
+ th {
357
+ background-color: #eee;
358
+ }
359
+
360
+ blockquote,
361
+ th,
362
+ td,
363
+ hr {
364
+ border-color: #999;
365
+ }
366
+
367
+ h1,
368
+ h2,
369
+ h3,
370
+ h4,
371
+ h5,
372
+ h6 {
373
+ break-after: avoid;
374
+ }
375
+
376
+ pre,
377
+ blockquote,
378
+ tr,
379
+ li,
380
+ .rich-text-node {
381
+ break-inside: avoid;
382
+ }
383
+
384
+ .ProseMirror-selectednode {
385
+ outline: none;
386
+ }
387
+ }
388
+ }
389
+ </style>
@@ -0,0 +1,99 @@
1
+ <script lang="ts">
2
+ import { text } from '@axium/client';
3
+ import { Icon } from '@axium/client/components';
4
+ import type { RichTextAction, RichTextContext } from './actions.js';
5
+
6
+ const {
7
+ context,
8
+ actions,
9
+ menu,
10
+ }: {
11
+ context: RichTextContext | undefined;
12
+ actions: RichTextAction[];
13
+ menu: { linking: boolean };
14
+ } = $props();
15
+
16
+ let href = $state('');
17
+
18
+ $effect(() => {
19
+ if (menu.linking && context) href = context.editor.getAttributes('link').href ?? '';
20
+ });
21
+
22
+ function applyLink(event: SubmitEvent) {
23
+ event.preventDefault();
24
+ if (!context) return;
25
+ const chain = context.editor.chain().focus().extendMarkRange('link');
26
+ if (href.trim()) chain.setLink({ href: href.trim() }).run();
27
+ else chain.unsetLink().run();
28
+ menu.linking = false;
29
+ }
30
+
31
+ function removeLink() {
32
+ context?.editor.chain().focus().extendMarkRange('link').unsetLink().run();
33
+ menu.linking = false;
34
+ }
35
+ </script>
36
+
37
+ {#if context && menu.linking}
38
+ <form class="link" onsubmit={applyLink}>
39
+ <input
40
+ type="url"
41
+ bind:value={href}
42
+ placeholder={text('RichText.link_placeholder')}
43
+ autofocus
44
+ onkeydown={event => {
45
+ if (event.key != 'Escape') return;
46
+ event.preventDefault();
47
+ menu.linking = false;
48
+ context.editor.commands.focus();
49
+ }}
50
+ />
51
+ <button class="icon" type="submit" title={text('RichText.link_apply')}><Icon i="check" /></button>
52
+ {#if context.editor.isActive('link')}
53
+ <button class="icon" type="button" title={text('RichText.unlink')} onclick={removeLink}>
54
+ <Icon i="link-slash" />
55
+ </button>
56
+ {/if}
57
+ </form>
58
+ {:else if context}
59
+ <div class="actions" role="toolbar">
60
+ {#each actions as action}
61
+ <button
62
+ type="button"
63
+ class={['icon', action.danger && 'danger']}
64
+ title={action.text}
65
+ aria-label={action.text}
66
+ aria-pressed={action.active?.(context)}
67
+ onmousedown={event => event.preventDefault()}
68
+ onclick={() => action.run(context)}
69
+ >
70
+ <Icon i={action.i} />
71
+ </button>
72
+ {/each}
73
+ </div>
74
+ {/if}
75
+
76
+ <style>
77
+ .actions,
78
+ .link {
79
+ display: flex;
80
+ align-items: center;
81
+ gap: 0.25em;
82
+ }
83
+
84
+ .link input {
85
+ min-width: 16em;
86
+ }
87
+
88
+ button.icon {
89
+ border: none;
90
+ background: none;
91
+ padding: 0.5em;
92
+ display: inline-flex;
93
+
94
+ &:hover,
95
+ &[aria-pressed='true'] {
96
+ background-color: var(--bg-accent);
97
+ }
98
+ }
99
+ </style>
@@ -0,0 +1,76 @@
1
+ <script lang="ts" generics="Data">
2
+ import { text } from '@axium/client';
3
+ import { Icon } from '@axium/client/components';
4
+ import type { SuggestionItem } from './nodes.svelte.js';
5
+
6
+ const {
7
+ suggestions,
8
+ }: {
9
+ suggestions: { items: SuggestionItem<Data>[]; loading: boolean; select(item: SuggestionItem<Data>): void };
10
+ } = $props();
11
+
12
+ let active = $state(0);
13
+
14
+ $effect(() => {
15
+ suggestions.items;
16
+ active = 0;
17
+ });
18
+
19
+ export function keydown(event: KeyboardEvent): boolean {
20
+ const count = suggestions.items.length;
21
+ if (!count) return false;
22
+
23
+ switch (event.key) {
24
+ case 'ArrowDown':
25
+ active = (active + 1) % count;
26
+ return true;
27
+ case 'ArrowUp':
28
+ active = (active - 1 + count) % count;
29
+ return true;
30
+ case 'Enter':
31
+ case 'Tab':
32
+ suggestions.select(suggestions.items[active]);
33
+ return true;
34
+ default:
35
+ return false;
36
+ }
37
+ }
38
+ </script>
39
+
40
+ <div class="suggestions" role="listbox">
41
+ {#each suggestions.items as item, index}
42
+ <div
43
+ class={['menu-item', 'icon-text', index == active && 'active']}
44
+ role="option"
45
+ aria-selected={index == active}
46
+ tabindex="-1"
47
+ onmousedown={event => event.preventDefault()}
48
+ onclick={() => suggestions.select(item)}
49
+ onpointerenter={() => (active = index)}
50
+ >
51
+ {#if item.i}<Icon i={item.i} />{/if}
52
+ {item.text}
53
+ </div>
54
+ {:else}
55
+ <div class="empty">{text(suggestions.loading ? 'RichText.suggestions_loading' : 'RichText.suggestions_empty')}</div>
56
+ {/each}
57
+ </div>
58
+
59
+ <style>
60
+ .suggestions {
61
+ display: flex;
62
+ flex-direction: column;
63
+ min-width: 12em;
64
+ max-height: 20em;
65
+ overflow-y: auto;
66
+ }
67
+
68
+ .active {
69
+ background-color: var(--bg-strong);
70
+ }
71
+
72
+ .empty {
73
+ padding: 0.5em 0.75em;
74
+ opacity: 0.7;
75
+ }
76
+ </style>
package/lib/actions.ts ADDED
@@ -0,0 +1,58 @@
1
+ import { text } from '@axium/client';
2
+ import type { Editor } from '@tiptap/core';
3
+ import type { CustomNode } from './nodes.svelte.js';
4
+
5
+ export interface RichTextContext {
6
+ editor: Editor;
7
+ /** The selected text */
8
+ text: string;
9
+ /** Replace the selection with a custom node built from the selected text. */
10
+ wrapSelection<Data>(node: CustomNode<Data>, build: (text: string) => Data): boolean;
11
+ /** Show the link field in the selection menu. */
12
+ editLink(): void;
13
+ }
14
+
15
+ /** An action shown in the selection menu and the right-click menu while text is selected. */
16
+ export interface RichTextAction {
17
+ /** Icon name */
18
+ i: string;
19
+ text: string;
20
+ danger?: boolean;
21
+ run(context: RichTextContext): unknown;
22
+ /** Whether the action is shown highlighted, e.g. bold while the selection is bold. */
23
+ active?(context: RichTextContext): boolean;
24
+ /** Whether the action is available. Defaults to always. */
25
+ visible?(context: RichTextContext): boolean;
26
+ }
27
+
28
+ function isEditable({ editor }: RichTextContext): boolean {
29
+ return editor.isEditable;
30
+ }
31
+
32
+ function mark(i: string, label: string, name: string, toggle: (editor: Editor) => unknown): RichTextAction {
33
+ return {
34
+ i,
35
+ text: label,
36
+ run: ({ editor }) => toggle(editor),
37
+ active: ({ editor }) => editor.isActive(name),
38
+ visible: isEditable,
39
+ };
40
+ }
41
+
42
+ /** Bold, italic, underline, strikethrough, code and link. */
43
+ export function formattingActions(): RichTextAction[] {
44
+ return [
45
+ mark('bold', text('RichText.bold'), 'bold', editor => editor.chain().focus().toggleBold().run()),
46
+ mark('italic', text('RichText.italic'), 'italic', editor => editor.chain().focus().toggleItalic().run()),
47
+ mark('underline', text('RichText.underline'), 'underline', editor => editor.chain().focus().toggleUnderline().run()),
48
+ mark('strikethrough', text('RichText.strike'), 'strike', editor => editor.chain().focus().toggleStrike().run()),
49
+ mark('code', text('RichText.code'), 'code', editor => editor.chain().focus().toggleCode().run()),
50
+ {
51
+ i: 'link',
52
+ text: text('RichText.link'),
53
+ run: context => context.editLink(),
54
+ active: ({ editor }) => editor.isActive('link'),
55
+ visible: isEditable,
56
+ },
57
+ ];
58
+ }
@@ -0,0 +1,26 @@
1
+ import type { Extensions } from '@tiptap/core';
2
+ import { TaskList } from '@tiptap/extension-list';
3
+ import { TableKit } from '@tiptap/extension-table';
4
+ import { StarterKit } from '@tiptap/starter-kit';
5
+ import type { CustomNode } from './nodes.svelte.js';
6
+ import { TaskItem } from './task-item.js';
7
+
8
+ /**
9
+ * Which formatting a document supports.
10
+ * `email` leaves out task lists, which mail clients can't show.
11
+ */
12
+ export type RichTextPreset = 'document' | 'email';
13
+
14
+ export function createExtensions(preset: RichTextPreset, nodes: CustomNode<any>[] = []): Extensions {
15
+ const extensions: Extensions = [
16
+ StarterKit.configure({
17
+ link: { openOnClick: false, autolink: true, defaultProtocol: 'https' },
18
+ }),
19
+ TableKit.configure({ table: { resizable: false } }),
20
+ ...nodes.map(node => node.extension),
21
+ ];
22
+
23
+ if (preset == 'document') extensions.push(TaskList, TaskItem.configure({ nested: true }));
24
+
25
+ return extensions;
26
+ }
package/lib/index.ts ADDED
@@ -0,0 +1,7 @@
1
+ import './locales.js';
2
+
3
+ export * from './actions.js';
4
+ export * from './extensions.js';
5
+ export * from './nodes.svelte.js';
6
+ export { default as RichText } from './RichText.svelte';
7
+ export * from './serialize.js';
package/lib/locales.ts ADDED
@@ -0,0 +1,4 @@
1
+ import * as locales from '@james-pre/locales';
2
+ import en from '../locales/en.json' with { type: 'json' };
3
+
4
+ locales.extend('en', en);