uncial 0.0.7 → 1.0.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 (67) hide show
  1. package/README.md +75 -8
  2. package/dist/core/attributes.d.ts +7 -1
  3. package/dist/core/attributes.js +35 -16
  4. package/dist/core/defineBlock.js +36 -9
  5. package/dist/core/index.d.ts +3 -1
  6. package/dist/core/index.js +2 -1
  7. package/dist/core/issues.d.ts +7 -0
  8. package/dist/core/issues.js +9 -0
  9. package/dist/core/meta.js +2 -7
  10. package/dist/core/migrations.d.ts +30 -0
  11. package/dist/core/migrations.js +43 -0
  12. package/dist/core/normalize.d.ts +12 -1
  13. package/dist/core/normalize.js +110 -21
  14. package/dist/core/registry.d.ts +7 -0
  15. package/dist/core/registry.js +22 -4
  16. package/dist/core/runtime.d.ts +7 -0
  17. package/dist/core/types.d.ts +8 -2
  18. package/dist/core/validate.js +22 -6
  19. package/dist/editor/AttributeFieldControl.svelte +31 -3
  20. package/dist/editor/BlockAttributesPanel.svelte +35 -30
  21. package/dist/editor/BlockAttributesPanel.svelte.d.ts +9 -1
  22. package/dist/editor/Editor.svelte +5 -16
  23. package/dist/editor/RichTextAttributeEditor.svelte +75 -145
  24. package/dist/editor/RichTextAttributeEditor.svelte.d.ts +2 -1
  25. package/dist/editor/Toolbar.svelte +2 -3
  26. package/dist/editor/attributeTargets.d.ts +23 -0
  27. package/dist/editor/attributeTargets.js +21 -0
  28. package/dist/editor/attributesController.d.ts +7 -0
  29. package/dist/editor/attributesController.js +118 -229
  30. package/dist/editor/bindEditor.js +102 -26
  31. package/dist/editor/chooseAttribute.d.ts +26 -0
  32. package/dist/editor/chooseAttribute.js +10 -0
  33. package/dist/editor/containerChildOps.d.ts +33 -0
  34. package/dist/editor/containerChildOps.js +94 -0
  35. package/dist/editor/dropdownDismiss.d.ts +18 -0
  36. package/dist/editor/dropdownDismiss.js +46 -0
  37. package/dist/editor/index.d.ts +3 -1
  38. package/dist/editor/index.js +2 -1
  39. package/dist/editor/linkController.d.ts +19 -0
  40. package/dist/editor/linkController.js +72 -0
  41. package/dist/editor/toolbarFeatures.d.ts +12 -0
  42. package/dist/editor/toolbarFeatures.js +36 -0
  43. package/dist/render/Renderer.svelte +1 -1
  44. package/dist/render/RichContent.svelte +2 -2
  45. package/dist/render/RichNode.svelte +16 -2
  46. package/dist/render/sanitize.d.ts +6 -0
  47. package/dist/render/sanitize.js +20 -1
  48. package/dist/runtime/reactiveProps.svelte.d.ts +16 -0
  49. package/dist/runtime/reactiveProps.svelte.js +16 -0
  50. package/dist/runtime/svelte.d.ts +2 -1
  51. package/dist/runtime/svelte.js +26 -6
  52. package/dist/shared/EditorBlockFixture.svelte +24 -0
  53. package/dist/shared/EditorBlockFixture.svelte.d.ts +9 -0
  54. package/dist/shared/content.js +2 -1
  55. package/dist/shared/guards.d.ts +13 -0
  56. package/dist/shared/guards.js +16 -0
  57. package/dist/shared/richText.js +20 -4
  58. package/dist/shared/runtimeId.d.ts +8 -0
  59. package/dist/shared/runtimeId.js +8 -0
  60. package/dist/shared/tiptap.js +58 -23
  61. package/dist/web-components/UncialEditor.svelte +16 -1
  62. package/dist/web-components/UncialEditor.svelte.d.ts +5 -2
  63. package/dist/web-components/index.d.ts +39 -10
  64. package/dist/web-components/index.js +86 -36
  65. package/dist/web-components/reactiveProps.svelte.d.ts +10 -0
  66. package/dist/web-components/reactiveProps.svelte.js +13 -0
  67. package/package.json +1 -1
@@ -1,4 +1,10 @@
1
- const DEFAULT_MARKS = ['bold', 'italic', 'strike', 'code', 'link'];
1
+ /**
2
+ * The default mark universe a schema allows when the host does not pass an
3
+ * explicit `allowedMarks`. This is the single source of truth for the default
4
+ * marks — the editor's base extensions (`shared/tiptap.ts`) consume it too, so
5
+ * the fallback schema and the fallback extension set never drift apart.
6
+ */
7
+ export const DEFAULT_MARKS = ['bold', 'italic', 'strike', 'code', 'link'];
2
8
  export function createBlockRegistry(blocks) {
3
9
  const byId = new Map();
4
10
  const metadata = [];
@@ -32,9 +38,21 @@ export function createBlockRegistry(blocks) {
32
38
  };
33
39
  }
34
40
  export function createSchema(registry, options = {}) {
35
- const allowedBlocks = options.allowedBlocks
36
- ? new Set(options.allowedBlocks.filter((id) => registry.has(id)))
37
- : new Set(registry.blocks.map((block) => block.id));
41
+ let allowedBlocks;
42
+ if (options.allowedBlocks) {
43
+ const unknown = options.allowedBlocks.filter((id) => !registry.has(id));
44
+ if (unknown.length > 0) {
45
+ console.warn(`createSchema: ignoring unknown block id(s) in allowedBlocks: ${unknown
46
+ .map((id) => `"${id}"`)
47
+ .join(', ')}. Known ids: ${registry.blocks
48
+ .map((block) => `"${block.id}"`)
49
+ .join(', ')}.`);
50
+ }
51
+ allowedBlocks = new Set(options.allowedBlocks.filter((id) => registry.has(id)));
52
+ }
53
+ else {
54
+ allowedBlocks = new Set(registry.blocks.map((block) => block.id));
55
+ }
38
56
  const allowedMarks = new Set(options.allowedMarks ?? DEFAULT_MARKS);
39
57
  const metaFields = new Map(Object.entries(options.metaFields ?? {}));
40
58
  return {
@@ -2,6 +2,13 @@ export interface BlockEditorMountOptions {
2
2
  target: HTMLElement;
3
3
  inline: boolean;
4
4
  component: NormalizedBlockComponentDefinition;
5
+ /**
6
+ * The ProseMirror-managed content host for container blocks (null for atomic
7
+ * blocks). Runtimes render this into the editor node view as the block's
8
+ * children slot. It is stable for the node view's lifetime, so it is only
9
+ * supplied at mount — never via `update()`.
10
+ */
11
+ contentDOM?: HTMLElement | null;
5
12
  props: Record<string, unknown>;
6
13
  }
7
14
  export interface BlockEditorMountHandle {
@@ -1,3 +1,4 @@
1
+ import type { Component, Snippet } from 'svelte';
1
2
  import type { PMDoc, PMPath } from '../shared/document.js';
2
3
  import type { NormalizedBlockComponentDefinition } from './runtime.js';
3
4
  export type AttrValidator<T> = (value: unknown) => value is T;
@@ -29,7 +30,12 @@ export type AttributeConfig<T> = AttributeSpec<T> | T;
29
30
  export type MetaFieldSpec<T> = AttributeSpec<T>;
30
31
  export type DocumentMetaSchema = Record<string, MetaFieldSpec<unknown>>;
31
32
  export type BlockAttributes = Record<string, unknown>;
32
- export type BlockIcon = string | unknown;
33
+ /**
34
+ * A block's icon for editor UI (toolbar / insert menu). Either an icon name or
35
+ * inline markup as a string, or a Svelte component/snippet that renders the
36
+ * icon. (`string | unknown` collapsed to `unknown`, disabling type checking.)
37
+ */
38
+ export type BlockIcon = string | Component | Snippet;
33
39
  export type HtmlSpecValue = string | number | boolean | null | undefined;
34
40
  export type HtmlSpec = [string, Record<string, unknown>?, ...(HtmlSpec | HtmlSpecValue)[]];
35
41
  export type BlockHtmlRenderer = (attrs: BlockAttributes) => HtmlSpec;
@@ -109,7 +115,7 @@ export interface ContentSchema {
109
115
  allowedMarks: ReadonlySet<string>;
110
116
  metaFields: ReadonlyMap<string, AttributeSpec<unknown>>;
111
117
  }
112
- export type ValidationCode = 'UNKNOWN_BLOCK' | 'INVALID_ATTR' | 'INVALID_META' | 'UNKNOWN_META' | 'INVALID_CONTENT' | 'DISALLOWED_BLOCK' | 'DISALLOWED_MARK' | 'MALFORMED_NODE';
118
+ export type ValidationCode = 'UNKNOWN_BLOCK' | 'INVALID_ATTR' | 'INVALID_META' | 'UNKNOWN_META' | 'INVALID_CONTENT' | 'DISALLOWED_BLOCK' | 'DISALLOWED_MARK' | 'MALFORMED_NODE' | 'UNSUPPORTED_VERSION';
113
119
  export interface ValidationIssue {
114
120
  code: ValidationCode;
115
121
  path: PMPath;
@@ -1,5 +1,7 @@
1
1
  import { resolveRegistry } from './registry.js';
2
2
  import { validateMeta } from './meta.js';
3
+ import { pushIssue } from './issues.js';
4
+ import { CURRENT_DOCUMENT_VERSION } from './migrations.js';
3
5
  const BUILTIN_NODE_TYPES = new Set([
4
6
  'doc',
5
7
  'paragraph',
@@ -13,13 +15,18 @@ const BUILTIN_NODE_TYPES = new Set([
13
15
  'orderedList',
14
16
  'listItem'
15
17
  ]);
16
- function pushIssue(issues, options, issue) {
17
- issues.push(issue);
18
- options?.onIssue?.(issue);
19
- }
20
18
  function validateMarks(marks, path, schema, issues, options) {
21
- if (!marks)
19
+ if (marks === undefined || marks === null)
20
+ return;
21
+ if (!Array.isArray(marks)) {
22
+ pushIssue(issues, options, {
23
+ code: 'MALFORMED_NODE',
24
+ path: [...path, 'marks'],
25
+ message: 'Node marks must be an array when present',
26
+ severity: 'error'
27
+ });
22
28
  return;
29
+ }
23
30
  marks.forEach((mark, markIndex) => {
24
31
  if (!mark?.type || typeof mark.type !== 'string') {
25
32
  pushIssue(issues, options, {
@@ -162,6 +169,15 @@ export function validateDocument(document, blocks, schema, options) {
162
169
  });
163
170
  return { ok: false, issues };
164
171
  }
172
+ if (typeof document.version === 'number' && document.version > CURRENT_DOCUMENT_VERSION) {
173
+ pushIssue(issues, options, {
174
+ code: 'UNSUPPORTED_VERSION',
175
+ path: ['version'],
176
+ message: `Document version ${document.version} is newer than the supported version ${CURRENT_DOCUMENT_VERSION}`,
177
+ severity: 'warning',
178
+ details: { version: document.version, supportedVersion: CURRENT_DOCUMENT_VERSION }
179
+ });
180
+ }
165
181
  if (document.content && !Array.isArray(document.content)) {
166
182
  pushIssue(issues, options, {
167
183
  code: 'MALFORMED_NODE',
@@ -172,7 +188,7 @@ export function validateDocument(document, blocks, schema, options) {
172
188
  return { ok: false, issues };
173
189
  }
174
190
  validateMeta(document.meta, schema.metaFields, issues, options);
175
- const registryBlocks = new Map(registry.blocks.map((block) => [block.id, block]));
191
+ const registryBlocks = registry.byId;
176
192
  document.content?.forEach((node, index) => {
177
193
  validateNode(node, ['content', index], registryBlocks, schema, issues, options);
178
194
  });
@@ -1,3 +1,10 @@
1
+ <script lang="ts" module>
2
+ // Per-instance id so each rendered field can associate its <label> with its
3
+ // control, even when several fields share the same attribute name across
4
+ // blocks. A module counter keeps ids unique and stable without crypto.
5
+ let nextFieldId = 0;
6
+ </script>
7
+
1
8
  <script lang="ts">
2
9
  import { inferAttributeInputKind, normalizeAttributeOptions } from '../core/attributes.js';
3
10
  import type { AttributeSpec } from '../core/types.js';
@@ -14,7 +21,12 @@
14
21
 
15
22
  let { name, spec, value = undefined, error = '', onChange, onCustom }: Props = $props();
16
23
 
24
+ const fieldId = `uncial-field-${nextFieldId++}`;
17
25
  const inputKind = $derived(inferAttributeInputKind(spec));
26
+ // The rich-text editor and custom choosers render a component / <button>,
27
+ // neither of which a <label for> can address, so only native form controls
28
+ // get an associated <label>.
29
+ const hasLabelableControl = $derived(isBuiltInInputKind(inputKind) && inputKind !== 'richtext');
18
30
  const options = $derived(normalizeAttributeOptions(spec) ?? []);
19
31
  const stringValue = $derived.by(() => {
20
32
  if (typeof value === 'string') return value;
@@ -22,6 +34,14 @@
22
34
  return String(value);
23
35
  });
24
36
  const customLabel = $derived(value ? `Change ${name}: ${value}` : `Choose ${name}`);
37
+ // A stored value outside the declared options (e.g. a legacy value from before the
38
+ // options list changed) must stay visible and re-selectable instead of being silently
39
+ // remapped to the first option on the next commit.
40
+ const selectOptions = $derived.by(() => {
41
+ if (stringValue === '') return options;
42
+ if (options.some((option) => String(option.value) === stringValue)) return options;
43
+ return [{ value: stringValue, label: `${stringValue} (current)` }, ...options];
44
+ });
25
45
 
26
46
  function isBuiltInInputKind(kind: string): boolean {
27
47
  return ['checkbox', 'number', 'richtext', 'select', 'textarea', 'json', 'text', 'hidden'].includes(
@@ -32,7 +52,11 @@
32
52
 
33
53
  {#if inputKind !== 'hidden'}
34
54
  <div class="uncial-field">
35
- <span class="uncial-field__label">{name}</span>
55
+ {#if hasLabelableControl}
56
+ <label class="uncial-field__label" for={fieldId}>{name}</label>
57
+ {:else}
58
+ <span class="uncial-field__label">{name}</span>
59
+ {/if}
36
60
  {#if !isBuiltInInputKind(inputKind)}
37
61
  <button
38
62
  type="button"
@@ -43,6 +67,7 @@
43
67
  </button>
44
68
  {:else if inputKind === 'checkbox'}
45
69
  <input
70
+ id={fieldId}
46
71
  class="uncial-checkbox uncial-checkbox--sm"
47
72
  type="checkbox"
48
73
  checked={Boolean(value)}
@@ -53,6 +78,7 @@
53
78
  />
54
79
  {:else if inputKind === 'number'}
55
80
  <input
81
+ id={fieldId}
56
82
  class="uncial-input uncial-input--sm"
57
83
  type="number"
58
84
  placeholder={spec.placeholder ?? name}
@@ -71,20 +97,21 @@
71
97
  />
72
98
  {:else if inputKind === 'select'}
73
99
  <select
100
+ id={fieldId}
74
101
  class="uncial-select uncial-select--sm"
75
- aria-label={name}
76
102
  value={stringValue}
77
103
  onchange={(event) => {
78
104
  const target = event.currentTarget as HTMLSelectElement;
79
105
  onChange(target.value);
80
106
  }}
81
107
  >
82
- {#each options as option (String(option.value))}
108
+ {#each selectOptions as option (String(option.value))}
83
109
  <option value={String(option.value)}>{option.label ?? String(option.value)}</option>
84
110
  {/each}
85
111
  </select>
86
112
  {:else if inputKind === 'textarea' || inputKind === 'json'}
87
113
  <textarea
114
+ id={fieldId}
88
115
  class="uncial-textarea uncial-textarea--tall"
89
116
  placeholder={spec.placeholder ?? name}
90
117
  spellcheck={inputKind !== 'json'}
@@ -96,6 +123,7 @@
96
123
  ></textarea>
97
124
  {:else}
98
125
  <input
126
+ id={fieldId}
99
127
  class="uncial-input uncial-input--sm"
100
128
  type="text"
101
129
  placeholder={spec.placeholder ?? name}
@@ -2,7 +2,11 @@
2
2
  import { resolveRegistry } from '../core/registry.js';
3
3
  import type { AttributeSpec, BlockDefinition, BlockRegistry } from '../core/types.js';
4
4
  import { CODE_BLOCK_ID, codeBlockAttributeTarget } from '../shared/codeBlockAttributes.js';
5
- import type { BlockAttributesController, BlockAttributesState } from './attributesController.js';
5
+ import {
6
+ createInitialState,
7
+ type BlockAttributesController,
8
+ type BlockAttributesState
9
+ } from './attributesController.js';
6
10
  import { flip } from 'svelte/animate';
7
11
  import ArrowUpIcon from 'phosphor-svelte/lib/ArrowUpIcon';
8
12
  import ArrowDownIcon from 'phosphor-svelte/lib/ArrowDownIcon';
@@ -12,28 +16,24 @@
12
16
  import TrashIcon from 'phosphor-svelte/lib/TrashIcon';
13
17
  import LinkAttributesPanel from './LinkAttributesPanel.svelte';
14
18
  import AttributeFieldControl from './AttributeFieldControl.svelte';
19
+ import { dropdownDismiss } from './dropdownDismiss.js';
20
+ import { CHOOSE_ATTRIBUTE_EVENT, type ChooseAttributeRequest } from './chooseAttribute.js';
15
21
 
16
22
  interface Props {
17
23
  controller: BlockAttributesController;
18
24
  blocks?: BlockRegistry | BlockDefinition[];
25
+ /**
26
+ * Resolve a custom attribute value through host-provided UI. Preferred
27
+ * over the deprecated `window`-level `uncial:choose-attribute` event,
28
+ * which cross-talks between multiple editors on one page. When omitted,
29
+ * the panel falls back to dispatching that window event for back-compat.
30
+ */
31
+ onChooseAttribute?: (request: ChooseAttributeRequest) => void;
19
32
  }
20
33
 
21
- let { controller, blocks = [] }: Props = $props();
34
+ let { controller, blocks = [], onChooseAttribute }: Props = $props();
22
35
 
23
- let controllerState = $state<BlockAttributesState>({
24
- open: false,
25
- mode: null,
26
- selectedBlockId: '',
27
- draftAttrs: {},
28
- validationErrors: {},
29
- activeBlock: null,
30
- allowedBlockIds: [],
31
- containerChildren: [],
32
- link: {
33
- open: false,
34
- attrs: {}
35
- }
36
- });
36
+ let controllerState = $state<BlockAttributesState>(createInitialState());
37
37
 
38
38
  const registry = $derived(resolveRegistry(blocks));
39
39
  const selectedBlock = $derived.by(() => {
@@ -86,20 +86,25 @@
86
86
  }
87
87
 
88
88
  function chooseCustomAttribute(name: string, inputKind: string): void {
89
- window.dispatchEvent(
90
- new CustomEvent('uncial:choose-attribute', {
91
- detail: {
92
- inputKind,
93
- name,
94
- attrs: controllerState.draftAttrs,
95
- setAttrs: (attrs: Record<string, unknown>) => {
96
- for (const [key, value] of Object.entries(attrs)) {
97
- controller.setDraftAttr(key, value);
98
- }
99
- }
89
+ const request: ChooseAttributeRequest = {
90
+ inputKind,
91
+ name,
92
+ attrs: controllerState.draftAttrs,
93
+ setAttrs: (attrs: Record<string, unknown>) => {
94
+ for (const [key, value] of Object.entries(attrs)) {
95
+ controller.setDraftAttr(key, value);
100
96
  }
101
- })
102
- );
97
+ }
98
+ };
99
+
100
+ if (onChooseAttribute) {
101
+ onChooseAttribute(request);
102
+ return;
103
+ }
104
+
105
+ // Deprecated fallback: a window-global channel that cross-talks between
106
+ // editors. Retained for one release for hosts not yet passing the prop.
107
+ window.dispatchEvent(new CustomEvent(CHOOSE_ATTRIBUTE_EVENT, { detail: request }));
103
108
  }
104
109
 
105
110
  function startChildDrag(event: PointerEvent, index: number): void {
@@ -196,7 +201,7 @@
196
201
  <div class="uncial-children-section__header">
197
202
  <p class="uncial-section-label">Nested blocks</p>
198
203
  {#if activeBlocks.length > 0}
199
- <details class="uncial-dropdown uncial-dropdown--end">
204
+ <details class="uncial-dropdown uncial-dropdown--end" use:dropdownDismiss>
200
205
  <summary class="uncial-btn uncial-btn--primary uncial-btn--xs">
201
206
  <PlusIcon size={12} weight="bold" />
202
207
  <span>Add block</span>
@@ -1,8 +1,16 @@
1
1
  import type { BlockDefinition, BlockRegistry } from '../core/types.js';
2
- import type { BlockAttributesController } from './attributesController.js';
2
+ import { type BlockAttributesController } from './attributesController.js';
3
+ import { type ChooseAttributeRequest } from './chooseAttribute.js';
3
4
  interface Props {
4
5
  controller: BlockAttributesController;
5
6
  blocks?: BlockRegistry | BlockDefinition[];
7
+ /**
8
+ * Resolve a custom attribute value through host-provided UI. Preferred
9
+ * over the deprecated `window`-level `uncial:choose-attribute` event,
10
+ * which cross-talks between multiple editors on one page. When omitted,
11
+ * the panel falls back to dispatching that window event for back-compat.
12
+ */
13
+ onChooseAttribute?: (request: ChooseAttributeRequest) => void;
6
14
  }
7
15
  declare const BlockAttributesPanel: import("svelte").Component<Props, {}, "">;
8
16
  type BlockAttributesPanel = ReturnType<typeof BlockAttributesPanel>;
@@ -14,6 +14,7 @@
14
14
  import { emptyDocument } from '../shared/content.js';
15
15
  import {
16
16
  createBlockAttributesController,
17
+ createInitialState,
17
18
  type BlockAttributesController,
18
19
  type BlockAttributesState
19
20
  } from './attributesController.js';
@@ -25,6 +26,7 @@
25
26
  } from './metaController.js';
26
27
  import DocumentMetaPanel from './DocumentMetaPanel.svelte';
27
28
  import Toolbar from './Toolbar.svelte';
29
+ import { dropdownDismiss } from './dropdownDismiss.js';
28
30
  import type { ToolbarFeature, ToolbarFeatureSelection } from './toolbarFeatures.js';
29
31
 
30
32
  interface Props {
@@ -58,20 +60,7 @@
58
60
  let editorHost: HTMLDivElement;
59
61
  let editor = $state<TiptapEditor | null>(null);
60
62
  let interactedNodeView = $state<HTMLElement | null>(null);
61
- let controllerState = $state<BlockAttributesState>({
62
- open: false,
63
- mode: null,
64
- selectedBlockId: '',
65
- draftAttrs: {},
66
- validationErrors: {},
67
- activeBlock: null,
68
- allowedBlockIds: [],
69
- containerChildren: [],
70
- link: {
71
- open: false,
72
- attrs: {}
73
- }
74
- });
63
+ let controllerState = $state<BlockAttributesState>(createInitialState());
75
64
  let attrsTriggerEl = $state<HTMLElement | null>(null);
76
65
  let metaTriggerEl = $state<HTMLElement | null>(null);
77
66
  const internalController = createBlockAttributesController();
@@ -278,7 +267,7 @@
278
267
  {#if hasMetaFields || activeBlocks.length > 0}
279
268
  <div class="uncial-toolbar__actions">
280
269
  {#if hasMetaFields}
281
- <details class="uncial-dropdown uncial-dropdown--end">
270
+ <details class="uncial-dropdown uncial-dropdown--end" use:dropdownDismiss>
282
271
  <summary
283
272
  bind:this={metaTriggerEl}
284
273
  aria-label="Edit document metadata"
@@ -297,7 +286,7 @@
297
286
  </details>
298
287
  {/if}
299
288
  {#if activeBlocks.length > 0}
300
- <details class="uncial-dropdown uncial-dropdown--end">
289
+ <details class="uncial-dropdown uncial-dropdown--end" use:dropdownDismiss>
301
290
  <summary
302
291
  bind:this={attrsTriggerEl}
303
292
  aria-label="Insert block"
@@ -1,5 +1,7 @@
1
1
  <script lang="ts">
2
2
  import { Editor } from '@tiptap/core';
3
+ import type { Component } from 'svelte';
4
+ import { createSubscriber } from 'svelte/reactivity';
3
5
  import CodeIcon from 'phosphor-svelte/lib/CodeIcon';
4
6
  import CodeBlockIcon from 'phosphor-svelte/lib/CodeBlockIcon';
5
7
  import ListBulletsIcon from 'phosphor-svelte/lib/ListBulletsIcon';
@@ -14,7 +16,8 @@
14
16
  import type { PMDoc } from '../shared/document.js';
15
17
  import { coerceRichTextDocument, resolveRichTextFeatures } from '../shared/richText.js';
16
18
  import { createRichTextExtensions } from '../shared/tiptap.js';
17
- import type { RichTextFeatureSelection } from '../core/types.js';
19
+ import type { RichTextFeature, RichTextFeatureSelection } from '../core/types.js';
20
+ import { richTextAttributeToolbarFeatures, type ToolbarFeature } from './toolbarFeatures.js';
18
21
 
19
22
  interface Props {
20
23
  value?: unknown;
@@ -35,17 +38,43 @@
35
38
  let lastJson = '';
36
39
 
37
40
  const resolvedFeatures = $derived(resolveRichTextFeatures(features));
38
- const activeEditor = $derived(editor);
39
- const canBold = $derived(resolvedFeatures.has('bold'));
40
- const canItalic = $derived(resolvedFeatures.has('italic'));
41
- const canStrike = $derived(resolvedFeatures.has('strike'));
42
- const canCode = $derived(resolvedFeatures.has('code'));
43
- const canHeading = $derived(resolvedFeatures.has('heading'));
44
- const canBulletList = $derived(resolvedFeatures.has('bulletList'));
45
- const canOrderedList = $derived(resolvedFeatures.has('orderedList'));
46
- const canBlockquote = $derived(resolvedFeatures.has('blockquote'));
47
- const canCodeBlock = $derived(resolvedFeatures.has('codeBlock'));
48
- const canHorizontalRule = $derived(resolvedFeatures.has('horizontalRule'));
41
+ const visibleFeatures = $derived(
42
+ richTextAttributeToolbarFeatures.filter((feature) =>
43
+ resolvedFeatures.has(feature.id as RichTextFeature)
44
+ )
45
+ );
46
+
47
+ const getEditorStateVersion = $derived.by(() => {
48
+ if (!editor) return () => 0;
49
+ const activeEditor = editor;
50
+
51
+ let version = 0;
52
+ const subscribe = createSubscriber((update) => {
53
+ const refreshToolbarState = () => {
54
+ version += 1;
55
+ update();
56
+ };
57
+
58
+ activeEditor.on('transaction', refreshToolbarState);
59
+ activeEditor.on('selectionUpdate', refreshToolbarState);
60
+ activeEditor.on('update', refreshToolbarState);
61
+
62
+ return () => {
63
+ activeEditor.off('transaction', refreshToolbarState);
64
+ activeEditor.off('selectionUpdate', refreshToolbarState);
65
+ activeEditor.off('update', refreshToolbarState);
66
+ };
67
+ });
68
+
69
+ return () => {
70
+ subscribe();
71
+ return version;
72
+ };
73
+ });
74
+ const toolbarContext = $derived.by(() => {
75
+ getEditorStateVersion();
76
+ return editor ? { editor } : null;
77
+ });
49
78
 
50
79
  function emitChange(nextEditor: Editor): void {
51
80
  const json = nextEditor.getJSON() as PMDoc;
@@ -53,8 +82,26 @@
53
82
  onChange(json);
54
83
  }
55
84
 
56
- function runCommand(command: () => boolean): void {
57
- command();
85
+ function runFeature(feature: ToolbarFeature): void {
86
+ if (!editor) return;
87
+ feature.run({ editor });
88
+ }
89
+
90
+ function iconFor(featureId: string): Component<Record<string, unknown>> | null {
91
+ return (
92
+ {
93
+ bold: TextBIcon,
94
+ italic: TextItalicIcon,
95
+ strike: TextStrikethroughIcon,
96
+ code: CodeIcon,
97
+ heading: TextHThreeIcon,
98
+ bulletList: ListBulletsIcon,
99
+ orderedList: ListNumbersIcon,
100
+ blockquote: QuotesIcon,
101
+ codeBlock: CodeBlockIcon,
102
+ horizontalRule: MinusIcon
103
+ }[featureId] ?? null
104
+ );
58
105
  }
59
106
 
60
107
  const iconSize = 14;
@@ -99,144 +146,27 @@
99
146
 
100
147
  <div class="uncial-richtext-wrapper">
101
148
  <div class="uncial-richtext-toolbar">
102
- {#if canBold}
149
+ {#each visibleFeatures as feature (feature.id)}
150
+ {@const context = toolbarContext}
151
+ {@const Icon = iconFor(feature.id)}
152
+ {@const active = context ? (feature.isActive?.(context) ?? false) : false}
103
153
  <button
104
154
  type="button"
105
155
  class={[
106
156
  'uncial-btn uncial-btn--square uncial-btn--xs uncial-tooltip',
107
- activeEditor?.isActive('bold') ? 'uncial-btn--active' : 'uncial-btn--ghost'
157
+ active ? 'uncial-btn--active' : 'uncial-btn--ghost'
108
158
  ]}
109
- aria-label="Bold"
110
- data-tip="Bold"
111
- onclick={() => runCommand(() => editor?.chain().focus().toggleBold().run() ?? false)}
112
- >
113
- <TextBIcon size={iconSize} weight="bold" />
114
- </button>
115
- {/if}
116
- {#if canItalic}
117
- <button
118
- type="button"
119
- class={[
120
- 'uncial-btn uncial-btn--square uncial-btn--xs uncial-tooltip',
121
- activeEditor?.isActive('italic') ? 'uncial-btn--active' : 'uncial-btn--ghost'
122
- ]}
123
- aria-label="Italic"
124
- data-tip="Italic"
125
- onclick={() => runCommand(() => editor?.chain().focus().toggleItalic().run() ?? false)}
126
- >
127
- <TextItalicIcon size={iconSize} weight="bold" />
128
- </button>
129
- {/if}
130
- {#if canStrike}
131
- <button
132
- type="button"
133
- class={[
134
- 'uncial-btn uncial-btn--square uncial-btn--xs uncial-tooltip',
135
- activeEditor?.isActive('strike') ? 'uncial-btn--active' : 'uncial-btn--ghost'
136
- ]}
137
- aria-label="Strikethrough"
138
- data-tip="Strikethrough"
139
- onclick={() => runCommand(() => editor?.chain().focus().toggleStrike().run() ?? false)}
140
- >
141
- <TextStrikethroughIcon size={iconSize} weight="bold" />
142
- </button>
143
- {/if}
144
- {#if canCode}
145
- <button
146
- type="button"
147
- class={[
148
- 'uncial-btn uncial-btn--square uncial-btn--xs uncial-tooltip',
149
- activeEditor?.isActive('code') ? 'uncial-btn--active' : 'uncial-btn--ghost'
150
- ]}
151
- aria-label="Inline code"
152
- data-tip="Inline code"
153
- onclick={() => runCommand(() => editor?.chain().focus().toggleCode().run() ?? false)}
154
- >
155
- <CodeIcon size={iconSize} weight="bold" />
156
- </button>
157
- {/if}
158
- {#if canHeading}
159
- <button
160
- type="button"
161
- class={[
162
- 'uncial-btn uncial-btn--square uncial-btn--xs uncial-tooltip',
163
- activeEditor?.isActive('heading') ? 'uncial-btn--active' : 'uncial-btn--ghost'
164
- ]}
165
- aria-label="Heading"
166
- data-tip="Heading"
167
- onclick={() =>
168
- runCommand(() => editor?.chain().focus().toggleHeading({ level: 3 }).run() ?? false)}
169
- >
170
- <TextHThreeIcon size={iconSize} weight="bold" />
171
- </button>
172
- {/if}
173
- {#if canBulletList}
174
- <button
175
- type="button"
176
- class={[
177
- 'uncial-btn uncial-btn--square uncial-btn--xs uncial-tooltip',
178
- activeEditor?.isActive('bulletList') ? 'uncial-btn--active' : 'uncial-btn--ghost'
179
- ]}
180
- aria-label="Bullet list"
181
- data-tip="Bullet list"
182
- onclick={() => runCommand(() => editor?.chain().focus().toggleBulletList().run() ?? false)}
183
- >
184
- <ListBulletsIcon size={iconSize} weight="bold" />
185
- </button>
186
- {/if}
187
- {#if canOrderedList}
188
- <button
189
- type="button"
190
- class={[
191
- 'uncial-btn uncial-btn--square uncial-btn--xs uncial-tooltip',
192
- activeEditor?.isActive('orderedList') ? 'uncial-btn--active' : 'uncial-btn--ghost'
193
- ]}
194
- aria-label="Ordered list"
195
- data-tip="Ordered list"
196
- onclick={() => runCommand(() => editor?.chain().focus().toggleOrderedList().run() ?? false)}
197
- >
198
- <ListNumbersIcon size={iconSize} weight="bold" />
199
- </button>
200
- {/if}
201
- {#if canBlockquote}
202
- <button
203
- type="button"
204
- class={[
205
- 'uncial-btn uncial-btn--square uncial-btn--xs uncial-tooltip',
206
- activeEditor?.isActive('blockquote') ? 'uncial-btn--active' : 'uncial-btn--ghost'
207
- ]}
208
- aria-label="Blockquote"
209
- data-tip="Blockquote"
210
- onclick={() => runCommand(() => editor?.chain().focus().toggleBlockquote().run() ?? false)}
211
- >
212
- <QuotesIcon size={iconSize} weight="bold" />
213
- </button>
214
- {/if}
215
- {#if canCodeBlock}
216
- <button
217
- type="button"
218
- class={[
219
- 'uncial-btn uncial-btn--square uncial-btn--xs uncial-tooltip',
220
- activeEditor?.isActive('codeBlock') ? 'uncial-btn--active' : 'uncial-btn--ghost'
221
- ]}
222
- aria-label="Code block"
223
- data-tip="Code block"
224
- onclick={() => runCommand(() => editor?.chain().focus().toggleCodeBlock().run() ?? false)}
225
- >
226
- <CodeBlockIcon size={iconSize} weight="bold" />
227
- </button>
228
- {/if}
229
- {#if canHorizontalRule}
230
- <button
231
- type="button"
232
- class="uncial-btn uncial-btn--ghost uncial-btn--square uncial-btn--xs uncial-tooltip"
233
- aria-label="Horizontal rule"
234
- data-tip="Horizontal rule"
235
- onclick={() => runCommand(() => editor?.chain().focus().setHorizontalRule().run() ?? false)}
159
+ aria-label={feature.label}
160
+ data-tip={feature.tooltip ?? feature.label}
161
+ onclick={() => runFeature(feature)}
236
162
  >
237
- <MinusIcon size={iconSize} weight="bold" />
163
+ {#if Icon}
164
+ <Icon size={iconSize} weight="bold" />
165
+ {:else}
166
+ {feature.label}
167
+ {/if}
238
168
  </button>
239
- {/if}
169
+ {/each}
240
170
  </div>
241
171
  <div bind:this={element}></div>
242
172
  </div>